KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > swt > internal > image > JPEGDecoder


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.swt.internal.image;
12
13 import java.io.*;
14
15 import org.eclipse.swt.*;
16 import org.eclipse.swt.graphics.*;
17
18 public class JPEGDecoder {
19     
20     static final int DCTSIZE = 8;
21     static final int DCTSIZE2 = 64;
22     static final int NUM_QUANT_TBLS = 4;
23     static final int NUM_HUFF_TBLS = 4;
24     static final int NUM_ARITH_TBLS = 16;
25     static final int MAX_COMPS_IN_SCAN = 4;
26     static final int MAX_COMPONENTS = 10;
27     static final int MAX_SAMP_FACTOR = 4;
28     static final int D_MAX_BLOCKS_IN_MCU = 10;
29     static final int HUFF_LOOKAHEAD = 8;
30     static final int MAX_Q_COMPS = 4;
31     static final int IFAST_SCALE_BITS = 2;
32     static final int MAXJSAMPLE = 255;
33     static final int CENTERJSAMPLE = 128;
34     static final int MIN_GET_BITS = 32-7;
35     static final int INPUT_BUFFER_SIZE = 4096;
36
37     static final int SCALEBITS = 16; /* speediest right-shift on some machines */
38     static final int ONE_HALF = 1 << (SCALEBITS-1);
39     
40     static final int RGB_RED = 2; /* Offset of Red in an RGB scanline element */
41     static final int RGB_GREEN = 1; /* Offset of Green */
42     static final int RGB_BLUE = 0; /* Offset of Blue */
43     static final int RGB_PIXELSIZE = 3;
44     
45     static final int JBUF_PASS_THRU = 0;
46     static final int JBUF_SAVE_SOURCE = 1; /* Run source subobject only, save output */
47     static final int JBUF_CRANK_DEST = 2; /* Run dest subobject only, using saved data */
48     static final int JBUF_SAVE_AND_PASS = 3;
49     
50     static final int JPEG_MAX_DIMENSION = 65500;
51     static final int BITS_IN_JSAMPLE = 8;
52     
53     static final int JDITHER_NONE = 0; /* no dithering */
54     static final int JDITHER_ORDERED = 1; /* simple ordered dither */
55     static final int JDITHER_FS = 2;
56     
57     static final int JDCT_ISLOW = 0; /* slow but accurate integer algorithm */
58     static final int JDCT_IFAST = 1; /* faster, less accurate integer method */
59     static final int JDCT_FLOAT = 2; /* floating-point: accurate, fast on fast HW */
60     static final int JDCT_DEFAULT = JDCT_ISLOW;
61
62     static final int JCS_UNKNOWN = 0; /* error/unspecified */
63     static final int JCS_GRAYSCALE = 1; /* monochrome */
64     static final int JCS_RGB = 2; /* red/green/blue */
65     static final int JCS_YCbCr = 3; /* Y/Cb/Cr (also known as YUV) */
66     static final int JCS_CMYK = 4; /* C/M/Y/K */
67     static final int JCS_YCCK = 5; /* Y/Cb/Cr/K */
68
69     static final int SAVED_COEFS = 6;
70     static final int Q01_POS = 1;
71     static final int Q10_POS = 8;
72     static final int Q20_POS = 16;
73     static final int Q11_POS = 9;
74     static final int Q02_POS = 2;
75     
76     static final int CTX_PREPARE_FOR_IMCU = 0; /* need to prepare for MCU row */
77     static final int CTX_PROCESS_IMCU = 1; /* feeding iMCU to postprocessor */
78     static final int CTX_POSTPONED_ROW = 2; /* feeding postponed row group */
79     
80     static final int APP0_DATA_LEN = 14; /* Length of interesting data in APP0 */
81     static final int APP14_DATA_LEN = 12; /* Length of interesting data in APP14 */
82     static final int APPN_DATA_LEN = 14; /* Must be the largest of the above!! */
83
84     /* markers */
85     static final int M_SOF0 = 0xc0;
86     static final int M_SOF1 = 0xc1;
87     static final int M_SOF2 = 0xc2;
88     static final int M_SOF3 = 0xc3;
89     static final int M_SOF5 = 0xc5;
90     static final int M_SOF6 = 0xc6;
91     static final int M_SOF7 = 0xc7;
92     static final int M_JPG = 0xc8;
93     static final int M_SOF9 = 0xc9;
94     static final int M_SOF10 = 0xca;
95     static final int M_SOF11 = 0xcb;
96     static final int M_SOF13 = 0xcd;
97     static final int M_SOF14 = 0xce;
98     static final int M_SOF15 = 0xcf;
99     static final int M_DHT = 0xc4;
100     static final int M_DAC = 0xcc;
101     static final int M_RST0 = 0xd0;
102     static final int M_RST1 = 0xd1;
103     static final int M_RST2 = 0xd2;
104     static final int M_RST3 = 0xd3;
105     static final int M_RST4 = 0xd4;
106     static final int M_RST5 = 0xd5;
107     static final int M_RST6 = 0xd6;
108     static final int M_RST7 = 0xd7;
109     static final int M_SOI = 0xd8;
110     static final int M_EOI = 0xd9;
111     static final int M_SOS = 0xda;
112     static final int M_DQT = 0xdb;
113     static final int M_DNL = 0xdc;
114     static final int M_DRI = 0xdd;
115     static final int M_DHP = 0xde;
116     static final int M_EXP = 0xdf;
117     static final int M_APP0 = 0xe0;
118     static final int M_APP1 = 0xe1;
119     static final int M_APP2 = 0xe2;
120     static final int M_APP3 = 0xe3;
121     static final int M_APP4 = 0xe4;
122     static final int M_APP5 = 0xe5;
123     static final int M_APP6 = 0xe6;
124     static final int M_APP7 = 0xe7;
125     static final int M_APP8 = 0xe8;
126     static final int M_APP9 = 0xe9;
127     static final int M_APP10 = 0xea;
128     static final int M_APP11 = 0xeb;
129     static final int M_APP12 = 0xec;
130     static final int M_APP13 = 0xed;
131     static final int M_APP14 = 0xee;
132     static final int M_APP15 = 0xef;
133     static final int M_JPG0 = 0xf0;
134     static final int M_JPG13 = 0xfd;
135     static final int M_COM = 0xfe;
136     static final int M_TEM = 0x01;
137     static final int M_ERROR = 0x100;
138     
139     /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
140     static final int CSTATE_START = 100; /* after create_compress */
141     static final int CSTATE_SCANNING = 101; /* start_compress done, write_scanlines OK */
142     static final int CSTATE_RAW_OK = 102; /* start_compress done, write_raw_data OK */
143     static final int CSTATE_WRCOEFS = 103; /* jpeg_write_coefficients done */
144     static final int DSTATE_START = 200; /* after create_decompress */
145     static final int DSTATE_INHEADER = 201; /* reading header markers, no SOS yet */
146     static final int DSTATE_READY = 202; /* found SOS, ready for start_decompress */
147     static final int DSTATE_PRELOAD = 203; /* reading multiscan file in start_decompress*/
148     static final int DSTATE_PRESCAN = 204; /* performing dummy pass for 2-pass quant */
149     static final int DSTATE_SCANNING = 205; /* start_decompress done, read_scanlines OK */
150     static final int DSTATE_RAW_OK = 206; /* start_decompress done, read_raw_data OK */
151     static final int DSTATE_BUFIMAGE = 207; /* expecting jpeg_start_output */
152     static final int DSTATE_BUFPOST = 208; /* looking for SOS/EOI in jpeg_finish_output */
153     static final int DSTATE_RDCOEFS = 209; /* reading file in jpeg_read_coefficients */
154     static final int DSTATE_STOPPING = 210; /* looking for EOI in jpeg_finish_decompress */
155
156     static final int JPEG_REACHED_SOS = 1; /* Reached start of new scan */
157     static final int JPEG_REACHED_EOI = 2; /* Reached end of image */
158     static final int JPEG_ROW_COMPLETED = 3; /* Completed one iMCU row */
159     static final int JPEG_SCAN_COMPLETED = 4; /* Completed last iMCU row of a scan */
160     
161     static final int JPEG_SUSPENDED = 0; /* Suspended due to lack of input data */
162     static final int JPEG_HEADER_OK = 1; /* Found valid image datastream */
163     static final int JPEG_HEADER_TABLES_ONLY = 2; /* Found valid table-specs-only datastream */
164
165     /* Function pointers */
166     static final int DECOMPRESS_DATA = 0;
167     static final int DECOMPRESS_SMOOTH_DATA = 1;
168     static final int DECOMPRESS_ONEPASS = 2;
169     
170     static final int CONSUME_DATA = 0;
171     static final int DUMMY_CONSUME_DATA = 1;
172     
173     static final int PROCESS_DATA_SIMPLE_MAIN = 0;
174     static final int PROCESS_DATA_CONTEXT_MAIN = 1;
175     static final int PROCESS_DATA_CRANK_POST = 2;
176     
177     static final int POST_PROCESS_1PASS = 0;
178     static final int POST_PROCESS_DATA_UPSAMPLE = 1;
179     
180     static final int NULL_CONVERT = 0;
181     static final int GRAYSCALE_CONVERT = 1;
182     static final int YCC_RGB_CONVERT = 2;
183     static final int GRAY_RGB_CONVERT = 3;
184     static final int YCCK_CMYK_CONVERT = 4;
185     
186     static final int NOOP_UPSAMPLE = 0;
187     static final int FULLSIZE_UPSAMPLE = 1;
188     static final int H2V1_FANCY_UPSAMPLE = 2;
189     static final int H2V1_UPSAMPLE = 3;
190     static final int H2V2_FANCY_UPSAMPLE = 4;
191     static final int H2V2_UPSAMPLE = 5;
192     static final int INT_UPSAMPLE = 6;
193     
194     static final int INPUT_CONSUME_INPUT = 0;
195     static final int COEF_CONSUME_INPUT = 1;
196     
197     static int extend_test[] = /* entry n is 2**(n-1) */
198     {
199         0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
200         0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000
201     };
202
203     static int extend_offset[] = /* entry n is (-1 << n) + 1 */
204     {
205         0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
206         ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
207         ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
208         ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1
209     };
210     
211     static int jpeg_natural_order[] = {
212         0, 1, 8, 16, 9, 2, 3, 10,
213         17, 24, 32, 25, 18, 11, 4, 5,
214         12, 19, 26, 33, 40, 48, 41, 34,
215         27, 20, 13, 6, 7, 14, 21, 28,
216         35, 42, 49, 56, 57, 50, 43, 36,
217         29, 22, 15, 23, 30, 37, 44, 51,
218         58, 59, 52, 45, 38, 31, 39, 46,
219         53, 60, 61, 54, 47, 55, 62, 63,
220         63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
221         63, 63, 63, 63, 63, 63, 63, 63
222     };
223     
224     static final class JQUANT_TBL {
225         /* This array gives the coefficient quantizers in natural array order
226          * (not the zigzag order in which they are stored in a JPEG DQT marker).
227          * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
228          */

229         short[] quantval = new short[DCTSIZE2]; /* quantization step for each coefficient */
230         /* This field is used only during compression. It's initialized false when
231          * the table is created, and set true when it's been output to the file.
232          * You could suppress output of a table by setting this to true.
233          * (See jpeg_suppress_tables for an example.)
234          */

235         boolean sent_table; /* true when table has been output */
236     }
237     
238     static final class JHUFF_TBL {
239         /* These two fields directly represent the contents of a JPEG DHT marker */
240         byte[] bits = new byte[17]; /* bits[k] = # of symbols with codes of */
241                                     /* length k bits; bits[0] is unused */
242         byte[] huffval = new byte[256]; /* The symbols, in order of incr code length */
243         /* This field is used only during compression. It's initialized false when
244          * the table is created, and set true when it's been output to the file.
245          * You could suppress output of a table by setting this to true.
246          * (See jpeg_suppress_tables for an example.)
247          */

248         boolean sent_table; /* true when table has been output */
249     }
250     
251     static final class bitread_perm_state { /* Bitreading state saved across MCUs */
252         int get_buffer; /* current bit-extraction buffer */
253         int bits_left; /* # of unused bits in it */
254     }
255     
256     static final class bitread_working_state { /* Bitreading working state within an MCU */
257         /* Current data source location */
258         /* We need a copy, rather than munging the original, in case of suspension */
259         byte[] buffer; /* => next byte to read from source */
260         int bytes_offset;
261         int bytes_in_buffer; /* # of bytes remaining in source buffer */
262         /* Bit input buffer --- note these values are kept in register variables,
263          * not in this struct, inside the inner loops.
264          */

265         int get_buffer; /* current bit-extraction buffer */
266         int bits_left; /* # of unused bits in it */
267         /* Pointer needed by jpeg_fill_bit_buffer. */
268         jpeg_decompress_struct cinfo; /* back link to decompress master record */
269     }
270     
271     static final class savable_state {
272         int EOBRUN; //Note that this is only used in the progressive case
273
int[] last_dc_val = new int[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
274     }
275     
276     static final class d_derived_tbl {
277         /* Basic tables: (element [0] of each array is unused) */
278         int[] maxcode = new int[18]; /* largest code of length k (-1 if none) */
279         /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
280         int[] valoffset = new int[17]; /* huffval[] offset for codes of length k */
281         /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
282          * the smallest code of length k; so given a code of length k, the
283          * corresponding symbol is huffval[code + valoffset[k]]
284          */

285
286         /* Link to public Huffman table (needed only in jpeg_huff_decode) */
287         JHUFF_TBL pub;
288
289         /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
290          * the input data stream. If the next Huffman code is no more
291          * than HUFF_LOOKAHEAD bits long, we can obtain its length and
292          * the corresponding symbol directly from these tables.
293          */

294         int[] look_nbits = new int[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
295         byte[] look_sym = new byte[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
296     }
297     
298     static final class jpeg_d_coef_controller {
299         int consume_data;
300         int decompress_data;
301
302         /* Pointer to array of coefficient virtual arrays, or null if none */
303         short[][][] coef_arrays;
304     
305         /* These variables keep track of the current location of the input side. */
306         /* cinfo.input_iMCU_row is also used for this. */
307         int MCU_ctr; /* counts MCUs processed in current row */
308         int MCU_vert_offset; /* counts MCU rows within iMCU row */
309         int MCU_rows_per_iMCU_row; /* number of such rows needed */
310
311         /* The output side's location is represented by cinfo.output_iMCU_row. */
312
313         /* In single-pass modes, it's sufficient to buffer just one MCU.
314          * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
315          * and let the entropy decoder write into that workspace each time.
316          * (On 80x86, the workspace is FAR even though it's not really very big;
317          * this is to keep the module interfaces unchanged when a large coefficient
318          * buffer is necessary.)
319          * In multi-pass modes, this array points to the current MCU's blocks
320          * within the virtual arrays; it is used only by the input side.
321          */

322         short[][] MCU_buffer = new short[D_MAX_BLOCKS_IN_MCU][];
323
324         /* In multi-pass modes, we need a virtual block array for each component. */
325         short[][][][] whole_image = new short[MAX_COMPONENTS][][][];
326
327         /* When doing block smoothing, we latch coefficient Al values here */
328         int[] coef_bits_latch;
329         
330         short[] workspace;
331
332         void start_input_pass (jpeg_decompress_struct cinfo) {
333             cinfo.input_iMCU_row = 0;
334             start_iMCU_row(cinfo);
335         }
336         
337         /* Reset within-iMCU-row counters for a new row (input side) */
338         void start_iMCU_row (jpeg_decompress_struct cinfo) {
339             jpeg_d_coef_controller coef = cinfo.coef;
340
341             /* In an interleaved scan, an MCU row is the same as an iMCU row.
342              * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
343              * But at the bottom of the image, process only what's left.
344              */

345             if (cinfo.comps_in_scan > 1) {
346                 coef.MCU_rows_per_iMCU_row = 1;
347             } else {
348                 if (cinfo.input_iMCU_row < (cinfo.total_iMCU_rows-1))
349                     coef.MCU_rows_per_iMCU_row = cinfo.cur_comp_info[0].v_samp_factor;
350                 else
351                     coef.MCU_rows_per_iMCU_row = cinfo.cur_comp_info[0].last_row_height;
352             }
353
354             coef.MCU_ctr = 0;
355             coef.MCU_vert_offset = 0;
356         }
357         
358     }
359     
360     static abstract class jpeg_entropy_decoder {
361         abstract void start_pass (jpeg_decompress_struct cinfo);
362         abstract boolean decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data);
363
364         /* This is here to share code between baseline and progressive decoders; */
365         /* other modules probably should not use it */
366         boolean insufficient_data; /* set true after emitting warning */
367         
368         bitread_working_state br_state_local = new bitread_working_state();
369         savable_state state_local = new savable_state();
370     }
371
372     static final class huff_entropy_decoder extends jpeg_entropy_decoder {
373         bitread_perm_state bitstate = new bitread_perm_state(); /* Bit buffer at start of MCU */
374         savable_state saved = new savable_state(); /* Other state at start of MCU */
375
376         /* These fields are NOT loaded into local working state. */
377         int restarts_to_go; /* MCUs left in this restart interval */
378
379         /* Pointers to derived tables (these workspaces have image lifespan) */
380         d_derived_tbl[] dc_derived_tbls = new d_derived_tbl[NUM_HUFF_TBLS];
381         d_derived_tbl[] ac_derived_tbls = new d_derived_tbl[NUM_HUFF_TBLS];
382
383         /* Precalculated info set up by start_pass for use in decode_mcu: */
384
385         /* Pointers to derived tables to be used for each block within an MCU */
386         d_derived_tbl[] dc_cur_tbls = new d_derived_tbl[D_MAX_BLOCKS_IN_MCU];
387         d_derived_tbl[] ac_cur_tbls = new d_derived_tbl[D_MAX_BLOCKS_IN_MCU];
388         /* Whether we care about the DC and AC coefficient values for each block */
389         boolean[] dc_needed = new boolean[D_MAX_BLOCKS_IN_MCU];
390         boolean[] ac_needed = new boolean[D_MAX_BLOCKS_IN_MCU];
391         
392         void start_pass (jpeg_decompress_struct cinfo) {
393             start_pass_huff_decoder(cinfo);
394         }
395
396         boolean decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data) {
397             huff_entropy_decoder entropy = this;
398             int blkn;
399 // BITREAD_STATE_VARS;
400
int get_buffer;
401             int bits_left;
402 // bitread_working_state br_state = new bitread_working_state();
403
// savable_state state = new savable_state();
404
bitread_working_state br_state = br_state_local;
405             savable_state state = state_local;
406
407                 /* Process restart marker if needed; may have to suspend */
408             if (cinfo.restart_interval != 0) {
409                 if (entropy.restarts_to_go == 0)
410                     if (! process_restart(cinfo))
411                         return false;
412             }
413
414             /* If we've run out of data, just leave the MCU set to zeroes.
415              * This way, we return uniform gray for the remainder of the segment.
416              */

417             if (! entropy.insufficient_data) {
418
419                 /* Load up working state */
420 // BITREAD_LOAD_STATE(cinfo,entropy.bitstate);
421
br_state.cinfo = cinfo;
422                 br_state.buffer = cinfo.buffer;
423                 br_state.bytes_in_buffer = cinfo.bytes_in_buffer;
424                 br_state.bytes_offset = cinfo.bytes_offset;
425                 get_buffer = entropy.bitstate.get_buffer;
426                 bits_left = entropy.bitstate.bits_left;
427                     
428 // ASSIGN_STATE(state, entropy.saved);
429
state.last_dc_val[0] = entropy.saved.last_dc_val[0];
430                 state.last_dc_val[1] = entropy.saved.last_dc_val[1];
431                 state.last_dc_val[2] = entropy.saved.last_dc_val[2];
432                 state.last_dc_val[3] = entropy.saved.last_dc_val[3];
433
434                 /* Outer loop handles each block in the MCU */
435
436                 for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) {
437                     short[] block = MCU_data[blkn];
438                     d_derived_tbl dctbl = entropy.dc_cur_tbls[blkn];
439                     d_derived_tbl actbl = entropy.ac_cur_tbls[blkn];
440                     int s = 0, k, r;
441
442                     /* Decode a single block's worth of coefficients */
443
444                     /* Section F.2.2.1: decode the DC coefficient difference */
445 // HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
446
{
447                     int nb = 0, look;
448                     if (bits_left < HUFF_LOOKAHEAD) {
449                         if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) {
450                             return false;
451                         }
452                         get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
453                         if (bits_left < HUFF_LOOKAHEAD) {
454                             nb = 1;
455 // goto slowlabel;
456
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,dctbl,nb)) < 0) {
457                                 return false;
458                             }
459                             get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
460                         }
461                     }
462 // look = PEEK_BITS(HUFF_LOOKAHEAD);
463
if (nb != 1) {
464                         look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1));
465                         if ((nb = dctbl.look_nbits[look]) != 0) {
466 // DROP_BITS(nb);
467
bits_left -= nb;
468                             s = dctbl.look_sym[look] & 0xFF;
469                         } else {
470                             nb = HUFF_LOOKAHEAD+1;
471 // slowlabel:
472
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,dctbl,nb)) < 0) {
473                                 return false;
474                             }
475                             get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
476                         }
477                     }
478                     }
479
480                     if (s != 0) {
481 // CHECK_BIT_BUFFER(br_state, s, return FALSE);
482
{
483                         if (bits_left < (s)) {
484                             if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) {
485                                 return false;
486                             }
487                             get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
488                         }
489                         }
490 // r = GET_BITS(s);
491
r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1));
492 // s = HUFF_EXTEND(r, s);
493
s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r));
494                     }
495
496                     if (entropy.dc_needed[blkn]) {
497                         /* Convert DC difference to actual value, update last_dc_val */
498                         int ci = cinfo.MCU_membership[blkn];
499                         s += state.last_dc_val[ci];
500                         state.last_dc_val[ci] = s;
501                         /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
502                         block[0] = (short) s;
503                     }
504
505                     if (entropy.ac_needed[blkn]) {
506
507                         /* Section F.2.2.2: decode the AC coefficients */
508                         /* Since zeroes are skipped, output area must be cleared beforehand */
509                         for (k = 1; k < DCTSIZE2; k++) {
510 // HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
511
{
512                             int nb = 0, look;
513                             if (bits_left < HUFF_LOOKAHEAD) {
514                                 if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) {
515                                     return false;
516                                 }
517                                 get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
518                                 if (bits_left < HUFF_LOOKAHEAD) {
519                                     nb = 1;
520 // goto slowlabel;
521
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) {
522                                         return false;
523                                     }
524                                     get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
525                                 }
526                             }
527                             if (nb != 1) {
528 // look = PEEK_BITS(HUFF_LOOKAHEAD);
529
look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1));
530                                 if ((nb = actbl.look_nbits[look]) != 0) {
531 // DROP_BITS(nb);
532
bits_left -= (nb);
533                                     s = actbl.look_sym[look] & 0xFF;
534                                 } else {
535                                     nb = HUFF_LOOKAHEAD+1;
536 // slowlabel:
537
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) {
538                                         return false;
539                                     }
540                                     get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
541                                 }
542                             }
543                             }
544                             r = s >> 4;
545                             s &= 15;
546                         
547                             if (s != 0) {
548                                 k += r;
549 // CHECK_BIT_BUFFER(br_state, s, return FALSE);
550
{
551                                 if (bits_left < (s)) {
552                                     if (!jpeg_fill_bit_buffer(br_state, get_buffer, bits_left, s)) {
553                                         return false;
554                                     }
555                                     get_buffer = (br_state).get_buffer;
556                                     bits_left = (br_state).bits_left;
557                                 }
558                                 }
559 // r = GET_BITS(s);
560
r = (((get_buffer >> (bits_left -= (s)))) & ((1 << (s)) - 1));
561 // s = HUFF_EXTEND(r, s);
562
s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r));
563                                 /*
564                                  * Output coefficient in natural (dezigzagged)
565                                  * order. Note: the extra entries in
566                                  * jpeg_natural_order[] will save us if k >=
567                                  * DCTSIZE2, which could happen if the data is
568                                  * corrupted.
569                                  */

570                                 block[jpeg_natural_order[k]] = (short) s;
571                             } else {
572                                 if (r != 15)
573                                     break;
574                                 k += 15;
575                             }
576                         }
577
578                     } else {
579
580                         /* Section F.2.2.2: decode the AC coefficients */
581                         /* In this path we just discard the values */
582                         for (k = 1; k < DCTSIZE2; k++) {
583 // HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
584
{
585                             int nb = 0, look;
586                             if (bits_left < HUFF_LOOKAHEAD) {
587                                 if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) {
588                                     return false;
589                                 }
590                                 get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
591                                 if (bits_left < HUFF_LOOKAHEAD) {
592                                     nb = 1;
593 // goto slowlabel;
594
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) {
595                                         return false;
596                                     }
597                                     get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
598                                 }
599                             }
600                             if (nb != 1) {
601 // look = PEEK_BITS(HUFF_LOOKAHEAD);
602
look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1));
603                                 if ((nb = actbl.look_nbits[look]) != 0) {
604 // DROP_BITS(nb);
605
bits_left -= (nb);
606                                     s = actbl.look_sym[look] & 0xFF;
607                                 } else {
608                                     nb = HUFF_LOOKAHEAD+1;
609 // slowlabel:
610
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,actbl,nb)) < 0) {
611                                         return false;
612                                     }
613                                     get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
614                                 }
615                             }
616                             }
617                             r = s >> 4;
618                             s &= 15;
619                         
620                             if (s != 0) {
621                                 k += r;
622 // CHECK_BIT_BUFFER(br_state, s, return FALSE);
623
{
624                                 if (bits_left < (s)) {
625                                     if (!jpeg_fill_bit_buffer((br_state),get_buffer,bits_left,s)) {
626                                         return false;
627                                     }
628                                     get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
629                                     }
630                                 }
631 // DROP_BITS(s);
632
bits_left -= s;
633                             } else {
634                                 if (r != 15)
635                                     break;
636                                 k += 15;
637                             }
638                         }
639
640                     }
641                 }
642
643                 /* Completed MCU, so update state */
644 // BITREAD_SAVE_STATE(cinfo,entropy.bitstate);
645
cinfo.buffer = br_state.buffer;
646                 cinfo.bytes_in_buffer = br_state.bytes_in_buffer;
647                 cinfo.bytes_offset = br_state.bytes_offset;
648                 entropy.bitstate.get_buffer = get_buffer;
649                 entropy.bitstate.bits_left = bits_left;
650 // ASSIGN_STATE(entropy.saved, state);
651
entropy.saved.last_dc_val[0] = state.last_dc_val[0];
652                 entropy.saved.last_dc_val[1] = state.last_dc_val[1];
653                 entropy.saved.last_dc_val[2] = state.last_dc_val[2];
654                 entropy.saved.last_dc_val[3] = state.last_dc_val[3];
655             }
656
657             /* Account for restart interval (no-op if not using restarts) */
658             entropy.restarts_to_go--;
659
660             return true;
661         }
662
663         void start_pass_huff_decoder (jpeg_decompress_struct cinfo) {
664             huff_entropy_decoder entropy = this;
665             int ci, blkn, dctbl, actbl;
666             jpeg_component_info compptr;
667
668             /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
669              * This ought to be an error condition, but we make it a warning because
670              * there are some baseline files out there with all zeroes in these bytes.
671              */

672             if (cinfo.Ss != 0 || cinfo.Se != DCTSIZE2-1 || cinfo.Ah != 0 || cinfo.Al != 0) {
673 // WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
674
}
675
676             for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
677                 compptr = cinfo.cur_comp_info[ci];
678                 dctbl = compptr.dc_tbl_no;
679                 actbl = compptr.ac_tbl_no;
680                 /* Compute derived values for Huffman tables */
681                 /* We may do this more than once for a table, but it's not expensive */
682                 jpeg_make_d_derived_tbl(cinfo, true, dctbl, entropy.dc_derived_tbls[dctbl] = new d_derived_tbl());
683                 jpeg_make_d_derived_tbl(cinfo, false, actbl, entropy.ac_derived_tbls[actbl] = new d_derived_tbl());
684                 /* Initialize DC predictions to 0 */
685                 entropy.saved.last_dc_val[ci] = 0;
686             }
687
688             /* Precalculate decoding info for each block in an MCU of this scan */
689             for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) {
690                 ci = cinfo.MCU_membership[blkn];
691                 compptr = cinfo.cur_comp_info[ci];
692                 /* Precalculate which table to use for each block */
693                 entropy.dc_cur_tbls[blkn] = entropy.dc_derived_tbls[compptr.dc_tbl_no];
694                 entropy.ac_cur_tbls[blkn] = entropy.ac_derived_tbls[compptr.ac_tbl_no];
695                 /* Decide whether we really care about the coefficient values */
696                 if (compptr.component_needed) {
697                     entropy.dc_needed[blkn] = true;
698                     /* we don't need the ACs if producing a 1/8th-size image */
699                     entropy.ac_needed[blkn] = (compptr.DCT_scaled_size > 1);
700                 } else {
701                     entropy.dc_needed[blkn] = entropy.ac_needed[blkn] = false;
702                 }
703             }
704
705             /* Initialize bitread state variables */
706             entropy.bitstate.bits_left = 0;
707             entropy.bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
708             entropy.insufficient_data = false;
709
710             /* Initialize restart counter */
711             entropy.restarts_to_go = cinfo.restart_interval;
712         }
713     
714         boolean process_restart (jpeg_decompress_struct cinfo) {
715             huff_entropy_decoder entropy = this;
716             int ci;
717
718             /* Throw away any unused bits remaining in bit buffer; */
719             /* include any full bytes in next_marker's count of discarded bytes */
720             cinfo.marker.discarded_bytes += entropy.bitstate.bits_left / 8;
721             entropy.bitstate.bits_left = 0;
722
723             /* Advance past the RSTn marker */
724             if (! read_restart_marker (cinfo))
725                 return false;
726
727             /* Re-initialize DC predictions to 0 */
728             for (ci = 0; ci < cinfo.comps_in_scan; ci++)
729                 entropy.saved.last_dc_val[ci] = 0;
730
731             /* Reset restart counter */
732             entropy.restarts_to_go = cinfo.restart_interval;
733
734             /* Reset out-of-data flag, unless read_restart_marker left us smack up
735              * against a marker. In that case we will end up treating the next data
736              * segment as empty, and we can avoid producing bogus output pixels by
737              * leaving the flag set.
738              */

739             if (cinfo.unread_marker == 0)
740                 entropy.insufficient_data = false;
741
742             return true;
743         }
744     }
745     
746     static final class phuff_entropy_decoder extends jpeg_entropy_decoder {
747
748         /* These fields are loaded into local variables at start of each MCU.
749          * In case of suspension, we exit WITHOUT updating them.
750          */

751         bitread_perm_state bitstate = new bitread_perm_state(); /* Bit buffer at start of MCU */
752         savable_state saved = new savable_state(); /* Other state at start of MCU */
753
754         /* These fields are NOT loaded into local working state. */
755         int restarts_to_go; /* MCUs left in this restart interval */
756
757         /* Pointers to derived tables (these workspaces have image lifespan) */
758         d_derived_tbl[] derived_tbls = new d_derived_tbl[NUM_HUFF_TBLS];
759
760         d_derived_tbl ac_derived_tbl; /* active table during an AC scan */
761         
762         int[] newnz_pos = new int[DCTSIZE2];
763             
764         void start_pass (jpeg_decompress_struct cinfo) {
765             start_pass_phuff_decoder(cinfo);
766         }
767             
768         boolean decode_mcu (jpeg_decompress_struct cinfo, short[][] MCU_data) {
769             boolean is_DC_band = (cinfo.Ss == 0);
770             if (cinfo.Ah == 0) {
771                 if (is_DC_band)
772                     return decode_mcu_DC_first(cinfo, MCU_data);
773                 else
774                     return decode_mcu_AC_first(cinfo, MCU_data);
775             } else {
776                 if (is_DC_band)
777                     return decode_mcu_DC_refine(cinfo, MCU_data);
778                 else
779                     return decode_mcu_AC_refine(cinfo, MCU_data);
780             }
781         }
782             
783         boolean decode_mcu_DC_refine (jpeg_decompress_struct cinfo, short[][] MCU_data) {
784             phuff_entropy_decoder entropy = this;
785             int p1 = 1 << cinfo.Al; /* 1 in the bit position being coded */
786             int blkn;
787             short[] block;
788 // BITREAD_STATE_VARS;
789
int get_buffer;
790             int bits_left;
791 // bitread_working_state br_state = new bitread_working_state();
792
bitread_working_state br_state = br_state_local;
793                     
794             /* Process restart marker if needed; may have to suspend */
795             if (cinfo.restart_interval != 0) {
796                 if (entropy.restarts_to_go == 0)
797                     if (! process_restart(cinfo))
798                         return false;
799             }
800
801             /* Not worth the cycles to check insufficient_data here,
802              * since we will not change the data anyway if we read zeroes.
803              */

804
805             /* Load up working state */
806 // BITREAD_LOAD_STATE(cinfo,entropy.bitstate);
807
br_state.cinfo = cinfo;
808             br_state.buffer = cinfo.buffer;
809             br_state.bytes_in_buffer = cinfo.bytes_in_buffer;
810             br_state.bytes_offset = cinfo.bytes_offset;
811             get_buffer = entropy.bitstate.get_buffer;
812             bits_left = entropy.bitstate.bits_left;
813                     
814             /* Outer loop handles each block in the MCU */
815
816             for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) {
817                 block = MCU_data[blkn];
818
819                 /* Encoded data is simply the next bit of the two's-complement DC value */
820 // CHECK_BIT_BUFFER(br_state, 1, return FALSE);
821
{
822                 if (bits_left < (1)) {
823                     if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) {
824                          return false;
825                     }
826                     get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
827                 }
828                 }
829 // if (GET_BITS(1))
830
if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0)
831                     block[0] |= p1;
832                     /* Note: since we use |=, repeating the assignment later is safe */
833             }
834
835             /* Completed MCU, so update state */
836 // BITREAD_SAVE_STATE(cinfo,entropy.bitstate);
837
cinfo.buffer = br_state.buffer;
838             cinfo.bytes_in_buffer = br_state.bytes_in_buffer;
839             cinfo.bytes_offset = br_state.bytes_offset;
840             entropy.bitstate.get_buffer = get_buffer;
841             entropy.bitstate.bits_left = bits_left;
842                     
843             /* Account for restart interval (no-op if not using restarts) */
844             entropy.restarts_to_go--;
845
846             return true;
847
848         }
849             
850         boolean decode_mcu_AC_refine (jpeg_decompress_struct cinfo, short[][] MCU_data) {
851             phuff_entropy_decoder entropy = this;
852             int Se = cinfo.Se;
853             int p1 = 1 << cinfo.Al; /* 1 in the bit position being coded */
854             int m1 = (-1) << cinfo.Al; /* -1 in the bit position being coded */
855             int s = 0, k, r;
856             int EOBRUN;
857             short[] block;
858             short[] thiscoef;
859 // BITREAD_STATE_VARS;
860
int get_buffer;
861             int bits_left;
862 // bitread_working_state br_state = new bitread_working_state();
863
bitread_working_state br_state = br_state_local;
864                 
865             d_derived_tbl tbl;
866             int num_newnz;
867             int[] newnz_pos = entropy.newnz_pos;
868
869                 /* Process restart marker if needed; may have to suspend */
870             if (cinfo.restart_interval != 0) {
871                 if (entropy.restarts_to_go == 0)
872                     if (! process_restart(cinfo))
873                         return false;
874             }
875
876             /* If we've run out of data, don't modify the MCU.
877              */

878             if (! entropy.insufficient_data) {
879
880                 /* Load up working state */
881 // BITREAD_LOAD_STATE(cinfo,entropy.bitstate);
882
br_state.cinfo = cinfo;
883                 br_state.buffer = cinfo.buffer;
884                 br_state.bytes_in_buffer = cinfo.bytes_in_buffer;
885                 br_state.bytes_offset = cinfo.bytes_offset;
886                 get_buffer = entropy.bitstate.get_buffer;
887                 bits_left = entropy.bitstate.bits_left;
888                     
889                 EOBRUN = entropy.saved.EOBRUN; /* only part of saved state we need */
890
891                 /* There is always only one block per MCU */
892                 block = MCU_data[0];
893                 tbl = entropy.ac_derived_tbl;
894
895                 /* If we are forced to suspend, we must undo the assignments to any newly
896                  * nonzero coefficients in the block, because otherwise we'd get confused
897                  * next time about which coefficients were already nonzero.
898                  * But we need not undo addition of bits to already-nonzero coefficients;
899                  * instead, we can test the current bit to see if we already did it.
900                  */

901                 num_newnz = 0;
902
903                 /* initialize coefficient loop counter to start of band */
904                 k = cinfo.Ss;
905
906                 if (EOBRUN == 0) {
907                     for (; k <= Se; k++) {
908 // HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
909
{
910                         int nb = 0, look;
911                         if (bits_left < HUFF_LOOKAHEAD) {
912                             if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) {
913 // failaction;
914
while (num_newnz > 0)
915                                     block[newnz_pos[--num_newnz]] = 0;
916
917                                 return false;
918                             }
919                             get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
920                             if (bits_left < HUFF_LOOKAHEAD) {
921                                 nb = 1;
922 // goto slowlabel;
923
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) {
924 // failaction;
925
while (num_newnz > 0)
926                                         block[newnz_pos[--num_newnz]] = 0;
927
928                                     return false;
929                                 }
930                                 get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
931                             }
932                         }
933                         if (nb != 1) {
934 // look = PEEK_BITS(HUFF_LOOKAHEAD);
935
look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1));
936                             if ((nb = tbl.look_nbits[look]) != 0) {
937 // DROP_BITS(nb);
938
bits_left -= nb;
939                                 s = tbl.look_sym[look] & 0xFF;
940                             } else {
941                                 nb = HUFF_LOOKAHEAD+1;
942 // slowlabel:
943
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) {
944 // failaction;
945
while (num_newnz > 0)
946                                         block[newnz_pos[--num_newnz]] = 0;
947
948                                     return false;
949                                 }
950                                 get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
951                             }
952                         }
953                         }
954                         r = s >> 4;
955                         s &= 15;
956                         if (s != 0) {
957                             if (s != 1) { /* size of new coef should always be 1 */
958 // WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
959
}
960 // CHECK_BIT_BUFFER(br_state, 1, goto undoit);
961
{
962                             if (bits_left < (1)) {
963                                 if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) {
964 // failaction;
965
while (num_newnz > 0)
966                                         block[newnz_pos[--num_newnz]] = 0;
967
968                                     return false;
969                                 }
970                                 get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
971                                 }
972                             }
973 // if (GET_BITS(1))
974
if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0)
975                                 s = p1; /* newly nonzero coef is positive */
976                             else
977                                 s = m1; /* newly nonzero coef is negative */
978                         } else {
979                             if (r != 15) {
980                                 EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
981                                 if (r != 0) {
982 // CHECK_BIT_BUFFER(br_state, r, goto undoit);
983
{
984                                     if (bits_left < (r)) {
985                                         if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,r)) {
986 // failaction;
987
while (num_newnz > 0)
988                                                 block[newnz_pos[--num_newnz]] = 0;
989
990                                             return false;
991                                         }
992                                         get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
993                                     }
994                                     }
995 // r = GET_BITS(r);
996
r = (( (get_buffer >> (bits_left -= (r)))) & ((1<<(r))-1));
997                                     EOBRUN += r;
998                                 }
999                                 break; /* rest of block is handled by EOB logic */
1000                            }
1001                            /* note s = 0 for processing ZRL */
1002                        }
1003                        /* Advance over already-nonzero coefs and r still-zero coefs,
1004                         * appending correction bits to the nonzeroes. A correction bit is 1
1005                         * if the absolute value of the coefficient must be increased.
1006                         */

1007                        do {
1008                            thiscoef = block;
1009                            int thiscoef_offset = jpeg_natural_order[k];
1010                            if (thiscoef[thiscoef_offset] != 0) {
1011// CHECK_BIT_BUFFER(br_state, 1, goto undoit);
1012
{
1013                                if (bits_left < (1)) {
1014                                    if (!jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) {
1015// failaction;
1016
while (num_newnz > 0)
1017                                            block[newnz_pos[--num_newnz]] = 0;
1018
1019                                        return false;
1020                                    }
1021                                    get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
1022                                }
1023                                }
1024// if (GET_BITS(1)) {
1025
if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) {
1026                                    if ((thiscoef[thiscoef_offset] & p1) == 0) { /* do nothing if already set it */
1027                                        if (thiscoef[thiscoef_offset] >= 0)
1028                                            thiscoef[thiscoef_offset] += p1;
1029                                        else
1030                                            thiscoef[thiscoef_offset] += m1;
1031                                    }
1032                                }
1033                            } else {
1034                                if (--r < 0)
1035                                    break; /* reached target zero coefficient */
1036                            }
1037                            k++;
1038                        } while (k <= Se);
1039                        if (s != 0) {
1040                            int pos = jpeg_natural_order[k];
1041                            /* Output newly nonzero coefficient */
1042                            block[pos] = (short) s;
1043                            /* Remember its position in case we have to suspend */
1044                            newnz_pos[num_newnz++] = pos;
1045                        }
1046                    }
1047                }
1048
1049                if (EOBRUN > 0) {
1050                    /* Scan any remaining coefficient positions after the end-of-band
1051                     * (the last newly nonzero coefficient, if any). Append a correction
1052                     * bit to each already-nonzero coefficient. A correction bit is 1
1053                     * if the absolute value of the coefficient must be increased.
1054                     */

1055                    for (; k <= Se; k++) {
1056                        thiscoef = block;
1057                        int thiscoef_offset = jpeg_natural_order[k];
1058                        if (thiscoef[thiscoef_offset] != 0) {
1059// CHECK_BIT_BUFFER(br_state, 1, goto undoit);
1060
{
1061                            if (bits_left < (1)) {
1062                                if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,1)) {
1063// failaction;
1064
while (num_newnz > 0)
1065                                        block[newnz_pos[--num_newnz]] = 0;
1066    
1067                                    return false;
1068                                }
1069                                get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
1070                            }
1071                            }
1072// if (GET_BITS(1)) {
1073
if ((( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1)) != 0) {
1074                                if ((thiscoef[thiscoef_offset] & p1) == 0) { /* do nothing if already changed it */
1075                                    if (thiscoef[thiscoef_offset] >= 0)
1076                                        thiscoef[thiscoef_offset] += p1;
1077                                    else
1078                                        thiscoef[thiscoef_offset] += m1;
1079                                }
1080                            }
1081                        }
1082                    }
1083                        /* Count one block completed in EOB run */
1084                    EOBRUN--;
1085                }
1086
1087                /* Completed MCU, so update state */
1088// BITREAD_SAVE_STATE(cinfo,entropy.bitstate);
1089
cinfo.buffer = br_state.buffer;
1090                cinfo.bytes_in_buffer = br_state.bytes_in_buffer;
1091                cinfo.bytes_offset = br_state.bytes_offset;
1092                entropy.bitstate.get_buffer = get_buffer;
1093                entropy.bitstate.bits_left = bits_left;
1094                        
1095                entropy.saved.EOBRUN = EOBRUN; /* only part of saved state we need */
1096            }
1097
1098            /* Account for restart interval (no-op if not using restarts) */
1099            entropy.restarts_to_go--;
1100
1101            return true;
1102
1103// undoit:
1104
// /* Re-zero any output coefficients that we made newly nonzero */
1105
// while (num_newnz > 0)
1106
// (*block)[newnz_pos[--num_newnz]] = 0;
1107
//
1108
// return false;
1109

1110        }
1111            
1112        boolean decode_mcu_AC_first (jpeg_decompress_struct cinfo, short[][] MCU_data) {
1113            phuff_entropy_decoder entropy = this;
1114            int Se = cinfo.Se;
1115            int Al = cinfo.Al;
1116            int s = 0, k, r;
1117            int EOBRUN;
1118            short[] block;
1119// BITREAD_STATE_VARS;
1120
int get_buffer;
1121            int bits_left;
1122// bitread_working_state br_state = new bitread_working_state();
1123
bitread_working_state br_state = br_state_local;
1124                    
1125            d_derived_tbl tbl;
1126
1127            /* Process restart marker if needed; may have to suspend */
1128            if (cinfo.restart_interval != 0) {
1129                if (entropy.restarts_to_go == 0)
1130                    if (! process_restart(cinfo))
1131                        return false;
1132            }
1133
1134            /* If we've run out of data, just leave the MCU set to zeroes.
1135             * This way, we return uniform gray for the remainder of the segment.
1136             */

1137            if (! entropy.insufficient_data) {
1138
1139                /* Load up working state.
1140                 * We can avoid loading/saving bitread state if in an EOB run.
1141                 */

1142                EOBRUN = entropy.saved.EOBRUN; /* only part of saved state we need */
1143
1144                /* There is always only one block per MCU */
1145
1146                if (EOBRUN > 0) /* if it's a band of zeroes... */
1147                    EOBRUN--; /* ...process it now (we do nothing) */
1148                else {
1149// BITREAD_LOAD_STATE(cinfo,entropy.bitstate);
1150
br_state.cinfo = cinfo;
1151                    br_state.buffer = cinfo.buffer;
1152                    br_state.bytes_in_buffer = cinfo.bytes_in_buffer;
1153                    br_state.bytes_offset = cinfo.bytes_offset;
1154                    get_buffer = entropy.bitstate.get_buffer;
1155                    bits_left = entropy.bitstate.bits_left;
1156                        
1157                    block = MCU_data[0];
1158                    tbl = entropy.ac_derived_tbl;
1159
1160                    for (k = cinfo.Ss; k <= Se; k++) {
1161// HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
1162
{
1163                        int nb = 0, look;
1164                        if (bits_left < HUFF_LOOKAHEAD) {
1165                            if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) {
1166                                return false;
1167                            }
1168                            get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
1169                            if (bits_left < HUFF_LOOKAHEAD) {
1170                                nb = 1;
1171// goto slowlabel;
1172
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) {
1173                                    return false;
1174                                }
1175                                get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
1176                            }
1177                        }
1178                        if (nb != 1) {
1179// look = PEEK_BITS(HUFF_LOOKAHEAD);
1180
look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1));
1181
1182                            if ((nb = tbl.look_nbits[look]) != 0) {
1183// DROP_BITS(nb);
1184
bits_left -= nb;
1185                                s = tbl.look_sym[look] & 0xFF;
1186                            } else {
1187                                nb = HUFF_LOOKAHEAD+1;
1188// slowlabel:
1189
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) {
1190                                    return false;
1191                                }
1192                                get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
1193                            }
1194                        }
1195                        }
1196                        r = s >> 4;
1197                        s &= 15;
1198                        if (s != 0) {
1199                            k += r;
1200// CHECK_BIT_BUFFER(br_state, s, return FALSE);
1201
{
1202                            if (bits_left < (s)) {
1203                                if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) {
1204                                    return false;
1205                                }
1206                                get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
1207                            }
1208                            }
1209// r = GET_BITS(s);
1210
r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1));
1211// s = HUFF_EXTEND(r, s);
1212
s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r));
1213                            /* Scale and output coefficient in natural (dezigzagged) order */
1214                            block[jpeg_natural_order[k]] = (short) (s << Al);
1215                        } else {
1216                            if (r == 15) { /* ZRL */
1217                                k += 15; /* skip 15 zeroes in band */
1218                            } else { /* EOBr, run length is 2^r + appended bits */
1219                                EOBRUN = 1 << r;
1220                                if (r != 0) { /* EOBr, r > 0 */
1221// CHECK_BIT_BUFFER(br_state, r, return FALSE);
1222
{
1223                                    if (bits_left < (r)) {
1224                                        if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,r)) {
1225                                            return false;
1226                                        }
1227                                        get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
1228                                    }
1229                                    }
1230// r = GET_BITS(r);
1231
r = (( (get_buffer >> (bits_left -= (r)))) & ((1<<(r))-1));
1232                                    EOBRUN += r;
1233                                }
1234                                EOBRUN--; /* this band is processed at this moment */
1235                                break; /* force end-of-band */
1236                            }
1237                        }
1238                    }
1239
1240// BITREAD_SAVE_STATE(cinfo,entropy.bitstate);
1241
cinfo.buffer = br_state.buffer;
1242                    cinfo.bytes_in_buffer = br_state.bytes_in_buffer;
1243                    cinfo.bytes_offset = br_state.bytes_offset;
1244                    entropy.bitstate.get_buffer = get_buffer;
1245                    entropy.bitstate.bits_left = bits_left;
1246                }
1247
1248                /* Completed MCU, so update state */
1249                entropy.saved.EOBRUN = EOBRUN; /* only part of saved state we need */
1250            }
1251
1252            /* Account for restart interval (no-op if not using restarts) */
1253            entropy.restarts_to_go--;
1254
1255            return true;
1256        }
1257            
1258        boolean decode_mcu_DC_first (jpeg_decompress_struct cinfo, short[][] MCU_data) {
1259            phuff_entropy_decoder entropy = this;
1260            int Al = cinfo.Al;
1261            int s = 0, r;
1262            int blkn, ci;
1263            short[] block;
1264// BITREAD_STATE_VARS;
1265
int get_buffer;
1266            int bits_left;
1267// bitread_working_state br_state = new bitread_working_state();
1268
bitread_working_state br_state = br_state_local;
1269                
1270// savable_state state = new savable_state();
1271
savable_state state = state_local;
1272            d_derived_tbl tbl;
1273            jpeg_component_info compptr;
1274
1275            /* Process restart marker if needed; may have to suspend */
1276            if (cinfo.restart_interval != 0) {
1277                if (entropy.restarts_to_go == 0)
1278                    if (! process_restart(cinfo))
1279                        return false;
1280            }
1281
1282            /* If we've run out of data, just leave the MCU set to zeroes.
1283             * This way, we return uniform gray for the remainder of the segment.
1284             */

1285            if (! entropy.insufficient_data) {
1286
1287                /* Load up working state */
1288// BITREAD_LOAD_STATE(cinfo,entropy.bitstate);
1289
br_state.cinfo = cinfo;
1290                br_state.buffer = cinfo.buffer;
1291                br_state.bytes_in_buffer = cinfo.bytes_in_buffer;
1292                br_state.bytes_offset = cinfo.bytes_offset;
1293                get_buffer = entropy.bitstate.get_buffer;
1294                bits_left = entropy.bitstate.bits_left;
1295                    
1296// ASSIGN_STATE(state, entropy.saved);
1297
state.EOBRUN = entropy.saved.EOBRUN;
1298                state.last_dc_val[0] = entropy.saved.last_dc_val[0];
1299                state.last_dc_val[1] = entropy.saved.last_dc_val[1];
1300                state.last_dc_val[2] = entropy.saved.last_dc_val[2];
1301                state.last_dc_val[3] = entropy.saved.last_dc_val[3];
1302                    
1303                /* Outer loop handles each block in the MCU */
1304
1305                for (blkn = 0; blkn < cinfo.blocks_in_MCU; blkn++) {
1306                    block = MCU_data[blkn];
1307                    ci = cinfo.MCU_membership[blkn];
1308                    compptr = cinfo.cur_comp_info[ci];
1309                    tbl = entropy.derived_tbls[compptr.dc_tbl_no];
1310
1311                    /* Decode a single block's worth of coefficients */
1312
1313                    /* Section F.2.2.1: decode the DC coefficient difference */
1314// HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
1315
{
1316                    int nb = 0, look;
1317                    if (bits_left < HUFF_LOOKAHEAD) {
1318                        if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left, 0)) {
1319                            return false;
1320                        }
1321                        get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
1322                        if (bits_left < HUFF_LOOKAHEAD) {
1323                            nb = 1;
1324// goto slowlabel;
1325
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) {
1326                                return false;
1327                            }
1328                            get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
1329                        }
1330                    }
1331                    if (nb != 1) {
1332// look = PEEK_BITS(HUFF_LOOKAHEAD);
1333
look = (( (get_buffer >> (bits_left - (HUFF_LOOKAHEAD)))) & ((1<<(HUFF_LOOKAHEAD))-1));
1334
1335                        if ((nb = tbl.look_nbits[look]) != 0) {
1336// DROP_BITS(nb);
1337
bits_left -= nb;
1338                            s = tbl.look_sym[look] & 0xFF;
1339                        } else {
1340                            nb = HUFF_LOOKAHEAD+1;
1341// slowlabel:
1342
if ((s=jpeg_huff_decode(br_state,get_buffer,bits_left,tbl,nb)) < 0) {
1343                                return false;
1344                            }
1345                            get_buffer = br_state.get_buffer; bits_left = br_state.bits_left;
1346                        }
1347                    }
1348                    }
1349                    if (s != 0) {
1350// CHECK_BIT_BUFFER(br_state, s, return FALSE);
1351
{
1352                        if (bits_left < (s)) {
1353                            if (! jpeg_fill_bit_buffer(br_state,get_buffer,bits_left,s)) {
1354                                return false;
1355                            }
1356                            get_buffer = (br_state).get_buffer; bits_left = (br_state).bits_left;
1357                        }
1358                        }
1359// r = GET_BITS(s);
1360
r = (( (get_buffer >> (bits_left -= (s)))) & ((1<<(s))-1));
1361// s = HUFF_EXTEND(r, s);
1362
s = ((r) < extend_test[s] ? (r) + extend_offset[s] : (r));
1363                    }
1364
1365                        /* Convert DC difference to actual value, update last_dc_val */
1366                    s += state.last_dc_val[ci];
1367                    state.last_dc_val[ci] = s;
1368                    /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
1369                    block[0] = (short) (s << Al);
1370                }
1371
1372                /* Completed MCU, so update state */
1373// BITREAD_SAVE_STATE(cinfo,entropy.bitstate);
1374
cinfo.buffer = br_state.buffer;
1375                cinfo.bytes_in_buffer = br_state.bytes_in_buffer;
1376                cinfo.bytes_offset = br_state.bytes_offset;
1377                entropy.bitstate.get_buffer = get_buffer;
1378                entropy.bitstate.bits_left = bits_left;
1379// ASSIGN_STATE(entropy.saved, state);
1380
entropy.saved.EOBRUN = state.EOBRUN;
1381                entropy.saved.last_dc_val[0] = state.last_dc_val[0];
1382                entropy.saved.last_dc_val[1] = state.last_dc_val[1];
1383                entropy.saved.last_dc_val[2] = state.last_dc_val[2];
1384                entropy.saved.last_dc_val[3] = state.last_dc_val[3];
1385            }
1386
1387            /* Account for restart interval (no-op if not using restarts) */
1388            entropy.restarts_to_go--;
1389
1390            return true;
1391        }
1392            
1393        boolean process_restart (jpeg_decompress_struct cinfo) {
1394            phuff_entropy_decoder entropy = this;
1395            int ci;
1396
1397            /* Throw away any unused bits remaining in bit buffer; */
1398            /* include any full bytes in next_marker's count of discarded bytes */
1399            cinfo.marker.discarded_bytes += entropy.bitstate.bits_left / 8;
1400            entropy.bitstate.bits_left = 0;
1401
1402            /* Advance past the RSTn marker */
1403            if (! read_restart_marker (cinfo))
1404                return false;
1405
1406            /* Re-initialize DC predictions to 0 */
1407            for (ci = 0; ci < cinfo.comps_in_scan; ci++)
1408                entropy.saved.last_dc_val[ci] = 0;
1409                /* Re-init EOB run count, too */
1410            entropy.saved.EOBRUN = 0;
1411
1412            /* Reset restart counter */
1413            entropy.restarts_to_go = cinfo.restart_interval;
1414
1415            /* Reset out-of-data flag, unless read_restart_marker left us smack up
1416             * against a marker. In that case we will end up treating the next data
1417             * segment as empty, and we can avoid producing bogus output pixels by
1418             * leaving the flag set.
1419             */

1420            if (cinfo.unread_marker == 0)
1421                entropy.insufficient_data = false;
1422
1423            return true;
1424        }
1425
1426        void start_pass_phuff_decoder (jpeg_decompress_struct cinfo) {
1427            phuff_entropy_decoder entropy = this;
1428            boolean is_DC_band, bad;
1429            int ci, coefi, tbl;
1430            int[] coef_bit_ptr;
1431            jpeg_component_info compptr;
1432
1433            is_DC_band = (cinfo.Ss == 0);
1434
1435            /* Validate scan parameters */
1436            bad = false;
1437            if (is_DC_band) {
1438                if (cinfo.Se != 0)
1439                    bad = true;
1440            } else {
1441                /* need not check Ss/Se < 0 since they came from unsigned bytes */
1442                if (cinfo.Ss > cinfo.Se || cinfo.Se >= DCTSIZE2)
1443                    bad = true;
1444                /* AC scans may have only one component */
1445                if (cinfo.comps_in_scan != 1)
1446                    bad = true;
1447            }
1448            if (cinfo.Ah != 0) {
1449                /* Successive approximation refinement scan: must have Al = Ah-1. */
1450                if (cinfo.Al != cinfo.Ah-1)
1451                    bad = true;
1452            }
1453            if (cinfo.Al > 13) /* need not check for < 0 */
1454                bad = true;
1455            /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
1456             * but the spec doesn't say so, and we try to be liberal about what we
1457             * accept. Note: large Al values could result in out-of-range DC
1458             * coefficients during early scans, leading to bizarre displays due to
1459             * overflows in the IDCT math. But we won't crash.
1460             */

1461            if (bad)
1462                error();
1463// ERREXIT4(cinfo, JERR_BAD_PROGRESSION, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al);
1464
/* Update progression status, and verify that scan order is legal.
1465             * Note that inter-scan inconsistencies are treated as warnings
1466             * not fatal errors ... not clear if this is right way to behave.
1467             */

1468            for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
1469                int cindex = cinfo.cur_comp_info[ci].component_index;
1470                coef_bit_ptr = cinfo.coef_bits[cindex];
1471                if (!is_DC_band && coef_bit_ptr[0] < 0) {/* AC without prior DC scan */
1472// WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
1473
}
1474                for (coefi = cinfo.Ss; coefi <= cinfo.Se; coefi++) {
1475                    int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
1476                    if (cinfo.Ah != expected) {
1477// WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
1478
}
1479                    coef_bit_ptr[coefi] = cinfo.Al;
1480                }
1481            }
1482
1483            /* Select MCU decoding routine */
1484// if (cinfo.Ah == 0) {
1485
// if (is_DC_band)
1486
// entropy.pub.decode_mcu = decode_mcu_DC_first;
1487
// else
1488
// entropy.pub.decode_mcu = decode_mcu_AC_first;
1489
// } else {
1490
// if (is_DC_band)
1491
// entropy.pub.decode_mcu = decode_mcu_DC_refine;
1492
// else
1493
// entropy.pub.decode_mcu = decode_mcu_AC_refine;
1494
// }
1495

1496            for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
1497                compptr = cinfo.cur_comp_info[ci];
1498                /* Make sure requested tables are present, and compute derived tables.
1499                 * We may build same derived table more than once, but it's not expensive.
1500                 */

1501                if (is_DC_band) {
1502                    if (cinfo.Ah == 0) { /* DC refinement needs no table */
1503                        tbl = compptr.dc_tbl_no;
1504                        jpeg_make_d_derived_tbl(cinfo, true, tbl, entropy.derived_tbls[tbl] = new d_derived_tbl());
1505                    }
1506                } else {
1507                    tbl = compptr.ac_tbl_no;
1508                    jpeg_make_d_derived_tbl(cinfo, false, tbl, entropy.derived_tbls[tbl] = new d_derived_tbl());
1509                    /* remember the single active table */
1510                    entropy.ac_derived_tbl = entropy.derived_tbls[tbl];
1511                }
1512                /* Initialize DC predictions to 0 */
1513                entropy.saved.last_dc_val[ci] = 0;
1514            }
1515
1516            /* Initialize bitread state variables */
1517            entropy.bitstate.bits_left = 0;
1518            entropy.bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
1519            entropy.insufficient_data = false;
1520
1521            /* Initialize private state variables */
1522            entropy.saved.EOBRUN = 0;
1523
1524            /* Initialize restart counter */
1525            entropy.restarts_to_go = cinfo.restart_interval;
1526        }
1527
1528    }
1529    
1530    static final class jpeg_component_info {
1531        /* These values are fixed over the whole image. */
1532        /* For compression, they must be supplied by parameter setup; */
1533        /* for decompression, they are read from the SOF marker. */
1534        int component_id; /* identifier for this component (0..255) */
1535        int component_index; /* its index in SOF or cinfo.comp_info[] */
1536        int h_samp_factor; /* horizontal sampling factor (1..4) */
1537        int v_samp_factor; /* vertical sampling factor (1..4) */
1538        int quant_tbl_no; /* quantization table selector (0..3) */
1539        /* These values may vary between scans. */
1540        /* For compression, they must be supplied by parameter setup; */
1541        /* for decompression, they are read from the SOS marker. */
1542        /* The decompressor output side may not use these variables. */
1543        int dc_tbl_no; /* DC entropy table selector (0..3) */
1544        int ac_tbl_no; /* AC entropy table selector (0..3) */
1545        
1546        /* Remaining fields should be treated as private by applications. */
1547        
1548        /* These values are computed during compression or decompression startup: */
1549        /* Component's size in DCT blocks.
1550         * Any dummy blocks added to complete an MCU are not counted; therefore
1551         * these values do not depend on whether a scan is interleaved or not.
1552         */

1553        int width_in_blocks;
1554        int height_in_blocks;
1555        /* Size of a DCT block in samples. Always DCTSIZE for compression.
1556         * For decompression this is the size of the output from one DCT block,
1557         * reflecting any scaling we choose to apply during the IDCT step.
1558         * Values of 1,2,4,8 are likely to be supported. Note that different
1559         * components may receive different IDCT scalings.
1560         */

1561        int DCT_scaled_size;
1562        /* The downsampled dimensions are the component's actual, unpadded number
1563         * of samples at the main buffer (preprocessing/compression interface), thus
1564         * downsampled_width = ceil(image_width * Hi/Hmax)
1565         * and similarly for height. For decompression, IDCT scaling is included, so
1566         * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
1567         */

1568        int downsampled_width; /* actual width in samples */
1569        int downsampled_height; /* actual height in samples */
1570        /* This flag is used only for decompression. In cases where some of the
1571         * components will be ignored (eg grayscale output from YCbCr image),
1572         * we can skip most computations for the unused components.
1573         */

1574        boolean component_needed; /* do we need the value of this component? */
1575
1576        /* These values are computed before starting a scan of the component. */
1577        /* The decompressor output side may not use these variables. */
1578        int MCU_width; /* number of blocks per MCU, horizontally */
1579        int MCU_height; /* number of blocks per MCU, vertically */
1580        int MCU_blocks; /* MCU_width * MCU_height */
1581        int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
1582        int last_col_width; /* # of non-dummy blocks across in last MCU */
1583        int last_row_height; /* # of non-dummy blocks down in last MCU */
1584
1585        /* Saved quantization table for component; null if none yet saved.
1586         * See jdinput.c comments about the need for this information.
1587         * This field is currently used only for decompression.
1588         */

1589        JQUANT_TBL quant_table;
1590
1591        /* Private per-component storage for DCT or IDCT subsystem. */
1592        int[] dct_table;
1593    }
1594    
1595    static final class jpeg_color_quantizer {
1596// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
1597
// JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
1598
// JSAMPARRAY input_buf, JSAMPARRAY output_buf,
1599
// int num_rows));
1600
// JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
1601
// JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
1602

1603        /* Initially allocated colormap is saved here */
1604        int[][] sv_colormap; /* The color map as a 2-D pixel array */
1605        int sv_actual; /* number of entries in use */
1606
1607        int[][] colorindex; /* Precomputed mapping for speed */
1608        /* colorindex[i][j] = index of color closest to pixel value j in component i,
1609         * premultiplied as described above. Since colormap indexes must fit into
1610         * JSAMPLEs, the entries of this array will too.
1611         */

1612        boolean is_padded; /* is the colorindex padded for odither? */
1613
1614        int[] Ncolors = new int [MAX_Q_COMPS]; /* # of values alloced to each component */
1615
1616        /* Variables for ordered dithering */
1617        int row_index; /* cur row's vertical index in dither matrix */
1618// ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
1619

1620        /* Variables for Floyd-Steinberg dithering */
1621// FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
1622
boolean on_odd_row;
1623            
1624        void start_pass (jpeg_decompress_struct cinfo, boolean is_pre_scan) {
1625            error();
1626        }
1627    }
1628    
1629    static final class jpeg_upsampler {
1630// JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
1631
// JMETHOD(void, upsample, (j_decompress_ptr cinfo,
1632
// JSAMPIMAGE input_buf,
1633
// JDIMENSION *in_row_group_ctr,
1634
// JDIMENSION in_row_groups_avail,
1635
// JSAMPARRAY output_buf,
1636
// JDIMENSION *out_row_ctr,
1637
// JDIMENSION out_rows_avail));
1638

1639        boolean need_context_rows; /* TRUE if need rows above & below */
1640            
1641        /* Color conversion buffer. When using separate upsampling and color
1642         * conversion steps, this buffer holds one upsampled row group until it
1643         * has been color converted and output.
1644         * Note: we do not allocate any storage for component(s) which are full-size,
1645         * ie do not need rescaling. The corresponding entry of color_buf[] is
1646         * simply set to point to the input data array, thereby avoiding copying.
1647         */

1648        byte[][][] color_buf = new byte[MAX_COMPONENTS][][];
1649        int[] color_buf_offset = new int[MAX_COMPONENTS];
1650
1651        /* Per-component upsampling method pointers */
1652        int[] methods = new int[MAX_COMPONENTS];
1653
1654        int next_row_out; /* counts rows emitted from color_buf */
1655        int rows_to_go; /* counts rows remaining in image */
1656
1657        /* Height of an input row group for each component. */
1658        int[] rowgroup_height = new int[MAX_COMPONENTS];
1659
1660        /* These arrays save pixel expansion factors so that int_expand need not
1661         * recompute them each time. They are unused for other upsampling methods.
1662         */

1663        byte[] h_expand = new byte[MAX_COMPONENTS];
1664        byte[] v_expand = new byte[MAX_COMPONENTS];
1665            
1666        void start_pass (jpeg_decompress_struct cinfo) {
1667            jpeg_upsampler upsample = cinfo.upsample;
1668
1669            /* Mark the conversion buffer empty */
1670            upsample.next_row_out = cinfo.max_v_samp_factor;
1671            /* Initialize total-height counter for detecting bottom of image */
1672            upsample.rows_to_go = cinfo.output_height;
1673        }
1674            
1675    }
1676    
1677    static final class jpeg_marker_reader {
1678        /* Read a restart marker --- exported for use by entropy decoder only */
1679// jpeg_marker_parser_method read_restart_marker;
1680

1681        /* State of marker reader --- nominally internal, but applications
1682         * supplying COM or APPn handlers might like to know the state.
1683         */

1684        boolean saw_SOI; /* found SOI? */
1685        boolean saw_SOF; /* found SOF? */
1686        int next_restart_num; /* next restart number expected (0-7) */
1687        int discarded_bytes; /* # of bytes skipped looking for a marker */
1688        
1689        /* Application-overridable marker processing methods */
1690// jpeg_marker_parser_method process_COM;
1691
// jpeg_marker_parser_method process_APPn[16];
1692

1693        /* Limit on marker data length to save for each marker type */
1694        int length_limit_COM;
1695        int[] length_limit_APPn = new int[16];
1696
1697        /* Status of COM/APPn marker saving */
1698// jpeg_marker_reader cur_marker; /* null if not processing a marker */
1699
// int bytes_read; /* data bytes read so far in marker */
1700
/* Note: cur_marker is not linked into marker_list until it's all read. */
1701    }
1702    
1703    
1704    static final class jpeg_d_main_controller {
1705// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
1706
int process_data;
1707                
1708         /* Pointer to allocated workspace (M or M+2 row groups). */
1709        byte[][][] buffer = new byte[MAX_COMPONENTS][][];
1710        int[] buffer_offset = new int[MAX_COMPONENTS];
1711
1712        boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
1713        int[] rowgroup_ctr = new int[1]; /* counts row groups output to postprocessor */
1714
1715        /* Remaining fields are only used in the context case. */
1716
1717        /* These are the master pointers to the funny-order pointer lists. */
1718        byte[][][][] xbuffer = new byte[2][][][]; /* pointers to weird pointer lists */
1719        int[][] xbuffer_offset = new int[2][];
1720
1721        int whichptr; /* indicates which pointer set is now in use */
1722        int context_state; /* process_data state machine status */
1723        int rowgroups_avail; /* row groups available to postprocessor */
1724        int iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
1725                    
1726        void start_pass (jpeg_decompress_struct cinfo, int pass_mode) {
1727            jpeg_d_main_controller main = cinfo.main;
1728
1729            switch (pass_mode) {
1730                case JBUF_PASS_THRU:
1731                    if (cinfo.upsample.need_context_rows) {
1732                        main.process_data = PROCESS_DATA_CONTEXT_MAIN;
1733                        make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
1734                        main.whichptr = 0; /* Read first iMCU row into xbuffer[0] */
1735                        main.context_state = CTX_PREPARE_FOR_IMCU;
1736                        main.iMCU_row_ctr = 0;
1737                    } else {
1738                        /* Simple case with no context needed */
1739                        main.process_data = PROCESS_DATA_SIMPLE_MAIN;
1740                    }
1741                    main.buffer_full = false; /* Mark buffer empty */
1742                    main.rowgroup_ctr[0] = 0;
1743                    break;
1744// #ifdef QUANT_2PASS_SUPPORTED
1745
// case JBUF_CRANK_DEST:
1746
// /* For last pass of 2-pass quantization, just crank the postprocessor */
1747
// main.process_data = PROCESS_DATA_CRANK_POST;
1748
// break;
1749
// #endif
1750
default:
1751                    error();
1752// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
1753
break;
1754            }
1755        }
1756                    
1757    }
1758
1759    static final class jpeg_decomp_master {
1760// JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
1761
// JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
1762

1763        /* State variables made visible to other modules */
1764        boolean is_dummy_pass;
1765
1766        int pass_number; /* # of passes completed */
1767
1768        boolean using_merged_upsample; /* true if using merged upsample/cconvert */
1769
1770        /* Saved references to initialized quantizer modules,
1771         * in case we need to switch modes.
1772         */

1773        jpeg_color_quantizer quantizer_1pass;
1774        jpeg_color_quantizer quantizer_2pass;
1775    }
1776    
1777    static final class jpeg_inverse_dct {
1778// JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
1779
// /* It is useful to allow each component to have a separate IDCT method. */
1780
// inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
1781
int[] cur_method = new int[MAX_COMPONENTS];
1782            
1783        void start_pass (jpeg_decompress_struct cinfo) {
1784            jpeg_inverse_dct idct = cinfo.idct;
1785            int ci, i;
1786            jpeg_component_info compptr;
1787            int method = 0;
1788// inverse_DCT_method_ptr method_ptr = NULL;
1789
JQUANT_TBL qtbl;
1790
1791            for (ci = 0; ci < cinfo.num_components; ci++) {
1792                compptr = cinfo.comp_info[ci];
1793                /* Select the proper IDCT routine for this component's scaling */
1794                switch (compptr.DCT_scaled_size) {
1795// #ifdef IDCT_SCALING_SUPPORTED
1796
// case 1:
1797
// method_ptr = jpeg_idct_1x1;
1798
// method = JDCT_ISLOW; /* jidctred uses islow-style table */
1799
// break;
1800
// case 2:
1801
// method_ptr = jpeg_idct_2x2;
1802
// method = JDCT_ISLOW; /* jidctred uses islow-style table */
1803
// break;
1804
// case 4:
1805
// method_ptr = jpeg_idct_4x4;
1806
// method = JDCT_ISLOW; /* jidctred uses islow-style table */
1807
// break;
1808
// #endif
1809
case DCTSIZE:
1810                        switch (cinfo.dct_method) {
1811// #ifdef DCT_ISLOW_SUPPORTED
1812
case JDCT_ISLOW:
1813// method_ptr = jpeg_idct_islow;
1814
method = JDCT_ISLOW;
1815                                break;
1816// #endif
1817
// #ifdef DCT_IFAST_SUPPORTED
1818
// case JDCT_IFAST:
1819
// method_ptr = jpeg_idct_ifast;
1820
// method = JDCT_IFAST;
1821
// break;
1822
// #endif
1823
// #ifdef DCT_FLOAT_SUPPORTED
1824
// case JDCT_FLOAT:
1825
// method_ptr = jpeg_idct_float;
1826
// method = JDCT_FLOAT;
1827
// break;
1828
// #endif
1829
default:
1830                                error();
1831// ERREXIT(cinfo, JERR_NOT_COMPILED);
1832
break;
1833                        }
1834                        break;
1835                    default:
1836                        error();
1837// ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr.DCT_scaled_size);
1838
break;
1839                    }
1840// idct.inverse_DCT[ci] = method_ptr;
1841
/* Create multiplier table from quant table.
1842                     * However, we can skip this if the component is uninteresting
1843                     * or if we already built the table. Also, if no quant table
1844                     * has yet been saved for the component, we leave the
1845                     * multiplier table all-zero; we'll be reading zeroes from the
1846                     * coefficient controller's buffer anyway.
1847                     */

1848                    if (! compptr.component_needed || idct.cur_method[ci] == method)
1849                        continue;
1850                    qtbl = compptr.quant_table;
1851                    if (qtbl == null) /* happens if no data yet for component */
1852                        continue;
1853                    idct.cur_method[ci] = method;
1854                    switch (method) {
1855// #ifdef PROVIDE_ISLOW_TABLES
1856
case JDCT_ISLOW:
1857                        {
1858                            /* For LL&M IDCT method, multipliers are equal to raw quantization
1859                             * coefficients, but are stored as ints to ensure access efficiency.
1860                             */

1861                            int[] ismtbl = compptr.dct_table;
1862                            for (i = 0; i < DCTSIZE2; i++) {
1863                                ismtbl[i] = qtbl.quantval[i];
1864                            }
1865                        }
1866                        break;
1867// #endif
1868
// #ifdef DCT_IFAST_SUPPORTED
1869
// case JDCT_IFAST:
1870
// {
1871
// /* For AA&N IDCT method, multipliers are equal to quantization
1872
// * coefficients scaled by scalefactor[row]*scalefactor[col], where
1873
// * scalefactor[0] = 1
1874
// * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
1875
// * For integer operation, the multiplier table is to be scaled by
1876
// * IFAST_SCALE_BITS.
1877
// */
1878
// int[] ifmtbl = compptr.dct_table;
1879
// short aanscales[] = {
1880
// /* precomputed values scaled up by 14 bits */
1881
// 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
1882
// 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
1883
// 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
1884
// 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
1885
// 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
1886
// 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
1887
// 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
1888
// 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
1889
// };
1890
// SHIFT_TEMPS
1891
//
1892
// for (i = 0; i < DCTSIZE2; i++) {
1893
// ifmtbl[i] = DESCALE(MULTIPLY16V16( qtbl.quantval[i], aanscales[i]), CONST_BITS-IFAST_SCALE_BITS);
1894
// }
1895
// }
1896
// break;
1897
// #endif
1898
// #ifdef DCT_FLOAT_SUPPORTED
1899
// case JDCT_FLOAT:
1900
// {
1901
// /* For float AA&N IDCT method, multipliers are equal to quantization
1902
// * coefficients scaled by scalefactor[row]*scalefactor[col], where
1903
// * scalefactor[0] = 1
1904
// * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
1905
// */
1906
// FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr.dct_table;
1907
// int row, col;
1908
// static const double aanscalefactor[DCTSIZE] = {
1909
// 1.0, 1.387039845, 1.306562965, 1.175875602,
1910
// 1.0, 0.785694958, 0.541196100, 0.275899379
1911
// };
1912
//
1913
// i = 0;
1914
// for (row = 0; row < DCTSIZE; row++) {
1915
// for (col = 0; col < DCTSIZE; col++) {
1916
// fmtbl[i] = (FLOAT_MULT_TYPE)
1917
// ((double) qtbl.quantval[i] *
1918
// aanscalefactor[row] * aanscalefactor[col]);
1919
// i++;
1920
// }
1921
// }
1922
// }
1923
// break;
1924
// #endif
1925
default:
1926                        error();
1927// ERREXIT(cinfo, JERR_NOT_COMPILED);
1928
break;
1929                }
1930            }
1931        }
1932    }
1933            
1934    static final class jpeg_input_controller {
1935        int consume_input;
1936        boolean has_multiple_scans; /* True if file has multiple scans */
1937        boolean eoi_reached;
1938
1939        boolean inheaders; /* true until first SOS is reached */
1940    }
1941    
1942    static final class jpeg_color_deconverter {
1943// JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
1944
int color_convert;
1945        
1946        /* Private state for YCC.RGB conversion */
1947        int[] Cr_r_tab; /* => table for Cr to R conversion */
1948        int[] Cb_b_tab; /* => table for Cb to B conversion */
1949        int[] Cr_g_tab; /* => table for Cr to G conversion */
1950        int[] Cb_g_tab; /* => table for Cb to G conversion */
1951            
1952        void start_pass (jpeg_decompress_struct cinfo) {
1953            /* no work needed */
1954        }
1955
1956    }
1957        
1958    static final class jpeg_d_post_controller {
1959// JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
1960
int post_process_data;
1961            
1962        /* Color quantization source buffer: this holds output data from
1963         * the upsample/color conversion step to be passed to the quantizer.
1964         * For two-pass color quantization, we need a full-image buffer;
1965         * for one-pass operation, a strip buffer is sufficient.
1966         */

1967        int[] whole_image; /* virtual array, or NULL if one-pass */
1968        int[][] buffer; /* strip buffer, or current strip of virtual */
1969        int strip_height; /* buffer size in rows */
1970        /* for two-pass mode only: */
1971        int starting_row; /* row # of first row in current strip */
1972        int next_row; /* index of next row to fill/empty in strip */
1973                
1974        void start_pass (jpeg_decompress_struct cinfo, int pass_mode) {
1975            jpeg_d_post_controller post = cinfo.post;
1976
1977            switch (pass_mode) {
1978                case JBUF_PASS_THRU:
1979                    if (cinfo.quantize_colors) {
1980                        error(SWT.ERROR_NOT_IMPLEMENTED);
1981// /* Single-pass processing with color quantization. */
1982
// post.post_process_data = POST_PROCESS_1PASS;
1983
// /* We could be doing buffered-image output before starting a 2-pass
1984
// * color quantization; in that case, jinit_d_post_controller did not
1985
// * allocate a strip buffer. Use the virtual-array buffer as workspace.
1986
// */
1987
// if (post.buffer == null) {
1988
// post.buffer = (*cinfo.mem.access_virt_sarray)
1989
// ((j_common_ptr) cinfo, post.whole_image,
1990
// (JDIMENSION) 0, post.strip_height, TRUE);
1991
// }
1992
} else {
1993                        /* For single-pass processing without color quantization,
1994                         * I have no work to do; just call the upsampler directly.
1995                         */

1996                        post.post_process_data = POST_PROCESS_DATA_UPSAMPLE;
1997                    }
1998                    break;
1999// #ifdef QUANT_2PASS_SUPPORTED
2000
// case JBUF_SAVE_AND_PASS:
2001
// /* First pass of 2-pass quantization */
2002
// if (post.whole_image == NULL)
2003
// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2004
// post.pub.post_process_data = post_process_prepass;
2005
// break;
2006
// case JBUF_CRANK_DEST:
2007
// /* Second pass of 2-pass quantization */
2008
// if (post.whole_image == NULL)
2009
// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2010
// post.pub.post_process_data = post_process_2pass;
2011
// break;
2012
// #endif /* QUANT_2PASS_SUPPORTED */
2013
default:
2014                        error();
2015// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2016
break;
2017            }
2018            post.starting_row = post.next_row = 0;
2019        }
2020
2021    }
2022    
2023    static final class jpeg_decompress_struct {
2024// jpeg_error_mgr * err; /* Error handler module */\
2025
// struct jpeg_memory_mgr * mem; /* Memory manager module */\
2026
// struct jpeg_progress_mgr * progress; /* Progress monitor, or null if none */\
2027
// void * client_data; /* Available for use by application */\
2028
boolean is_decompressor; /* So common code can tell which is which */
2029        int global_state; /* For checking call sequence validity */
2030
2031// /* Source of compressed data */
2032
// struct jpeg_source_mgr * src;
2033
InputStream inputStream;
2034        byte[] buffer;
2035        int bytes_in_buffer;
2036        int bytes_offset;
2037        boolean start_of_file;
2038
2039        /* Basic description of image --- filled in by jpeg_read_header(). */
2040        /* Application may inspect these values to decide how to process image. */
2041
2042        int image_width; /* nominal image width (from SOF marker) */
2043        int image_height; /* nominal image height */
2044        int num_components; /* # of color components in JPEG image */
2045        int jpeg_color_space; /* colorspace of JPEG image */
2046
2047        /* Decompression processing parameters --- these fields must be set before
2048         * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
2049         * them to default values.
2050         */

2051
2052        int out_color_space; /* colorspace for output */
2053
2054        int scale_num, scale_denom; /* fraction by which to scale image */
2055
2056        double output_gamma; /* image gamma wanted in output */
2057
2058        boolean buffered_image; /* true=multiple output passes */
2059        boolean raw_data_out; /* true=downsampled data wanted */
2060
2061        int dct_method; /* IDCT algorithm selector */
2062        boolean do_fancy_upsampling; /* true=apply fancy upsampling */
2063        boolean do_block_smoothing; /* true=apply interblock smoothing */
2064
2065        boolean quantize_colors; /* true=colormapped output wanted */
2066        /* the following are ignored if not quantize_colors: */
2067        int dither_mode; /* type of color dithering to use */
2068        boolean two_pass_quantize; /* true=use two-pass color quantization */
2069        int desired_number_of_colors; /* max # colors to use in created colormap */
2070        /* these are significant only in buffered-image mode: */
2071        boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
2072        boolean enable_external_quant;/* enable future use of external colormap */
2073        boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
2074
2075        /* Description of actual output image that will be returned to application.
2076         * These fields are computed by jpeg_start_decompress().
2077         * You can also use jpeg_calc_output_dimensions() to determine these values
2078         * in advance of calling jpeg_start_decompress().
2079         */

2080
2081        int output_width; /* scaled image width */
2082        int output_height; /* scaled image height */
2083        int out_color_components; /* # of color components in out_color_space */
2084        int output_components; /* # of color components returned */
2085        /* output_components is 1 (a colormap index) when quantizing colors;
2086         * otherwise it equals out_color_components.
2087         */

2088        int rec_outbuf_height; /* min recommended height of scanline buffer */
2089        /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
2090         * high, space and time will be wasted due to unnecessary data copying.
2091         * Usually rec_outbuf_height will be 1 or 2, at most 4.
2092         */

2093
2094        /* When quantizing colors, the output colormap is described by these fields.
2095         * The application can supply a colormap by setting colormap non-null before
2096         * calling jpeg_start_decompress; otherwise a colormap is created during
2097         * jpeg_start_decompress or jpeg_start_output.
2098         * The map has out_color_components rows and actual_number_of_colors columns.
2099         */

2100        int actual_number_of_colors; /* number of entries in use */
2101        int[] colormap; /* The color map as a 2-D pixel array */
2102
2103        /* State variables: these variables indicate the progress of decompression.
2104         * The application may examine these but must not modify them.
2105         */

2106
2107        /* Row index of next scanline to be read from jpeg_read_scanlines().
2108         * Application may use this to control its processing loop, e.g.,
2109         * "while (output_scanline < output_height)".
2110         */

2111        int output_scanline; /* 0 .. output_height-1 */
2112
2113        /* Current input scan number and number of iMCU rows completed in scan.
2114         * These indicate the progress of the decompressor input side.
2115         */

2116        int input_scan_number; /* Number of SOS markers seen so far */
2117        int input_iMCU_row; /* Number of iMCU rows completed */
2118
2119        /* The "output scan number" is the notional scan being displayed by the
2120         * output side. The decompressor will not allow output scan/row number
2121         * to get ahead of input scan/row, but it can fall arbitrarily far behind.
2122         */

2123        int output_scan_number; /* Nominal scan number being displayed */
2124        int output_iMCU_row; /* Number of iMCU rows read */
2125
2126        /* Current progression status. coef_bits[c][i] indicates the precision
2127         * with which component c's DCT coefficient i (in zigzag order) is known.
2128         * It is -1 when no data has yet been received, otherwise it is the point
2129         * transform (shift) value for the most recent scan of the coefficient
2130         * (thus, 0 at completion of the progression).
2131         * This pointer is null when reading a non-progressive file.
2132         */

2133        int[][] coef_bits; /* -1 or current Al value for each coef */
2134
2135        /* Internal JPEG parameters --- the application usually need not look at
2136         * these fields. Note that the decompressor output side may not use
2137         * any parameters that can change between scans.
2138         */

2139
2140        /* Quantization and Huffman tables are carried forward across input
2141         * datastreams when processing abbreviated JPEG datastreams.
2142         */

2143
2144        JQUANT_TBL[] quant_tbl_ptrs = new JQUANT_TBL[NUM_QUANT_TBLS];
2145        /* ptrs to coefficient quantization tables, or null if not defined */
2146
2147        JHUFF_TBL[] dc_huff_tbl_ptrs = new JHUFF_TBL[NUM_HUFF_TBLS];
2148        JHUFF_TBL[] ac_huff_tbl_ptrs = new JHUFF_TBL[NUM_HUFF_TBLS];
2149        /* ptrs to Huffman coding tables, or null if not defined */
2150
2151        /* These parameters are never carried across datastreams, since they
2152         * are given in SOF/SOS markers or defined to be reset by SOI.
2153         */

2154
2155        int data_precision; /* bits of precision in image data */
2156
2157        jpeg_component_info[] comp_info;
2158        /* comp_info[i] describes component that appears i'th in SOF */
2159
2160        boolean progressive_mode; /* true if SOFn specifies progressive mode */
2161        boolean arith_code; /* true=arithmetic coding, false=Huffman */
2162
2163        byte[] arith_dc_L = new byte[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
2164        byte[] arith_dc_U = new byte[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
2165        byte[] arith_ac_K = new byte[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
2166
2167        int restart_interval; /* MCUs per restart interval, or 0 for no restart */
2168
2169        /* These fields record data obtained from optional markers recognized by
2170         * the JPEG library.
2171         */

2172        boolean saw_JFIF_marker; /* true iff a JFIF APP0 marker was found */
2173        /* Data copied from JFIF marker; only valid if saw_JFIF_marker is true: */
2174        byte JFIF_major_version; /* JFIF version number */
2175        byte JFIF_minor_version;
2176        byte density_unit; /* JFIF code for pixel size units */
2177        short X_density; /* Horizontal pixel density */
2178        short Y_density; /* Vertical pixel density */
2179        boolean saw_Adobe_marker; /* true iff an Adobe APP14 marker was found */
2180        byte Adobe_transform; /* Color transform code from Adobe marker */
2181
2182        boolean CCIR601_sampling; /* true=first samples are cosited */
2183
2184        /* Aside from the specific data retained from APPn markers known to the
2185         * library, the uninterpreted contents of any or all APPn and COM markers
2186         * can be saved in a list for examination by the application.
2187         */

2188        jpeg_marker_reader marker_list; /* Head of list of saved markers */
2189
2190        /* Remaining fields are known throughout decompressor, but generally
2191         * should not be touched by a surrounding application.
2192         */

2193
2194        /*
2195         * These fields are computed during decompression startup
2196         */

2197        int max_h_samp_factor; /* largest h_samp_factor */
2198        int max_v_samp_factor; /* largest v_samp_factor */
2199
2200        int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
2201
2202        int total_iMCU_rows; /* # of iMCU rows in image */
2203        /* The coefficient controller's input and output progress is measured in
2204         * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
2205         * in fully interleaved JPEG scans, but are used whether the scan is
2206         * interleaved or not. We define an iMCU row as v_samp_factor DCT block
2207         * rows of each component. Therefore, the IDCT output contains
2208         * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
2209         */

2210
2211        byte[] sample_range_limit; /* table for fast range-limiting */
2212        int sample_range_limit_offset;
2213
2214        /*
2215         * These fields are valid during any one scan.
2216         * They describe the components and MCUs actually appearing in the scan.
2217         * Note that the decompressor output side must not use these fields.
2218         */

2219        int comps_in_scan; /* # of JPEG components in this scan */
2220        jpeg_component_info[] cur_comp_info = new jpeg_component_info[MAX_COMPS_IN_SCAN];
2221        /* *cur_comp_info[i] describes component that appears i'th in SOS */
2222
2223        int MCUs_per_row; /* # of MCUs across the image */
2224        int MCU_rows_in_scan; /* # of MCU rows in the image */
2225
2226        int blocks_in_MCU; /* # of DCT blocks per MCU */
2227        int[] MCU_membership = new int[D_MAX_BLOCKS_IN_MCU];
2228        /* MCU_membership[i] is index in cur_comp_info of component owning */
2229        /* i'th block in an MCU */
2230
2231        int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
2232
2233        /* This field is shared between entropy decoder and marker parser.
2234         * It is either zero or the code of a JPEG marker that has been
2235         * read from the data source, but has not yet been processed.
2236         */

2237        int unread_marker;
2238        
2239        int[] workspace = new int[DCTSIZE2];
2240        int[] row_ctr = new int[1];
2241
2242        /*
2243         * Links to decompression subobjects (methods, private variables of modules)
2244         */

2245        jpeg_decomp_master master;
2246        jpeg_d_main_controller main;
2247        jpeg_d_coef_controller coef;
2248        jpeg_d_post_controller post;
2249        jpeg_input_controller inputctl;
2250        jpeg_marker_reader marker;
2251        jpeg_entropy_decoder entropy;
2252        jpeg_inverse_dct idct;
2253        jpeg_upsampler upsample;
2254        jpeg_color_deconverter cconvert;
2255        jpeg_color_quantizer cquantize;
2256    }
2257
2258static void error() {
2259    SWT.error(SWT.ERROR_INVALID_IMAGE);
2260}
2261
2262static void error(int code) {
2263    SWT.error(code);
2264}
2265
2266static void error(String JavaDoc msg) {
2267    SWT.error(SWT.ERROR_INVALID_IMAGE, null, msg);
2268}
2269
2270static void jinit_marker_reader (jpeg_decompress_struct cinfo) {
2271    jpeg_marker_reader marker = cinfo.marker = new jpeg_marker_reader();
2272// int i;
2273

2274    /* Initialize COM/APPn processing.
2275     * By default, we examine and then discard APP0 and APP14,
2276     * but simply discard COM and all other APPn.
2277     */

2278// marker.process_COM = skip_variable;
2279
marker.length_limit_COM = 0;
2280// for (i = 0; i < 16; i++) {
2281
// marker.process_APPn[i] = skip_variable;
2282
// marker.length_limit_APPn[i] = 0;
2283
// }
2284
// marker.process_APPn[0] = get_interesting_appn;
2285
// marker.process_APPn[14] = get_interesting_appn;
2286
/* Reset marker processing state */
2287    reset_marker_reader(cinfo);
2288}
2289
2290static void jinit_d_coef_controller (jpeg_decompress_struct cinfo, boolean need_full_buffer) {
2291    jpeg_d_coef_controller coef = new jpeg_d_coef_controller();
2292    cinfo.coef = coef;
2293// coef.pub.start_input_pass = start_input_pass;
2294
// coef.pub.start_output_pass = start_output_pass;
2295
coef.coef_bits_latch = null;
2296
2297    /* Create the coefficient buffer. */
2298    if (need_full_buffer) {
2299//#ifdef D_MULTISCAN_FILES_SUPPORTED
2300
/* Allocate a full-image virtual array for each component, */
2301        /* padded to a multiple of samp_factor DCT blocks in each direction. */
2302        /* Note we ask for a pre-zeroed array. */
2303        int ci, access_rows;
2304        jpeg_component_info compptr;
2305
2306        for (ci = 0; ci < cinfo.num_components; ci++) {
2307            compptr = cinfo.comp_info[ci];
2308            access_rows = compptr.v_samp_factor;
2309//#ifdef BLOCK_SMOOTHING_SUPPORTED
2310
/* If block smoothing could be used, need a bigger window */
2311            if (cinfo.progressive_mode)
2312                access_rows *= 3;
2313//#endif
2314
coef.whole_image[ci] =
2315                new short
2316                    [(int)jround_up( compptr.height_in_blocks, compptr.v_samp_factor)]
2317                    [(int)jround_up( compptr.width_in_blocks, compptr.h_samp_factor)]
2318                    [DCTSIZE2];
2319        }
2320// coef.consume_data = consume_data;
2321
coef.decompress_data = DECOMPRESS_DATA;
2322        coef.coef_arrays = coef.whole_image[0]; /* link to virtual arrays */
2323// #else
2324
// ERREXIT(cinfo, JERR_NOT_COMPILED);
2325
// #endif
2326
} else {
2327        /* We only need a single-MCU buffer. */
2328        coef.MCU_buffer = new short[D_MAX_BLOCKS_IN_MCU][DCTSIZE2];
2329// coef.consume_data = dummy_consume_data;
2330
coef.decompress_data = DECOMPRESS_ONEPASS;
2331        coef.coef_arrays = null; /* flag for no virtual arrays */
2332    }
2333}
2334
2335static void start_output_pass (jpeg_decompress_struct cinfo) {
2336//#ifdef BLOCK_SMOOTHING_SUPPORTED
2337
jpeg_d_coef_controller coef = cinfo.coef;
2338
2339    /* If multipass, check to see whether to use block smoothing on this pass */
2340    if (coef.coef_arrays != null) {
2341        if (cinfo.do_block_smoothing && smoothing_ok(cinfo))
2342            coef.decompress_data = DECOMPRESS_SMOOTH_DATA;
2343        else
2344            coef.decompress_data = DECOMPRESS_DATA;
2345    }
2346//#endif
2347
cinfo.output_iMCU_row = 0;
2348}
2349
2350static void jpeg_create_decompress(jpeg_decompress_struct cinfo) {
2351    cinfo.is_decompressor = true;
2352
2353
2354    /* Initialize marker processor so application can override methods
2355     * for COM, APPn markers before calling jpeg_read_header.
2356     */

2357    cinfo.marker_list = null;
2358    jinit_marker_reader(cinfo);
2359
2360    /* And initialize the overall input controller. */
2361    jinit_input_controller(cinfo);
2362
2363    /* OK, I'm ready */
2364    cinfo.global_state = DSTATE_START;
2365}
2366
2367static void jpeg_calc_output_dimensions (jpeg_decompress_struct cinfo)
2368/* Do computations that are needed before master selection phase */
2369{
2370//#ifdef IDCT_SCALING_SUPPORTED
2371
// int ci;
2372
// jpeg_component_info compptr;
2373
//#endif
2374

2375    /* Prevent application from calling me at wrong times */
2376    if (cinfo.global_state != DSTATE_READY)
2377        error();
2378// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
2379

2380//#ifdef IDCT_SCALING_SUPPORTED
2381
//
2382
// /* Compute actual output image dimensions and DCT scaling choices. */
2383
// if (cinfo.scale_num * 8 <= cinfo.scale_denom) {
2384
// /* Provide 1/8 scaling */
2385
// cinfo.output_width = (int)
2386
// jdiv_round_up(cinfo.image_width, 8L);
2387
// cinfo.output_height = (int)
2388
// jdiv_round_up(cinfo.image_height, 8L);
2389
// cinfo.min_DCT_scaled_size = 1;
2390
// } else if (cinfo.scale_num * 4 <= cinfo.scale_denom) {
2391
// /* Provide 1/4 scaling */
2392
// cinfo.output_width = (int)
2393
// jdiv_round_up(cinfo.image_width, 4L);
2394
// cinfo.output_height = (int)
2395
// jdiv_round_up(cinfo.image_height, 4L);
2396
// cinfo.min_DCT_scaled_size = 2;
2397
// } else if (cinfo.scale_num * 2 <= cinfo.scale_denom) {
2398
// /* Provide 1/2 scaling */
2399
// cinfo.output_width = (int)
2400
// jdiv_round_up(cinfo.image_width, 2L);
2401
// cinfo.output_height = (int)
2402
// jdiv_round_up(cinfo.image_height, 2L);
2403
// cinfo.min_DCT_scaled_size = 4;
2404
// } else {
2405
// /* Provide 1/1 scaling */
2406
// cinfo.output_width = cinfo.image_width;
2407
// cinfo.output_height = cinfo.image_height;
2408
// cinfo.min_DCT_scaled_size = DCTSIZE;
2409
// }
2410
// /* In selecting the actual DCT scaling for each component, we try to
2411
// * scale up the chroma components via IDCT scaling rather than upsampling.
2412
// * This saves time if the upsampler gets to use 1:1 scaling.
2413
// * Note this code assumes that the supported DCT scalings are powers of 2.
2414
// */
2415
// for (ci = 0; ci < cinfo.num_components; ci++) {
2416
// compptr = cinfo.comp_info[ci];
2417
// int ssize = cinfo.min_DCT_scaled_size;
2418
// while (ssize < DCTSIZE &&
2419
// (compptr.h_samp_factor * ssize * 2 <= cinfo.max_h_samp_factor * cinfo.min_DCT_scaled_size) &&
2420
// (compptr.v_samp_factor * ssize * 2 <= cinfo.max_v_samp_factor * cinfo.min_DCT_scaled_size))
2421
// {
2422
// ssize = ssize * 2;
2423
// }
2424
// compptr.DCT_scaled_size = ssize;
2425
// }
2426
//
2427
// /* Recompute downsampled dimensions of components;
2428
// * application needs to know these if using raw downsampled data.
2429
// */
2430
// for (ci = 0; ci < cinfo.num_components; ci++) {
2431
// compptr = cinfo.comp_info[ci];
2432
// /* Size in samples, after IDCT scaling */
2433
// compptr.downsampled_width = (int)
2434
// jdiv_round_up((long) cinfo.image_width * (long) (compptr.h_samp_factor * compptr.DCT_scaled_size),
2435
// (cinfo.max_h_samp_factor * DCTSIZE));
2436
// compptr.downsampled_height = (int)
2437
// jdiv_round_up((long) cinfo.image_height * (long) (compptr.v_samp_factor * compptr.DCT_scaled_size),
2438
// (cinfo.max_v_samp_factor * DCTSIZE));
2439
// }
2440
//
2441
//#else /* !IDCT_SCALING_SUPPORTED */
2442

2443    /* Hardwire it to "no scaling" */
2444    cinfo.output_width = cinfo.image_width;
2445    cinfo.output_height = cinfo.image_height;
2446    /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
2447     * and has computed unscaled downsampled_width and downsampled_height.
2448     */

2449
2450//#endif /* IDCT_SCALING_SUPPORTED */
2451

2452    /* Report number of components in selected colorspace. */
2453    /* Probably this should be in the color conversion module... */
2454    switch (cinfo.out_color_space) {
2455        case JCS_GRAYSCALE:
2456            cinfo.out_color_components = 1;
2457            break;
2458        case JCS_RGB:
2459            if (RGB_PIXELSIZE != 3) {
2460                cinfo.out_color_components = RGB_PIXELSIZE;
2461                break;
2462            }
2463            //FALLTHROUGH
2464
case JCS_YCbCr:
2465            cinfo.out_color_components = 3;
2466            break;
2467        case JCS_CMYK:
2468        case JCS_YCCK:
2469            cinfo.out_color_components = 4;
2470            break;
2471        default: /* else must be same colorspace as in file */
2472            cinfo.out_color_components = cinfo.num_components;
2473            break;
2474    }
2475    cinfo.output_components = (cinfo.quantize_colors ? 1 : cinfo.out_color_components);
2476
2477    /* See if upsampler will want to emit more than one row at a time */
2478    if (use_merged_upsample(cinfo))
2479        cinfo.rec_outbuf_height = cinfo.max_v_samp_factor;
2480    else
2481        cinfo.rec_outbuf_height = 1;
2482}
2483
2484static boolean use_merged_upsample (jpeg_decompress_struct cinfo) {
2485//#ifdef UPSAMPLE_MERGING_SUPPORTED
2486
/* Merging is the equivalent of plain box-filter upsampling */
2487    if (cinfo.do_fancy_upsampling || cinfo.CCIR601_sampling)
2488        return false;
2489    /* jdmerge.c only supports YCC=>RGB color conversion */
2490    if (cinfo.jpeg_color_space != JCS_YCbCr || cinfo.num_components != 3 ||
2491            cinfo.out_color_space != JCS_RGB ||
2492            cinfo.out_color_components != RGB_PIXELSIZE)
2493        return false;
2494    /* and it only handles 2h1v or 2h2v sampling ratios */
2495    if (cinfo.comp_info[0].h_samp_factor != 2 ||
2496            cinfo.comp_info[1].h_samp_factor != 1 ||
2497            cinfo.comp_info[2].h_samp_factor != 1 ||
2498            cinfo.comp_info[0].v_samp_factor > 2 ||
2499            cinfo.comp_info[1].v_samp_factor != 1 ||
2500            cinfo.comp_info[2].v_samp_factor != 1)
2501        return false;
2502    /* furthermore, it doesn't work if we've scaled the IDCTs differently */
2503    if (cinfo.comp_info[0].DCT_scaled_size != cinfo.min_DCT_scaled_size ||
2504            cinfo.comp_info[1].DCT_scaled_size != cinfo.min_DCT_scaled_size ||
2505            cinfo.comp_info[2].DCT_scaled_size != cinfo.min_DCT_scaled_size)
2506        return false;
2507    /* ??? also need to test for upsample-time rescaling, when & if supported */
2508    return true; /* by golly, it'll work... */
2509//#else
2510
// return false;
2511
//#endif
2512
}
2513
2514static void prepare_range_limit_table (jpeg_decompress_struct cinfo)
2515/* Allocate and fill in the sample_range_limit table */
2516{
2517    byte[] table;
2518    int i;
2519
2520    table = new byte[5 * (MAXJSAMPLE+1) + CENTERJSAMPLE];
2521    int offset = (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
2522    cinfo.sample_range_limit_offset = offset;
2523    cinfo.sample_range_limit = table;
2524    /* First segment of "simple" table: limit[x] = 0 for x < 0 */
2525    /* Main part of "simple" table: limit[x] = x */
2526    for (i = 0; i <= MAXJSAMPLE; i++)
2527        table[i + offset] = (byte)i;
2528    offset += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
2529    /* End of simple table, rest of first half of post-IDCT table */
2530    for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
2531        table[i+offset] = (byte)MAXJSAMPLE;
2532    /* Second half of post-IDCT table */
2533    System.arraycopy(cinfo.sample_range_limit, cinfo.sample_range_limit_offset, table, offset + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE), CENTERJSAMPLE);
2534}
2535
2536static void build_ycc_rgb_table (jpeg_decompress_struct cinfo) {
2537    jpeg_color_deconverter cconvert = cinfo.cconvert;
2538    int i;
2539    int x;
2540// SHIFT_TEMPS
2541

2542    cconvert.Cr_r_tab = new int[MAXJSAMPLE+1];
2543    cconvert.Cb_b_tab = new int[MAXJSAMPLE+1];
2544    cconvert.Cr_g_tab = new int[MAXJSAMPLE+1];
2545    cconvert.Cb_g_tab = new int[MAXJSAMPLE+1];
2546
2547    for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
2548        /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
2549        /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
2550        /* Cr=>R value is nearest int to 1.40200 * x */
2551        cconvert.Cr_r_tab[i] = ((int)(1.40200f * (1<<SCALEBITS) + 0.5f) * x + ONE_HALF) >> SCALEBITS;
2552        /* Cb=>B value is nearest int to 1.77200 * x */
2553        cconvert.Cb_b_tab[i] = ((int)(1.77200f * (1<<SCALEBITS) + 0.5f) * x + ONE_HALF) >> SCALEBITS;
2554        /* Cr=>G value is scaled-up -0.71414 * x */
2555        cconvert.Cr_g_tab[i] = ((int)(- (0.71414f * (1<<SCALEBITS) + 0.5f)) * x);
2556        /* Cb=>G value is scaled-up -0.34414 * x */
2557        /* We also add in ONE_HALF so that need not do it in inner loop */
2558        cconvert.Cb_g_tab[i] = ((int)(- (0.34414f* (1<<SCALEBITS) + 0.5f)) * x + ONE_HALF);
2559    }
2560}
2561
2562static void jinit_color_deconverter (jpeg_decompress_struct cinfo) {
2563    jpeg_color_deconverter cconvert = cinfo.cconvert = new jpeg_color_deconverter();
2564// cconvert.start_pass = start_pass_dcolor;
2565

2566    /* Make sure num_components agrees with jpeg_color_space */
2567    switch (cinfo.jpeg_color_space) {
2568        case JCS_GRAYSCALE:
2569            if (cinfo.num_components != 1)
2570                error();
2571// ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2572
break;
2573
2574        case JCS_RGB:
2575        case JCS_YCbCr:
2576            if (cinfo.num_components != 3)
2577                error();
2578// ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2579
break;
2580
2581        case JCS_CMYK:
2582        case JCS_YCCK:
2583            if (cinfo.num_components != 4)
2584                error();
2585// ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2586
break;
2587
2588        default: /* JCS_UNKNOWN can be anything */
2589            if (cinfo.num_components < 1)
2590                error();
2591// ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2592
break;
2593    }
2594
2595    /* Set out_color_components and conversion method based on requested space.
2596     * Also clear the component_needed flags for any unused components,
2597     * so that earlier pipeline stages can avoid useless computation.
2598     */

2599
2600    int ci;
2601    switch (cinfo.out_color_space) {
2602        case JCS_GRAYSCALE:
2603            cinfo.out_color_components = 1;
2604            if (cinfo.jpeg_color_space == JCS_GRAYSCALE || cinfo.jpeg_color_space == JCS_YCbCr) {
2605                cconvert.color_convert = GRAYSCALE_CONVERT;
2606                /* For color.grayscale conversion, only the Y (0) component is needed */
2607                for (ci = 1; ci < cinfo.num_components; ci++)
2608                    cinfo.comp_info[ci].component_needed = false;
2609            } else
2610                error();
2611// ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2612
break;
2613
2614        case JCS_RGB:
2615            cinfo.out_color_components = RGB_PIXELSIZE;
2616            if (cinfo.jpeg_color_space == JCS_YCbCr) {
2617                cconvert.color_convert = YCC_RGB_CONVERT;
2618                build_ycc_rgb_table(cinfo);
2619            } else if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
2620                cconvert.color_convert = GRAY_RGB_CONVERT;
2621            } else if (cinfo.jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
2622                cconvert.color_convert = NULL_CONVERT;
2623            } else
2624                error();
2625// ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2626
break;
2627
2628        case JCS_CMYK:
2629            cinfo.out_color_components = 4;
2630            if (cinfo.jpeg_color_space == JCS_YCCK) {
2631                cconvert.color_convert = YCCK_CMYK_CONVERT;
2632                build_ycc_rgb_table(cinfo);
2633            } else if (cinfo.jpeg_color_space == JCS_CMYK) {
2634                cconvert.color_convert = NULL_CONVERT;
2635            } else
2636                error();
2637// ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2638
break;
2639
2640        default:
2641            /* Permit null conversion to same output space */
2642            if (cinfo.out_color_space == cinfo.jpeg_color_space) {
2643                cinfo.out_color_components = cinfo.num_components;
2644                cconvert.color_convert = NULL_CONVERT;
2645            } else /* unsupported non-null conversion */
2646                error();
2647// ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2648
break;
2649    }
2650
2651    if (cinfo.quantize_colors)
2652        cinfo.output_components = 1; /* single colormapped output component */
2653    else
2654        cinfo.output_components = cinfo.out_color_components;
2655}
2656
2657static void jinit_d_post_controller (jpeg_decompress_struct cinfo, boolean need_full_buffer) {
2658    jpeg_d_post_controller post = cinfo.post = new jpeg_d_post_controller();
2659// post.pub.start_pass = start_pass_dpost;
2660
post.whole_image = null; /* flag for no virtual arrays */
2661    post.buffer = null; /* flag for no strip buffer */
2662
2663    /* Create the quantization buffer, if needed */
2664    if (cinfo.quantize_colors) {
2665        error(SWT.ERROR_NOT_IMPLEMENTED);
2666// /* The buffer strip height is max_v_samp_factor, which is typically
2667
// * an efficient number of rows for upsampling to return.
2668
// * (In the presence of output rescaling, we might want to be smarter?)
2669
// */
2670
// post.strip_height = cinfo.max_v_samp_factor;
2671
// if (need_full_buffer) {
2672
// /* Two-pass color quantization: need full-image storage. */
2673
// /* We round up the number of rows to a multiple of the strip height. */
2674
//#ifdef QUANT_2PASS_SUPPORTED
2675
// post.whole_image = (*cinfo.mem.request_virt_sarray)
2676
// ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
2677
// cinfo.output_width * cinfo.out_color_components,
2678
// (JDIMENSION) jround_up((long) cinfo.output_height,
2679
// (long) post.strip_height),
2680
// post.strip_height);
2681
//#else
2682
// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2683
//#endif /* QUANT_2PASS_SUPPORTED */
2684
// } else {
2685
// /* One-pass color quantization: just make a strip buffer. */
2686
// post.buffer = (*cinfo.mem.alloc_sarray)
2687
// ((j_common_ptr) cinfo, JPOOL_IMAGE,
2688
// cinfo.output_width * cinfo.out_color_components,
2689
// post.strip_height);
2690
// }
2691
}
2692}
2693
2694static void make_funny_pointers (jpeg_decompress_struct cinfo)
2695/* Create the funny pointer lists discussed in the comments above.
2696 * The actual workspace is already allocated (in main.buffer),
2697 * and the space for the pointer lists is allocated too.
2698 * This routine just fills in the curiously ordered lists.
2699 * This will be repeated at the beginning of each pass.
2700 */

2701{
2702    jpeg_d_main_controller main = cinfo.main;
2703    int ci, i, rgroup;
2704    int M = cinfo.min_DCT_scaled_size;
2705    jpeg_component_info compptr;
2706    byte[][] buf, xbuf0, xbuf1;
2707    
2708    for (ci = 0; ci < cinfo.num_components; ci++) {
2709        compptr = cinfo.comp_info[ci];
2710        rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) /
2711            cinfo.min_DCT_scaled_size; /* height of a row group of component */
2712        xbuf0 = main.xbuffer[0][ci];
2713        int xbuf0_offset = main.xbuffer_offset[0][ci];
2714        xbuf1 = main.xbuffer[1][ci];
2715        int xbuf1_offset = main.xbuffer_offset[1][ci];
2716        /* First copy the workspace pointers as-is */
2717        buf = main.buffer[ci];
2718        for (i = 0; i < rgroup * (M + 2); i++) {
2719            xbuf0[i + xbuf0_offset] = xbuf1[i + xbuf1_offset] = buf[i];
2720        }
2721        /* In the second list, put the last four row groups in swapped order */
2722        for (i = 0; i < rgroup * 2; i++) {
2723            xbuf1[rgroup*(M-2) + i + xbuf1_offset] = buf[rgroup*M + i];
2724            xbuf1[rgroup*M + i + xbuf1_offset] = buf[rgroup*(M-2) + i];
2725        }
2726        /* The wraparound pointers at top and bottom will be filled later
2727         * (see set_wraparound_pointers, below). Initially we want the "above"
2728         * pointers to duplicate the first actual data line. This only needs
2729         * to happen in xbuffer[0].
2730         */

2731        for (i = 0; i < rgroup; i++) {
2732            xbuf0[i - rgroup + xbuf0_offset] = xbuf0[0 + xbuf0_offset];
2733        }
2734    }
2735}
2736
2737static void alloc_funny_pointers (jpeg_decompress_struct cinfo)
2738/* Allocate space for the funny pointer lists.
2739 * This is done only once, not once per pass.
2740 */

2741{
2742    jpeg_d_main_controller main = cinfo.main;
2743    int ci, rgroup;
2744    int M = cinfo.min_DCT_scaled_size;
2745    jpeg_component_info compptr;
2746    byte[][] xbuf;
2747
2748    /* Get top-level space for component array pointers.
2749     * We alloc both arrays with one call to save a few cycles.
2750     */

2751    main.xbuffer[0] = new byte[cinfo.num_components][][];
2752    main.xbuffer[1] = new byte[cinfo.num_components][][];
2753    main.xbuffer_offset[0] = new int[cinfo.num_components];
2754    main.xbuffer_offset[1] = new int[cinfo.num_components];
2755
2756    for (ci = 0; ci < cinfo.num_components; ci++) {
2757        compptr = cinfo.comp_info[ci];
2758        rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) / cinfo.min_DCT_scaled_size; /* height of a row group of component */
2759        /* Get space for pointer lists --- M+4 row groups in each list.
2760         * We alloc both pointer lists with one call to save a few cycles.
2761         */

2762        xbuf = new byte[2 * (rgroup * (M + 4))][];
2763        int offset = rgroup;
2764        main.xbuffer_offset[0][ci] = offset;
2765        main.xbuffer[0][ci] = xbuf;
2766        offset += rgroup * (M + 4);
2767        main.xbuffer_offset[1][ci] = offset;
2768        main.xbuffer[1][ci] = xbuf;
2769    }
2770}
2771
2772
2773static void jinit_d_main_controller (jpeg_decompress_struct cinfo, boolean need_full_buffer) {
2774    int ci, rgroup, ngroups;
2775    jpeg_component_info compptr;
2776
2777    jpeg_d_main_controller main = cinfo.main = new jpeg_d_main_controller();
2778// main.pub.start_pass = start_pass_main;
2779

2780    if (need_full_buffer) /* shouldn't happen */
2781        error();
2782// ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2783

2784    /* Allocate the workspace.
2785     * ngroups is the number of row groups we need.
2786     */

2787    if (cinfo.upsample.need_context_rows) {
2788        if (cinfo.min_DCT_scaled_size < 2) /* unsupported, see comments above */
2789            error();
2790// ERREXIT(cinfo, JERR_NOTIMPL);
2791
alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
2792        ngroups = cinfo.min_DCT_scaled_size + 2;
2793    } else {
2794        ngroups = cinfo.min_DCT_scaled_size;
2795    }
2796
2797    for (ci = 0; ci < cinfo.num_components; ci++) {
2798        compptr = cinfo.comp_info[ci];
2799        rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) / cinfo.min_DCT_scaled_size; /* height of a row group of component */
2800        main.buffer[ci] = new byte[rgroup * ngroups][compptr.width_in_blocks * compptr.DCT_scaled_size];
2801    }
2802}
2803
2804static long jround_up (long a, long b)
2805/* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
2806/* Assumes a >= 0, b > 0 */
2807{
2808    a += b - 1L;
2809    return a - (a % b);
2810}
2811
2812static void jinit_upsampler (jpeg_decompress_struct cinfo) {
2813    int ci;
2814    jpeg_component_info compptr;
2815    boolean need_buffer, do_fancy;
2816    int h_in_group, v_in_group, h_out_group, v_out_group;
2817
2818    jpeg_upsampler upsample = new jpeg_upsampler();
2819    cinfo.upsample = upsample;
2820// upsample.start_pass = start_pass_upsample;
2821
// upsample.upsample = sep_upsample;
2822
upsample.need_context_rows = false; /* until we find out differently */
2823
2824    if (cinfo.CCIR601_sampling) /* this isn't supported */
2825        error();
2826// ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
2827

2828    /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
2829     * so don't ask for it.
2830     */

2831    do_fancy = cinfo.do_fancy_upsampling && cinfo.min_DCT_scaled_size > 1;
2832
2833    /* Verify we can handle the sampling factors, select per-component methods,
2834     * and create storage as needed.
2835     */

2836    for (ci = 0; ci < cinfo.num_components; ci++) {
2837        compptr = cinfo.comp_info[ci];
2838        /* Compute size of an "input group" after IDCT scaling. This many samples
2839         * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
2840         */

2841        h_in_group = (compptr.h_samp_factor * compptr.DCT_scaled_size) /
2842         cinfo.min_DCT_scaled_size;
2843        v_in_group = (compptr.v_samp_factor * compptr.DCT_scaled_size) /
2844         cinfo.min_DCT_scaled_size;
2845        h_out_group = cinfo.max_h_samp_factor;
2846        v_out_group = cinfo.max_v_samp_factor;
2847        upsample.rowgroup_height[ci] = v_in_group; /* save for use later */
2848        need_buffer = true;
2849        if (! compptr.component_needed) {
2850            /* Don't bother to upsample an uninteresting component. */
2851            upsample.methods[ci] = NOOP_UPSAMPLE;
2852            need_buffer = false;
2853        } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
2854            /* Fullsize components can be processed without any work. */
2855            upsample.methods[ci] = FULLSIZE_UPSAMPLE;
2856            need_buffer = false;
2857        } else if (h_in_group * 2 == h_out_group && v_in_group == v_out_group) {
2858            /* Special cases for 2h1v upsampling */
2859            if (do_fancy && compptr.downsampled_width > 2)
2860                upsample.methods[ci] = H2V1_FANCY_UPSAMPLE;
2861            else
2862                upsample.methods[ci] = H2V1_UPSAMPLE;
2863        } else if (h_in_group * 2 == h_out_group && v_in_group * 2 == v_out_group) {
2864            /* Special cases for 2h2v upsampling */
2865            if (do_fancy && compptr.downsampled_width > 2) {
2866                upsample.methods[ci] = H2V2_FANCY_UPSAMPLE;
2867                upsample.need_context_rows = true;
2868            } else
2869                upsample.methods[ci] = H2V2_UPSAMPLE;
2870        } else if ((h_out_group % h_in_group) == 0 && (v_out_group % v_in_group) == 0) {
2871            /* Generic integral-factors upsampling method */
2872            upsample.methods[ci] = INT_UPSAMPLE;
2873            upsample.h_expand[ci] = (byte) (h_out_group / h_in_group);
2874            upsample.v_expand[ci] = (byte) (v_out_group / v_in_group);
2875        } else
2876            error();
2877// ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
2878
if (need_buffer) {
2879            upsample.color_buf[ci] = new byte[cinfo.max_v_samp_factor]
2880                         [(int) jround_up(cinfo.output_width, cinfo.max_h_samp_factor)];
2881        }
2882    }
2883}
2884
2885static void jinit_phuff_decoder (jpeg_decompress_struct cinfo) {
2886    int[][] coef_bit_ptr;
2887    int ci, i;
2888
2889    cinfo.entropy = new phuff_entropy_decoder();
2890// entropy.pub.start_pass = start_pass_phuff_decoder;
2891

2892    /* Create progression status table */
2893    cinfo.coef_bits = new int[cinfo.num_components][DCTSIZE2];
2894    coef_bit_ptr = cinfo.coef_bits;
2895    for (ci = 0; ci < cinfo.num_components; ci++)
2896        for (i = 0; i < DCTSIZE2; i++)
2897            coef_bit_ptr[ci][i] = -1;
2898}
2899
2900
2901static void jinit_huff_decoder (jpeg_decompress_struct cinfo) {
2902
2903    cinfo.entropy = new huff_entropy_decoder();
2904// entropy.pub.start_pass = start_pass_huff_decoder;
2905
// entropy.pub.decode_mcu = decode_mcu;
2906

2907}
2908
2909static void jinit_inverse_dct (jpeg_decompress_struct cinfo) {
2910    int ci;
2911    jpeg_component_info compptr;
2912
2913    jpeg_inverse_dct idct = cinfo.idct = new jpeg_inverse_dct();
2914// idct.pub.start_pass = start_pass;
2915

2916    for (ci = 0; ci < cinfo.num_components; ci++) {
2917        compptr = cinfo.comp_info[ci];
2918        /* Allocate and pre-zero a multiplier table for each component */
2919        compptr.dct_table = new int[DCTSIZE2];
2920        /* Mark multiplier table not yet set up for any method */
2921        idct.cur_method[ci] = -1;
2922    }
2923}
2924
2925static final int CONST_BITS = 13;
2926static final int PASS1_BITS = 2;
2927static final int RANGE_MASK =(MAXJSAMPLE * 4 + 3);
2928static void jpeg_idct_islow (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
2929    short[] coef_block,
2930    byte[][] output_buf, int output_buf_offset, int output_col)
2931{
2932    int tmp0, tmp1, tmp2, tmp3;
2933    int tmp10, tmp11, tmp12, tmp13;
2934    int z1, z2, z3, z4, z5;
2935    short[] inptr;
2936    int[] quantptr;
2937    int[] wsptr;
2938    byte[] outptr;
2939    byte[] range_limit = cinfo.sample_range_limit;
2940    int range_limit_offset = cinfo.sample_range_limit_offset + CENTERJSAMPLE;
2941    int ctr;
2942    int[] workspace = cinfo.workspace; /* buffers data between passes */
2943// SHIFT_TEMPS
2944

2945    /* Pass 1: process columns from input, store into work array. */
2946    /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
2947    /* furthermore, we scale the results by 2**PASS1_BITS. */
2948    
2949    inptr = coef_block;
2950    quantptr = compptr.dct_table;
2951    wsptr = workspace;
2952    int inptr_offset = 0, quantptr_offset = 0, wsptr_offset = 0;
2953    for (ctr = DCTSIZE; ctr > 0; ctr--) {
2954        /* Due to quantization, we will usually find that many of the input
2955         * coefficients are zero, especially the AC terms. We can exploit this
2956         * by short-circuiting the IDCT calculation for any column in which all
2957         * the AC terms are zero. In that case each output is equal to the
2958         * DC coefficient (with scale factor as needed).
2959         * With typical images and quantization tables, half or more of the
2960         * column DCT calculations can be simplified this way.
2961         */

2962        
2963        if (inptr[DCTSIZE*1+inptr_offset] == 0 && inptr[DCTSIZE*2+inptr_offset] == 0 &&
2964            inptr[DCTSIZE*3+inptr_offset] == 0 && inptr[DCTSIZE*4+inptr_offset] == 0 &&
2965            inptr[DCTSIZE*5+inptr_offset] == 0 && inptr[DCTSIZE*6+inptr_offset] == 0 &&
2966            inptr[DCTSIZE*7+inptr_offset] == 0)
2967        {
2968            /* AC terms all zero */
2969            int dcval = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]) << PASS1_BITS;
2970            
2971            wsptr[DCTSIZE*0+wsptr_offset] = dcval;
2972            wsptr[DCTSIZE*1+wsptr_offset] = dcval;
2973            wsptr[DCTSIZE*2+wsptr_offset] = dcval;
2974            wsptr[DCTSIZE*3+wsptr_offset] = dcval;
2975            wsptr[DCTSIZE*4+wsptr_offset] = dcval;
2976            wsptr[DCTSIZE*5+wsptr_offset] = dcval;
2977            wsptr[DCTSIZE*6+wsptr_offset] = dcval;
2978            wsptr[DCTSIZE*7+wsptr_offset] = dcval;
2979            
2980            inptr_offset++; /* advance pointers to next column */
2981            quantptr_offset++;
2982            wsptr_offset++;
2983            continue;
2984        }
2985        
2986        /* Even part: reverse the even part of the forward DCT. */
2987        /* The rotator is sqrt(2)*c(-6). */
2988        
2989        z2 = ((inptr[DCTSIZE*2+inptr_offset]) * quantptr[DCTSIZE*2+quantptr_offset]);
2990        z3 = ((inptr[DCTSIZE*6+inptr_offset]) * quantptr[DCTSIZE*6+quantptr_offset]);
2991        
2992        z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/);
2993        tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/);
2994        tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/);
2995        
2996        z2 = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]);
2997        z3 = ((inptr[DCTSIZE*4+inptr_offset]) * quantptr[DCTSIZE*4+quantptr_offset]);
2998
2999        tmp0 = (z2 + z3) << CONST_BITS;
3000        tmp1 = (z2 - z3) << CONST_BITS;
3001        
3002        tmp10 = tmp0 + tmp3;
3003        tmp13 = tmp0 - tmp3;
3004        tmp11 = tmp1 + tmp2;
3005        tmp12 = tmp1 - tmp2;
3006        
3007        /* Odd part per figure 8; the matrix is unitary and hence its
3008         * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
3009         */

3010        
3011        tmp0 = ((inptr[DCTSIZE*7+inptr_offset]) * quantptr[DCTSIZE*7+quantptr_offset]);
3012        tmp1 = ((inptr[DCTSIZE*5+inptr_offset]) * quantptr[DCTSIZE*5+quantptr_offset]);
3013        tmp2 = ((inptr[DCTSIZE*3+inptr_offset]) * quantptr[DCTSIZE*3+quantptr_offset]);
3014        tmp3 = ((inptr[DCTSIZE*1+inptr_offset]) * quantptr[DCTSIZE*1+quantptr_offset]);
3015        
3016        z1 = tmp0 + tmp3;
3017        z2 = tmp1 + tmp2;
3018        z3 = tmp0 + tmp2;
3019        z4 = tmp1 + tmp3;
3020        z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */
3021        
3022        tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */
3023        tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */
3024        tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */
3025        tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */
3026        z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */
3027        z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */
3028        z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */
3029        z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */
3030        
3031        z3 += z5;
3032        z4 += z5;
3033        
3034        tmp0 += z1 + z3;
3035        tmp1 += z2 + z4;
3036        tmp2 += z2 + z3;
3037        tmp3 += z1 + z4;
3038        
3039        /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
3040        
3041// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
3042
wsptr[DCTSIZE*0+wsptr_offset] = (((tmp10 + tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3043        wsptr[DCTSIZE*7+wsptr_offset] = (((tmp10 - tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3044        wsptr[DCTSIZE*1+wsptr_offset] = (((tmp11 + tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3045        wsptr[DCTSIZE*6+wsptr_offset] = (((tmp11 - tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3046        wsptr[DCTSIZE*2+wsptr_offset] = (((tmp12 + tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3047        wsptr[DCTSIZE*5+wsptr_offset] = (((tmp12 - tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3048        wsptr[DCTSIZE*3+wsptr_offset] = (((tmp13 + tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3049        wsptr[DCTSIZE*4+wsptr_offset] = (((tmp13 - tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3050        
3051        inptr_offset++; /* advance pointers to next column */
3052        quantptr_offset++;
3053        wsptr_offset++;
3054    }
3055
3056    
3057    /* Pass 2: process rows from work array, store into output array. */
3058    /* Note that we must descale the results by a factor of 8 == 2**3, */
3059    /* and also undo the PASS1_BITS scaling. */
3060
3061    int outptr_offset = 0;
3062    wsptr = workspace;
3063    wsptr_offset =0;
3064    for (ctr = 0; ctr < DCTSIZE; ctr++) {
3065        outptr = output_buf[ctr+output_buf_offset];
3066        outptr_offset = output_col;
3067        /* Rows of zeroes can be exploited in the same way as we did with columns.
3068         * However, the column calculation has created many nonzero AC terms, so
3069         * the simplification applies less often (typically 5% to 10% of the time).
3070         * On machines with very fast multiplication, it's possible that the
3071         * test takes more time than it's worth. In that case this section
3072         * may be commented out.
3073         */

3074        
3075//#ifndef NO_ZERO_ROW_TEST
3076
if (wsptr[1+wsptr_offset] == 0 && wsptr[2+wsptr_offset] == 0 && wsptr[3+wsptr_offset] == 0 && wsptr[4+wsptr_offset] == 0 &&
3077            wsptr[5+wsptr_offset] == 0 && wsptr[6+wsptr_offset] == 0 && wsptr[7+wsptr_offset] == 0)
3078        {
3079            /* AC terms all zero */
3080// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
3081
byte dcval = range_limit[range_limit_offset + ((((wsptr[0+wsptr_offset]) + (1 << ((PASS1_BITS+3)-1))) >> PASS1_BITS+3)
3082                    & RANGE_MASK)];
3083            
3084            outptr[0+outptr_offset] = dcval;
3085            outptr[1+outptr_offset] = dcval;
3086            outptr[2+outptr_offset] = dcval;
3087            outptr[3+outptr_offset] = dcval;
3088            outptr[4+outptr_offset] = dcval;
3089            outptr[5+outptr_offset] = dcval;
3090            outptr[6+outptr_offset] = dcval;
3091            outptr[7+outptr_offset] = dcval;
3092
3093            wsptr_offset += DCTSIZE; /* advance pointer to next row */
3094            continue;
3095        }
3096//#endif
3097

3098        /* Even part: reverse the even part of the forward DCT. */
3099        /* The rotator is sqrt(2)*c(-6). */
3100        
3101        z2 = wsptr[2+wsptr_offset];
3102        z3 = wsptr[6+wsptr_offset];
3103        
3104        z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/);
3105        tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/);
3106        tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/);
3107        
3108        tmp0 = (wsptr[0+wsptr_offset] + wsptr[4+wsptr_offset]) << CONST_BITS;
3109        tmp1 = (wsptr[0+wsptr_offset] - wsptr[4+wsptr_offset]) << CONST_BITS;
3110        
3111        tmp10 = tmp0 + tmp3;
3112        tmp13 = tmp0 - tmp3;
3113        tmp11 = tmp1 + tmp2;
3114        tmp12 = tmp1 - tmp2;
3115        
3116        /* Odd part per figure 8; the matrix is unitary and hence its
3117         * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
3118         */

3119        
3120        tmp0 = wsptr[7+wsptr_offset];
3121        tmp1 = wsptr[5+wsptr_offset];
3122        tmp2 = wsptr[3+wsptr_offset];
3123        tmp3 = wsptr[1+wsptr_offset];
3124        
3125        z1 = tmp0 + tmp3;
3126        z2 = tmp1 + tmp2;
3127        z3 = tmp0 + tmp2;
3128        z4 = tmp1 + tmp3;
3129        z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */
3130        
3131        tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */
3132        tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */
3133        tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */
3134        tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */
3135        z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */
3136        z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */
3137        z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */
3138        z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */
3139        
3140        z3 += z5;
3141        z4 += z5;
3142        
3143        tmp0 += z1 + z3;
3144        tmp1 += z2 + z4;
3145        tmp2 += z2 + z3;
3146        tmp3 += z1 + z4;
3147        
3148        /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
3149        
3150
3151// #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
3152
outptr[0+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 + tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3153                        CONST_BITS+PASS1_BITS+3)
3154                    & RANGE_MASK)];
3155        outptr[7+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 - tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3156                                    CONST_BITS+PASS1_BITS+3)
3157                    & RANGE_MASK)];
3158        outptr[1+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 + tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3159                                    CONST_BITS+PASS1_BITS+3)
3160                    & RANGE_MASK)];
3161        outptr[6+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 - tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3162                                    CONST_BITS+PASS1_BITS+3)
3163                    & RANGE_MASK)];
3164        outptr[2+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 + tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3165                                    CONST_BITS+PASS1_BITS+3)
3166                    & RANGE_MASK)];
3167        outptr[5+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 - tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3168                                    CONST_BITS+PASS1_BITS+3)
3169                    & RANGE_MASK)];
3170        outptr[3+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 + tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3171                                    CONST_BITS+PASS1_BITS+3)
3172                    & RANGE_MASK)];
3173        outptr[4+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 - tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3174                                    CONST_BITS+PASS1_BITS+3)
3175                    & RANGE_MASK)];
3176
3177        wsptr_offset += DCTSIZE; /* advance pointer to next row */
3178    }
3179}
3180
3181static void upsample (jpeg_decompress_struct cinfo,
3182    byte[][][] input_buf, int[] input_buf_offset, int[] in_row_group_ctr,
3183    int in_row_groups_avail,
3184    byte[][] output_buf, int[] out_row_ctr,
3185    int out_rows_avail)
3186{
3187    sep_upsample(cinfo, input_buf, input_buf_offset, in_row_group_ctr, in_row_groups_avail, output_buf, out_row_ctr, out_rows_avail);
3188}
3189
3190static boolean smoothing_ok (jpeg_decompress_struct cinfo) {
3191    jpeg_d_coef_controller coef = cinfo.coef;
3192    boolean smoothing_useful = false;
3193    int ci, coefi;
3194    jpeg_component_info compptr;
3195    JQUANT_TBL qtable;
3196    int[] coef_bits;
3197    int[] coef_bits_latch;
3198
3199    if (! cinfo.progressive_mode || cinfo.coef_bits == null)
3200        return false;
3201
3202    /* Allocate latch area if not already done */
3203    if (coef.coef_bits_latch == null)
3204        coef.coef_bits_latch = new int[cinfo.num_components * SAVED_COEFS];
3205    coef_bits_latch = coef.coef_bits_latch;
3206    int coef_bits_latch_offset = 0;
3207
3208    for (ci = 0; ci < cinfo.num_components; ci++) {
3209        compptr = cinfo.comp_info[ci];
3210        /* All components' quantization values must already be latched. */
3211        if ((qtable = compptr.quant_table) == null)
3212            return false;
3213        /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
3214        if (qtable.quantval[0] == 0 ||
3215            qtable.quantval[Q01_POS] == 0 ||
3216            qtable.quantval[Q10_POS] == 0 ||
3217            qtable.quantval[Q20_POS] == 0 ||
3218            qtable.quantval[Q11_POS] == 0 ||
3219            qtable.quantval[Q02_POS] == 0)
3220                return false;
3221        /* DC values must be at least partly known for all components. */
3222        coef_bits = cinfo.coef_bits[ci];
3223        if (coef_bits[0] < 0)
3224            return false;
3225        /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
3226        for (coefi = 1; coefi <= 5; coefi++) {
3227            coef_bits_latch[coefi+coef_bits_latch_offset] = coef_bits[coefi];
3228            if (coef_bits[coefi] != 0)
3229                smoothing_useful = true;
3230        }
3231        coef_bits_latch_offset += SAVED_COEFS;
3232    }
3233
3234    return smoothing_useful;
3235}
3236
3237static void master_selection (jpeg_decompress_struct cinfo) {
3238    jpeg_decomp_master master = cinfo.master;
3239    boolean use_c_buffer;
3240    long samplesperrow;
3241    int jd_samplesperrow;
3242
3243    /* Initialize dimensions and other stuff */
3244    jpeg_calc_output_dimensions(cinfo);
3245    prepare_range_limit_table(cinfo);
3246
3247    /* Width of an output scanline must be representable as JDIMENSION. */
3248    samplesperrow = (long) cinfo.output_width * (long) cinfo.out_color_components;
3249    jd_samplesperrow = (int) samplesperrow;
3250    if ( jd_samplesperrow != samplesperrow)
3251        error();
3252// ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
3253

3254    /* Initialize my private state */
3255    master.pass_number = 0;
3256    master.using_merged_upsample = use_merged_upsample(cinfo);
3257
3258    /* Color quantizer selection */
3259    master.quantizer_1pass = null;
3260    master.quantizer_2pass = null;
3261    /* No mode changes if not using buffered-image mode. */
3262    if (! cinfo.quantize_colors || ! cinfo.buffered_image) {
3263        cinfo.enable_1pass_quant = false;
3264        cinfo.enable_external_quant = false;
3265        cinfo.enable_2pass_quant = false;
3266    }
3267    if (cinfo.quantize_colors) {
3268        error(SWT.ERROR_NOT_IMPLEMENTED);
3269// if (cinfo.raw_data_out)
3270
// ERREXIT(cinfo, JERR_NOTIMPL);
3271
// /* 2-pass quantizer only works in 3-component color space. */
3272
// if (cinfo.out_color_components != 3) {
3273
// cinfo.enable_1pass_quant = true;
3274
// cinfo.enable_external_quant = false;
3275
// cinfo.enable_2pass_quant = false;
3276
// cinfo.colormap = null;
3277
// } else if (cinfo.colormap != null) {
3278
// cinfo.enable_external_quant = true;
3279
// } else if (cinfo.two_pass_quantize) {
3280
// cinfo.enable_2pass_quant = true;
3281
// } else {
3282
// cinfo.enable_1pass_quant = true;
3283
// }
3284
//
3285
// if (cinfo.enable_1pass_quant) {
3286
//#ifdef QUANT_1PASS_SUPPORTED
3287
// jinit_1pass_quantizer(cinfo);
3288
// master.quantizer_1pass = cinfo.cquantize;
3289
//#else
3290
// ERREXIT(cinfo, JERR_NOT_COMPILED);
3291
//#endif
3292
// }
3293
//
3294
// /* We use the 2-pass code to map to external colormaps. */
3295
// if (cinfo.enable_2pass_quant || cinfo.enable_external_quant) {
3296
//#ifdef QUANT_2PASS_SUPPORTED
3297
// jinit_2pass_quantizer(cinfo);
3298
// master.quantizer_2pass = cinfo.cquantize;
3299
//#else
3300
// ERREXIT(cinfo, JERR_NOT_COMPILED);
3301
//#endif
3302
// }
3303
// /* If both quantizers are initialized, the 2-pass one is left active;
3304
// * this is necessary for starting with quantization to an external map.
3305
// */
3306
}
3307
3308    /* Post-processing: in particular, color conversion first */
3309    if (! cinfo.raw_data_out) {
3310        if (master.using_merged_upsample) {
3311//#ifdef UPSAMPLE_MERGING_SUPPORTED
3312
// jinit_merged_upsampler(cinfo); /* does color conversion too */
3313
//#else
3314
error();
3315// ERREXIT(cinfo, JERR_NOT_COMPILED);
3316
//#endif
3317
} else {
3318            jinit_color_deconverter(cinfo);
3319            jinit_upsampler(cinfo);
3320        }
3321        jinit_d_post_controller(cinfo, cinfo.enable_2pass_quant);
3322    }
3323    /* Inverse DCT */
3324    jinit_inverse_dct(cinfo);
3325    /* Entropy decoding: either Huffman or arithmetic coding. */
3326    if (cinfo.arith_code) {
3327        error();
3328// ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
3329
} else {
3330        if (cinfo.progressive_mode) {
3331//#ifdef D_PROGRESSIVE_SUPPORTED
3332
jinit_phuff_decoder(cinfo);
3333//#else
3334
// ERREXIT(cinfo, JERR_NOT_COMPILED);
3335
//#endif
3336
} else
3337            jinit_huff_decoder(cinfo);
3338    }
3339
3340    /* Initialize principal buffer controllers. */
3341    use_c_buffer = cinfo.inputctl.has_multiple_scans || cinfo.buffered_image;
3342    jinit_d_coef_controller(cinfo, use_c_buffer);
3343
3344    if (! cinfo.raw_data_out)
3345        jinit_d_main_controller(cinfo, false /* never need full buffer here */);
3346
3347    /* Initialize input side of decompressor to consume first scan. */
3348    start_input_pass (cinfo);
3349
3350//#ifdef D_MULTISCAN_FILES_SUPPORTED
3351
/* If jpeg_start_decompress will read the whole file, initialize
3352     * progress monitoring appropriately. The input step is counted
3353     * as one pass.
3354     */

3355// if (cinfo.progress != null && ! cinfo.buffered_image &&
3356
// cinfo.inputctl.has_multiple_scans) {
3357
// int nscans;
3358
// /* Estimate number of scans to set pass_limit. */
3359
// if (cinfo.progressive_mode) {
3360
// /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
3361
// nscans = 2 + 3 * cinfo.num_components;
3362
// } else {
3363
// /* For a nonprogressive multiscan file, estimate 1 scan per component. */
3364
// nscans = cinfo.num_components;
3365
// }
3366
// cinfo.progress.pass_counter = 0L;
3367
// cinfo.progress.pass_limit = (long) cinfo.total_iMCU_rows * nscans;
3368
// cinfo.progress.completed_passes = 0;
3369
// cinfo.progress.total_passes = (cinfo.enable_2pass_quant ? 3 : 2);
3370
// /* Count the input pass as done */
3371
// master.pass_number++;
3372
// }
3373
//#endif /* D_MULTISCAN_FILES_SUPPORTED */
3374
}
3375
3376static void jinit_master_decompress (jpeg_decompress_struct cinfo) {
3377    jpeg_decomp_master master = new jpeg_decomp_master();
3378    cinfo.master = master;
3379// master.prepare_for_output_pass = prepare_for_output_pass;
3380
// master.finish_output_pass = finish_output_pass;
3381

3382    master.is_dummy_pass = false;
3383
3384    master_selection(cinfo);
3385}
3386
3387static void
3388jcopy_sample_rows (byte[][] input_array, int source_row,
3389           byte[][] output_array, int dest_row,
3390           int num_rows, int num_cols)
3391/* Copy some rows of samples from one place to another.
3392 * num_rows rows are copied from input_array[source_row++]
3393 * to output_array[dest_row++]; these areas may overlap for duplication.
3394 * The source and destination arrays must be at least as wide as num_cols.
3395 */

3396{
3397  byte[] inptr, outptr;
3398  int count = num_cols;
3399  int row;
3400
3401  int input_array_offset = source_row;
3402  int output_array_offset = dest_row;
3403
3404  for (row = num_rows; row > 0; row--) {
3405    inptr = input_array[input_array_offset++];
3406    outptr = output_array[output_array_offset++];
3407    System.arraycopy(inptr, 0, outptr, 0, count);
3408  }
3409}
3410
3411static boolean jpeg_start_decompress (jpeg_decompress_struct cinfo) {
3412    if (cinfo.global_state == DSTATE_READY) {
3413        /* First call: initialize master control, select active modules */
3414        jinit_master_decompress(cinfo);
3415        if (cinfo.buffered_image) {
3416            /* No more work here; expecting jpeg_start_output next */
3417            cinfo.global_state = DSTATE_BUFIMAGE;
3418            return true;
3419        }
3420        cinfo.global_state = DSTATE_PRELOAD;
3421    }
3422    if (cinfo.global_state == DSTATE_PRELOAD) {
3423        /* If file has multiple scans, absorb them all into the coef buffer */
3424        if (cinfo.inputctl.has_multiple_scans) {
3425//#ifdef D_MULTISCAN_FILES_SUPPORTED
3426
for (;;) {
3427                int retcode;
3428                /* Call progress monitor hook if present */
3429// if (cinfo.progress != null)
3430
// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo);
3431
/* Absorb some more input */
3432                retcode = consume_input (cinfo);
3433                if (retcode == JPEG_SUSPENDED)
3434                    return false;
3435                if (retcode == JPEG_REACHED_EOI)
3436                    break;
3437                /* Advance progress counter if appropriate */
3438// if (cinfo.progress != null && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
3439
// if (++cinfo.progress.pass_counter >= cinfo.progress.pass_limit) {
3440
// /* jdmaster underestimated number of scans; ratchet up one scan */
3441
// cinfo.progress.pass_limit += (long) cinfo.total_iMCU_rows;
3442
// }
3443
// }
3444
}
3445//#else
3446
// ERREXIT(cinfo, JERR_NOT_COMPILED);
3447
//#endif /* D_MULTISCAN_FILES_SUPPORTED */
3448
}
3449        cinfo.output_scan_number = cinfo.input_scan_number;
3450    } else if (cinfo.global_state != DSTATE_PRESCAN)
3451        error();
3452// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
3453
/* Perform any dummy output passes, and set up for the final pass */
3454    return output_pass_setup(cinfo);
3455}
3456
3457static void prepare_for_output_pass (jpeg_decompress_struct cinfo) {
3458    jpeg_decomp_master master = cinfo.master;
3459
3460    if (master.is_dummy_pass) {
3461//#ifdef QUANT_2PASS_SUPPORTED
3462
// /* Final pass of 2-pass quantization */
3463
// master.pub.is_dummy_pass = FALSE;
3464
// (*cinfo.cquantize.start_pass) (cinfo, FALSE);
3465
// (*cinfo.post.start_pass) (cinfo, JBUF_CRANK_DEST);
3466
// (*cinfo.main.start_pass) (cinfo, JBUF_CRANK_DEST);
3467
//#else
3468
error(SWT.ERROR_NOT_IMPLEMENTED);
3469// ERREXIT(cinfo, JERR_NOT_COMPILED);
3470
//#endif /* QUANT_2PASS_SUPPORTED */
3471
} else {
3472        if (cinfo.quantize_colors && cinfo.colormap == null) {
3473            /* Select new quantization method */
3474            if (cinfo.two_pass_quantize && cinfo.enable_2pass_quant) {
3475                cinfo.cquantize = master.quantizer_2pass;
3476                master.is_dummy_pass = true;
3477            } else if (cinfo.enable_1pass_quant) {
3478                cinfo.cquantize = master.quantizer_1pass;
3479            } else {
3480                error();
3481// ERREXIT(cinfo, JERR_MODE_CHANGE);
3482
}
3483        }
3484        cinfo.idct.start_pass (cinfo);
3485        start_output_pass (cinfo);
3486        if (! cinfo.raw_data_out) {
3487            if (! master.using_merged_upsample)
3488                cinfo.cconvert.start_pass (cinfo);
3489            cinfo.upsample.start_pass (cinfo);
3490            if (cinfo.quantize_colors)
3491                cinfo.cquantize.start_pass (cinfo, master.is_dummy_pass);
3492            cinfo.post.start_pass (cinfo, (master.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
3493            cinfo.main.start_pass (cinfo, JBUF_PASS_THRU);
3494        }
3495    }
3496
3497// /* Set up progress monitor's pass info if present */
3498
// if (cinfo.progress != NULL) {
3499
// cinfo.progress.completed_passes = master.pass_number;
3500
// cinfo.progress.total_passes = master.pass_number +
3501
// (master.pub.is_dummy_pass ? 2 : 1);
3502
// /* In buffered-image mode, we assume one more output pass if EOI not
3503
// * yet reached, but no more passes if EOI has been reached.
3504
// */
3505
// if (cinfo.buffered_image && ! cinfo.inputctl.eoi_reached) {
3506
// cinfo.progress.total_passes += (cinfo.enable_2pass_quant ? 2 : 1);
3507
// }
3508
// }
3509
}
3510
3511
3512static boolean jpeg_resync_to_restart (jpeg_decompress_struct cinfo, int desired) {
3513    int marker = cinfo.unread_marker;
3514    int action = 1;
3515    
3516    /* Always put up a warning. */
3517// WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
3518

3519    /* Outer loop handles repeated decision after scanning forward. */
3520    for (;;) {
3521        if (marker < M_SOF0)
3522            action = 2; /* invalid marker */
3523        else if (marker < M_RST0 || marker > M_RST7)
3524            action = 3; /* valid non-restart marker */
3525        else {
3526            if (marker == (M_RST0 + ((desired+1) & 7)) || marker == ( M_RST0 + ((desired+2) & 7)))
3527                action = 3; /* one of the next two expected restarts */
3528            else if (marker == (M_RST0 + ((desired-1) & 7)) || marker == ( M_RST0 + ((desired-2) & 7)))
3529                action = 2; /* a prior restart, so advance */
3530            else
3531                action = 1; /* desired restart or too far away */
3532        }
3533// TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
3534
switch (action) {
3535            case 1:
3536                /* Discard marker and let entropy decoder resume processing. */
3537                cinfo.unread_marker = 0;
3538                return true;
3539            case 2:
3540                /* Scan to the next marker, and repeat the decision loop. */
3541                if (! next_marker(cinfo))
3542                    return false;
3543                marker = cinfo.unread_marker;
3544                break;
3545            case 3:
3546                /* Return without advancing past this marker. */
3547                /* Entropy decoder will be forced to process an empty segment. */
3548                return true;
3549        }
3550    } /* end loop */
3551}
3552
3553static boolean read_restart_marker (jpeg_decompress_struct cinfo) {
3554    /* Obtain a marker unless we already did. */
3555    /* Note that next_marker will complain if it skips any data. */
3556    if (cinfo.unread_marker == 0) {
3557        if (! next_marker(cinfo))
3558            return false;
3559    }
3560
3561    if (cinfo.unread_marker == (M_RST0 + cinfo.marker.next_restart_num)) {
3562        /* Normal case --- swallow the marker and let entropy decoder continue */
3563// TRACEMS1(cinfo, 3, JTRC_RST, cinfo.marker.next_restart_num);
3564
cinfo.unread_marker = 0;
3565    } else {
3566        /* Uh-oh, the restart markers have been messed up. */
3567        /* Let the data source manager determine how to resync. */
3568        if (! jpeg_resync_to_restart (cinfo, cinfo.marker.next_restart_num))
3569            return false;
3570    }
3571
3572    /* Update next-restart state */
3573    cinfo.marker.next_restart_num = (cinfo.marker.next_restart_num + 1) & 7;
3574
3575    return true;
3576}
3577
3578static boolean jpeg_fill_bit_buffer (bitread_working_state state, int get_buffer, int bits_left, int nbits)
3579/* Load up the bit buffer to a depth of at least nbits */
3580{
3581    /* Copy heavily used state fields into locals (hopefully registers) */
3582    byte[] buffer = state.buffer;
3583    int bytes_in_buffer = state.bytes_in_buffer;
3584    int bytes_offset = state.bytes_offset;
3585    jpeg_decompress_struct cinfo = state.cinfo;
3586
3587    /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
3588    /* (It is assumed that no request will be for more than that many bits.) */
3589    /* We fail to do so only if we hit a marker or are forced to suspend. */
3590
3591    if (cinfo.unread_marker == 0) { /* cannot advance past a marker */
3592        while (bits_left < MIN_GET_BITS) {
3593            int c;
3594
3595            /* Attempt to read a byte */
3596            if (bytes_offset == bytes_in_buffer) {
3597                if (! fill_input_buffer (cinfo))
3598                    return false;
3599                buffer = cinfo.buffer;
3600                bytes_in_buffer = cinfo.bytes_in_buffer;
3601                bytes_offset = cinfo.bytes_offset;
3602            }
3603            c = buffer[bytes_offset++] & 0xFF;
3604
3605            /* If it's 0xFF, check and discard stuffed zero byte */
3606            if (c == 0xFF) {
3607                /* Loop here to discard any padding FF's on terminating marker,
3608                 * so that we can save a valid unread_marker value. NOTE: we will
3609                 * accept multiple FF's followed by a 0 as meaning a single FF data
3610                 * byte. This data pattern is not valid according to the standard.
3611                 */

3612                do {
3613                    if (bytes_offset == bytes_in_buffer) {
3614                        if (! fill_input_buffer (cinfo))
3615                            return false;
3616                        buffer = cinfo.buffer;
3617                        bytes_in_buffer = cinfo.bytes_in_buffer;
3618                        bytes_offset = cinfo.bytes_offset;
3619                    }
3620                    c = buffer[bytes_offset++] & 0xFF;
3621                } while (c == 0xFF);
3622
3623                if (c == 0) {
3624                    /* Found FF/00, which represents an FF data byte */
3625                    c = 0xFF;
3626                } else {
3627                    /* Oops, it's actually a marker indicating end of compressed data.
3628                     * Save the marker code for later use.
3629                     * Fine point: it might appear that we should save the marker into
3630                     * bitread working state, not straight into permanent state. But
3631                     * once we have hit a marker, we cannot need to suspend within the
3632                     * current MCU, because we will read no more bytes from the data
3633                     * source. So it is OK to update permanent state right away.
3634                     */

3635                    cinfo.unread_marker = c;
3636                    /* See if we need to insert some fake zero bits. */
3637// goto no_more_bytes;
3638
if (nbits > bits_left) {
3639                        /* Uh-oh. Report corrupted data to user and stuff zeroes into
3640                         * the data stream, so that we can produce some kind of image.
3641                         * We use a nonvolatile flag to ensure that only one warning message
3642                         * appears per data segment.
3643                         */

3644                        if (! cinfo.entropy.insufficient_data) {
3645// WARNMS(cinfo, JWRN_HIT_MARKER);
3646
cinfo.entropy.insufficient_data = true;
3647                        }
3648                    /* Fill the buffer with zero bits */
3649                        get_buffer <<= MIN_GET_BITS - bits_left;
3650                        bits_left = MIN_GET_BITS;
3651                    }
3652
3653                    /* Unload the local registers */
3654                    state.buffer = buffer;
3655                    state.bytes_in_buffer = bytes_in_buffer;
3656                    state.bytes_offset = bytes_offset;
3657                    state.get_buffer = get_buffer;
3658                    state.bits_left = bits_left;
3659
3660                    return true;
3661        
3662                }
3663            }
3664
3665            /* OK, load c into get_buffer */
3666            get_buffer = (get_buffer << 8) | c;
3667            bits_left += 8;
3668        } /* end while */
3669    } else {
3670// no_more_bytes:
3671
/* We get here if we've read the marker that terminates the compressed
3672         * data segment. There should be enough bits in the buffer register
3673         * to satisfy the request; if so, no problem.
3674         */

3675        if (nbits > bits_left) {
3676            /* Uh-oh. Report corrupted data to user and stuff zeroes into
3677             * the data stream, so that we can produce some kind of image.
3678             * We use a nonvolatile flag to ensure that only one warning message
3679             * appears per data segment.
3680             */

3681            if (! cinfo.entropy.insufficient_data) {
3682// WARNMS(cinfo, JWRN_HIT_MARKER);
3683
cinfo.entropy.insufficient_data = true;
3684            }
3685            /* Fill the buffer with zero bits */
3686            get_buffer <<= MIN_GET_BITS - bits_left;
3687            bits_left = MIN_GET_BITS;
3688        }
3689    }
3690
3691    /* Unload the local registers */
3692    state.buffer = buffer;
3693    state.bytes_in_buffer = bytes_in_buffer;
3694    state.bytes_offset = bytes_offset;
3695    state.get_buffer = get_buffer;
3696    state.bits_left = bits_left;
3697
3698    return true;
3699}
3700
3701static int jpeg_huff_decode (bitread_working_state state, int get_buffer, int bits_left, d_derived_tbl htbl, int min_bits) {
3702    int l = min_bits;
3703    int code;
3704
3705    /* HUFF_DECODE has determined that the code is at least min_bits */
3706    /* bits long, so fetch that many bits in one swoop. */
3707
3708// CHECK_BIT_BUFFER(*state, l, return -1);
3709
{
3710    if (bits_left < (l)) {
3711        if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,l)) {
3712            return -1;
3713        }
3714        get_buffer = (state).get_buffer; bits_left = (state).bits_left;
3715    }
3716    }
3717// code = GET_BITS(l);
3718
code = (( (get_buffer >> (bits_left -= (l)))) & ((1<<(l))-1));
3719
3720    /* Collect the rest of the Huffman code one bit at a time. */
3721    /* This is per Figure F.16 in the JPEG spec. */
3722
3723    while (code > htbl.maxcode[l]) {
3724        code <<= 1;
3725// CHECK_BIT_BUFFER(*state, 1, return -1);
3726
{
3727        if (bits_left < (1)) {
3728            if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,1)) {
3729                return -1;
3730            }
3731            get_buffer = (state).get_buffer; bits_left = (state).bits_left;
3732        }
3733        }
3734// code |= GET_BITS(1);
3735
code |= (( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1));
3736        l++;
3737    }
3738
3739    /* Unload the local registers */
3740    state.get_buffer = get_buffer;
3741    state.bits_left = bits_left;
3742
3743    /* With garbage input we may reach the sentinel value l = 17. */
3744
3745    if (l > 16) {
3746// WARNMS(state.cinfo, JWRN_HUFF_BAD_CODE);
3747
return 0; /* fake a zero as the safest result */
3748    }
3749
3750    return htbl.pub.huffval[ (code + htbl.valoffset[l]) ] & 0xFF;
3751}
3752
3753static int decompress_onepass (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) {
3754    jpeg_d_coef_controller coef = cinfo.coef;
3755    int MCU_col_num; /* index of current MCU within row */
3756    int last_MCU_col = cinfo.MCUs_per_row - 1;
3757    int last_iMCU_row = cinfo.total_iMCU_rows - 1;
3758    int blkn, ci, xindex, yindex, yoffset, useful_width;
3759    byte[][] output_ptr;
3760    int start_col, output_col;
3761    jpeg_component_info compptr;
3762// inverse_DCT_method_ptr inverse_DCT;
3763

3764    /* Loop to process as much as one whole iMCU row */
3765    for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) {
3766        for (MCU_col_num = coef.MCU_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) {
3767            /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
3768            for (int i = 0; i < cinfo.blocks_in_MCU; i++) {
3769                short[] blk = coef.MCU_buffer[i];
3770                for (int j = 0; j < blk.length; j++) {
3771                    blk[j] = 0;
3772                }
3773            }
3774            if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) {
3775                /* Suspension forced; update state counters and exit */
3776                coef.MCU_vert_offset = yoffset;
3777                coef.MCU_ctr = MCU_col_num;
3778                return JPEG_SUSPENDED;
3779            }
3780            /* Determine where data should go in output_buf and do the IDCT thing.
3781             * We skip dummy blocks at the right and bottom edges (but blkn gets
3782             * incremented past them!). Note the inner loop relies on having
3783             * allocated the MCU_buffer[] blocks sequentially.
3784             */

3785            blkn = 0; /* index of current DCT block within MCU */
3786            for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
3787                compptr = cinfo.cur_comp_info[ci];
3788                /* Don't bother to IDCT an uninteresting component. */
3789                if (! compptr.component_needed) {
3790                    blkn += compptr.MCU_blocks;
3791                    continue;
3792                }
3793// inverse_DCT = cinfo.idct.inverse_DCT[compptr.component_index];
3794
useful_width = (MCU_col_num < last_MCU_col) ? compptr.MCU_width : compptr.last_col_width;
3795                output_ptr = output_buf[compptr.component_index];
3796                int output_ptr_offset = output_buf_offset[compptr.component_index] + yoffset * compptr.DCT_scaled_size;
3797                start_col = MCU_col_num * compptr.MCU_sample_width;
3798                for (yindex = 0; yindex < compptr.MCU_height; yindex++) {
3799                    if (cinfo.input_iMCU_row < last_iMCU_row || yoffset+yindex < compptr.last_row_height) {
3800                        output_col = start_col;
3801                        for (xindex = 0; xindex < useful_width; xindex++) {
3802                            jpeg_idct_islow(cinfo, compptr, coef.MCU_buffer[blkn+xindex], output_ptr, output_ptr_offset, output_col);
3803                            output_col += compptr.DCT_scaled_size;
3804                        }
3805                    }
3806                    blkn += compptr.MCU_width;
3807                    output_ptr_offset += compptr.DCT_scaled_size;
3808                }
3809            }
3810        }
3811        /* Completed an MCU row, but perhaps not an iMCU row */
3812        coef.MCU_ctr = 0;
3813    }
3814    /* Completed the iMCU row, advance counters for next one */
3815    cinfo.output_iMCU_row++;
3816    if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) {
3817        coef.start_iMCU_row(cinfo);
3818        return JPEG_ROW_COMPLETED;
3819    }
3820    /* Completed the scan */
3821    finish_input_pass (cinfo);
3822    return JPEG_SCAN_COMPLETED;
3823}
3824
3825static int decompress_smooth_data (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) {
3826    jpeg_d_coef_controller coef = cinfo.coef;
3827    int last_iMCU_row = cinfo.total_iMCU_rows - 1;
3828    int block_num, last_block_column;
3829    int ci, block_row, block_rows, access_rows;
3830    short[][][] buffer;
3831    short[][] buffer_ptr, prev_block_row, next_block_row;
3832    byte[][] output_ptr;
3833    int output_col;
3834    jpeg_component_info compptr;
3835// inverse_DCT_method_ptr inverse_DCT;
3836
boolean first_row, last_row;
3837    short[] workspace = coef.workspace;
3838    if (workspace == null) workspace = coef.workspace = new short[DCTSIZE2];
3839    int[] coef_bits;
3840    JQUANT_TBL quanttbl;
3841    int Q00,Q01,Q02,Q10,Q11,Q20, num;
3842    int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
3843    int Al, pred;
3844
3845    /* Force some input to be done if we are getting ahead of the input. */
3846    while (cinfo.input_scan_number <= cinfo.output_scan_number && ! cinfo.inputctl.eoi_reached) {
3847        if (cinfo.input_scan_number == cinfo.output_scan_number) {
3848            /* If input is working on current scan, we ordinarily want it to
3849             * have completed the current row. But if input scan is DC,
3850             * we want it to keep one row ahead so that next block row's DC
3851             * values are up to date.
3852             */

3853            int delta = (cinfo.Ss == 0) ? 1 : 0;
3854            if (cinfo.input_iMCU_row > cinfo.output_iMCU_row+delta)
3855                break;
3856        }
3857        if (consume_input(cinfo) == JPEG_SUSPENDED)
3858            return JPEG_SUSPENDED;
3859    }
3860
3861    /* OK, output from the virtual arrays. */
3862    for (ci = 0; ci < cinfo.num_components; ci++) {
3863        compptr = cinfo.comp_info[ci];
3864        /* Don't bother to IDCT an uninteresting component. */
3865        if (! compptr.component_needed)
3866            continue;
3867        /* Count non-dummy DCT block rows in this iMCU row. */
3868        if (cinfo.output_iMCU_row < last_iMCU_row) {
3869            block_rows = compptr.v_samp_factor;
3870            access_rows = block_rows * 2; /* this and next iMCU row */
3871            last_row = false;
3872        } else {
3873            /* NB: can't use last_row_height here; it is input-side-dependent! */
3874            block_rows = (compptr.height_in_blocks % compptr.v_samp_factor);
3875            if (block_rows == 0) block_rows = compptr.v_samp_factor;
3876            access_rows = block_rows; /* this iMCU row only */
3877            last_row = true;
3878        }
3879        /* Align the virtual buffer for this component. */
3880        int buffer_offset;
3881        if (cinfo.output_iMCU_row > 0) {
3882            access_rows += compptr.v_samp_factor; /* prior iMCU row too */
3883            buffer = coef.whole_image[ci];
3884            buffer_offset = (cinfo.output_iMCU_row - 1) * compptr.v_samp_factor;
3885            buffer_offset += compptr.v_samp_factor; /* point to current iMCU row */
3886            first_row = false;
3887        } else {
3888            buffer = coef.whole_image[ci];
3889            buffer_offset = 0;
3890            first_row = true;
3891        }
3892        /* Fetch component-dependent info */
3893        coef_bits = coef.coef_bits_latch;
3894        int coef_offset = (ci * SAVED_COEFS);
3895        quanttbl = compptr.quant_table;
3896        Q00 = quanttbl.quantval[0];
3897        Q01 = quanttbl.quantval[Q01_POS];
3898        Q10 = quanttbl.quantval[Q10_POS];
3899        Q20 = quanttbl.quantval[Q20_POS];
3900        Q11 = quanttbl.quantval[Q11_POS];
3901        Q02 = quanttbl.quantval[Q02_POS];
3902// inverse_DCT = cinfo.idct.inverse_DCT[ci];
3903
output_ptr = output_buf[ci];
3904        int output_ptr_offset = output_buf_offset[ci];
3905        /* Loop over all DCT blocks to be processed. */
3906        for (block_row = 0; block_row < block_rows; block_row++) {
3907            buffer_ptr = buffer[block_row+buffer_offset];
3908            int buffer_ptr_offset = 0, prev_block_row_offset = 0, next_block_row_offset = 0;
3909            if (first_row && block_row == 0) {
3910                prev_block_row = buffer_ptr;
3911                prev_block_row_offset = buffer_ptr_offset;
3912            } else {
3913                prev_block_row = buffer[block_row-1+buffer_offset];
3914                prev_block_row_offset = 0;
3915            }
3916            if (last_row && block_row == block_rows-1) {
3917                next_block_row = buffer_ptr;
3918                next_block_row_offset = buffer_ptr_offset;
3919            } else {
3920                next_block_row = buffer[block_row+1+buffer_offset];
3921                next_block_row_offset = 0;
3922            }
3923            /* We fetch the surrounding DC values using a sliding-register approach.
3924             * Initialize all nine here so as to do the right thing on narrow pics.
3925             */

3926            DC1 = DC2 = DC3 = prev_block_row[0+prev_block_row_offset][0];
3927            DC4 = DC5 = DC6 = buffer_ptr[0+buffer_ptr_offset][0];
3928            DC7 = DC8 = DC9 = next_block_row[0+next_block_row_offset][0];
3929            output_col = 0;
3930            last_block_column = compptr.width_in_blocks - 1;
3931            for (block_num = 0; block_num <= last_block_column; block_num++) {
3932                /* Fetch current DCT block into workspace so we can modify it. */
3933// jcopy_block_row(buffer_ptr, workspace, 1);
3934
System.arraycopy(buffer_ptr[buffer_ptr_offset], 0, workspace, 0, workspace.length);
3935                /* Update DC values */
3936                if (block_num < last_block_column) {
3937                    DC3 = prev_block_row[1+prev_block_row_offset][0];
3938                    DC6 = buffer_ptr[1+buffer_ptr_offset][0];
3939                    DC9 = next_block_row[1+next_block_row_offset][0];
3940                }
3941                /* Compute coefficient estimates per K.8.
3942                 * An estimate is applied only if coefficient is still zero,
3943                 * and is not known to be fully accurate.
3944                 */

3945                /* AC01 */
3946                if ((Al=coef_bits[1+coef_offset]) != 0 && workspace[1] == 0) {
3947                    num = 36 * Q00 * (DC4 - DC6);
3948                    if (num >= 0) {
3949                        pred = (((Q01<<7) + num) / (Q01<<8));
3950                        if (Al > 0 && pred >= (1<<Al))
3951                            pred = (1<<Al)-1;
3952                    } else {
3953                        pred = (((Q01<<7) - num) / (Q01<<8));
3954                        if (Al > 0 && pred >= (1<<Al))
3955                            pred = (1<<Al)-1;
3956                        pred = -pred;
3957                    }
3958                    workspace[1] = (short) pred;
3959                }
3960                /* AC10 */
3961                if ((Al=coef_bits[2+coef_offset]) != 0 && workspace[8] == 0) {
3962                    num = 36 * Q00 * (DC2 - DC8);
3963                    if (num >= 0) {
3964                        pred = (((Q10<<7) + num) / (Q10<<8));
3965                        if (Al > 0 && pred >= (1<<Al))
3966                            pred = (1<<Al)-1;
3967                    } else {
3968                        pred = (((Q10<<7) - num) / (Q10<<8));
3969                        if (Al > 0 && pred >= (1<<Al))
3970                            pred = (1<<Al)-1;
3971                        pred = -pred;
3972                    }
3973                    workspace[8] = (short) pred;
3974                }
3975                /* AC20 */
3976                if ((Al=coef_bits[3+coef_offset]) != 0 && workspace[16] == 0) {
3977                    num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
3978                    if (num >= 0) {
3979                        pred = (((Q20<<7) + num) / (Q20<<8));
3980                        if (Al > 0 && pred >= (1<<Al))
3981                            pred = (1<<Al)-1;
3982                    } else {
3983                        pred = (((Q20<<7) - num) / (Q20<<8));
3984                        if (Al > 0 && pred >= (1<<Al))
3985                            pred = (1<<Al)-1;
3986                        pred = -pred;
3987                    }
3988                    workspace[16] = (short) pred;
3989                }
3990                /* AC11 */
3991                if ((Al=coef_bits[4+coef_offset]) != 0 && workspace[9] == 0) {
3992                    num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
3993                    if (num >= 0) {
3994                        pred = (((Q11<<7) + num) / (Q11<<8));
3995                        if (Al > 0 && pred >= (1<<Al))
3996                            pred = (1<<Al)-1;
3997                    } else {
3998                        pred = (((Q11<<7) - num) / (Q11<<8));
3999                        if (Al > 0 && pred >= (1<<Al))
4000                            pred = (1<<Al)-1;
4001                        pred = -pred;
4002                    }
4003                    workspace[9] = (short) pred;
4004                }
4005                /* AC02 */
4006                if ((Al=coef_bits[5+coef_offset]) != 0 && workspace[2] == 0) {
4007                    num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
4008                    if (num >= 0) {
4009                        pred = (((Q02<<7) + num) / (Q02<<8));
4010                        if (Al > 0 && pred >= (1<<Al))
4011                            pred = (1<<Al)-1;
4012                    } else {
4013                        pred = (((Q02<<7) - num) / (Q02<<8));
4014                        if (Al > 0 && pred >= (1<<Al))
4015                            pred = (1<<Al)-1;
4016                        pred = -pred;
4017                    }
4018                    workspace[2] = (short) pred;
4019                }
4020                /* OK, do the IDCT */
4021                jpeg_idct_islow(cinfo, compptr, workspace, output_ptr, output_ptr_offset, output_col);
4022                /* Advance for next column */
4023                DC1 = DC2; DC2 = DC3;
4024                DC4 = DC5; DC5 = DC6;
4025                DC7 = DC8; DC8 = DC9;
4026                buffer_ptr_offset++; prev_block_row_offset++; next_block_row_offset++;
4027                output_col += compptr.DCT_scaled_size;
4028            }
4029            output_ptr_offset += compptr.DCT_scaled_size;
4030        }
4031    }
4032
4033    if (++(cinfo.output_iMCU_row) < cinfo.total_iMCU_rows)
4034        return JPEG_ROW_COMPLETED;
4035    return JPEG_SCAN_COMPLETED;
4036}
4037
4038static int decompress_data (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) {
4039    jpeg_d_coef_controller coef = cinfo.coef;
4040    int last_iMCU_row = cinfo.total_iMCU_rows - 1;
4041    int block_num;
4042    int ci, block_row, block_rows;
4043    short[][][] buffer;
4044    short[][] buffer_ptr;
4045    byte[][] output_ptr;
4046    int output_col;
4047    jpeg_component_info compptr;
4048// inverse_DCT_method_ptr inverse_DCT;
4049

4050    /* Force some input to be done if we are getting ahead of the input. */
4051    while (cinfo.input_scan_number < cinfo.output_scan_number ||
4052     (cinfo.input_scan_number == cinfo.output_scan_number &&
4053        cinfo.input_iMCU_row <= cinfo.output_iMCU_row))
4054    {
4055        if (consume_input(cinfo) == JPEG_SUSPENDED)
4056            return JPEG_SUSPENDED;
4057    }
4058
4059    /* OK, output from the virtual arrays. */
4060    for (ci = 0; ci < cinfo.num_components; ci++) {
4061        compptr = cinfo.comp_info[ci];
4062        /* Don't bother to IDCT an uninteresting component. */
4063        if (! compptr.component_needed)
4064            continue;
4065        /* Align the virtual buffer for this component. */
4066        buffer = coef.whole_image[ci];
4067        int buffer_offset = cinfo.output_iMCU_row * compptr.v_samp_factor;
4068        /* Count non-dummy DCT block rows in this iMCU row. */
4069        if (cinfo.output_iMCU_row < last_iMCU_row)
4070            block_rows = compptr.v_samp_factor;
4071        else {
4072            /* NB: can't use last_row_height here; it is input-side-dependent! */
4073            block_rows = (compptr.height_in_blocks % compptr.v_samp_factor);
4074            if (block_rows == 0) block_rows = compptr.v_samp_factor;
4075        }
4076// inverse_DCT = cinfo.idct.inverse_DCT[ci];
4077
output_ptr = output_buf[ci];
4078        int output_ptr_offset = output_buf_offset[ci];
4079        /* Loop over all DCT blocks to be processed. */
4080        for (block_row = 0; block_row < block_rows; block_row++) {
4081            buffer_ptr = buffer[block_row+buffer_offset];
4082            int buffer_ptr_offset = 0;
4083            output_col = 0;
4084            for (block_num = 0; block_num < compptr.width_in_blocks; block_num++) {
4085                jpeg_idct_islow(cinfo, compptr, buffer_ptr[buffer_ptr_offset], output_ptr, output_ptr_offset, output_col);
4086
4087                buffer_ptr_offset++;
4088                output_col += compptr.DCT_scaled_size;
4089            }
4090            output_ptr_offset += compptr.DCT_scaled_size;
4091        }
4092    }
4093
4094    if (++(cinfo.output_iMCU_row) < cinfo.total_iMCU_rows)
4095        return JPEG_ROW_COMPLETED;
4096    return JPEG_SCAN_COMPLETED;
4097}
4098
4099static void post_process_data (jpeg_decompress_struct cinfo,
4100                byte[][][] input_buf, int[] input_buf_offset, int[] in_row_group_ctr,
4101                int in_row_groups_avail,
4102                byte[][] output_buf, int[] out_row_ctr,
4103                int out_rows_avail)
4104{
4105    upsample(cinfo, input_buf, input_buf_offset, in_row_group_ctr, in_row_groups_avail, output_buf, out_row_ctr, out_rows_avail);
4106}
4107
4108static void set_bottom_pointers (jpeg_decompress_struct cinfo)
4109/* Change the pointer lists to duplicate the last sample row at the bottom
4110 * of the image. whichptr indicates which xbuffer holds the final iMCU row.
4111 * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
4112 */

4113{
4114    jpeg_d_main_controller main = cinfo.main;
4115    int ci, i, rgroup, iMCUheight, rows_left;
4116    jpeg_component_info compptr;
4117    byte[][] xbuf;
4118
4119    for (ci = 0; ci < cinfo.num_components; ci++) {
4120        compptr = cinfo.comp_info[ci];
4121        /* Count sample rows in one iMCU row and in one row group */
4122        iMCUheight = compptr.v_samp_factor * compptr.DCT_scaled_size;
4123        rgroup = iMCUheight / cinfo.min_DCT_scaled_size;
4124        /* Count nondummy sample rows remaining for this component */
4125        rows_left = (compptr.downsampled_height % iMCUheight);
4126        if (rows_left == 0) rows_left = iMCUheight;
4127        /* Count nondummy row groups. Should get same answer for each component,
4128         * so we need only do it once.
4129         */

4130        if (ci == 0) {
4131            main.rowgroups_avail = ((rows_left-1) / rgroup + 1);
4132        }
4133        /* Duplicate the last real sample row rgroup*2 times; this pads out the
4134         * last partial rowgroup and ensures at least one full rowgroup of context.
4135         */

4136        xbuf = main.xbuffer[main.whichptr][ci];
4137        int xbuf_offset = main.xbuffer_offset[main.whichptr][ci];
4138        for (i = 0; i < rgroup * 2; i++) {
4139            xbuf[rows_left + i + xbuf_offset] = xbuf[rows_left-1 + xbuf_offset];
4140        }
4141    }
4142}
4143
4144static void set_wraparound_pointers (jpeg_decompress_struct cinfo)
4145/* Set up the "wraparound" pointers at top and bottom of the pointer lists.
4146 * This changes the pointer list state from top-of-image to the normal state.
4147 */

4148{
4149    jpeg_d_main_controller main = cinfo.main;
4150    int ci, i, rgroup;
4151    int M = cinfo.min_DCT_scaled_size;
4152    jpeg_component_info compptr;
4153    byte[][] xbuf0, xbuf1;
4154
4155    for (ci = 0; ci < cinfo.num_components; ci++) {
4156        compptr = cinfo.comp_info[ci];
4157        rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) / cinfo.min_DCT_scaled_size; /* height of a row group of component */
4158        xbuf0 = main.xbuffer[0][ci];
4159        int xbuf0_offset = main.xbuffer_offset[0][ci];
4160        xbuf1 = main.xbuffer[1][ci];
4161        int xbuf1_offset = main.xbuffer_offset[1][ci];
4162        for (i = 0; i < rgroup; i++) {
4163            xbuf0[i - rgroup + xbuf0_offset] = xbuf0[rgroup*(M+1) + i + xbuf0_offset];
4164            xbuf1[i - rgroup + xbuf1_offset] = xbuf1[rgroup*(M+1) + i + xbuf1_offset];
4165            xbuf0[rgroup*(M+2) + i + xbuf0_offset] = xbuf0[i + xbuf0_offset];
4166            xbuf1[rgroup*(M+2) + i + xbuf1_offset] = xbuf1[i + xbuf1_offset];
4167        }
4168    }
4169}
4170
4171static void process_data_crank_post (jpeg_decompress_struct cinfo,
4172    byte[][] output_buf, int[] out_row_ctr,
4173    int out_rows_avail)
4174{
4175    error();
4176}
4177
4178static void process_data_context_main (jpeg_decompress_struct cinfo,
4179    byte[][] output_buf, int[] out_row_ctr,
4180    int out_rows_avail)
4181{
4182    jpeg_d_main_controller main = cinfo.main;
4183
4184    /* Read input data if we haven't filled the main buffer yet */
4185    if (! main.buffer_full) {
4186        int result;
4187        switch (cinfo.coef.decompress_data) {
4188            case DECOMPRESS_DATA:
4189                result = decompress_data(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]);
4190                break;
4191            case DECOMPRESS_SMOOTH_DATA:
4192                result = decompress_smooth_data(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]);
4193                break;
4194            case DECOMPRESS_ONEPASS:
4195                result = decompress_onepass(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]);
4196                break;
4197            default: result = 0;
4198        }
4199        if (result == 0)
4200            return; /* suspension forced, can do nothing more */
4201        main.buffer_full = true; /* OK, we have an iMCU row to work with */
4202        main.iMCU_row_ctr++; /* count rows received */
4203    }
4204
4205    /* Postprocessor typically will not swallow all the input data it is handed
4206     * in one call (due to filling the output buffer first). Must be prepared
4207     * to exit and restart. This switch lets us keep track of how far we got.
4208     * Note that each case falls through to the next on successful completion.
4209     */

4210    switch (main.context_state) {
4211        case CTX_POSTPONED_ROW:
4212            /* Call postprocessor using previously set pointers for postponed row */
4213            post_process_data (cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr], main.rowgroup_ctr, main.rowgroups_avail, output_buf, out_row_ctr, out_rows_avail);
4214            if (main.rowgroup_ctr[0] < main.rowgroups_avail)
4215                return; /* Need to suspend */
4216            main.context_state = CTX_PREPARE_FOR_IMCU;
4217            if (out_row_ctr[0] >= out_rows_avail)
4218                return; /* Postprocessor exactly filled output buf */
4219            /*FALLTHROUGH*/
4220        case CTX_PREPARE_FOR_IMCU:
4221            /* Prepare to process first M-1 row groups of this iMCU row */
4222            main.rowgroup_ctr[0] = 0;
4223            main.rowgroups_avail = (cinfo.min_DCT_scaled_size - 1);
4224            /* Check for bottom of image: if so, tweak pointers to "duplicate"
4225             * the last sample row, and adjust rowgroups_avail to ignore padding rows.
4226             */

4227            if (main.iMCU_row_ctr == cinfo.total_iMCU_rows)
4228                set_bottom_pointers(cinfo);
4229            main.context_state = CTX_PROCESS_IMCU;
4230            /*FALLTHROUGH*/
4231        case CTX_PROCESS_IMCU:
4232            /* Call postprocessor using previously set pointers */
4233            post_process_data (cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr], main.rowgroup_ctr, main.rowgroups_avail, output_buf, out_row_ctr, out_rows_avail);
4234            if (main.rowgroup_ctr[0] < main.rowgroups_avail)
4235                return; /* Need to suspend */
4236            /* After the first iMCU, change wraparound pointers to normal state */
4237            if (main.iMCU_row_ctr == 1)
4238                set_wraparound_pointers(cinfo);
4239            /* Prepare to load new iMCU row using other xbuffer list */
4240            main.whichptr ^= 1; /* 0=>1 or 1=>0 */
4241            main.buffer_full = false;
4242            /* Still need to process last row group of this iMCU row, */
4243            /* which is saved at index M+1 of the other xbuffer */
4244            main.rowgroup_ctr[0] = (cinfo.min_DCT_scaled_size + 1);
4245            main.rowgroups_avail = (cinfo.min_DCT_scaled_size + 2);
4246            main.context_state = CTX_POSTPONED_ROW;
4247    }
4248}
4249
4250static void process_data_simple_main (jpeg_decompress_struct cinfo, byte[][] output_buf, int[] out_row_ctr, int out_rows_avail) {
4251    jpeg_d_main_controller main = cinfo.main;
4252    int rowgroups_avail;
4253
4254    /* Read input data if we haven't filled the main buffer yet */
4255    if (! main.buffer_full) {
4256        int result;
4257        switch (cinfo.coef.decompress_data) {
4258            case DECOMPRESS_DATA:
4259                result = decompress_data(cinfo, main.buffer, main.buffer_offset);
4260                break;
4261            case DECOMPRESS_SMOOTH_DATA:
4262                result = decompress_smooth_data(cinfo, main.buffer, main.buffer_offset);
4263                break;
4264            case DECOMPRESS_ONEPASS:
4265                result = decompress_onepass(cinfo, main.buffer, main.buffer_offset);
4266                break;
4267            default: result = 0;
4268        }
4269        if (result == 0)
4270            return; /* suspension forced, can do nothing more */
4271        main.buffer_full = true; /* OK, we have an iMCU row to work with */
4272    }
4273
4274    /* There are always min_DCT_scaled_size row groups in an iMCU row. */
4275    rowgroups_avail = cinfo.min_DCT_scaled_size;
4276    /* Note: at the bottom of the image, we may pass extra garbage row groups
4277     * to the postprocessor. The postprocessor has to check for bottom
4278     * of image anyway (at row resolution), so no point in us doing it too.
4279     */

4280
4281    /* Feed the postprocessor */
4282    post_process_data (cinfo, main.buffer, main.buffer_offset, main.rowgroup_ctr, rowgroups_avail, output_buf, out_row_ctr, out_rows_avail);
4283
4284    /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
4285    if (main.rowgroup_ctr[0] >= rowgroups_avail) {
4286        main.buffer_full = false;
4287        main.rowgroup_ctr[0] = 0;
4288    }
4289}
4290
4291static int jpeg_read_scanlines (jpeg_decompress_struct cinfo, byte[][] scanlines, int max_lines) {
4292
4293    if (cinfo.global_state != DSTATE_SCANNING)
4294        error();
4295// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
4296
if (cinfo.output_scanline >= cinfo.output_height) {
4297// WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
4298
return 0;
4299    }
4300
4301    /* Call progress monitor hook if present */
4302// if (cinfo.progress != NULL) {
4303
// cinfo.progress.pass_counter = (long) cinfo.output_scanline;
4304
// cinfo.progress.pass_limit = (long) cinfo.output_height;
4305
// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo);
4306
// }
4307

4308    /* Process some data */
4309    cinfo.row_ctr[0] = 0;
4310    switch (cinfo.main.process_data) {
4311        case PROCESS_DATA_SIMPLE_MAIN:
4312            process_data_simple_main (cinfo, scanlines, cinfo.row_ctr, max_lines);
4313            break;
4314        case PROCESS_DATA_CONTEXT_MAIN:
4315            process_data_context_main (cinfo, scanlines, cinfo.row_ctr, max_lines);
4316            break;
4317        case PROCESS_DATA_CRANK_POST:
4318            process_data_crank_post (cinfo, scanlines, cinfo.row_ctr, max_lines);
4319            break;
4320        default: error();
4321    }
4322    cinfo.output_scanline += cinfo.row_ctr[0];
4323    return cinfo.row_ctr[0];
4324}
4325
4326
4327static boolean output_pass_setup (jpeg_decompress_struct cinfo) {
4328    if (cinfo.global_state != DSTATE_PRESCAN) {
4329        /* First call: do pass setup */
4330        prepare_for_output_pass (cinfo);
4331        cinfo.output_scanline = 0;
4332        cinfo.global_state = DSTATE_PRESCAN;
4333    }
4334    /* Loop over any required dummy passes */
4335    while (cinfo.master.is_dummy_pass) {
4336        error();
4337//#ifdef QUANT_2PASS_SUPPORTED
4338
// /* Crank through the dummy pass */
4339
// while (cinfo.output_scanline < cinfo.output_height) {
4340
// JDIMENSION last_scanline;
4341
// /* Call progress monitor hook if present */
4342
// if (cinfo.progress != NULL) {
4343
// cinfo.progress.pass_counter = (long) cinfo.output_scanline;
4344
// cinfo.progress.pass_limit = (long) cinfo.output_height;
4345
// (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo);
4346
// }
4347
// /* Process some data */
4348
// last_scanline = cinfo.output_scanline;
4349
// (*cinfo.main.process_data) (cinfo, (JSAMPARRAY) NULL,
4350
// &cinfo.output_scanline, (JDIMENSION) 0);
4351
// if (cinfo.output_scanline == last_scanline)
4352
// return FALSE; /* No progress made, must suspend */
4353
// }
4354
// /* Finish up dummy pass, and set up for another one */
4355
// (*cinfo.master.finish_output_pass) (cinfo);
4356
// (*cinfo.master.prepare_for_output_pass) (cinfo);
4357
// cinfo.output_scanline = 0;
4358
//#else
4359
// ERREXIT(cinfo, JERR_NOT_COMPILED);
4360
//#endif /* QUANT_2PASS_SUPPORTED */
4361
}
4362    /* Ready for application to drive output pass through
4363     * jpeg_read_scanlines or jpeg_read_raw_data.
4364     */

4365    cinfo.global_state = cinfo.raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
4366    return true;
4367}
4368
4369static boolean get_dht (jpeg_decompress_struct cinfo)
4370/* Process a DHT marker */
4371{
4372    int length;
4373    byte[] bits = new byte[17];
4374    byte[] huffval = new byte[256];
4375    int i, index, count;
4376    JHUFF_TBL htblptr;
4377
4378    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4379    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4380    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4381    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4382    length -= 2;
4383    
4384    while (length > 16) {
4385        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4386        index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4387
4388// TRACEMS1(cinfo, 1, JTRC_DHT, index);
4389

4390        bits[0] = 0;
4391        count = 0;
4392        for (i = 1; i <= 16; i++) {
4393            if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4394        bits[i] = cinfo.buffer[cinfo.bytes_offset++];
4395            count += bits[i] & 0xFF;
4396        }
4397
4398        length -= 1 + 16;
4399
4400// TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
4401
// bits[1], bits[2], bits[3], bits[4],
4402
// bits[5], bits[6], bits[7], bits[8]);
4403
// TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
4404
// bits[9], bits[10], bits[11], bits[12],
4405
// bits[13], bits[14], bits[15], bits[16]);
4406

4407        /* Here we just do minimal validation of the counts to avoid walking
4408         * off the end of our table space. jdhuff.c will check more carefully.
4409         */

4410        if (count > 256 || (count) > length)
4411            error();
4412// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
4413

4414        for (i = 0; i < count; i++) {
4415            if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4416            huffval[i] = cinfo.buffer[cinfo.bytes_offset++];
4417        }
4418
4419        length -= count;
4420
4421        if ((index & 0x10) != 0) { /* AC table definition */
4422            index -= 0x10;
4423            htblptr = cinfo.ac_huff_tbl_ptrs[index] = new JHUFF_TBL();
4424        } else { /* DC table definition */
4425            htblptr = cinfo.dc_huff_tbl_ptrs[index] = new JHUFF_TBL();
4426        }
4427
4428        if (index < 0 || index >= NUM_HUFF_TBLS)
4429            error();
4430// ERREXIT1(cinfo, JERR_DHT_INDEX, index);
4431

4432        System.arraycopy(bits, 0, htblptr.bits, 0, bits.length);
4433        System.arraycopy(huffval, 0, htblptr.huffval, 0, huffval.length);
4434    }
4435
4436    if (length != 0)
4437        error();
4438// ERREXIT(cinfo, JERR_BAD_LENGTH);
4439

4440    return true;
4441}
4442
4443
4444static boolean get_dqt (jpeg_decompress_struct cinfo)
4445/* Process a DQT marker */
4446{
4447    int length;
4448    int n, i, prec;
4449    int tmp;
4450    JQUANT_TBL quant_ptr;
4451
4452    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4453    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4454    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4455    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4456    length -= 2;
4457
4458    while (length > 0) {
4459        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4460    n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4461        prec = n >> 4;
4462        n &= 0x0F;
4463
4464// TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
4465

4466        if (n >= NUM_QUANT_TBLS)
4467            error();
4468// ERREXIT1(cinfo, JERR_DQT_INDEX, n);
4469

4470        if (cinfo.quant_tbl_ptrs[n] == null)
4471            cinfo.quant_tbl_ptrs[n] = new JQUANT_TBL();
4472        quant_ptr = cinfo.quant_tbl_ptrs[n];
4473
4474        for (i = 0; i < DCTSIZE2; i++) {
4475            if (prec != 0) {
4476                if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4477                tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4478                if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4479                tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4480            } else {
4481                    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4482                tmp = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4483            }
4484            /* We convert the zigzag-order table to natural array order. */
4485            quant_ptr.quantval[jpeg_natural_order[i]] = (short) tmp;
4486        }
4487
4488// if (cinfo.err.trace_level >= 2) {
4489
// for (i = 0; i < DCTSIZE2; i += 8) {
4490
// TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
4491
// quant_ptr.quantval[i], quant_ptr.quantval[i+1],
4492
// quant_ptr.quantval[i+2], quant_ptr.quantval[i+3],
4493
// quant_ptr.quantval[i+4], quant_ptr.quantval[i+5],
4494
// quant_ptr.quantval[i+6], quant_ptr.quantval[i+7]);
4495
// }
4496
// }
4497

4498        length -= (DCTSIZE2+1);
4499        if (prec != 0) length -= DCTSIZE2;
4500    }
4501
4502    if (length != 0)
4503        error();
4504// ERREXIT(cinfo, JERR_BAD_LENGTH);
4505

4506    return true;
4507}
4508
4509static boolean get_dri (jpeg_decompress_struct cinfo)
4510/* Process a DRI marker */
4511{
4512    int length;
4513    int tmp;
4514
4515    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4516    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4517    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4518    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4519    
4520    if (length != 4)
4521    error();
4522// ERREXIT(cinfo, JERR_BAD_LENGTH);
4523

4524    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4525    tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4526    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4527    tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4528
4529// TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
4530

4531    cinfo.restart_interval = tmp;
4532
4533    return true;
4534}
4535
4536static boolean get_dac (jpeg_decompress_struct cinfo)
4537/* Process a DAC marker */
4538{
4539    int length;
4540    int index, val;
4541    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4542    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4543    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4544    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4545    length -= 2;
4546    
4547    while (length > 0) {
4548        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4549        index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4550        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4551        val = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4552
4553        length -= 2;
4554
4555// TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
4556

4557        if (index < 0 || index >= (2*NUM_ARITH_TBLS))
4558            error();
4559// ERREXIT1(cinfo, JERR_DAC_INDEX, index);
4560

4561        if (index >= NUM_ARITH_TBLS) { /* define AC table */
4562            cinfo.arith_ac_K[index-NUM_ARITH_TBLS] = (byte) val;
4563        } else { /* define DC table */
4564            cinfo.arith_dc_L[index] = (byte) (val & 0x0F);
4565            cinfo.arith_dc_U[index] = (byte) (val >> 4);
4566            if (cinfo.arith_dc_L[index] > cinfo.arith_dc_U[index])
4567                error();
4568// ERREXIT1(cinfo, JERR_DAC_VALUE, val);
4569
}
4570    }
4571
4572    if (length != 0)
4573        error();
4574// ERREXIT(cinfo, JERR_BAD_LENGTH);
4575

4576    return true;
4577}
4578
4579
4580static boolean get_sos (jpeg_decompress_struct cinfo)
4581/* Process a SOS marker */
4582{
4583    int length;
4584    int i, ci, n, c, cc;
4585    jpeg_component_info compptr = null;
4586
4587    if (! cinfo.marker.saw_SOF)
4588        error();
4589// ERREXIT(cinfo, JERR_SOS_NO_SOF);
4590

4591    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4592    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4593    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4594    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4595
4596    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4597    n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4598
4599// TRACEMS1(cinfo, 1, JTRC_SOS, n);
4600

4601    if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
4602        error();
4603// ERREXIT(cinfo, JERR_BAD_LENGTH);
4604

4605    cinfo.comps_in_scan = n;
4606
4607    /* Collect the component-spec parameters */
4608
4609    for (i = 0; i < n; i++) {
4610        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4611        cc = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4612        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4613        c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4614        
4615        for (ci = 0; ci < cinfo.num_components; ci++) {
4616            compptr = cinfo.comp_info[ci];
4617            if (cc == compptr.component_id)
4618                break;
4619        }
4620
4621        if (ci == cinfo.num_components)
4622            error();
4623// ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
4624

4625        cinfo.cur_comp_info[i] = compptr;
4626        compptr.dc_tbl_no = (c >> 4) & 15;
4627        compptr.ac_tbl_no = (c ) & 15;
4628        
4629// TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc, compptr.dc_tbl_no, compptr.ac_tbl_no);
4630
}
4631
4632    /* Collect the additional scan parameters Ss, Se, Ah/Al. */
4633    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4634    c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4635    cinfo.Ss = c;
4636    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4637    c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4638    cinfo.Se = c;
4639    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4640    c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4641    cinfo.Ah = (c >> 4) & 15;
4642    cinfo.Al = (c ) & 15;
4643
4644// TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al);
4645

4646    /* Prepare to scan data & restart markers */
4647    cinfo.marker.next_restart_num = 0;
4648
4649    /* Count another SOS marker */
4650    cinfo.input_scan_number++;
4651
4652    return true;
4653}
4654
4655static boolean get_sof (jpeg_decompress_struct cinfo, boolean is_prog, boolean is_arith) {
4656    int length;
4657    int c, ci;
4658
4659    cinfo.progressive_mode = is_prog;
4660    cinfo.arith_code = is_arith;
4661
4662    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4663    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4664    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4665    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4666
4667    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4668    cinfo.data_precision = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4669
4670    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4671    cinfo.image_height = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4672    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4673    cinfo.image_height |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4674
4675    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4676    cinfo.image_width = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4677    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4678    cinfo.image_width |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4679    
4680    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4681    cinfo.num_components = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4682
4683    length -= 8;
4684
4685// TRACEMS4(cinfo, 1, JTRC_SOF, cinfo.unread_marker,
4686
// (int) cinfo.image_width, (int) cinfo.image_height,
4687
// cinfo.num_components);
4688

4689    if (cinfo.marker.saw_SOF)
4690        error();
4691// ERREXIT(cinfo, JERR_SOF_DUPLICATE);
4692

4693    /* We don't support files in which the image height is initially specified */
4694    /* as 0 and is later redefined by DNL. As long as we have to check that, */
4695    /* might as well have a general sanity check. */
4696    if (cinfo.image_height <= 0 || cinfo.image_width <= 0 || cinfo.num_components <= 0)
4697        error();
4698// ERREXIT(cinfo, JERR_EMPTY_IMAGE);
4699

4700    if (length != (cinfo.num_components * 3))
4701        error();
4702// ERREXIT(cinfo, JERR_BAD_LENGTH);
4703

4704    if (cinfo.comp_info == null) /* do only once, even if suspend */
4705        cinfo.comp_info = new jpeg_component_info[cinfo.num_components];
4706    
4707    for (ci = 0; ci < cinfo.num_components; ci++) {
4708        jpeg_component_info compptr = cinfo.comp_info[ci] = new jpeg_component_info();
4709        compptr.component_index = ci;
4710        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4711        compptr.component_id = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4712        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4713        c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4714        compptr.h_samp_factor = (c >> 4) & 15;
4715        compptr.v_samp_factor = (c ) & 15;
4716        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4717        compptr.quant_tbl_no = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4718
4719// TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
4720
// compptr.component_id, compptr.h_samp_factor,
4721
// compptr.v_samp_factor, compptr.quant_tbl_no);
4722
}
4723
4724    cinfo.marker.saw_SOF = true;
4725
4726    return true;
4727}
4728
4729static void sep_upsample (jpeg_decompress_struct cinfo, byte[][][] input_buf, int[] input_buf_offset,
4730        int[] in_row_group_ctr, int in_row_groups_avail,
4731        byte[][] output_buf, int[] out_row_ctr, int out_rows_avail)
4732{
4733    jpeg_upsampler upsample = cinfo.upsample;
4734    int ci;
4735    jpeg_component_info compptr;
4736    int num_rows;
4737
4738    /* Fill the conversion buffer, if it's empty */
4739    if (upsample.next_row_out >= cinfo.max_v_samp_factor) {
4740        for (ci = 0; ci < cinfo.num_components; ci++) {
4741            compptr = cinfo.comp_info[ci];
4742            /* Invoke per-component upsample method. Notice we pass a POINTER
4743             * to color_buf[ci], so that fullsize_upsample can change it.
4744             */

4745            int offset = input_buf_offset[ci] + (in_row_group_ctr[0] * upsample.rowgroup_height[ci]);
4746            switch (upsample.methods[ci]) {
4747                case NOOP_UPSAMPLE: noop_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4748                case FULLSIZE_UPSAMPLE: fullsize_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4749                case H2V1_FANCY_UPSAMPLE: h2v1_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4750                case H2V1_UPSAMPLE: h2v1_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4751                case H2V2_FANCY_UPSAMPLE: h2v2_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4752                case H2V2_UPSAMPLE: h2v2_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4753                case INT_UPSAMPLE: int_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4754            }
4755        }
4756        upsample.next_row_out = 0;
4757    }
4758
4759    /* Color-convert and emit rows */
4760
4761    /* How many we have in the buffer: */
4762    num_rows = (cinfo.max_v_samp_factor - upsample.next_row_out);
4763    /* Not more than the distance to the end of the image. Need this test
4764     * in case the image height is not a multiple of max_v_samp_factor:
4765     */

4766    if (num_rows > upsample.rows_to_go)
4767        num_rows = upsample.rows_to_go;
4768    /* And not more than what the client can accept: */
4769    out_rows_avail -= out_row_ctr[0];
4770    if (num_rows > out_rows_avail)
4771        num_rows = out_rows_avail;
4772
4773    switch (cinfo.cconvert.color_convert) {
4774        case NULL_CONVERT: null_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break;
4775        case GRAYSCALE_CONVERT: grayscale_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break;
4776        case YCC_RGB_CONVERT: ycc_rgb_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break;
4777        case GRAY_RGB_CONVERT: gray_rgb_convert (cinfo, upsample.color_buf, upsample.color_buf_offset, upsample.next_row_out, output_buf, out_row_ctr[0], num_rows); break;
4778        case YCCK_CMYK_CONVERT: error(); break;
4779    }
4780
4781    /* Adjust counts */
4782    out_row_ctr[0] += num_rows;
4783    upsample.rows_to_go -= num_rows;
4784    upsample.next_row_out += num_rows;
4785    /* When the buffer is emptied, declare this input row group consumed */
4786    if (upsample.next_row_out >= cinfo.max_v_samp_factor) {
4787        in_row_group_ctr[0]++;
4788    }
4789}
4790    
4791static void noop_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4792     byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4793{
4794    output_data_ptr[output_data_index] = null; /* safety check */
4795}
4796    
4797static void fullsize_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4798     byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4799{
4800    output_data_ptr[output_data_index] = input_data;
4801    output_data_offset[output_data_index] = input_data_offset;
4802}
4803    
4804static void h2v1_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4805     byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4806{
4807    byte[][] output_data = output_data_ptr[output_data_index];
4808    byte[] inptr, outptr;
4809    byte invalue;
4810    int outend;
4811    int inrow;
4812    output_data_offset[output_data_index] = 0;
4813
4814    for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) {
4815        inptr = input_data[inrow+input_data_offset];
4816        outptr = output_data[inrow];
4817        int inptr_offset = 0, outptr_offset = 0;
4818        outend = outptr_offset + cinfo.output_width;
4819        while (outptr_offset < outend) {
4820            invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */
4821            outptr[outptr_offset++] = invalue;
4822            outptr[outptr_offset++] = invalue;
4823        }
4824    }
4825}
4826    
4827static void h2v2_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4828    byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4829{
4830    byte[][] output_data = output_data_ptr[output_data_index];
4831    byte[] inptr, outptr;
4832    byte invalue;
4833    int outend;
4834    int inrow, outrow;
4835    output_data_offset[output_data_index] = 0;
4836
4837    inrow = outrow = 0;
4838    while (outrow < cinfo.max_v_samp_factor) {
4839        inptr = input_data[inrow+input_data_offset];
4840        outptr = output_data[outrow];
4841        int inptr_offset = 0, outptr_offset = 0;
4842        outend = outptr_offset + cinfo.output_width;
4843        while (outptr_offset < outend) {
4844            invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */
4845            outptr[outptr_offset++] = invalue;
4846            outptr[outptr_offset++] = invalue;
4847        }
4848        jcopy_sample_rows(output_data, outrow, output_data, outrow+1, 1, cinfo.output_width);
4849        inrow++;
4850        outrow += 2;
4851    }
4852}
4853    
4854static void h2v1_fancy_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4855     byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4856{
4857    byte[][] output_data = output_data_ptr[output_data_index];
4858    byte[] inptr, outptr;
4859    int invalue;
4860    int colctr;
4861    int inrow;
4862    output_data_offset[output_data_index] = 0;
4863
4864    for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) {
4865        inptr = input_data[inrow+input_data_offset];
4866        outptr = output_data[inrow];
4867        int inptr_offset = 0, outptr_offset = 0;
4868        /* Special case for first column */
4869        invalue = inptr[inptr_offset++] & 0xFF;
4870        outptr[outptr_offset++] = (byte) invalue;
4871        outptr[outptr_offset++] = (byte) ((invalue * 3 + (inptr[inptr_offset] & 0xFF) + 2) >> 2);
4872
4873        for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) {
4874            /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
4875            invalue = (inptr[inptr_offset++] & 0xFF) * 3;
4876            outptr[outptr_offset++] = (byte) ((invalue + (inptr[inptr_offset-2] & 0xFF) + 1) >> 2);
4877            outptr[outptr_offset++] = (byte) ((invalue + (inptr[inptr_offset] & 0xFF) + 2) >> 2);
4878        }
4879
4880        /* Special case for last column */
4881        invalue = (inptr[inptr_offset] & 0xFF);
4882        outptr[outptr_offset++] = (byte) ((invalue * 3 + (inptr[inptr_offset-1] & 0xFF) + 1) >> 2);
4883        outptr[outptr_offset++] = (byte) invalue;
4884    }
4885}
4886    
4887static void h2v2_fancy_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4888    byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4889{
4890    byte[][] output_data = output_data_ptr[output_data_index];
4891    byte[] inptr0, inptr1, outptr;
4892    int thiscolsum, lastcolsum, nextcolsum;
4893    int colctr;
4894    int inrow, outrow, v;
4895    output_data_offset[output_data_index] = 0;
4896
4897    inrow = outrow = 0;
4898    while (outrow < cinfo.max_v_samp_factor) {
4899        for (v = 0; v < 2; v++) {
4900            /* inptr0 points to nearest input row, inptr1 points to next nearest */
4901            inptr0 = input_data[inrow+input_data_offset];
4902            if (v == 0) /* next nearest is row above */
4903                inptr1 = input_data[inrow-1+input_data_offset];
4904            else /* next nearest is row below */
4905                inptr1 = input_data[inrow+1+input_data_offset];
4906            outptr = output_data[outrow++];
4907                
4908            int inptr0_offset = 0, inptr1_offset = 0, outptr_offset = 0;
4909
4910            /* Special case for first column */
4911            thiscolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF);
4912            nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF);
4913            outptr[outptr_offset++] = (byte) ((thiscolsum * 4 + 8) >> 4);
4914            outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
4915            lastcolsum = thiscolsum; thiscolsum = nextcolsum;
4916
4917            for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) {
4918                /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
4919                /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
4920                nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF);
4921                outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
4922                outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
4923                lastcolsum = thiscolsum; thiscolsum = nextcolsum;
4924            }
4925
4926            /* Special case for last column */
4927            outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
4928            outptr[outptr_offset++] = (byte) ((thiscolsum * 4 + 7) >> 4);
4929        }
4930        inrow++;
4931    }
4932}
4933    
4934static void int_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4935     byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4936{
4937    jpeg_upsampler upsample = cinfo.upsample;
4938    byte[][] output_data = output_data_ptr[output_data_index];
4939    byte[] inptr, outptr;
4940    byte invalue;
4941    int h;
4942    int outend;
4943    int h_expand, v_expand;
4944    int inrow, outrow;
4945    output_data_offset[output_data_index] = 0;
4946        
4947    h_expand = upsample.h_expand[compptr.component_index];
4948    v_expand = upsample.v_expand[compptr.component_index];
4949
4950    inrow = outrow = 0;
4951    while (outrow < cinfo.max_v_samp_factor) {
4952        /* Generate one output row with proper horizontal expansion */
4953        inptr = input_data[inrow+input_data_offset];
4954        int inptr_offset = 0;
4955        outptr = output_data[outrow];
4956        int outptr_offset = 0;
4957        outend = outptr_offset + cinfo.output_width;
4958        while (outptr_offset < outend) {
4959            invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */
4960            for (h = h_expand; h > 0; h--) {
4961                outptr[outptr_offset++] = invalue;
4962            }
4963        }
4964        /* Generate any additional output rows by duplicating the first one */
4965        if (v_expand > 1) {
4966            jcopy_sample_rows(output_data, outrow, output_data, outrow+1, v_expand-1, cinfo.output_width);
4967        }
4968        inrow++;
4969        outrow += v_expand;
4970    }
4971}
4972
4973static void null_convert (jpeg_decompress_struct cinfo,
4974    byte[][][] input_buf, int[] input_buf_offset, int input_row,
4975    byte[][] output_buf, int output_buf_offset, int num_rows)
4976{
4977    byte[] inptr, outptr;
4978    int count;
4979    int num_components = cinfo.num_components;
4980    int num_cols = cinfo.output_width;
4981    int ci;
4982
4983    while (--num_rows >= 0) {
4984        for (ci = 0; ci < num_components; ci++) {
4985            inptr = input_buf[ci][input_row+input_buf_offset[0]];
4986            outptr = output_buf[output_buf_offset];
4987            /* BGR instead of RGB */
4988            int offset = 0;
4989            switch (ci) {
4990                case 2: offset = RGB_BLUE; break;
4991                case 1: offset = RGB_GREEN; break;
4992                case 0: offset = RGB_RED; break;
4993            }
4994            int outptr_offset = offset, inptr_offset = 0;
4995            for (count = num_cols; count > 0; count--) {
4996                outptr[outptr_offset] = inptr[inptr_offset++]; /* needn't bother with GETJSAMPLE() here */
4997                outptr_offset += num_components;
4998            }
4999        }
5000        input_row++;
5001        output_buf_offset++;
5002    }
5003}
5004    
5005static void grayscale_convert (jpeg_decompress_struct cinfo,
5006    byte[][][] input_buf, int[] input_buf_offset, int input_row,
5007    byte[][] output_buf, int output_buf_offset, int num_rows)
5008{
5009  jcopy_sample_rows(input_buf[0], input_row+input_buf_offset[0], output_buf, output_buf_offset,
5010            num_rows, cinfo.output_width);
5011}
5012
5013static void gray_rgb_convert (jpeg_decompress_struct cinfo,
5014    byte[][][] input_buf, int[] input_buf_offset, int input_row,
5015    byte[][] output_buf, int output_buf_offset, int num_rows)
5016{
5017    byte[] inptr, outptr;
5018    int col;
5019    int num_cols = cinfo.output_width;
5020
5021    while (--num_rows >= 0) {
5022        inptr = input_buf[0][input_row+++input_buf_offset[0]];
5023        outptr = output_buf[output_buf_offset++];
5024        int outptr_offset = 0;
5025        for (col = 0; col < num_cols; col++) {
5026            /* We can dispense with GETJSAMPLE() here */
5027            outptr[RGB_RED+outptr_offset] = outptr[RGB_GREEN+outptr_offset] = outptr[RGB_BLUE+outptr_offset] = inptr[col];
5028            outptr_offset += RGB_PIXELSIZE;
5029        }
5030    }
5031}
5032    
5033static void ycc_rgb_convert (jpeg_decompress_struct cinfo,
5034    byte[][][] input_buf, int[] input_buf_offset, int input_row,
5035    byte[][] output_buf, int output_buf_offset, int num_rows)
5036{
5037    jpeg_color_deconverter cconvert = cinfo.cconvert;
5038    int y, cb, cr;
5039    byte[] outptr;
5040    byte[] inptr0, inptr1, inptr2;
5041    int col;
5042    int num_cols = cinfo.output_width;
5043    /* copy these pointers into registers if possible */
5044    byte[] range_limit = cinfo.sample_range_limit;
5045    int range_limit_offset = cinfo.sample_range_limit_offset;
5046    int[] Crrtab = cconvert.Cr_r_tab;
5047    int[] Cbbtab = cconvert.Cb_b_tab;
5048    int[] Crgtab = cconvert.Cr_g_tab;
5049    int[] Cbgtab = cconvert.Cb_g_tab;
5050// SHIFT_TEMPS
5051

5052    while (--num_rows >= 0) {
5053        inptr0 = input_buf[0][input_row+input_buf_offset[0]];
5054        inptr1 = input_buf[1][input_row+input_buf_offset[1]];
5055        inptr2 = input_buf[2][input_row+input_buf_offset[2]];
5056        input_row++;
5057        outptr = output_buf[output_buf_offset++];
5058        int outptr_offset = 0;
5059        for (col = 0; col < num_cols; col++) {
5060            y = (inptr0[col] & 0xFF);
5061            cb = (inptr1[col] & 0xFF);
5062            cr = (inptr2[col] & 0xFF);
5063            /* Range-limiting is essential due to noise introduced by DCT losses. */
5064            outptr[outptr_offset + RGB_RED] = range_limit[y + Crrtab[cr] + range_limit_offset];
5065            outptr[outptr_offset + RGB_GREEN] = range_limit[y + ((Cbgtab[cb] + Crgtab[cr]>>SCALEBITS)) + range_limit_offset];
5066            outptr[outptr_offset + RGB_BLUE] = range_limit[y + Cbbtab[cb] + range_limit_offset];
5067            outptr_offset += RGB_PIXELSIZE;
5068        }
5069    }
5070}
5071
5072static boolean process_APPn(int n, jpeg_decompress_struct cinfo) {
5073    if (n == 0 || n == 14) {
5074        return get_interesting_appn(cinfo);
5075    }
5076    return skip_variable(cinfo);
5077}
5078
5079static boolean process_COM(jpeg_decompress_struct cinfo) {
5080    return skip_variable(cinfo);
5081}
5082
5083static void skip_input_data (jpeg_decompress_struct cinfo, int num_bytes) {
5084    if (num_bytes > 0) {
5085        while (num_bytes > cinfo.bytes_in_buffer - cinfo.bytes_offset) {
5086            num_bytes -= cinfo.bytes_in_buffer - cinfo.bytes_offset;
5087            if (!fill_input_buffer(cinfo)) error();
5088            /* note we assume that fill_input_buffer will never return FALSE,
5089             * so suspension need not be handled.
5090             */

5091        }
5092        cinfo.bytes_offset += num_bytes;
5093    }
5094}
5095
5096static boolean skip_variable (jpeg_decompress_struct cinfo)
5097/* Skip over an unknown or uninteresting variable-length marker */
5098{
5099    int length;
5100
5101    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5102    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
5103    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5104    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5105
5106    length -= 2;
5107    
5108// TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo.unread_marker, (int) length);
5109

5110    if (length > 0) {
5111        skip_input_data (cinfo, length);
5112    }
5113    
5114    return true;
5115}
5116
5117static boolean get_interesting_appn (jpeg_decompress_struct cinfo)
5118/* Process an APP0 or APP14 marker without saving it */
5119{
5120    int length;
5121    byte[] b = new byte[APPN_DATA_LEN];
5122    int i, numtoread;
5123
5124    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5125    length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
5126    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5127    length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5128    length -= 2;
5129
5130    /* get the interesting part of the marker data */
5131    if (length >= APPN_DATA_LEN)
5132        numtoread = APPN_DATA_LEN;
5133    else if (length > 0)
5134        numtoread = length;
5135    else
5136        numtoread = 0;
5137    for (i = 0; i < numtoread; i++) {
5138        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5139        b[i] = cinfo.buffer[cinfo.bytes_offset++];
5140    }
5141    length -= numtoread;
5142
5143    /* process it */
5144    switch (cinfo.unread_marker) {
5145        case M_APP0:
5146            examine_app0(cinfo, b, numtoread, length);
5147            break;
5148        case M_APP14:
5149            examine_app14(cinfo, b, numtoread, length);
5150            break;
5151        default:
5152            /* can't get here unless jpeg_save_markers chooses wrong processor */
5153            error();
5154// ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker);
5155
break;
5156    }
5157
5158    /* skip any remaining data -- could be lots */
5159    if (length > 0)
5160        skip_input_data (cinfo, length);
5161
5162    return true;
5163}
5164
5165static void examine_app0 (jpeg_decompress_struct cinfo, byte[] data, int datalen, int remaining)
5166/* Examine first few bytes from an APP0.
5167 * Take appropriate action if it is a JFIF marker.
5168 * datalen is # of bytes at data[], remaining is length of rest of marker data.
5169 */

5170{
5171    int totallen = datalen + remaining;
5172
5173    if (datalen >= APP0_DATA_LEN &&
5174            (data[0] & 0xFF) == 0x4A &&
5175            (data[1] & 0xFF) == 0x46 &&
5176            (data[2] & 0xFF) == 0x49 &&
5177            (data[3] & 0xFF) == 0x46 &&
5178            (data[4] & 0xFF) == 0)
5179    {
5180        /* Found JFIF APP0 marker: save info */
5181        cinfo.saw_JFIF_marker = true;
5182        cinfo.JFIF_major_version = (data[5]);
5183        cinfo.JFIF_minor_version = (byte)(data[6] & 0xFF);
5184        cinfo.density_unit = (byte)(data[7] & 0xFF);
5185        cinfo.X_density = (short)(((data[8] & 0xFF) << 8) + (data[9] & 0xFF));
5186        cinfo.Y_density = (short)(((data[10] & 0xFF) << 8) + (data[11] & 0xFF));
5187        /* Check version.
5188         * Major version must be 1, anything else signals an incompatible change.
5189         * (We used to treat this as an error, but now it's a nonfatal warning,
5190         * because some bozo at Hijaak couldn't read the spec.)
5191         * Minor version should be 0..2, but process anyway if newer.
5192         */

5193        if (cinfo.JFIF_major_version != 1) {
5194// WARNMS2(cinfo, JWRN_JFIF_MAJOR,
5195
// cinfo.JFIF_major_version, cinfo.JFIF_minor_version);
5196
}
5197        /* Generate trace messages */
5198// TRACEMS5(cinfo, 1, JTRC_JFIF,
5199
// cinfo.JFIF_major_version, cinfo.JFIF_minor_version,
5200
// cinfo.X_density, cinfo.Y_density, cinfo.density_unit);
5201
/* Validate thumbnail dimensions and issue appropriate messages */
5202        if (((data[12] & 0xFF) | (data[13]) & 0xFF) != 0) {
5203// TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
5204
// GETJOCTET(data[12]), GETJOCTET(data[13]));
5205
}
5206        totallen -= APP0_DATA_LEN;
5207        if (totallen != ((data[12] & 0xFF) * (data[13] & 0xFF) * 3)) {
5208// TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
5209
}
5210    } else if (datalen >= 6 &&
5211            (data[0] & 0xFF) == 0x4A &&
5212            (data[1] & 0xFF) == 0x46 &&
5213            (data[2] & 0xFF) == 0x58 &&
5214            (data[3] & 0xFF) == 0x58 &&
5215            (data[4] & 0xFF) == 0)
5216    {
5217        /* Found JFIF "JFXX" extension APP0 marker */
5218        /* The library doesn't actually do anything with these,
5219         * but we try to produce a helpful trace message.
5220         */

5221        switch ((data[5]) & 0xFF) {
5222            case 0x10:
5223// TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
5224
break;
5225            case 0x11:
5226// TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
5227
break;
5228            case 0x13:
5229// TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
5230
break;
5231            default:
5232// TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, GETJOCTET(data[5]), (int) totallen);
5233
break;
5234        }
5235    } else {
5236        /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
5237// TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
5238
}
5239}
5240
5241static void examine_app14 (jpeg_decompress_struct cinfo, byte[] data, int datalen, int remaining)
5242/* Examine first few bytes from an APP14.
5243 * Take appropriate action if it is an Adobe marker.
5244 * datalen is # of bytes at data[], remaining is length of rest of marker data.
5245 */

5246{
5247    int /*version, flags0, flags1, */transform;
5248
5249    if (datalen >= APP14_DATA_LEN &&
5250            (data[0] & 0xFF) == 0x41 &&
5251            (data[1] & 0xFF) == 0x64 &&
5252            (data[2] & 0xFF) == 0x6F &&
5253            (data[3] & 0xFF) == 0x62 &&
5254            (data[4] & 0xFF) == 0x65)
5255    {
5256        /* Found Adobe APP14 marker */
5257// version = ((data[5] & 0xFF) << 8) + (data[6] & 0xFF);
5258
// flags0 = ((data[7] & 0xFF) << 8) + (data[8] & 0xFF);
5259
// flags1 = ((data[9] & 0xFF) << 8) + (data[10] & 0xFF);
5260
transform = (data[11] & 0xFF);
5261// TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
5262
cinfo.saw_Adobe_marker = true;
5263        cinfo.Adobe_transform = (byte) transform;
5264    } else {
5265        /* Start of APP14 does not match "Adobe", or too short */
5266// TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
5267
}
5268}
5269
5270static boolean get_soi (jpeg_decompress_struct cinfo) /* Process an SOI marker */ {
5271    int i;
5272    
5273// TRACEMS(cinfo, 1, JTRC_SOI);
5274

5275    if (cinfo.marker.saw_SOI)
5276        error();
5277// ERREXIT(cinfo, JERR_SOI_DUPLICATE);
5278

5279    /* Reset all parameters that are defined to be reset by SOI */
5280
5281    for (i = 0; i < NUM_ARITH_TBLS; i++) {
5282        cinfo.arith_dc_L[i] = 0;
5283        cinfo.arith_dc_U[i] = 1;
5284        cinfo.arith_ac_K[i] = 5;
5285    }
5286    cinfo.restart_interval = 0;
5287
5288    /* Set initial assumptions for colorspace etc */
5289
5290    cinfo.jpeg_color_space = JCS_UNKNOWN;
5291    cinfo.CCIR601_sampling = false; /* Assume non-CCIR sampling??? */
5292
5293    cinfo.saw_JFIF_marker = false;
5294    cinfo.JFIF_major_version = 1; /* set default JFIF APP0 values */
5295    cinfo.JFIF_minor_version = 1;
5296    cinfo.density_unit = 0;
5297    cinfo.X_density = 1;
5298    cinfo.Y_density = 1;
5299    cinfo.saw_Adobe_marker = false;
5300    cinfo.Adobe_transform = 0;
5301
5302    cinfo.marker.saw_SOI = true;
5303
5304    return true;
5305}
5306
5307static void jinit_input_controller (jpeg_decompress_struct cinfo)
5308{
5309    /* Initialize state: can't use reset_input_controller since we don't
5310     * want to try to reset other modules yet.
5311     */

5312    jpeg_input_controller inputctl = cinfo.inputctl = new jpeg_input_controller();
5313    inputctl.has_multiple_scans = false; /* "unknown" would be better */
5314    inputctl.eoi_reached = false;
5315    inputctl.inheaders = true;
5316}
5317
5318static void reset_marker_reader (jpeg_decompress_struct cinfo) {
5319    jpeg_marker_reader marker = cinfo.marker;
5320
5321    cinfo.comp_info = null; /* until allocated by get_sof */
5322    cinfo.input_scan_number = 0; /* no SOS seen yet */
5323    cinfo.unread_marker = 0; /* no pending marker */
5324    marker.saw_SOI = false; /* set internal state too */
5325    marker.saw_SOF = false;
5326    marker.discarded_bytes = 0;
5327// marker.cur_marker = null;
5328
}
5329
5330static void reset_input_controller (jpeg_decompress_struct cinfo) {
5331    jpeg_input_controller inputctl = cinfo.inputctl;
5332
5333    inputctl.has_multiple_scans = false; /* "unknown" would be better */
5334    inputctl.eoi_reached = false;
5335    inputctl.inheaders = true;
5336    /* Reset other modules */
5337    reset_marker_reader (cinfo);
5338    /* Reset progression state -- would be cleaner if entropy decoder did this */
5339    cinfo.coef_bits = null;
5340}
5341
5342static void finish_output_pass (jpeg_decompress_struct cinfo) {
5343    jpeg_decomp_master master = cinfo.master;
5344
5345    if (cinfo.quantize_colors) {
5346        error(SWT.ERROR_NOT_IMPLEMENTED);
5347// (*cinfo.cquantize.finish_pass) (cinfo);
5348
}
5349    master.pass_number++;
5350}
5351
5352static void jpeg_destroy (jpeg_decompress_struct cinfo) {
5353    /* We need only tell the memory manager to release everything. */
5354    /* NB: mem pointer is NULL if memory mgr failed to initialize. */
5355// if (cinfo.mem != NULL)
5356
// (*cinfo.mem.self_destruct) (cinfo);
5357
// cinfo.mem = NULL; /* be safe if jpeg_destroy is called twice */
5358
cinfo.global_state = 0; /* mark it destroyed */
5359}
5360
5361static void jpeg_destroy_decompress (jpeg_decompress_struct cinfo) {
5362    jpeg_destroy(cinfo); /* use common routine */
5363}
5364
5365static boolean jpeg_input_complete (jpeg_decompress_struct cinfo) {
5366    /* Check for valid jpeg object */
5367    if (cinfo.global_state < DSTATE_START || cinfo.global_state > DSTATE_STOPPING)
5368        error();
5369// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5370
return cinfo.inputctl.eoi_reached;
5371}
5372
5373static boolean jpeg_start_output (jpeg_decompress_struct cinfo, int scan_number) {
5374    if (cinfo.global_state != DSTATE_BUFIMAGE && cinfo.global_state != DSTATE_PRESCAN)
5375        error();
5376// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5377
/* Limit scan number to valid range */
5378    if (scan_number <= 0)
5379        scan_number = 1;
5380    if (cinfo.inputctl.eoi_reached && scan_number > cinfo.input_scan_number)
5381        scan_number = cinfo.input_scan_number;
5382    cinfo.output_scan_number = scan_number;
5383    /* Perform any dummy output passes, and set up for the real pass */
5384    return output_pass_setup(cinfo);
5385}
5386
5387static boolean jpeg_finish_output (jpeg_decompress_struct cinfo) {
5388    if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && cinfo.buffered_image) {
5389        /* Terminate this pass. */
5390        /* We do not require the whole pass to have been completed. */
5391        finish_output_pass (cinfo);
5392        cinfo.global_state = DSTATE_BUFPOST;
5393    } else if (cinfo.global_state != DSTATE_BUFPOST) {
5394        /* BUFPOST = repeat call after a suspension, anything else is error */
5395        error();
5396// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5397
}
5398    /* Read markers looking for SOS or EOI */
5399    while (cinfo.input_scan_number <= cinfo.output_scan_number && !cinfo.inputctl.eoi_reached) {
5400        if (consume_input (cinfo) == JPEG_SUSPENDED)
5401            return false; /* Suspend, come back later */
5402    }
5403    cinfo.global_state = DSTATE_BUFIMAGE;
5404    return true;
5405}
5406
5407static boolean jpeg_finish_decompress (jpeg_decompress_struct cinfo) {
5408    if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && ! cinfo.buffered_image) {
5409        /* Terminate final pass of non-buffered mode */
5410        if (cinfo.output_scanline < cinfo.output_height)
5411            error();
5412// ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
5413
finish_output_pass (cinfo);
5414        cinfo.global_state = DSTATE_STOPPING;
5415    } else if (cinfo.global_state == DSTATE_BUFIMAGE) {
5416        /* Finishing after a buffered-image operation */
5417        cinfo.global_state = DSTATE_STOPPING;
5418    } else if (cinfo.global_state != DSTATE_STOPPING) {
5419        /* STOPPING = repeat call after a suspension, anything else is error */
5420        error();
5421// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5422
}
5423    /* Read until EOI */
5424    while (! cinfo.inputctl.eoi_reached) {
5425        if (consume_input (cinfo) == JPEG_SUSPENDED)
5426            return false; /* Suspend, come back later */
5427    }
5428    /* Do final cleanup */
5429// (*cinfo.src.term_source) (cinfo);
5430
/* We can use jpeg_abort to release memory and reset global_state */
5431    jpeg_abort(cinfo);
5432    return true;
5433}
5434
5435
5436static int jpeg_read_header (jpeg_decompress_struct cinfo, boolean require_image) {
5437    int retcode;
5438
5439    if (cinfo.global_state != DSTATE_START && cinfo.global_state != DSTATE_INHEADER)
5440        error();
5441// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5442

5443    retcode = jpeg_consume_input(cinfo);
5444
5445    switch (retcode) {
5446        case JPEG_REACHED_SOS:
5447            retcode = JPEG_HEADER_OK;
5448            break;
5449        case JPEG_REACHED_EOI:
5450            if (require_image) /* Complain if application wanted an image */
5451                error();
5452// ERREXIT(cinfo, JERR_NO_IMAGE);
5453
/* Reset to start state; it would be safer to require the application to
5454             * call jpeg_abort, but we can't change it now for compatibility reasons.
5455             * A side effect is to free any temporary memory (there shouldn't be any).
5456             */

5457            jpeg_abort(cinfo); /* sets state = DSTATE_START */
5458            retcode = JPEG_HEADER_TABLES_ONLY;
5459            break;
5460        case JPEG_SUSPENDED:
5461            /* no work */
5462            break;
5463    }
5464
5465    return retcode;
5466}
5467
5468static int dummy_consume_data (jpeg_decompress_struct cinfo) {
5469    return JPEG_SUSPENDED; /* Always indicate nothing was done */
5470}
5471
5472static int consume_data (jpeg_decompress_struct cinfo) {
5473    jpeg_d_coef_controller coef = cinfo.coef;
5474    int MCU_col_num; /* index of current MCU within row */
5475    int blkn, ci, xindex, yindex, yoffset;
5476    int start_col;
5477// short[][][][] buffer = new short[MAX_COMPS_IN_SCAN][][][];
5478
short[][] buffer_ptr;
5479    jpeg_component_info compptr;
5480
5481// /* Align the virtual buffers for the components used in this scan. */
5482
// for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5483
// compptr = cinfo.cur_comp_info[ci];
5484
// buffer[ci] = coef.whole_image[compptr.component_index];
5485
// /* Note: entropy decoder expects buffer to be zeroed,
5486
// * but this is handled automatically by the memory manager
5487
// * because we requested a pre-zeroed array.
5488
// */
5489
// }
5490

5491    /* Loop to process one whole iMCU row */
5492    for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) {
5493        for (MCU_col_num = coef.MCU_ctr; MCU_col_num < cinfo.MCUs_per_row; MCU_col_num++) {
5494            /* Construct list of pointers to DCT blocks belonging to this MCU */
5495            blkn = 0; /* index of current DCT block within MCU */
5496            for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5497                compptr = cinfo.cur_comp_info[ci];
5498                start_col = MCU_col_num * compptr.MCU_width;
5499                for (yindex = 0; yindex < compptr.MCU_height; yindex++) {
5500// buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
5501
buffer_ptr = coef.whole_image[compptr.component_index][yindex+yoffset+cinfo.input_iMCU_row*compptr.v_samp_factor];
5502                    int buffer_ptr_offset = start_col;
5503                    for (xindex = 0; xindex < compptr.MCU_width; xindex++) {
5504                        coef.MCU_buffer[blkn++] = buffer_ptr[buffer_ptr_offset++];
5505                    }
5506                }
5507            }
5508            /* Try to fetch the MCU. */
5509            if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) {
5510                /* Suspension forced; update state counters and exit */
5511                coef.MCU_vert_offset = yoffset;
5512                coef.MCU_ctr = MCU_col_num;
5513                return JPEG_SUSPENDED;
5514            }
5515        }
5516        /* Completed an MCU row, but perhaps not an iMCU row */
5517        coef.MCU_ctr = 0;
5518    }
5519    /* Completed the iMCU row, advance counters for next one */
5520    if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) {
5521        coef.start_iMCU_row(cinfo);
5522        return JPEG_ROW_COMPLETED;
5523    }
5524    /* Completed the scan */
5525    finish_input_pass (cinfo);
5526    return JPEG_SCAN_COMPLETED;
5527}
5528
5529static int consume_input (jpeg_decompress_struct cinfo) {
5530    switch (cinfo.inputctl.consume_input) {
5531        case COEF_CONSUME_INPUT:
5532             switch (cinfo.coef.consume_data) {
5533                case CONSUME_DATA: return consume_data(cinfo);
5534                case DUMMY_CONSUME_DATA: return dummy_consume_data(cinfo);
5535                default: error();
5536             }
5537             break;
5538        case INPUT_CONSUME_INPUT:
5539            return consume_markers(cinfo);
5540        default:
5541            error();
5542    }
5543    return 0;
5544}
5545
5546static boolean fill_input_buffer(jpeg_decompress_struct cinfo) {
5547    try {
5548        InputStream inputStream = cinfo.inputStream;
5549        int nbytes = inputStream.read(cinfo.buffer);
5550        if (nbytes <= 0) {
5551            if (cinfo.start_of_file) /* Treat empty input file as fatal error */
5552                error();
5553// ERREXIT(cinfo, JERR_INPUT_EMPTY);
5554
// WARNMS(cinfo, JWRN_JPEG_EOF);
5555
/* Insert a fake EOI marker */
5556            cinfo.buffer[0] = (byte)0xFF;
5557            cinfo.buffer[1] = (byte)M_EOI;
5558            nbytes = 2;
5559        }
5560        cinfo.bytes_in_buffer = nbytes;
5561        cinfo.bytes_offset = 0;
5562        cinfo.start_of_file = false;
5563    } catch (IOException e) {
5564        error(SWT.ERROR_IO);
5565        return false;
5566    }
5567    return true;
5568}
5569
5570static boolean first_marker (jpeg_decompress_struct cinfo) {
5571    /* Like next_marker, but used to obtain the initial SOI marker. */
5572    /* For this marker, we do not allow preceding garbage or fill; otherwise,
5573     * we might well scan an entire input file before realizing it ain't JPEG.
5574     * If an application wants to process non-JFIF files, it must seek to the
5575     * SOI before calling the JPEG library.
5576     */

5577    int c, c2;
5578
5579    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5580    c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5581    if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5582    c2 = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5583    if (c != 0xFF || c2 != M_SOI)
5584        error();
5585// ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
5586

5587    cinfo.unread_marker = c2;
5588
5589    return true;
5590}
5591
5592static boolean next_marker (jpeg_decompress_struct cinfo) {
5593    int c;
5594
5595    for (;;) {
5596        if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5597        c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5598        /* Skip any non-FF bytes.
5599         * This may look a bit inefficient, but it will not occur in a valid file.
5600         * We sync after each discarded byte so that a suspending data source
5601         * can discard the byte from its buffer.
5602         */

5603        while (c != 0xFF) {
5604            cinfo.marker.discarded_bytes++;
5605            if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5606            c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5607        }
5608        /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
5609         * pad bytes, so don't count them in discarded_bytes. We assume there
5610         * will not be so many consecutive FF bytes as to overflow a suspending
5611         * data source's input buffer.
5612         */

5613        do {
5614             if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5615                c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5616        } while (c == 0xFF);
5617        if (c != 0)
5618            break; /* found a valid marker, exit loop */
5619        /* Reach here if we found a stuffed-zero data sequence (FF/00).
5620         * Discard it and loop back to try again.
5621         */

5622        cinfo.marker.discarded_bytes += 2;
5623    }
5624
5625    if (cinfo.marker.discarded_bytes != 0) {
5626// WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo.marker.discarded_bytes, c);
5627
cinfo.marker.discarded_bytes = 0;
5628    }
5629
5630    cinfo.unread_marker = c;
5631
5632    return true;
5633}
5634
5635static int read_markers (jpeg_decompress_struct cinfo) {
5636    /* Outer loop repeats once for each marker. */
5637    for (;;) {
5638        /* Collect the marker proper, unless we already did. */
5639        /* NB: first_marker() enforces the requirement that SOI appear first. */
5640        if (cinfo.unread_marker == 0) {
5641            if (! cinfo.marker.saw_SOI) {
5642                if (! first_marker(cinfo))
5643                    return JPEG_SUSPENDED;
5644                } else {
5645                    if (! next_marker(cinfo))
5646                        return JPEG_SUSPENDED;
5647                }
5648        }
5649        /* At this point cinfo.unread_marker contains the marker code and the
5650         * input point is just past the marker proper, but before any parameters.
5651         * A suspension will cause us to return with this state still true.
5652         */

5653        switch (cinfo.unread_marker) {
5654            case M_SOI:
5655                if (! get_soi(cinfo))
5656                    return JPEG_SUSPENDED;
5657                break;
5658
5659            case M_SOF0: /* Baseline */
5660            case M_SOF1: /* Extended sequential, Huffman */
5661                if (! get_sof(cinfo, false, false))
5662                    return JPEG_SUSPENDED;
5663                break;
5664
5665            case M_SOF2: /* Progressive, Huffman */
5666                if (! get_sof(cinfo, true, false))
5667                    return JPEG_SUSPENDED;
5668                break;
5669
5670            case M_SOF9: /* Extended sequential, arithmetic */
5671                if (! get_sof(cinfo, false, true))
5672                    return JPEG_SUSPENDED;
5673                break;
5674
5675            case M_SOF10: /* Progressive, arithmetic */
5676                if (! get_sof(cinfo, true, true))
5677                    return JPEG_SUSPENDED;
5678                break;
5679
5680            /* Currently unsupported SOFn types */
5681            case M_SOF3: /* Lossless, Huffman */
5682            case M_SOF5: /* Differential sequential, Huffman */
5683            case M_SOF6: /* Differential progressive, Huffman */
5684            case M_SOF7: /* Differential lossless, Huffman */
5685            case M_JPG: /* Reserved for JPEG extensions */
5686            case M_SOF11: /* Lossless, arithmetic */
5687            case M_SOF13: /* Differential sequential, arithmetic */
5688            case M_SOF14: /* Differential progressive, arithmetic */
5689            case M_SOF15: /* Differential lossless, arithmetic */
5690                error();
5691// ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo.unread_marker);
5692
break;
5693
5694            case M_SOS:
5695                if (! get_sos(cinfo))
5696                    return JPEG_SUSPENDED;
5697                cinfo.unread_marker = 0; /* processed the marker */
5698                return JPEG_REACHED_SOS;
5699    
5700            case M_EOI:
5701// TRACEMS(cinfo, 1, JTRC_EOI);
5702
cinfo.unread_marker = 0; /* processed the marker */
5703                return JPEG_REACHED_EOI;
5704        
5705            case M_DAC:
5706                if (! get_dac(cinfo))
5707                    return JPEG_SUSPENDED;
5708                break;
5709        
5710            case M_DHT:
5711                if (! get_dht(cinfo))
5712                    return JPEG_SUSPENDED;
5713                break;
5714        
5715            case M_DQT:
5716                if (! get_dqt(cinfo))
5717                    return JPEG_SUSPENDED;
5718                break;
5719        
5720            case M_DRI:
5721                if (! get_dri(cinfo))
5722                    return JPEG_SUSPENDED;
5723                break;
5724        
5725            case M_APP0:
5726            case M_APP1:
5727            case M_APP2:
5728            case M_APP3:
5729            case M_APP4:
5730            case M_APP5:
5731            case M_APP6:
5732            case M_APP7:
5733            case M_APP8:
5734            case M_APP9:
5735            case M_APP10:
5736            case M_APP11:
5737            case M_APP12:
5738            case M_APP13:
5739            case M_APP14:
5740            case M_APP15:
5741                if (! process_APPn(cinfo.unread_marker - M_APP0, cinfo))
5742                    return JPEG_SUSPENDED;
5743                break;
5744        
5745            case M_COM:
5746                if (! process_COM(cinfo))
5747                    return JPEG_SUSPENDED;
5748                break;
5749
5750            case M_RST0: /* these are all parameterless */
5751            case M_RST1:
5752            case M_RST2:
5753            case M_RST3:
5754            case M_RST4:
5755            case M_RST5:
5756            case M_RST6:
5757            case M_RST7:
5758            case M_TEM:
5759// TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo.unread_marker);
5760
break;
5761
5762            case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
5763                if (! skip_variable(cinfo))
5764                    return JPEG_SUSPENDED;
5765                break;
5766
5767            default: /* must be DHP, EXP, JPGn, or RESn */
5768                /* For now, we treat the reserved markers as fatal errors since they are
5769                 * likely to be used to signal incompatible JPEG Part 3 extensions.
5770                 * Once the JPEG 3 version-number marker is well defined, this code
5771                 * ought to change!
5772                 */

5773                error();
5774 // ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker);
5775
break;
5776        }
5777        /* Successfully processed marker, so reset state variable */
5778        cinfo.unread_marker = 0;
5779    } /* end loop */
5780}
5781
5782static long jdiv_round_up (long a, long b)
5783/* Compute a/b rounded up to next integer, ie, ceil(a/b) */
5784/* Assumes a >= 0, b > 0 */
5785{
5786    return (a + b - 1) / b;
5787}
5788
5789static void initial_setup (jpeg_decompress_struct cinfo)
5790/* Called once, when first SOS marker is reached */
5791{
5792    int ci;
5793    jpeg_component_info compptr;
5794
5795    /* Make sure image isn't bigger than I can handle */
5796    if (cinfo.image_height > JPEG_MAX_DIMENSION || cinfo.image_width > JPEG_MAX_DIMENSION)
5797        error();
5798// ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
5799

5800    /* For now, precision must match compiled-in value... */
5801    if (cinfo.data_precision != BITS_IN_JSAMPLE)
5802        error(" [data precision=" + cinfo.data_precision + "]");
5803// ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo.data_precision);
5804

5805    /* Check that number of components won't exceed internal array sizes */
5806    if (cinfo.num_components > MAX_COMPONENTS)
5807        error();
5808// ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.num_components, MAX_COMPONENTS);
5809

5810    /* Compute maximum sampling factors; check factor validity */
5811    cinfo.max_h_samp_factor = 1;
5812    cinfo.max_v_samp_factor = 1;
5813    for (ci = 0; ci < cinfo.num_components; ci++) {
5814        compptr = cinfo.comp_info[ci];
5815        if (compptr.h_samp_factor<=0 || compptr.h_samp_factor>MAX_SAMP_FACTOR || compptr.v_samp_factor<=0 || compptr.v_samp_factor>MAX_SAMP_FACTOR)
5816            error();
5817// ERREXIT(cinfo, JERR_BAD_SAMPLING);
5818
cinfo.max_h_samp_factor = Math.max(cinfo.max_h_samp_factor, compptr.h_samp_factor);
5819        cinfo.max_v_samp_factor = Math.max(cinfo.max_v_samp_factor, compptr.v_samp_factor);
5820    }
5821
5822    /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
5823     * In the full decompressor, this will be overridden by jdmaster.c;
5824     * but in the transcoder, jdmaster.c is not used, so we must do it here.
5825     */

5826    cinfo.min_DCT_scaled_size = DCTSIZE;
5827
5828    /* Compute dimensions of components */
5829    for (ci = 0; ci < cinfo.num_components; ci++) {
5830        compptr = cinfo.comp_info[ci];
5831        compptr.DCT_scaled_size = DCTSIZE;
5832        /* Size in DCT blocks */
5833        compptr.width_in_blocks = (int)jdiv_round_up((long) cinfo.image_width * (long) compptr.h_samp_factor, (cinfo.max_h_samp_factor * DCTSIZE));
5834        compptr.height_in_blocks = (int)jdiv_round_up((long) cinfo.image_height * (long) compptr.v_samp_factor, (cinfo.max_v_samp_factor * DCTSIZE));
5835        /* downsampled_width and downsampled_height will also be overridden by
5836         * jdmaster.c if we are doing full decompression. The transcoder library
5837         * doesn't use these values, but the calling application might.
5838         */

5839        /* Size in samples */
5840        compptr.downsampled_width = (int)jdiv_round_up((long) cinfo.image_width * (long) compptr.h_samp_factor, cinfo.max_h_samp_factor);
5841        compptr.downsampled_height = (int)jdiv_round_up((long) cinfo.image_height * (long) compptr.v_samp_factor, cinfo.max_v_samp_factor);
5842        /* Mark component needed, until color conversion says otherwise */
5843        compptr.component_needed = true;
5844        /* Mark no quantization table yet saved for component */
5845        compptr.quant_table = null;
5846    }
5847
5848    /* Compute number of fully interleaved MCU rows. */
5849    cinfo.total_iMCU_rows = (int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE));
5850
5851    /* Decide whether file contains multiple scans */
5852    if (cinfo.comps_in_scan < cinfo.num_components || cinfo.progressive_mode)
5853        cinfo.inputctl.has_multiple_scans = true;
5854    else
5855        cinfo.inputctl.has_multiple_scans = false;
5856}
5857
5858
5859static void per_scan_setup (jpeg_decompress_struct cinfo)
5860/* Do computations that are needed before processing a JPEG scan */
5861/* cinfo.comps_in_scan and cinfo.cur_comp_info[] were set from SOS marker */
5862{
5863    int ci, mcublks, tmp = 0;
5864    jpeg_component_info compptr;
5865    
5866    if (cinfo.comps_in_scan == 1) {
5867        
5868        /* Noninterleaved (single-component) scan */
5869        compptr = cinfo.cur_comp_info[0];
5870        
5871        /* Overall image size in MCUs */
5872        cinfo.MCUs_per_row = compptr.width_in_blocks;
5873        cinfo.MCU_rows_in_scan = compptr.height_in_blocks;
5874        
5875        /* For noninterleaved scan, always one block per MCU */
5876        compptr.MCU_width = 1;
5877        compptr.MCU_height = 1;
5878        compptr.MCU_blocks = 1;
5879        compptr.MCU_sample_width = compptr.DCT_scaled_size;
5880        compptr.last_col_width = 1;
5881        /* For noninterleaved scans, it is convenient to define last_row_height
5882         * as the number of block rows present in the last iMCU row.
5883         */

5884        tmp = (compptr.height_in_blocks % compptr.v_samp_factor);
5885        if (tmp == 0) tmp = compptr.v_samp_factor;
5886        compptr.last_row_height = tmp;
5887        
5888        /* Prepare array describing MCU composition */
5889        cinfo.blocks_in_MCU = 1;
5890        cinfo.MCU_membership[0] = 0;
5891        
5892    } else {
5893        
5894        /* Interleaved (multi-component) scan */
5895        if (cinfo.comps_in_scan <= 0 || cinfo.comps_in_scan > MAX_COMPS_IN_SCAN)
5896            error();
5897// ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.comps_in_scan, MAX_COMPS_IN_SCAN);
5898

5899        /* Overall image size in MCUs */
5900        cinfo.MCUs_per_row = (int)jdiv_round_up( cinfo.image_width, (cinfo.max_h_samp_factor*DCTSIZE));
5901        cinfo.MCU_rows_in_scan = (int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE));
5902        
5903        cinfo.blocks_in_MCU = 0;
5904        
5905        for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5906            compptr = cinfo.cur_comp_info[ci];
5907            /* Sampling factors give # of blocks of component in each MCU */
5908            compptr.MCU_width = compptr.h_samp_factor;
5909            compptr.MCU_height = compptr.v_samp_factor;
5910            compptr.MCU_blocks = compptr.MCU_width * compptr.MCU_height;
5911            compptr.MCU_sample_width = compptr.MCU_width * compptr.DCT_scaled_size;
5912            /* Figure number of non-dummy blocks in last MCU column & row */
5913            tmp = (compptr.width_in_blocks % compptr.MCU_width);
5914            if (tmp == 0) tmp = compptr.MCU_width;
5915            compptr.last_col_width = tmp;
5916            tmp = (compptr.height_in_blocks % compptr.MCU_height);
5917            if (tmp == 0) tmp = compptr.MCU_height;
5918            compptr.last_row_height = tmp;
5919            /* Prepare array describing MCU composition */
5920            mcublks = compptr.MCU_blocks;
5921            if (cinfo.blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
5922                error();
5923// ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
5924
while (mcublks-- > 0) {
5925                cinfo.MCU_membership[cinfo.blocks_in_MCU++] = ci;
5926            }
5927        }
5928        
5929    }
5930}
5931
5932static void latch_quant_tables (jpeg_decompress_struct cinfo) {
5933    int ci, qtblno;
5934    jpeg_component_info compptr;
5935    JQUANT_TBL qtbl;
5936
5937    for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5938        compptr = cinfo.cur_comp_info[ci];
5939        /* No work if we already saved Q-table for this component */
5940        if (compptr.quant_table != null)
5941            continue;
5942        /* Make sure specified quantization table is present */
5943        qtblno = compptr.quant_tbl_no;
5944        if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo.quant_tbl_ptrs[qtblno] == null)
5945            error();
5946// ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
5947
/* OK, save away the quantization table */
5948        qtbl = new JQUANT_TBL();
5949        System.arraycopy(cinfo.quant_tbl_ptrs[qtblno].quantval, 0, qtbl.quantval, 0, qtbl.quantval.length);
5950        qtbl.sent_table = cinfo.quant_tbl_ptrs[qtblno].sent_table;
5951        compptr.quant_table = qtbl;
5952    }
5953}
5954
5955static void jpeg_make_d_derived_tbl (jpeg_decompress_struct cinfo, boolean isDC, int tblno, d_derived_tbl dtbl) {
5956    JHUFF_TBL htbl;
5957    int p, i = 0, l, si, numsymbols;
5958    int lookbits, ctr;
5959    byte[] huffsize = new byte[257];
5960    int[] huffcode = new int[257];
5961    int code;
5962
5963    /* Note that huffsize[] and huffcode[] are filled in code-length order,
5964     * paralleling the order of the symbols themselves in htbl.huffval[].
5965     */

5966
5967    /* Find the input Huffman table */
5968    if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
5969        error();
5970// ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
5971
htbl = isDC ? cinfo.dc_huff_tbl_ptrs[tblno] : cinfo.ac_huff_tbl_ptrs[tblno];
5972    if (htbl == null)
5973        error();
5974// ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
5975

5976    /* Allocate a workspace if we haven't already done so. */
5977    dtbl.pub = htbl; /* fill in back link */
5978    
5979    /* Figure C.1: make table of Huffman code length for each symbol */
5980
5981    p = 0;
5982    for (l = 1; l <= 16; l++) {
5983        i = htbl.bits[l] & 0xFF;
5984        if (i < 0 || p + i > 256) /* protect against table overrun */
5985            error();
5986// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
5987
while (i-- != 0)
5988            huffsize[p++] = (byte) l;
5989    }
5990    huffsize[p] = 0;
5991    numsymbols = p;
5992    
5993    /* Figure C.2: generate the codes themselves */
5994    /* We also validate that the counts represent a legal Huffman code tree. */
5995    
5996    code = 0;
5997    si = huffsize[0];
5998    p = 0;
5999    while ((huffsize[p]) != 0) {
6000        while (( huffsize[p]) == si) {
6001            huffcode[p++] = code;
6002            code++;
6003        }
6004        /* code is now 1 more than the last code used for codelength si; but
6005         * it must still fit in si bits, since no code is allowed to be all ones.
6006         */

6007        if (( code) >= (( 1) << si))
6008            error();
6009// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
6010
code <<= 1;
6011        si++;
6012    }
6013
6014    /* Figure F.15: generate decoding tables for bit-sequential decoding */
6015
6016    p = 0;
6017    for (l = 1; l <= 16; l++) {
6018        if ((htbl.bits[l] & 0xFF) != 0) {
6019            /* valoffset[l] = huffval[] index of 1st symbol of code length l,
6020             * minus the minimum code of length l
6021             */

6022            dtbl.valoffset[l] = p - huffcode[p];
6023            p += (htbl.bits[l] & 0xFF);
6024            dtbl.maxcode[l] = huffcode[p-1]; /* maximum code of length l */
6025        } else {
6026            dtbl.maxcode[l] = -1; /* -1 if no codes of this length */
6027        }
6028    }
6029    dtbl.maxcode[17] = 0xFFFFF; /* ensures jpeg_huff_decode terminates */
6030
6031    /* Compute lookahead tables to speed up decoding.
6032     * First we set all the table entries to 0, indicating "too long";
6033     * then we iterate through the Huffman codes that are short enough and
6034     * fill in all the entries that correspond to bit sequences starting
6035     * with that code.
6036     */

6037
6038    for (int j = 0; j < dtbl.look_nbits.length; j++) {
6039        dtbl.look_nbits[j] = 0;
6040    }
6041
6042    p = 0;
6043    for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
6044        for (i = 1; i <= (htbl.bits[l] & 0xFF); i++, p++) {
6045            /* l = current code's length, p = its index in huffcode[] & huffval[]. */
6046            /* Generate left-justified code followed by all possible bit sequences */
6047            lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
6048            for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
6049                dtbl.look_nbits[lookbits] = l;
6050                dtbl.look_sym[lookbits] = htbl.huffval[p];
6051                lookbits++;
6052            }
6053        }
6054    }
6055
6056    /* Validate symbols as being reasonable.
6057     * For AC tables, we make no check, but accept all byte values 0..255.
6058     * For DC tables, we require the symbols to be in range 0..15.
6059     * (Tighter bounds could be applied depending on the data depth and mode,
6060     * but this is sufficient to ensure safe decoding.)
6061     */

6062    if (isDC) {
6063        for (i = 0; i < numsymbols; i++) {
6064            int sym = htbl.huffval[i] & 0xFF;
6065            if (sym < 0 || sym > 15)
6066                error();
6067// ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
6068
}
6069    }
6070}
6071
6072static void start_input_pass (jpeg_decompress_struct cinfo) {
6073    per_scan_setup(cinfo);
6074    latch_quant_tables(cinfo);
6075    cinfo.entropy.start_pass(cinfo);
6076    cinfo.coef.start_input_pass (cinfo);
6077    cinfo.inputctl.consume_input = COEF_CONSUME_INPUT;
6078}
6079
6080static void finish_input_pass (jpeg_decompress_struct cinfo) {
6081    cinfo.inputctl.consume_input = INPUT_CONSUME_INPUT;
6082}
6083
6084static int consume_markers (jpeg_decompress_struct cinfo) {
6085    jpeg_input_controller inputctl = cinfo.inputctl;
6086    int val;
6087
6088    if (inputctl.eoi_reached) /* After hitting EOI, read no further */
6089        return JPEG_REACHED_EOI;
6090
6091    val = read_markers (cinfo);
6092
6093    switch (val) {
6094    case JPEG_REACHED_SOS: /* Found SOS */
6095        if (inputctl.inheaders) { /* 1st SOS */
6096            initial_setup(cinfo);
6097            inputctl.inheaders = false;
6098            /* Note: start_input_pass must be called by jdmaster.c
6099             * before any more input can be consumed. jdapimin.c is
6100             * responsible for enforcing this sequencing.
6101             */

6102        } else { /* 2nd or later SOS marker */
6103            if (! inputctl.has_multiple_scans)
6104                error();
6105// ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
6106
start_input_pass(cinfo);
6107        }
6108        break;
6109    case JPEG_REACHED_EOI: /* Found EOI */
6110        inputctl.eoi_reached = true;
6111        if (inputctl.inheaders) { /* Tables-only datastream, apparently */
6112            if (cinfo.marker.saw_SOF)
6113                error();
6114// ERREXIT(cinfo, JERR_SOF_NO_SOS);
6115
} else {
6116            /* Prevent infinite loop in coef ctlr's decompress_data routine
6117             * if user set output_scan_number larger than number of scans.
6118             */

6119            if (cinfo.output_scan_number > cinfo.input_scan_number)
6120                cinfo.output_scan_number = cinfo.input_scan_number;
6121        }
6122        break;
6123    case JPEG_SUSPENDED:
6124        break;
6125    }
6126
6127    return val;
6128}
6129
6130static void default_decompress_parms (jpeg_decompress_struct cinfo) {
6131    /* Guess the input colorspace, and set output colorspace accordingly. */
6132    /* (Wish JPEG committee had provided a real way to specify this...) */
6133    /* Note application may override our guesses. */
6134    switch (cinfo.num_components) {
6135        case 1:
6136            cinfo.jpeg_color_space = JCS_GRAYSCALE;
6137            cinfo.out_color_space = JCS_GRAYSCALE;
6138            break;
6139            
6140        case 3:
6141            if (cinfo.saw_JFIF_marker) {
6142                cinfo.jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
6143            } else if (cinfo.saw_Adobe_marker) {
6144                switch (cinfo.Adobe_transform) {
6145                    case 0:
6146                        cinfo.jpeg_color_space = JCS_RGB;
6147                        break;
6148                    case 1:
6149                        cinfo.jpeg_color_space = JCS_YCbCr;
6150                        break;
6151                    default:
6152// WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform);
6153
cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
6154                    break;
6155                }
6156            } else {
6157                /* Saw no special markers, try to guess from the component IDs */
6158                int cid0 = cinfo.comp_info[0].component_id;
6159                int cid1 = cinfo.comp_info[1].component_id;
6160                int cid2 = cinfo.comp_info[2].component_id;
6161    
6162                if (cid0 == 1 && cid1 == 2 && cid2 == 3)
6163                    cinfo.jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
6164                else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
6165                    cinfo.jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
6166                else {
6167// TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
6168
cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
6169                }
6170            }
6171            /* Always guess RGB is proper output colorspace. */
6172            cinfo.out_color_space = JCS_RGB;
6173            break;
6174            
6175        case 4:
6176            if (cinfo.saw_Adobe_marker) {
6177                switch (cinfo.Adobe_transform) {
6178                    case 0:
6179                        cinfo.jpeg_color_space = JCS_CMYK;
6180                        break;
6181                    case 2:
6182                        cinfo.jpeg_color_space = JCS_YCCK;
6183                        break;
6184                    default:
6185// WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform);
6186
cinfo.jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
6187                        break;
6188                }
6189            } else {
6190                /* No special markers, assume straight CMYK. */
6191                cinfo.jpeg_color_space = JCS_CMYK;
6192            }
6193            cinfo.out_color_space = JCS_CMYK;
6194            break;
6195            
6196        default:
6197            cinfo.jpeg_color_space = JCS_UNKNOWN;
6198            cinfo.out_color_space = JCS_UNKNOWN;
6199            break;
6200    }
6201
6202    /* Set defaults for other decompression parameters. */
6203    cinfo.scale_num = 1; /* 1:1 scaling */
6204    cinfo.scale_denom = 1;
6205    cinfo.output_gamma = 1.0;
6206    cinfo.buffered_image = false;
6207    cinfo.raw_data_out = false;
6208    cinfo.dct_method = JDCT_DEFAULT;
6209    cinfo.do_fancy_upsampling = true;
6210    cinfo.do_block_smoothing = true;
6211    cinfo.quantize_colors = false;
6212    /* We set these in case application only sets quantize_colors. */
6213    cinfo.dither_mode = JDITHER_FS;
6214    cinfo.two_pass_quantize = true;
6215    cinfo.desired_number_of_colors = 256;
6216    cinfo.colormap = null;
6217    /* Initialize for no mode change in buffered-image mode. */
6218    cinfo.enable_1pass_quant = false;
6219    cinfo.enable_external_quant = false;
6220    cinfo.enable_2pass_quant = false;
6221}
6222
6223static void init_source(jpeg_decompress_struct cinfo) {
6224    cinfo.buffer = new byte[INPUT_BUFFER_SIZE];
6225    cinfo.bytes_in_buffer = 0;
6226    cinfo.bytes_offset = 0;
6227    cinfo.start_of_file = true;
6228}
6229
6230static int jpeg_consume_input (jpeg_decompress_struct cinfo) {
6231    int retcode = JPEG_SUSPENDED;
6232
6233    /* NB: every possible DSTATE value should be listed in this switch */
6234    switch (cinfo.global_state) {
6235    case DSTATE_START:
6236        /* Start-of-datastream actions: reset appropriate modules */
6237        reset_input_controller(cinfo);
6238        /* Initialize application's data source module */
6239        init_source (cinfo);
6240        cinfo.global_state = DSTATE_INHEADER;
6241        /*FALLTHROUGH*/
6242    case DSTATE_INHEADER:
6243        retcode = consume_input(cinfo);
6244        if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
6245            /* Set up default parameters based on header data */
6246            default_decompress_parms(cinfo);
6247            /* Set global state: ready for start_decompress */
6248            cinfo.global_state = DSTATE_READY;
6249        }
6250        break;
6251    case DSTATE_READY:
6252        /* Can't advance past first SOS until start_decompress is called */
6253        retcode = JPEG_REACHED_SOS;
6254        break;
6255    case DSTATE_PRELOAD:
6256    case DSTATE_PRESCAN:
6257    case DSTATE_SCANNING:
6258    case DSTATE_RAW_OK:
6259    case DSTATE_BUFIMAGE:
6260    case DSTATE_BUFPOST:
6261    case DSTATE_STOPPING:
6262        retcode = consume_input (cinfo);
6263        break;
6264    default:
6265        error();
6266// ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
6267
}
6268    return retcode;
6269}
6270
6271
6272static void jpeg_abort (jpeg_decompress_struct cinfo) {
6273// int pool;
6274
//
6275
// /* Releasing pools in reverse order might help avoid fragmentation
6276
// * with some (brain-damaged) malloc libraries.
6277
// */
6278
// for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
6279
// (*cinfo.mem.free_pool) (cinfo, pool);
6280
// }
6281

6282    /* Reset overall state for possible reuse of object */
6283    if (cinfo.is_decompressor) {
6284        cinfo.global_state = DSTATE_START;
6285        /* Try to keep application from accessing now-deleted marker list.
6286         * A bit kludgy to do it here, but this is the most central place.
6287         */

6288// ((j_decompress_ptr) cinfo).marker_list = null;
6289
} else {
6290        cinfo.global_state = CSTATE_START;
6291    }
6292}
6293
6294
6295static boolean isFileFormat(LEDataInputStream stream) {
6296    try {
6297        byte[] buffer = new byte[2];
6298        stream.read(buffer);
6299        stream.unread(buffer);
6300        return (buffer[0] & 0xFF) == 0xFF && (buffer[1] & 0xFF) == M_SOI;
6301    } catch (Exception JavaDoc e) {
6302        return false;
6303    }
6304}
6305    
6306static ImageData[] loadFromByteStream(InputStream inputStream, ImageLoader loader) {
6307    jpeg_decompress_struct cinfo = new jpeg_decompress_struct();
6308    cinfo.inputStream = inputStream;
6309    jpeg_create_decompress(cinfo);
6310    jpeg_read_header(cinfo, true);
6311    cinfo.buffered_image = cinfo.progressive_mode && loader.hasListeners();
6312    jpeg_start_decompress(cinfo);
6313    PaletteData palette = null;
6314    switch (cinfo.out_color_space) {
6315        case JCS_RGB:
6316            palette = new PaletteData(0xFF, 0xFF00, 0xFF0000);
6317            break;
6318        case JCS_GRAYSCALE:
6319            RGB[] colors = new RGB[256];
6320            for (int i = 0; i < colors.length; i++) {
6321                colors[i] = new RGB(i, i, i);
6322            }
6323            palette = new PaletteData(colors);
6324            break;
6325        default:
6326            error();
6327    }
6328    int scanlinePad = 4;
6329    int row_stride = (((cinfo.output_width * cinfo.out_color_components * 8 + 7) / 8) + (scanlinePad - 1)) / scanlinePad * scanlinePad;
6330    byte[][] buffer = new byte[1][row_stride];
6331    byte[] data = new byte[row_stride * cinfo.output_height];
6332    ImageData imageData = ImageData.internal_new(
6333            cinfo.output_width, cinfo.output_height, palette.isDirect ? 24 : 8, palette, scanlinePad, data,
6334            0, null, null, -1, -1, SWT.IMAGE_JPEG, 0, 0, 0, 0);
6335    if (cinfo.buffered_image) {
6336        boolean done;
6337        do {
6338            int incrementCount = cinfo.input_scan_number - 1;
6339            jpeg_start_output(cinfo, cinfo.input_scan_number);
6340            while (cinfo.output_scanline < cinfo.output_height) {
6341                int offset = row_stride * cinfo.output_scanline;
6342                jpeg_read_scanlines(cinfo, buffer, 1);
6343                System.arraycopy(buffer[0], 0, data, offset, row_stride);
6344            }
6345            jpeg_finish_output(cinfo);
6346            loader.notifyListeners(new ImageLoaderEvent(loader, (ImageData)imageData.clone(), incrementCount, done = jpeg_input_complete(cinfo)));
6347        } while (!done);
6348    } else {
6349        while (cinfo.output_scanline < cinfo.output_height) {
6350            int offset = row_stride * cinfo.output_scanline;
6351            jpeg_read_scanlines(cinfo, buffer, 1);
6352            System.arraycopy(buffer[0], 0, data, offset, row_stride);
6353        }
6354    }
6355    jpeg_finish_decompress(cinfo);
6356    jpeg_destroy_decompress(cinfo);
6357    return new ImageData[]{imageData};
6358}
6359
6360}
6361
Popular Tags