1 /*******************************************************************************
2 * Copyright (c) 2000, 2009 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
2258 static void error() {
2259 SWT.error(SWT.ERROR_INVALID_IMAGE);
2260 }
2261
2262 static void error(int code) {
2263 SWT.error(code);
2264 }
2265
2266 static void error(String msg) {
2267 SWT.error(SWT.ERROR_INVALID_IMAGE, null, msg);
2268 }
2269
2270 static 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
2290 static 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
2335 static 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
2350 static 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
2367 static 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 case JCS_YCbCr:
2460 cinfo.out_color_components = 3;
2461 break;
2462 case JCS_CMYK:
2463 case JCS_YCCK:
2464 cinfo.out_color_components = 4;
2465 break;
2466 default: /* else must be same colorspace as in file */
2467 cinfo.out_color_components = cinfo.num_components;
2468 break;
2469 }
2470 cinfo.output_components = (cinfo.quantize_colors ? 1 : cinfo.out_color_components);
2471
2472 /* See if upsampler will want to emit more than one row at a time */
2473 if (use_merged_upsample(cinfo))
2474 cinfo.rec_outbuf_height = cinfo.max_v_samp_factor;
2475 else
2476 cinfo.rec_outbuf_height = 1;
2477 }
2478
2479 static boolean use_merged_upsample (jpeg_decompress_struct cinfo) {
2480 //#ifdef UPSAMPLE_MERGING_SUPPORTED
2481 /* Merging is the equivalent of plain box-filter upsampling */
2482 if (cinfo.do_fancy_upsampling || cinfo.CCIR601_sampling)
2483 return false;
2484 /* jdmerge.c only supports YCC=>RGB color conversion */
2485 if (cinfo.jpeg_color_space != JCS_YCbCr || cinfo.num_components != 3 ||
2486 cinfo.out_color_space != JCS_RGB ||
2487 cinfo.out_color_components != RGB_PIXELSIZE)
2488 return false;
2489 /* and it only handles 2h1v or 2h2v sampling ratios */
2490 if (cinfo.comp_info[0].h_samp_factor != 2 ||
2491 cinfo.comp_info[1].h_samp_factor != 1 ||
2492 cinfo.comp_info[2].h_samp_factor != 1 ||
2493 cinfo.comp_info[0].v_samp_factor > 2 ||
2494 cinfo.comp_info[1].v_samp_factor != 1 ||
2495 cinfo.comp_info[2].v_samp_factor != 1)
2496 return false;
2497 /* furthermore, it doesn't work if we've scaled the IDCTs differently */
2498 if (cinfo.comp_info[0].DCT_scaled_size != cinfo.min_DCT_scaled_size ||
2499 cinfo.comp_info[1].DCT_scaled_size != cinfo.min_DCT_scaled_size ||
2500 cinfo.comp_info[2].DCT_scaled_size != cinfo.min_DCT_scaled_size)
2501 return false;
2502 /* ??? also need to test for upsample-time rescaling, when & if supported */
2503 return true; /* by golly, it'll work... */
2504 //#else
2505 // return false;
2506 //#endif
2507 }
2508
2509 static void prepare_range_limit_table (jpeg_decompress_struct cinfo)
2510 /* Allocate and fill in the sample_range_limit table */
2511 {
2512 byte[] table;
2513 int i;
2514
2515 table = new byte[5 * (MAXJSAMPLE+1) + CENTERJSAMPLE];
2516 int offset = (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
2517 cinfo.sample_range_limit_offset = offset;
2518 cinfo.sample_range_limit = table;
2519 /* First segment of "simple" table: limit[x] = 0 for x < 0 */
2520 /* Main part of "simple" table: limit[x] = x */
2521 for (i = 0; i <= MAXJSAMPLE; i++)
2522 table[i + offset] = (byte)i;
2523 offset += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
2524 /* End of simple table, rest of first half of post-IDCT table */
2525 for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
2526 table[i+offset] = (byte)MAXJSAMPLE;
2527 /* Second half of post-IDCT table */
2528 System.arraycopy(cinfo.sample_range_limit, cinfo.sample_range_limit_offset, table, offset + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE), CENTERJSAMPLE);
2529 }
2530
2531 static void build_ycc_rgb_table (jpeg_decompress_struct cinfo) {
2532 jpeg_color_deconverter cconvert = cinfo.cconvert;
2533 int i;
2534 int x;
2535 // SHIFT_TEMPS
2536
2537 cconvert.Cr_r_tab = new int[MAXJSAMPLE+1];
2538 cconvert.Cb_b_tab = new int[MAXJSAMPLE+1];
2539 cconvert.Cr_g_tab = new int[MAXJSAMPLE+1];
2540 cconvert.Cb_g_tab = new int[MAXJSAMPLE+1];
2541
2542 for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
2543 /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
2544 /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
2545 /* Cr=>R value is nearest int to 1.40200 * x */
2546 cconvert.Cr_r_tab[i] = ((int)(1.40200f * (1<<SCALEBITS) + 0.5f) * x + ONE_HALF) >> SCALEBITS;
2547 /* Cb=>B value is nearest int to 1.77200 * x */
2548 cconvert.Cb_b_tab[i] = ((int)(1.77200f * (1<<SCALEBITS) + 0.5f) * x + ONE_HALF) >> SCALEBITS;
2549 /* Cr=>G value is scaled-up -0.71414 * x */
2550 cconvert.Cr_g_tab[i] = ((int)(- (0.71414f * (1<<SCALEBITS) + 0.5f)) * x);
2551 /* Cb=>G value is scaled-up -0.34414 * x */
2552 /* We also add in ONE_HALF so that need not do it in inner loop */
2553 cconvert.Cb_g_tab[i] = ((int)(- (0.34414f* (1<<SCALEBITS) + 0.5f)) * x + ONE_HALF);
2554 }
2555 }
2556
2557 static void jinit_color_deconverter (jpeg_decompress_struct cinfo) {
2558 jpeg_color_deconverter cconvert = cinfo.cconvert = new jpeg_color_deconverter();
2559 // cconvert.start_pass = start_pass_dcolor;
2560
2561 /* Make sure num_components agrees with jpeg_color_space */
2562 switch (cinfo.jpeg_color_space) {
2563 case JCS_GRAYSCALE:
2564 if (cinfo.num_components != 1)
2565 error();
2566 // ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2567 break;
2568
2569 case JCS_RGB:
2570 case JCS_YCbCr:
2571 if (cinfo.num_components != 3)
2572 error();
2573 // ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2574 break;
2575
2576 case JCS_CMYK:
2577 case JCS_YCCK:
2578 if (cinfo.num_components != 4)
2579 error();
2580 // ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2581 break;
2582
2583 default: /* JCS_UNKNOWN can be anything */
2584 if (cinfo.num_components < 1)
2585 error();
2586 // ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
2587 break;
2588 }
2589
2590 /* Set out_color_components and conversion method based on requested space.
2591 * Also clear the component_needed flags for any unused components,
2592 * so that earlier pipeline stages can avoid useless computation.
2593 */
2594
2595 int ci;
2596 switch (cinfo.out_color_space) {
2597 case JCS_GRAYSCALE:
2598 cinfo.out_color_components = 1;
2599 if (cinfo.jpeg_color_space == JCS_GRAYSCALE || cinfo.jpeg_color_space == JCS_YCbCr) {
2600 cconvert.color_convert = GRAYSCALE_CONVERT;
2601 /* For color.grayscale conversion, only the Y (0) component is needed */
2602 for (ci = 1; ci < cinfo.num_components; ci++)
2603 cinfo.comp_info[ci].component_needed = false;
2604 } else
2605 error();
2606 // ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2607 break;
2608
2609 case JCS_RGB:
2610 cinfo.out_color_components = RGB_PIXELSIZE;
2611 if (cinfo.jpeg_color_space == JCS_YCbCr) {
2612 cconvert.color_convert = YCC_RGB_CONVERT;
2613 build_ycc_rgb_table(cinfo);
2614 } else if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
2615 cconvert.color_convert = GRAY_RGB_CONVERT;
2616 } else if (cinfo.jpeg_color_space == JCS_RGB) {
2617 cconvert.color_convert = NULL_CONVERT;
2618 } else
2619 error();
2620 // ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2621 break;
2622
2623 case JCS_CMYK:
2624 cinfo.out_color_components = 4;
2625 if (cinfo.jpeg_color_space == JCS_YCCK) {
2626 cconvert.color_convert = YCCK_CMYK_CONVERT;
2627 build_ycc_rgb_table(cinfo);
2628 } else if (cinfo.jpeg_color_space == JCS_CMYK) {
2629 cconvert.color_convert = NULL_CONVERT;
2630 } else
2631 error();
2632 // ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2633 break;
2634
2635 default:
2636 /* Permit null conversion to same output space */
2637 if (cinfo.out_color_space == cinfo.jpeg_color_space) {
2638 cinfo.out_color_components = cinfo.num_components;
2639 cconvert.color_convert = NULL_CONVERT;
2640 } else /* unsupported non-null conversion */
2641 error();
2642 // ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
2643 break;
2644 }
2645
2646 if (cinfo.quantize_colors)
2647 cinfo.output_components = 1; /* single colormapped output component */
2648 else
2649 cinfo.output_components = cinfo.out_color_components;
2650 }
2651
2652 static void jinit_d_post_controller (jpeg_decompress_struct cinfo, boolean need_full_buffer) {
2653 jpeg_d_post_controller post = cinfo.post = new jpeg_d_post_controller();
2654 // post.pub.start_pass = start_pass_dpost;
2655 post.whole_image = null; /* flag for no virtual arrays */
2656 post.buffer = null; /* flag for no strip buffer */
2657
2658 /* Create the quantization buffer, if needed */
2659 if (cinfo.quantize_colors) {
2660 error(SWT.ERROR_NOT_IMPLEMENTED);
2661 // /* The buffer strip height is max_v_samp_factor, which is typically
2662 // * an efficient number of rows for upsampling to return.
2663 // * (In the presence of output rescaling, we might want to be smarter?)
2664 // */
2665 // post.strip_height = cinfo.max_v_samp_factor;
2666 // if (need_full_buffer) {
2667 // /* Two-pass color quantization: need full-image storage. */
2668 // /* We round up the number of rows to a multiple of the strip height. */
2669 //#ifdef QUANT_2PASS_SUPPORTED
2670 // post.whole_image = (*cinfo.mem.request_virt_sarray)
2671 // ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
2672 // cinfo.output_width * cinfo.out_color_components,
2673 // (JDIMENSION) jround_up((long) cinfo.output_height,
2674 // (long) post.strip_height),
2675 // post.strip_height);
2676 //#else
2677 // ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2678 //#endif /* QUANT_2PASS_SUPPORTED */
2679 // } else {
2680 // /* One-pass color quantization: just make a strip buffer. */
2681 // post.buffer = (*cinfo.mem.alloc_sarray)
2682 // ((j_common_ptr) cinfo, JPOOL_IMAGE,
2683 // cinfo.output_width * cinfo.out_color_components,
2684 // post.strip_height);
2685 // }
2686 }
2687 }
2688
2689 static void make_funny_pointers (jpeg_decompress_struct cinfo)
2690 /* Create the funny pointer lists discussed in the comments above.
2691 * The actual workspace is already allocated (in main.buffer),
2692 * and the space for the pointer lists is allocated too.
2693 * This routine just fills in the curiously ordered lists.
2694 * This will be repeated at the beginning of each pass.
2695 */
2696 {
2697 jpeg_d_main_controller main = cinfo.main;
2698 int ci, i, rgroup;
2699 int M = cinfo.min_DCT_scaled_size;
2700 jpeg_component_info compptr;
2701 byte[][] buf, xbuf0, xbuf1;
2702
2703 for (ci = 0; ci < cinfo.num_components; ci++) {
2704 compptr = cinfo.comp_info[ci];
2705 rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) /
2706 cinfo.min_DCT_scaled_size; /* height of a row group of component */
2707 xbuf0 = main.xbuffer[0][ci];
2708 int xbuf0_offset = main.xbuffer_offset[0][ci];
2709 xbuf1 = main.xbuffer[1][ci];
2710 int xbuf1_offset = main.xbuffer_offset[1][ci];
2711 /* First copy the workspace pointers as-is */
2712 buf = main.buffer[ci];
2713 for (i = 0; i < rgroup * (M + 2); i++) {
2714 xbuf0[i + xbuf0_offset] = xbuf1[i + xbuf1_offset] = buf[i];
2715 }
2716 /* In the second list, put the last four row groups in swapped order */
2717 for (i = 0; i < rgroup * 2; i++) {
2718 xbuf1[rgroup*(M-2) + i + xbuf1_offset] = buf[rgroup*M + i];
2719 xbuf1[rgroup*M + i + xbuf1_offset] = buf[rgroup*(M-2) + i];
2720 }
2721 /* The wraparound pointers at top and bottom will be filled later
2722 * (see set_wraparound_pointers, below). Initially we want the "above"
2723 * pointers to duplicate the first actual data line. This only needs
2724 * to happen in xbuffer[0].
2725 */
2726 for (i = 0; i < rgroup; i++) {
2727 xbuf0[i - rgroup + xbuf0_offset] = xbuf0[0 + xbuf0_offset];
2728 }
2729 }
2730 }
2731
2732 static void alloc_funny_pointers (jpeg_decompress_struct cinfo)
2733 /* Allocate space for the funny pointer lists.
2734 * This is done only once, not once per pass.
2735 */
2736 {
2737 jpeg_d_main_controller main = cinfo.main;
2738 int ci, rgroup;
2739 int M = cinfo.min_DCT_scaled_size;
2740 jpeg_component_info compptr;
2741 byte[][] xbuf;
2742
2743 /* Get top-level space for component array pointers.
2744 * We alloc both arrays with one call to save a few cycles.
2745 */
2746 main.xbuffer[0] = new byte[cinfo.num_components][][];
2747 main.xbuffer[1] = new byte[cinfo.num_components][][];
2748 main.xbuffer_offset[0] = new int[cinfo.num_components];
2749 main.xbuffer_offset[1] = new int[cinfo.num_components];
2750
2751 for (ci = 0; ci < cinfo.num_components; ci++) {
2752 compptr = cinfo.comp_info[ci];
2753 rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) / cinfo.min_DCT_scaled_size; /* height of a row group of component */
2754 /* Get space for pointer lists --- M+4 row groups in each list.
2755 * We alloc both pointer lists with one call to save a few cycles.
2756 */
2757 xbuf = new byte[2 * (rgroup * (M + 4))][];
2758 int offset = rgroup;
2759 main.xbuffer_offset[0][ci] = offset;
2760 main.xbuffer[0][ci] = xbuf;
2761 offset += rgroup * (M + 4);
2762 main.xbuffer_offset[1][ci] = offset;
2763 main.xbuffer[1][ci] = xbuf;
2764 }
2765 }
2766
2767
2768 static void jinit_d_main_controller (jpeg_decompress_struct cinfo, boolean need_full_buffer) {
2769 int ci, rgroup, ngroups;
2770 jpeg_component_info compptr;
2771
2772 jpeg_d_main_controller main = cinfo.main = new jpeg_d_main_controller();
2773 // main.pub.start_pass = start_pass_main;
2774
2775 if (need_full_buffer) /* shouldn't happen */
2776 error();
2777 // ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
2778
2779 /* Allocate the workspace.
2780 * ngroups is the number of row groups we need.
2781 */
2782 if (cinfo.upsample.need_context_rows) {
2783 if (cinfo.min_DCT_scaled_size < 2) /* unsupported, see comments above */
2784 error();
2785 // ERREXIT(cinfo, JERR_NOTIMPL);
2786 alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
2787 ngroups = cinfo.min_DCT_scaled_size + 2;
2788 } else {
2789 ngroups = cinfo.min_DCT_scaled_size;
2790 }
2791
2792 for (ci = 0; ci < cinfo.num_components; ci++) {
2793 compptr = cinfo.comp_info[ci];
2794 rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) / cinfo.min_DCT_scaled_size; /* height of a row group of component */
2795 main.buffer[ci] = new byte[rgroup * ngroups][compptr.width_in_blocks * compptr.DCT_scaled_size];
2796 }
2797 }
2798
2799 static long jround_up (long a, long b)
2800 /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
2801 /* Assumes a >= 0, b > 0 */
2802 {
2803 a += b - 1L;
2804 return a - (a % b);
2805 }
2806
2807 static void jinit_upsampler (jpeg_decompress_struct cinfo) {
2808 int ci;
2809 jpeg_component_info compptr;
2810 boolean need_buffer, do_fancy;
2811 int h_in_group, v_in_group, h_out_group, v_out_group;
2812
2813 jpeg_upsampler upsample = new jpeg_upsampler();
2814 cinfo.upsample = upsample;
2815 // upsample.start_pass = start_pass_upsample;
2816 // upsample.upsample = sep_upsample;
2817 upsample.need_context_rows = false; /* until we find out differently */
2818
2819 if (cinfo.CCIR601_sampling) /* this isn't supported */
2820 error();
2821 // ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
2822
2823 /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
2824 * so don't ask for it.
2825 */
2826 do_fancy = cinfo.do_fancy_upsampling && cinfo.min_DCT_scaled_size > 1;
2827
2828 /* Verify we can handle the sampling factors, select per-component methods,
2829 * and create storage as needed.
2830 */
2831 for (ci = 0; ci < cinfo.num_components; ci++) {
2832 compptr = cinfo.comp_info[ci];
2833 /* Compute size of an "input group" after IDCT scaling. This many samples
2834 * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
2835 */
2836 h_in_group = (compptr.h_samp_factor * compptr.DCT_scaled_size) /
2837 cinfo.min_DCT_scaled_size;
2838 v_in_group = (compptr.v_samp_factor * compptr.DCT_scaled_size) /
2839 cinfo.min_DCT_scaled_size;
2840 h_out_group = cinfo.max_h_samp_factor;
2841 v_out_group = cinfo.max_v_samp_factor;
2842 upsample.rowgroup_height[ci] = v_in_group; /* save for use later */
2843 need_buffer = true;
2844 if (! compptr.component_needed) {
2845 /* Don't bother to upsample an uninteresting component. */
2846 upsample.methods[ci] = NOOP_UPSAMPLE;
2847 need_buffer = false;
2848 } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
2849 /* Fullsize components can be processed without any work. */
2850 upsample.methods[ci] = FULLSIZE_UPSAMPLE;
2851 need_buffer = false;
2852 } else if (h_in_group * 2 == h_out_group && v_in_group == v_out_group) {
2853 /* Special cases for 2h1v upsampling */
2854 if (do_fancy && compptr.downsampled_width > 2)
2855 upsample.methods[ci] = H2V1_FANCY_UPSAMPLE;
2856 else
2857 upsample.methods[ci] = H2V1_UPSAMPLE;
2858 } else if (h_in_group * 2 == h_out_group && v_in_group * 2 == v_out_group) {
2859 /* Special cases for 2h2v upsampling */
2860 if (do_fancy && compptr.downsampled_width > 2) {
2861 upsample.methods[ci] = H2V2_FANCY_UPSAMPLE;
2862 upsample.need_context_rows = true;
2863 } else
2864 upsample.methods[ci] = H2V2_UPSAMPLE;
2865 } else if ((h_out_group % h_in_group) == 0 && (v_out_group % v_in_group) == 0) {
2866 /* Generic integral-factors upsampling method */
2867 upsample.methods[ci] = INT_UPSAMPLE;
2868 upsample.h_expand[ci] = (byte) (h_out_group / h_in_group);
2869 upsample.v_expand[ci] = (byte) (v_out_group / v_in_group);
2870 } else
2871 error();
2872 // ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
2873 if (need_buffer) {
2874 upsample.color_buf[ci] = new byte[cinfo.max_v_samp_factor]
2875 [(int) jround_up(cinfo.output_width, cinfo.max_h_samp_factor)];
2876 }
2877 }
2878 }
2879
2880 static void jinit_phuff_decoder (jpeg_decompress_struct cinfo) {
2881 int[][] coef_bit_ptr;
2882 int ci, i;
2883
2884 cinfo.entropy = new phuff_entropy_decoder();
2885 // entropy.pub.start_pass = start_pass_phuff_decoder;
2886
2887 /* Create progression status table */
2888 cinfo.coef_bits = new int[cinfo.num_components][DCTSIZE2];
2889 coef_bit_ptr = cinfo.coef_bits;
2890 for (ci = 0; ci < cinfo.num_components; ci++)
2891 for (i = 0; i < DCTSIZE2; i++)
2892 coef_bit_ptr[ci][i] = -1;
2893 }
2894
2895
2896 static void jinit_huff_decoder (jpeg_decompress_struct cinfo) {
2897
2898 cinfo.entropy = new huff_entropy_decoder();
2899 // entropy.pub.start_pass = start_pass_huff_decoder;
2900 // entropy.pub.decode_mcu = decode_mcu;
2901
2902 }
2903
2904 static void jinit_inverse_dct (jpeg_decompress_struct cinfo) {
2905 int ci;
2906 jpeg_component_info compptr;
2907
2908 jpeg_inverse_dct idct = cinfo.idct = new jpeg_inverse_dct();
2909 // idct.pub.start_pass = start_pass;
2910
2911 for (ci = 0; ci < cinfo.num_components; ci++) {
2912 compptr = cinfo.comp_info[ci];
2913 /* Allocate and pre-zero a multiplier table for each component */
2914 compptr.dct_table = new int[DCTSIZE2];
2915 /* Mark multiplier table not yet set up for any method */
2916 idct.cur_method[ci] = -1;
2917 }
2918 }
2919
2920 static final int CONST_BITS = 13;
2921 static final int PASS1_BITS = 2;
2922 static final int RANGE_MASK =(MAXJSAMPLE * 4 + 3);
2923 static void jpeg_idct_islow (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
2924 short[] coef_block,
2925 byte[][] output_buf, int output_buf_offset, int output_col)
2926 {
2927 int tmp0, tmp1, tmp2, tmp3;
2928 int tmp10, tmp11, tmp12, tmp13;
2929 int z1, z2, z3, z4, z5;
2930 short[] inptr;
2931 int[] quantptr;
2932 int[] wsptr;
2933 byte[] outptr;
2934 byte[] range_limit = cinfo.sample_range_limit;
2935 int range_limit_offset = cinfo.sample_range_limit_offset + CENTERJSAMPLE;
2936 int ctr;
2937 int[] workspace = cinfo.workspace; /* buffers data between passes */
2938 // SHIFT_TEMPS
2939
2940 /* Pass 1: process columns from input, store into work array. */
2941 /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
2942 /* furthermore, we scale the results by 2**PASS1_BITS. */
2943
2944 inptr = coef_block;
2945 quantptr = compptr.dct_table;
2946 wsptr = workspace;
2947 int inptr_offset = 0, quantptr_offset = 0, wsptr_offset = 0;
2948 for (ctr = DCTSIZE; ctr > 0; ctr--) {
2949 /* Due to quantization, we will usually find that many of the input
2950 * coefficients are zero, especially the AC terms. We can exploit this
2951 * by short-circuiting the IDCT calculation for any column in which all
2952 * the AC terms are zero. In that case each output is equal to the
2953 * DC coefficient (with scale factor as needed).
2954 * With typical images and quantization tables, half or more of the
2955 * column DCT calculations can be simplified this way.
2956 */
2957
2958 if (inptr[DCTSIZE*1+inptr_offset] == 0 && inptr[DCTSIZE*2+inptr_offset] == 0 &&
2959 inptr[DCTSIZE*3+inptr_offset] == 0 && inptr[DCTSIZE*4+inptr_offset] == 0 &&
2960 inptr[DCTSIZE*5+inptr_offset] == 0 && inptr[DCTSIZE*6+inptr_offset] == 0 &&
2961 inptr[DCTSIZE*7+inptr_offset] == 0)
2962 {
2963 /* AC terms all zero */
2964 int dcval = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]) << PASS1_BITS;
2965
2966 wsptr[DCTSIZE*0+wsptr_offset] = dcval;
2967 wsptr[DCTSIZE*1+wsptr_offset] = dcval;
2968 wsptr[DCTSIZE*2+wsptr_offset] = dcval;
2969 wsptr[DCTSIZE*3+wsptr_offset] = dcval;
2970 wsptr[DCTSIZE*4+wsptr_offset] = dcval;
2971 wsptr[DCTSIZE*5+wsptr_offset] = dcval;
2972 wsptr[DCTSIZE*6+wsptr_offset] = dcval;
2973 wsptr[DCTSIZE*7+wsptr_offset] = dcval;
2974
2975 inptr_offset++; /* advance pointers to next column */
2976 quantptr_offset++;
2977 wsptr_offset++;
2978 continue;
2979 }
2980
2981 /* Even part: reverse the even part of the forward DCT. */
2982 /* The rotator is sqrt(2)*c(-6). */
2983
2984 z2 = ((inptr[DCTSIZE*2+inptr_offset]) * quantptr[DCTSIZE*2+quantptr_offset]);
2985 z3 = ((inptr[DCTSIZE*6+inptr_offset]) * quantptr[DCTSIZE*6+quantptr_offset]);
2986
2987 z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/);
2988 tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/);
2989 tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/);
2990
2991 z2 = ((inptr[DCTSIZE*0+inptr_offset]) * quantptr[DCTSIZE*0+quantptr_offset]);
2992 z3 = ((inptr[DCTSIZE*4+inptr_offset]) * quantptr[DCTSIZE*4+quantptr_offset]);
2993
2994 tmp0 = (z2 + z3) << CONST_BITS;
2995 tmp1 = (z2 - z3) << CONST_BITS;
2996
2997 tmp10 = tmp0 + tmp3;
2998 tmp13 = tmp0 - tmp3;
2999 tmp11 = tmp1 + tmp2;
3000 tmp12 = tmp1 - tmp2;
3001
3002 /* Odd part per figure 8; the matrix is unitary and hence its
3003 * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
3004 */
3005
3006 tmp0 = ((inptr[DCTSIZE*7+inptr_offset]) * quantptr[DCTSIZE*7+quantptr_offset]);
3007 tmp1 = ((inptr[DCTSIZE*5+inptr_offset]) * quantptr[DCTSIZE*5+quantptr_offset]);
3008 tmp2 = ((inptr[DCTSIZE*3+inptr_offset]) * quantptr[DCTSIZE*3+quantptr_offset]);
3009 tmp3 = ((inptr[DCTSIZE*1+inptr_offset]) * quantptr[DCTSIZE*1+quantptr_offset]);
3010
3011 z1 = tmp0 + tmp3;
3012 z2 = tmp1 + tmp2;
3013 z3 = tmp0 + tmp2;
3014 z4 = tmp1 + tmp3;
3015 z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */
3016
3017 tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */
3018 tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */
3019 tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */
3020 tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */
3021 z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */
3022 z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */
3023 z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */
3024 z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */
3025
3026 z3 += z5;
3027 z4 += z5;
3028
3029 tmp0 += z1 + z3;
3030 tmp1 += z2 + z4;
3031 tmp2 += z2 + z3;
3032 tmp3 += z1 + z4;
3033
3034 /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
3035
3036 // #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
3037 wsptr[DCTSIZE*0+wsptr_offset] = (((tmp10 + tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3038 wsptr[DCTSIZE*7+wsptr_offset] = (((tmp10 - tmp3) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3039 wsptr[DCTSIZE*1+wsptr_offset] = (((tmp11 + tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3040 wsptr[DCTSIZE*6+wsptr_offset] = (((tmp11 - tmp2) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3041 wsptr[DCTSIZE*2+wsptr_offset] = (((tmp12 + tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3042 wsptr[DCTSIZE*5+wsptr_offset] = (((tmp12 - tmp1) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3043 wsptr[DCTSIZE*3+wsptr_offset] = (((tmp13 + tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3044 wsptr[DCTSIZE*4+wsptr_offset] = (((tmp13 - tmp0) + (1 << ((CONST_BITS-PASS1_BITS)-1))) >> (CONST_BITS-PASS1_BITS));
3045
3046 inptr_offset++; /* advance pointers to next column */
3047 quantptr_offset++;
3048 wsptr_offset++;
3049 }
3050
3051
3052 /* Pass 2: process rows from work array, store into output array. */
3053 /* Note that we must descale the results by a factor of 8 == 2**3, */
3054 /* and also undo the PASS1_BITS scaling. */
3055
3056 int outptr_offset = 0;
3057 wsptr = workspace;
3058 wsptr_offset =0;
3059 for (ctr = 0; ctr < DCTSIZE; ctr++) {
3060 outptr = output_buf[ctr+output_buf_offset];
3061 outptr_offset = output_col;
3062 /* Rows of zeroes can be exploited in the same way as we did with columns.
3063 * However, the column calculation has created many nonzero AC terms, so
3064 * the simplification applies less often (typically 5% to 10% of the time).
3065 * On machines with very fast multiplication, it's possible that the
3066 * test takes more time than it's worth. In that case this section
3067 * may be commented out.
3068 */
3069
3070 //#ifndef NO_ZERO_ROW_TEST
3071 if (wsptr[1+wsptr_offset] == 0 && wsptr[2+wsptr_offset] == 0 && wsptr[3+wsptr_offset] == 0 && wsptr[4+wsptr_offset] == 0 &&
3072 wsptr[5+wsptr_offset] == 0 && wsptr[6+wsptr_offset] == 0 && wsptr[7+wsptr_offset] == 0)
3073 {
3074 /* AC terms all zero */
3075 // #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
3076 byte dcval = range_limit[range_limit_offset + ((((wsptr[0+wsptr_offset]) + (1 << ((PASS1_BITS+3)-1))) >> PASS1_BITS+3)
3077 & RANGE_MASK)];
3078
3079 outptr[0+outptr_offset] = dcval;
3080 outptr[1+outptr_offset] = dcval;
3081 outptr[2+outptr_offset] = dcval;
3082 outptr[3+outptr_offset] = dcval;
3083 outptr[4+outptr_offset] = dcval;
3084 outptr[5+outptr_offset] = dcval;
3085 outptr[6+outptr_offset] = dcval;
3086 outptr[7+outptr_offset] = dcval;
3087
3088 wsptr_offset += DCTSIZE; /* advance pointer to next row */
3089 continue;
3090 }
3091 //#endif
3092
3093 /* Even part: reverse the even part of the forward DCT. */
3094 /* The rotator is sqrt(2)*c(-6). */
3095
3096 z2 = wsptr[2+wsptr_offset];
3097 z3 = wsptr[6+wsptr_offset];
3098
3099 z1 = ((z2 + z3) * 4433/*FIX_0_541196100*/);
3100 tmp2 = z1 + (z3 * - 15137/*FIX_1_847759065*/);
3101 tmp3 = z1 + (z2 * 6270/*FIX_0_765366865*/);
3102
3103 tmp0 = (wsptr[0+wsptr_offset] + wsptr[4+wsptr_offset]) << CONST_BITS;
3104 tmp1 = (wsptr[0+wsptr_offset] - wsptr[4+wsptr_offset]) << CONST_BITS;
3105
3106 tmp10 = tmp0 + tmp3;
3107 tmp13 = tmp0 - tmp3;
3108 tmp11 = tmp1 + tmp2;
3109 tmp12 = tmp1 - tmp2;
3110
3111 /* Odd part per figure 8; the matrix is unitary and hence its
3112 * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
3113 */
3114
3115 tmp0 = wsptr[7+wsptr_offset];
3116 tmp1 = wsptr[5+wsptr_offset];
3117 tmp2 = wsptr[3+wsptr_offset];
3118 tmp3 = wsptr[1+wsptr_offset];
3119
3120 z1 = tmp0 + tmp3;
3121 z2 = tmp1 + tmp2;
3122 z3 = tmp0 + tmp2;
3123 z4 = tmp1 + tmp3;
3124 z5 = ((z3 + z4) * 9633/*FIX_1_175875602*/); /* sqrt(2) * c3 */
3125
3126 tmp0 = (tmp0 * 2446/*FIX_0_298631336*/); /* sqrt(2) * (-c1+c3+c5-c7) */
3127 tmp1 = (tmp1 * 16819/*FIX_2_053119869*/); /* sqrt(2) * ( c1+c3-c5+c7) */
3128 tmp2 = (tmp2 * 25172/*FIX_3_072711026*/); /* sqrt(2) * ( c1+c3+c5-c7) */
3129 tmp3 = (tmp3 * 12299/*FIX_1_501321110*/); /* sqrt(2) * ( c1+c3-c5-c7) */
3130 z1 = (z1 * - 7373/*FIX_0_899976223*/); /* sqrt(2) * (c7-c3) */
3131 z2 = (z2 * - 20995/*FIX_2_562915447*/); /* sqrt(2) * (-c1-c3) */
3132 z3 = (z3 * - 16069/*FIX_1_961570560*/); /* sqrt(2) * (-c3-c5) */
3133 z4 = (z4 * - 3196/*FIX_0_390180644*/); /* sqrt(2) * (c5-c3) */
3134
3135 z3 += z5;
3136 z4 += z5;
3137
3138 tmp0 += z1 + z3;
3139 tmp1 += z2 + z4;
3140 tmp2 += z2 + z3;
3141 tmp3 += z1 + z4;
3142
3143 /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
3144
3145
3146 // #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
3147 outptr[0+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 + tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3148 CONST_BITS+PASS1_BITS+3)
3149 & RANGE_MASK)];
3150 outptr[7+outptr_offset] = range_limit[range_limit_offset + ((((tmp10 - tmp3) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3151 CONST_BITS+PASS1_BITS+3)
3152 & RANGE_MASK)];
3153 outptr[1+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 + tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3154 CONST_BITS+PASS1_BITS+3)
3155 & RANGE_MASK)];
3156 outptr[6+outptr_offset] = range_limit[range_limit_offset + ((((tmp11 - tmp2) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3157 CONST_BITS+PASS1_BITS+3)
3158 & RANGE_MASK)];
3159 outptr[2+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 + tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3160 CONST_BITS+PASS1_BITS+3)
3161 & RANGE_MASK)];
3162 outptr[5+outptr_offset] = range_limit[range_limit_offset + ((((tmp12 - tmp1) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3163 CONST_BITS+PASS1_BITS+3)
3164 & RANGE_MASK)];
3165 outptr[3+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 + tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3166 CONST_BITS+PASS1_BITS+3)
3167 & RANGE_MASK)];
3168 outptr[4+outptr_offset] = range_limit[range_limit_offset + ((((tmp13 - tmp0) + (1 << ((CONST_BITS+PASS1_BITS+3)-1))) >>
3169 CONST_BITS+PASS1_BITS+3)
3170 & RANGE_MASK)];
3171
3172 wsptr_offset += DCTSIZE; /* advance pointer to next row */
3173 }
3174 }
3175
3176 static void upsample (jpeg_decompress_struct cinfo,
3177 byte[][][] input_buf, int[] input_buf_offset, int[] in_row_group_ctr,
3178 int in_row_groups_avail,
3179 byte[][] output_buf, int[] out_row_ctr,
3180 int out_rows_avail)
3181 {
3182 sep_upsample(cinfo, input_buf, input_buf_offset, in_row_group_ctr, in_row_groups_avail, output_buf, out_row_ctr, out_rows_avail);
3183 }
3184
3185 static boolean smoothing_ok (jpeg_decompress_struct cinfo) {
3186 jpeg_d_coef_controller coef = cinfo.coef;
3187 boolean smoothing_useful = false;
3188 int ci, coefi;
3189 jpeg_component_info compptr;
3190 JQUANT_TBL qtable;
3191 int[] coef_bits;
3192 int[] coef_bits_latch;
3193
3194 if (! cinfo.progressive_mode || cinfo.coef_bits == null)
3195 return false;
3196
3197 /* Allocate latch area if not already done */
3198 if (coef.coef_bits_latch == null)
3199 coef.coef_bits_latch = new int[cinfo.num_components * SAVED_COEFS];
3200 coef_bits_latch = coef.coef_bits_latch;
3201 int coef_bits_latch_offset = 0;
3202
3203 for (ci = 0; ci < cinfo.num_components; ci++) {
3204 compptr = cinfo.comp_info[ci];
3205 /* All components' quantization values must already be latched. */
3206 if ((qtable = compptr.quant_table) == null)
3207 return false;
3208 /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
3209 if (qtable.quantval[0] == 0 ||
3210 qtable.quantval[Q01_POS] == 0 ||
3211 qtable.quantval[Q10_POS] == 0 ||
3212 qtable.quantval[Q20_POS] == 0 ||
3213 qtable.quantval[Q11_POS] == 0 ||
3214 qtable.quantval[Q02_POS] == 0)
3215 return false;
3216 /* DC values must be at least partly known for all components. */
3217 coef_bits = cinfo.coef_bits[ci];
3218 if (coef_bits[0] < 0)
3219 return false;
3220 /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
3221 for (coefi = 1; coefi <= 5; coefi++) {
3222 coef_bits_latch[coefi+coef_bits_latch_offset] = coef_bits[coefi];
3223 if (coef_bits[coefi] != 0)
3224 smoothing_useful = true;
3225 }
3226 coef_bits_latch_offset += SAVED_COEFS;
3227 }
3228
3229 return smoothing_useful;
3230 }
3231
3232 static void master_selection (jpeg_decompress_struct cinfo) {
3233 jpeg_decomp_master master = cinfo.master;
3234 boolean use_c_buffer;
3235 long samplesperrow;
3236 int jd_samplesperrow;
3237
3238 /* Initialize dimensions and other stuff */
3239 jpeg_calc_output_dimensions(cinfo);
3240 prepare_range_limit_table(cinfo);
3241
3242 /* Width of an output scanline must be representable as JDIMENSION. */
3243 samplesperrow = (long) cinfo.output_width * (long) cinfo.out_color_components;
3244 jd_samplesperrow = (int) samplesperrow;
3245 if ( jd_samplesperrow != samplesperrow)
3246 error();
3247 // ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
3248
3249 /* Initialize my private state */
3250 master.pass_number = 0;
3251 master.using_merged_upsample = use_merged_upsample(cinfo);
3252
3253 /* Color quantizer selection */
3254 master.quantizer_1pass = null;
3255 master.quantizer_2pass = null;
3256 /* No mode changes if not using buffered-image mode. */
3257 if (! cinfo.quantize_colors || ! cinfo.buffered_image) {
3258 cinfo.enable_1pass_quant = false;
3259 cinfo.enable_external_quant = false;
3260 cinfo.enable_2pass_quant = false;
3261 }
3262 if (cinfo.quantize_colors) {
3263 error(SWT.ERROR_NOT_IMPLEMENTED);
3264 // if (cinfo.raw_data_out)
3265 // ERREXIT(cinfo, JERR_NOTIMPL);
3266 // /* 2-pass quantizer only works in 3-component color space. */
3267 // if (cinfo.out_color_components != 3) {
3268 // cinfo.enable_1pass_quant = true;
3269 // cinfo.enable_external_quant = false;
3270 // cinfo.enable_2pass_quant = false;
3271 // cinfo.colormap = null;
3272 // } else if (cinfo.colormap != null) {
3273 // cinfo.enable_external_quant = true;
3274 // } else if (cinfo.two_pass_quantize) {
3275 // cinfo.enable_2pass_quant = true;
3276 // } else {
3277 // cinfo.enable_1pass_quant = true;
3278 // }
3279 //
3280 // if (cinfo.enable_1pass_quant) {
3281 //#ifdef QUANT_1PASS_SUPPORTED
3282 // jinit_1pass_quantizer(cinfo);
3283 // master.quantizer_1pass = cinfo.cquantize;
3284 //#else
3285 // ERREXIT(cinfo, JERR_NOT_COMPILED);
3286 //#endif
3287 // }
3288 //
3289 // /* We use the 2-pass code to map to external colormaps. */
3290 // if (cinfo.enable_2pass_quant || cinfo.enable_external_quant) {
3291 //#ifdef QUANT_2PASS_SUPPORTED
3292 // jinit_2pass_quantizer(cinfo);
3293 // master.quantizer_2pass = cinfo.cquantize;
3294 //#else
3295 // ERREXIT(cinfo, JERR_NOT_COMPILED);
3296 //#endif
3297 // }
3298 // /* If both quantizers are initialized, the 2-pass one is left active;
3299 // * this is necessary for starting with quantization to an external map.
3300 // */
3301 }
3302
3303 /* Post-processing: in particular, color conversion first */
3304 if (! cinfo.raw_data_out) {
3305 if (master.using_merged_upsample) {
3306 //#ifdef UPSAMPLE_MERGING_SUPPORTED
3307 // jinit_merged_upsampler(cinfo); /* does color conversion too */
3308 //#else
3309 error();
3310 // ERREXIT(cinfo, JERR_NOT_COMPILED);
3311 //#endif
3312 } else {
3313 jinit_color_deconverter(cinfo);
3314 jinit_upsampler(cinfo);
3315 }
3316 jinit_d_post_controller(cinfo, cinfo.enable_2pass_quant);
3317 }
3318 /* Inverse DCT */
3319 jinit_inverse_dct(cinfo);
3320 /* Entropy decoding: either Huffman or arithmetic coding. */
3321 if (cinfo.arith_code) {
3322 error();
3323 // ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
3324 } else {
3325 if (cinfo.progressive_mode) {
3326 //#ifdef D_PROGRESSIVE_SUPPORTED
3327 jinit_phuff_decoder(cinfo);
3328 //#else
3329 // ERREXIT(cinfo, JERR_NOT_COMPILED);
3330 //#endif
3331 } else
3332 jinit_huff_decoder(cinfo);
3333 }
3334
3335 /* Initialize principal buffer controllers. */
3336 use_c_buffer = cinfo.inputctl.has_multiple_scans || cinfo.buffered_image;
3337 jinit_d_coef_controller(cinfo, use_c_buffer);
3338
3339 if (! cinfo.raw_data_out)
3340 jinit_d_main_controller(cinfo, false /* never need full buffer here */);
3341
3342 /* Initialize input side of decompressor to consume first scan. */
3343 start_input_pass (cinfo);
3344
3345 //#ifdef D_MULTISCAN_FILES_SUPPORTED
3346 /* If jpeg_start_decompress will read the whole file, initialize
3347 * progress monitoring appropriately. The input step is counted
3348 * as one pass.
3349 */
3350 // if (cinfo.progress != null && ! cinfo.buffered_image &&
3351 // cinfo.inputctl.has_multiple_scans) {
3352 // int nscans;
3353 // /* Estimate number of scans to set pass_limit. */
3354 // if (cinfo.progressive_mode) {
3355 // /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
3356 // nscans = 2 + 3 * cinfo.num_components;
3357 // } else {
3358 // /* For a nonprogressive multiscan file, estimate 1 scan per component. */
3359 // nscans = cinfo.num_components;
3360 // }
3361 // cinfo.progress.pass_counter = 0L;
3362 // cinfo.progress.pass_limit = (long) cinfo.total_iMCU_rows * nscans;
3363 // cinfo.progress.completed_passes = 0;
3364 // cinfo.progress.total_passes = (cinfo.enable_2pass_quant ? 3 : 2);
3365 // /* Count the input pass as done */
3366 // master.pass_number++;
3367 // }
3368 //#endif /* D_MULTISCAN_FILES_SUPPORTED */
3369 }
3370
3371 static void jinit_master_decompress (jpeg_decompress_struct cinfo) {
3372 jpeg_decomp_master master = new jpeg_decomp_master();
3373 cinfo.master = master;
3374 // master.prepare_for_output_pass = prepare_for_output_pass;
3375 // master.finish_output_pass = finish_output_pass;
3376
3377 master.is_dummy_pass = false;
3378
3379 master_selection(cinfo);
3380 }
3381
3382 static void
3383 jcopy_sample_rows (byte[][] input_array, int source_row,
3384 byte[][] output_array, int dest_row,
3385 int num_rows, int num_cols)
3386 /* Copy some rows of samples from one place to another.
3387 * num_rows rows are copied from input_array[source_row++]
3388 * to output_array[dest_row++]; these areas may overlap for duplication.
3389 * The source and destination arrays must be at least as wide as num_cols.
3390 */
3391 {
3392 byte[] inptr, outptr;
3393 int count = num_cols;
3394 int row;
3395
3396 int input_array_offset = source_row;
3397 int output_array_offset = dest_row;
3398
3399 for (row = num_rows; row > 0; row--) {
3400 inptr = input_array[input_array_offset++];
3401 outptr = output_array[output_array_offset++];
3402 System.arraycopy(inptr, 0, outptr, 0, count);
3403 }
3404 }
3405
3406 static boolean jpeg_start_decompress (jpeg_decompress_struct cinfo) {
3407 if (cinfo.global_state == DSTATE_READY) {
3408 /* First call: initialize master control, select active modules */
3409 jinit_master_decompress(cinfo);
3410 if (cinfo.buffered_image) {
3411 /* No more work here; expecting jpeg_start_output next */
3412 cinfo.global_state = DSTATE_BUFIMAGE;
3413 return true;
3414 }
3415 cinfo.global_state = DSTATE_PRELOAD;
3416 }
3417 if (cinfo.global_state == DSTATE_PRELOAD) {
3418 /* If file has multiple scans, absorb them all into the coef buffer */
3419 if (cinfo.inputctl.has_multiple_scans) {
3420 //#ifdef D_MULTISCAN_FILES_SUPPORTED
3421 for (;;) {
3422 int retcode;
3423 /* Call progress monitor hook if present */
3424 // if (cinfo.progress != null)
3425 // (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo);
3426 /* Absorb some more input */
3427 retcode = consume_input (cinfo);
3428 if (retcode == JPEG_SUSPENDED)
3429 return false;
3430 if (retcode == JPEG_REACHED_EOI)
3431 break;
3432 /* Advance progress counter if appropriate */
3433 // if (cinfo.progress != null && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
3434 // if (++cinfo.progress.pass_counter >= cinfo.progress.pass_limit) {
3435 // /* jdmaster underestimated number of scans; ratchet up one scan */
3436 // cinfo.progress.pass_limit += (long) cinfo.total_iMCU_rows;
3437 // }
3438 // }
3439 }
3440 //#else
3441 // ERREXIT(cinfo, JERR_NOT_COMPILED);
3442 //#endif /* D_MULTISCAN_FILES_SUPPORTED */
3443 }
3444 cinfo.output_scan_number = cinfo.input_scan_number;
3445 } else if (cinfo.global_state != DSTATE_PRESCAN)
3446 error();
3447 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
3448 /* Perform any dummy output passes, and set up for the final pass */
3449 return output_pass_setup(cinfo);
3450 }
3451
3452 static void prepare_for_output_pass (jpeg_decompress_struct cinfo) {
3453 jpeg_decomp_master master = cinfo.master;
3454
3455 if (master.is_dummy_pass) {
3456 //#ifdef QUANT_2PASS_SUPPORTED
3457 // /* Final pass of 2-pass quantization */
3458 // master.pub.is_dummy_pass = FALSE;
3459 // (*cinfo.cquantize.start_pass) (cinfo, FALSE);
3460 // (*cinfo.post.start_pass) (cinfo, JBUF_CRANK_DEST);
3461 // (*cinfo.main.start_pass) (cinfo, JBUF_CRANK_DEST);
3462 //#else
3463 error(SWT.ERROR_NOT_IMPLEMENTED);
3464 // ERREXIT(cinfo, JERR_NOT_COMPILED);
3465 //#endif /* QUANT_2PASS_SUPPORTED */
3466 } else {
3467 if (cinfo.quantize_colors && cinfo.colormap == null) {
3468 /* Select new quantization method */
3469 if (cinfo.two_pass_quantize && cinfo.enable_2pass_quant) {
3470 cinfo.cquantize = master.quantizer_2pass;
3471 master.is_dummy_pass = true;
3472 } else if (cinfo.enable_1pass_quant) {
3473 cinfo.cquantize = master.quantizer_1pass;
3474 } else {
3475 error();
3476 // ERREXIT(cinfo, JERR_MODE_CHANGE);
3477 }
3478 }
3479 cinfo.idct.start_pass (cinfo);
3480 start_output_pass (cinfo);
3481 if (! cinfo.raw_data_out) {
3482 if (! master.using_merged_upsample)
3483 cinfo.cconvert.start_pass (cinfo);
3484 cinfo.upsample.start_pass (cinfo);
3485 if (cinfo.quantize_colors)
3486 cinfo.cquantize.start_pass (cinfo, master.is_dummy_pass);
3487 cinfo.post.start_pass (cinfo, (master.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
3488 cinfo.main.start_pass (cinfo, JBUF_PASS_THRU);
3489 }
3490 }
3491
3492 // /* Set up progress monitor's pass info if present */
3493 // if (cinfo.progress != NULL) {
3494 // cinfo.progress.completed_passes = master.pass_number;
3495 // cinfo.progress.total_passes = master.pass_number +
3496 // (master.pub.is_dummy_pass ? 2 : 1);
3497 // /* In buffered-image mode, we assume one more output pass if EOI not
3498 // * yet reached, but no more passes if EOI has been reached.
3499 // */
3500 // if (cinfo.buffered_image && ! cinfo.inputctl.eoi_reached) {
3501 // cinfo.progress.total_passes += (cinfo.enable_2pass_quant ? 2 : 1);
3502 // }
3503 // }
3504 }
3505
3506
3507 static boolean jpeg_resync_to_restart (jpeg_decompress_struct cinfo, int desired) {
3508 int marker = cinfo.unread_marker;
3509 int action = 1;
3510
3511 /* Always put up a warning. */
3512 // WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
3513
3514 /* Outer loop handles repeated decision after scanning forward. */
3515 for (;;) {
3516 if (marker < M_SOF0)
3517 action = 2; /* invalid marker */
3518 else if (marker < M_RST0 || marker > M_RST7)
3519 action = 3; /* valid non-restart marker */
3520 else {
3521 if (marker == (M_RST0 + ((desired+1) & 7)) || marker == ( M_RST0 + ((desired+2) & 7)))
3522 action = 3; /* one of the next two expected restarts */
3523 else if (marker == (M_RST0 + ((desired-1) & 7)) || marker == ( M_RST0 + ((desired-2) & 7)))
3524 action = 2; /* a prior restart, so advance */
3525 else
3526 action = 1; /* desired restart or too far away */
3527 }
3528 // TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
3529 switch (action) {
3530 case 1:
3531 /* Discard marker and let entropy decoder resume processing. */
3532 cinfo.unread_marker = 0;
3533 return true;
3534 case 2:
3535 /* Scan to the next marker, and repeat the decision loop. */
3536 if (! next_marker(cinfo))
3537 return false;
3538 marker = cinfo.unread_marker;
3539 break;
3540 case 3:
3541 /* Return without advancing past this marker. */
3542 /* Entropy decoder will be forced to process an empty segment. */
3543 return true;
3544 }
3545 } /* end loop */
3546 }
3547
3548 static boolean read_restart_marker (jpeg_decompress_struct cinfo) {
3549 /* Obtain a marker unless we already did. */
3550 /* Note that next_marker will complain if it skips any data. */
3551 if (cinfo.unread_marker == 0) {
3552 if (! next_marker(cinfo))
3553 return false;
3554 }
3555
3556 if (cinfo.unread_marker == (M_RST0 + cinfo.marker.next_restart_num)) {
3557 /* Normal case --- swallow the marker and let entropy decoder continue */
3558 // TRACEMS1(cinfo, 3, JTRC_RST, cinfo.marker.next_restart_num);
3559 cinfo.unread_marker = 0;
3560 } else {
3561 /* Uh-oh, the restart markers have been messed up. */
3562 /* Let the data source manager determine how to resync. */
3563 if (! jpeg_resync_to_restart (cinfo, cinfo.marker.next_restart_num))
3564 return false;
3565 }
3566
3567 /* Update next-restart state */
3568 cinfo.marker.next_restart_num = (cinfo.marker.next_restart_num + 1) & 7;
3569
3570 return true;
3571 }
3572
3573 static boolean jpeg_fill_bit_buffer (bitread_working_state state, int get_buffer, int bits_left, int nbits)
3574 /* Load up the bit buffer to a depth of at least nbits */
3575 {
3576 /* Copy heavily used state fields into locals (hopefully registers) */
3577 byte[] buffer = state.buffer;
3578 int bytes_in_buffer = state.bytes_in_buffer;
3579 int bytes_offset = state.bytes_offset;
3580 jpeg_decompress_struct cinfo = state.cinfo;
3581
3582 /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
3583 /* (It is assumed that no request will be for more than that many bits.) */
3584 /* We fail to do so only if we hit a marker or are forced to suspend. */
3585
3586 if (cinfo.unread_marker == 0) { /* cannot advance past a marker */
3587 while (bits_left < MIN_GET_BITS) {
3588 int c;
3589
3590 /* Attempt to read a byte */
3591 if (bytes_offset == bytes_in_buffer) {
3592 if (! fill_input_buffer (cinfo))
3593 return false;
3594 buffer = cinfo.buffer;
3595 bytes_in_buffer = cinfo.bytes_in_buffer;
3596 bytes_offset = cinfo.bytes_offset;
3597 }
3598 c = buffer[bytes_offset++] & 0xFF;
3599
3600 /* If it's 0xFF, check and discard stuffed zero byte */
3601 if (c == 0xFF) {
3602 /* Loop here to discard any padding FF's on terminating marker,
3603 * so that we can save a valid unread_marker value. NOTE: we will
3604 * accept multiple FF's followed by a 0 as meaning a single FF data
3605 * byte. This data pattern is not valid according to the standard.
3606 */
3607 do {
3608 if (bytes_offset == bytes_in_buffer) {
3609 if (! fill_input_buffer (cinfo))
3610 return false;
3611 buffer = cinfo.buffer;
3612 bytes_in_buffer = cinfo.bytes_in_buffer;
3613 bytes_offset = cinfo.bytes_offset;
3614 }
3615 c = buffer[bytes_offset++] & 0xFF;
3616 } while (c == 0xFF);
3617
3618 if (c == 0) {
3619 /* Found FF/00, which represents an FF data byte */
3620 c = 0xFF;
3621 } else {
3622 /* Oops, it's actually a marker indicating end of compressed data.
3623 * Save the marker code for later use.
3624 * Fine point: it might appear that we should save the marker into
3625 * bitread working state, not straight into permanent state. But
3626 * once we have hit a marker, we cannot need to suspend within the
3627 * current MCU, because we will read no more bytes from the data
3628 * source. So it is OK to update permanent state right away.
3629 */
3630 cinfo.unread_marker = c;
3631 /* See if we need to insert some fake zero bits. */
3632 // goto no_more_bytes;
3633 if (nbits > bits_left) {
3634 /* Uh-oh. Report corrupted data to user and stuff zeroes into
3635 * the data stream, so that we can produce some kind of image.
3636 * We use a nonvolatile flag to ensure that only one warning message
3637 * appears per data segment.
3638 */
3639 if (! cinfo.entropy.insufficient_data) {
3640 // WARNMS(cinfo, JWRN_HIT_MARKER);
3641 cinfo.entropy.insufficient_data = true;
3642 }
3643 /* Fill the buffer with zero bits */
3644 get_buffer <<= MIN_GET_BITS - bits_left;
3645 bits_left = MIN_GET_BITS;
3646 }
3647
3648 /* Unload the local registers */
3649 state.buffer = buffer;
3650 state.bytes_in_buffer = bytes_in_buffer;
3651 state.bytes_offset = bytes_offset;
3652 state.get_buffer = get_buffer;
3653 state.bits_left = bits_left;
3654
3655 return true;
3656
3657 }
3658 }
3659
3660 /* OK, load c into get_buffer */
3661 get_buffer = (get_buffer << 8) | c;
3662 bits_left += 8;
3663 } /* end while */
3664 } else {
3665 // no_more_bytes:
3666 /* We get here if we've read the marker that terminates the compressed
3667 * data segment. There should be enough bits in the buffer register
3668 * to satisfy the request; if so, no problem.
3669 */
3670 if (nbits > bits_left) {
3671 /* Uh-oh. Report corrupted data to user and stuff zeroes into
3672 * the data stream, so that we can produce some kind of image.
3673 * We use a nonvolatile flag to ensure that only one warning message
3674 * appears per data segment.
3675 */
3676 if (! cinfo.entropy.insufficient_data) {
3677 // WARNMS(cinfo, JWRN_HIT_MARKER);
3678 cinfo.entropy.insufficient_data = true;
3679 }
3680 /* Fill the buffer with zero bits */
3681 get_buffer <<= MIN_GET_BITS - bits_left;
3682 bits_left = MIN_GET_BITS;
3683 }
3684 }
3685
3686 /* Unload the local registers */
3687 state.buffer = buffer;
3688 state.bytes_in_buffer = bytes_in_buffer;
3689 state.bytes_offset = bytes_offset;
3690 state.get_buffer = get_buffer;
3691 state.bits_left = bits_left;
3692
3693 return true;
3694 }
3695
3696 static int jpeg_huff_decode (bitread_working_state state, int get_buffer, int bits_left, d_derived_tbl htbl, int min_bits) {
3697 int l = min_bits;
3698 int code;
3699
3700 /* HUFF_DECODE has determined that the code is at least min_bits */
3701 /* bits long, so fetch that many bits in one swoop. */
3702
3703 // CHECK_BIT_BUFFER(*state, l, return -1);
3704 {
3705 if (bits_left < (l)) {
3706 if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,l)) {
3707 return -1;
3708 }
3709 get_buffer = (state).get_buffer; bits_left = (state).bits_left;
3710 }
3711 }
3712 // code = GET_BITS(l);
3713 code = (( (get_buffer >> (bits_left -= (l)))) & ((1<<(l))-1));
3714
3715 /* Collect the rest of the Huffman code one bit at a time. */
3716 /* This is per Figure F.16 in the JPEG spec. */
3717
3718 while (code > htbl.maxcode[l]) {
3719 code <<= 1;
3720 // CHECK_BIT_BUFFER(*state, 1, return -1);
3721 {
3722 if (bits_left < (1)) {
3723 if (! jpeg_fill_bit_buffer(state,get_buffer,bits_left,1)) {
3724 return -1;
3725 }
3726 get_buffer = (state).get_buffer; bits_left = (state).bits_left;
3727 }
3728 }
3729 // code |= GET_BITS(1);
3730 code |= (( (get_buffer >> (bits_left -= (1)))) & ((1<<(1))-1));
3731 l++;
3732 }
3733
3734 /* Unload the local registers */
3735 state.get_buffer = get_buffer;
3736 state.bits_left = bits_left;
3737
3738 /* With garbage input we may reach the sentinel value l = 17. */
3739
3740 if (l > 16) {
3741 // WARNMS(state.cinfo, JWRN_HUFF_BAD_CODE);
3742 return 0; /* fake a zero as the safest result */
3743 }
3744
3745 return htbl.pub.huffval[ (code + htbl.valoffset[l]) ] & 0xFF;
3746 }
3747
3748 static int decompress_onepass (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) {
3749 jpeg_d_coef_controller coef = cinfo.coef;
3750 int MCU_col_num; /* index of current MCU within row */
3751 int last_MCU_col = cinfo.MCUs_per_row - 1;
3752 int last_iMCU_row = cinfo.total_iMCU_rows - 1;
3753 int blkn, ci, xindex, yindex, yoffset, useful_width;
3754 byte[][] output_ptr;
3755 int start_col, output_col;
3756 jpeg_component_info compptr;
3757 // inverse_DCT_method_ptr inverse_DCT;
3758
3759 /* Loop to process as much as one whole iMCU row */
3760 for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) {
3761 for (MCU_col_num = coef.MCU_ctr; MCU_col_num <= last_MCU_col; MCU_col_num++) {
3762 /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
3763 for (int i = 0; i < cinfo.blocks_in_MCU; i++) {
3764 short[] blk = coef.MCU_buffer[i];
3765 for (int j = 0; j < blk.length; j++) {
3766 blk[j] = 0;
3767 }
3768 }
3769 if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) {
3770 /* Suspension forced; update state counters and exit */
3771 coef.MCU_vert_offset = yoffset;
3772 coef.MCU_ctr = MCU_col_num;
3773 return JPEG_SUSPENDED;
3774 }
3775 /* Determine where data should go in output_buf and do the IDCT thing.
3776 * We skip dummy blocks at the right and bottom edges (but blkn gets
3777 * incremented past them!). Note the inner loop relies on having
3778 * allocated the MCU_buffer[] blocks sequentially.
3779 */
3780 blkn = 0; /* index of current DCT block within MCU */
3781 for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
3782 compptr = cinfo.cur_comp_info[ci];
3783 /* Don't bother to IDCT an uninteresting component. */
3784 if (! compptr.component_needed) {
3785 blkn += compptr.MCU_blocks;
3786 continue;
3787 }
3788 // inverse_DCT = cinfo.idct.inverse_DCT[compptr.component_index];
3789 useful_width = (MCU_col_num < last_MCU_col) ? compptr.MCU_width : compptr.last_col_width;
3790 output_ptr = output_buf[compptr.component_index];
3791 int output_ptr_offset = output_buf_offset[compptr.component_index] + yoffset * compptr.DCT_scaled_size;
3792 start_col = MCU_col_num * compptr.MCU_sample_width;
3793 for (yindex = 0; yindex < compptr.MCU_height; yindex++) {
3794 if (cinfo.input_iMCU_row < last_iMCU_row || yoffset+yindex < compptr.last_row_height) {
3795 output_col = start_col;
3796 for (xindex = 0; xindex < useful_width; xindex++) {
3797 jpeg_idct_islow(cinfo, compptr, coef.MCU_buffer[blkn+xindex], output_ptr, output_ptr_offset, output_col);
3798 output_col += compptr.DCT_scaled_size;
3799 }
3800 }
3801 blkn += compptr.MCU_width;
3802 output_ptr_offset += compptr.DCT_scaled_size;
3803 }
3804 }
3805 }
3806 /* Completed an MCU row, but perhaps not an iMCU row */
3807 coef.MCU_ctr = 0;
3808 }
3809 /* Completed the iMCU row, advance counters for next one */
3810 cinfo.output_iMCU_row++;
3811 if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) {
3812 coef.start_iMCU_row(cinfo);
3813 return JPEG_ROW_COMPLETED;
3814 }
3815 /* Completed the scan */
3816 finish_input_pass (cinfo);
3817 return JPEG_SCAN_COMPLETED;
3818 }
3819
3820 static int decompress_smooth_data (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) {
3821 jpeg_d_coef_controller coef = cinfo.coef;
3822 int last_iMCU_row = cinfo.total_iMCU_rows - 1;
3823 int block_num, last_block_column;
3824 int ci, block_row, block_rows, access_rows;
3825 short[][][] buffer;
3826 short[][] buffer_ptr, prev_block_row, next_block_row;
3827 byte[][] output_ptr;
3828 int output_col;
3829 jpeg_component_info compptr;
3830 // inverse_DCT_method_ptr inverse_DCT;
3831 boolean first_row, last_row;
3832 short[] workspace = coef.workspace;
3833 if (workspace == null) workspace = coef.workspace = new short[DCTSIZE2];
3834 int[] coef_bits;
3835 JQUANT_TBL quanttbl;
3836 int Q00,Q01,Q02,Q10,Q11,Q20, num;
3837 int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
3838 int Al, pred;
3839
3840 /* Force some input to be done if we are getting ahead of the input. */
3841 while (cinfo.input_scan_number <= cinfo.output_scan_number && ! cinfo.inputctl.eoi_reached) {
3842 if (cinfo.input_scan_number == cinfo.output_scan_number) {
3843 /* If input is working on current scan, we ordinarily want it to
3844 * have completed the current row. But if input scan is DC,
3845 * we want it to keep one row ahead so that next block row's DC
3846 * values are up to date.
3847 */
3848 int delta = (cinfo.Ss == 0) ? 1 : 0;
3849 if (cinfo.input_iMCU_row > cinfo.output_iMCU_row+delta)
3850 break;
3851 }
3852 if (consume_input(cinfo) == JPEG_SUSPENDED)
3853 return JPEG_SUSPENDED;
3854 }
3855
3856 /* OK, output from the virtual arrays. */
3857 for (ci = 0; ci < cinfo.num_components; ci++) {
3858 compptr = cinfo.comp_info[ci];
3859 /* Don't bother to IDCT an uninteresting component. */
3860 if (! compptr.component_needed)
3861 continue;
3862 /* Count non-dummy DCT block rows in this iMCU row. */
3863 if (cinfo.output_iMCU_row < last_iMCU_row) {
3864 block_rows = compptr.v_samp_factor;
3865 access_rows = block_rows * 2; /* this and next iMCU row */
3866 last_row = false;
3867 } else {
3868 /* NB: can't use last_row_height here; it is input-side-dependent! */
3869 block_rows = (compptr.height_in_blocks % compptr.v_samp_factor);
3870 if (block_rows == 0) block_rows = compptr.v_samp_factor;
3871 access_rows = block_rows; /* this iMCU row only */
3872 last_row = true;
3873 }
3874 /* Align the virtual buffer for this component. */
3875 int buffer_offset;
3876 if (cinfo.output_iMCU_row > 0) {
3877 access_rows += compptr.v_samp_factor; /* prior iMCU row too */
3878 buffer = coef.whole_image[ci];
3879 buffer_offset = (cinfo.output_iMCU_row - 1) * compptr.v_samp_factor;
3880 buffer_offset += compptr.v_samp_factor; /* point to current iMCU row */
3881 first_row = false;
3882 } else {
3883 buffer = coef.whole_image[ci];
3884 buffer_offset = 0;
3885 first_row = true;
3886 }
3887 /* Fetch component-dependent info */
3888 coef_bits = coef.coef_bits_latch;
3889 int coef_offset = (ci * SAVED_COEFS);
3890 quanttbl = compptr.quant_table;
3891 Q00 = quanttbl.quantval[0];
3892 Q01 = quanttbl.quantval[Q01_POS];
3893 Q10 = quanttbl.quantval[Q10_POS];
3894 Q20 = quanttbl.quantval[Q20_POS];
3895 Q11 = quanttbl.quantval[Q11_POS];
3896 Q02 = quanttbl.quantval[Q02_POS];
3897 // inverse_DCT = cinfo.idct.inverse_DCT[ci];
3898 output_ptr = output_buf[ci];
3899 int output_ptr_offset = output_buf_offset[ci];
3900 /* Loop over all DCT blocks to be processed. */
3901 for (block_row = 0; block_row < block_rows; block_row++) {
3902 buffer_ptr = buffer[block_row+buffer_offset];
3903 int buffer_ptr_offset = 0, prev_block_row_offset = 0, next_block_row_offset = 0;
3904 if (first_row && block_row == 0) {
3905 prev_block_row = buffer_ptr;
3906 prev_block_row_offset = buffer_ptr_offset;
3907 } else {
3908 prev_block_row = buffer[block_row-1+buffer_offset];
3909 prev_block_row_offset = 0;
3910 }
3911 if (last_row && block_row == block_rows-1) {
3912 next_block_row = buffer_ptr;
3913 next_block_row_offset = buffer_ptr_offset;
3914 } else {
3915 next_block_row = buffer[block_row+1+buffer_offset];
3916 next_block_row_offset = 0;
3917 }
3918 /* We fetch the surrounding DC values using a sliding-register approach.
3919 * Initialize all nine here so as to do the right thing on narrow pics.
3920 */
3921 DC1 = DC2 = DC3 = prev_block_row[0+prev_block_row_offset][0];
3922 DC4 = DC5 = DC6 = buffer_ptr[0+buffer_ptr_offset][0];
3923 DC7 = DC8 = DC9 = next_block_row[0+next_block_row_offset][0];
3924 output_col = 0;
3925 last_block_column = compptr.width_in_blocks - 1;
3926 for (block_num = 0; block_num <= last_block_column; block_num++) {
3927 /* Fetch current DCT block into workspace so we can modify it. */
3928 // jcopy_block_row(buffer_ptr, workspace, 1);
3929 System.arraycopy(buffer_ptr[buffer_ptr_offset], 0, workspace, 0, workspace.length);
3930 /* Update DC values */
3931 if (block_num < last_block_column) {
3932 DC3 = prev_block_row[1+prev_block_row_offset][0];
3933 DC6 = buffer_ptr[1+buffer_ptr_offset][0];
3934 DC9 = next_block_row[1+next_block_row_offset][0];
3935 }
3936 /* Compute coefficient estimates per K.8.
3937 * An estimate is applied only if coefficient is still zero,
3938 * and is not known to be fully accurate.
3939 */
3940 /* AC01 */
3941 if ((Al=coef_bits[1+coef_offset]) != 0 && workspace[1] == 0) {
3942 num = 36 * Q00 * (DC4 - DC6);
3943 if (num >= 0) {
3944 pred = (((Q01<<7) + num) / (Q01<<8));
3945 if (Al > 0 && pred >= (1<<Al))
3946 pred = (1<<Al)-1;
3947 } else {
3948 pred = (((Q01<<7) - num) / (Q01<<8));
3949 if (Al > 0 && pred >= (1<<Al))
3950 pred = (1<<Al)-1;
3951 pred = -pred;
3952 }
3953 workspace[1] = (short) pred;
3954 }
3955 /* AC10 */
3956 if ((Al=coef_bits[2+coef_offset]) != 0 && workspace[8] == 0) {
3957 num = 36 * Q00 * (DC2 - DC8);
3958 if (num >= 0) {
3959 pred = (((Q10<<7) + num) / (Q10<<8));
3960 if (Al > 0 && pred >= (1<<Al))
3961 pred = (1<<Al)-1;
3962 } else {
3963 pred = (((Q10<<7) - num) / (Q10<<8));
3964 if (Al > 0 && pred >= (1<<Al))
3965 pred = (1<<Al)-1;
3966 pred = -pred;
3967 }
3968 workspace[8] = (short) pred;
3969 }
3970 /* AC20 */
3971 if ((Al=coef_bits[3+coef_offset]) != 0 && workspace[16] == 0) {
3972 num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
3973 if (num >= 0) {
3974 pred = (((Q20<<7) + num) / (Q20<<8));
3975 if (Al > 0 && pred >= (1<<Al))
3976 pred = (1<<Al)-1;
3977 } else {
3978 pred = (((Q20<<7) - num) / (Q20<<8));
3979 if (Al > 0 && pred >= (1<<Al))
3980 pred = (1<<Al)-1;
3981 pred = -pred;
3982 }
3983 workspace[16] = (short) pred;
3984 }
3985 /* AC11 */
3986 if ((Al=coef_bits[4+coef_offset]) != 0 && workspace[9] == 0) {
3987 num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
3988 if (num >= 0) {
3989 pred = (((Q11<<7) + num) / (Q11<<8));
3990 if (Al > 0 && pred >= (1<<Al))
3991 pred = (1<<Al)-1;
3992 } else {
3993 pred = (((Q11<<7) - num) / (Q11<<8));
3994 if (Al > 0 && pred >= (1<<Al))
3995 pred = (1<<Al)-1;
3996 pred = -pred;
3997 }
3998 workspace[9] = (short) pred;
3999 }
4000 /* AC02 */
4001 if ((Al=coef_bits[5+coef_offset]) != 0 && workspace[2] == 0) {
4002 num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
4003 if (num >= 0) {
4004 pred = (((Q02<<7) + num) / (Q02<<8));
4005 if (Al > 0 && pred >= (1<<Al))
4006 pred = (1<<Al)-1;
4007 } else {
4008 pred = (((Q02<<7) - num) / (Q02<<8));
4009 if (Al > 0 && pred >= (1<<Al))
4010 pred = (1<<Al)-1;
4011 pred = -pred;
4012 }
4013 workspace[2] = (short) pred;
4014 }
4015 /* OK, do the IDCT */
4016 jpeg_idct_islow(cinfo, compptr, workspace, output_ptr, output_ptr_offset, output_col);
4017 /* Advance for next column */
4018 DC1 = DC2; DC2 = DC3;
4019 DC4 = DC5; DC5 = DC6;
4020 DC7 = DC8; DC8 = DC9;
4021 buffer_ptr_offset++; prev_block_row_offset++; next_block_row_offset++;
4022 output_col += compptr.DCT_scaled_size;
4023 }
4024 output_ptr_offset += compptr.DCT_scaled_size;
4025 }
4026 }
4027
4028 if (++(cinfo.output_iMCU_row) < cinfo.total_iMCU_rows)
4029 return JPEG_ROW_COMPLETED;
4030 return JPEG_SCAN_COMPLETED;
4031 }
4032
4033 static int decompress_data (jpeg_decompress_struct cinfo, byte[][][] output_buf, int[] output_buf_offset) {
4034 jpeg_d_coef_controller coef = cinfo.coef;
4035 int last_iMCU_row = cinfo.total_iMCU_rows - 1;
4036 int block_num;
4037 int ci, block_row, block_rows;
4038 short[][][] buffer;
4039 short[][] buffer_ptr;
4040 byte[][] output_ptr;
4041 int output_col;
4042 jpeg_component_info compptr;
4043 // inverse_DCT_method_ptr inverse_DCT;
4044
4045 /* Force some input to be done if we are getting ahead of the input. */
4046 while (cinfo.input_scan_number < cinfo.output_scan_number ||
4047 (cinfo.input_scan_number == cinfo.output_scan_number &&
4048 cinfo.input_iMCU_row <= cinfo.output_iMCU_row))
4049 {
4050 if (consume_input(cinfo) == JPEG_SUSPENDED)
4051 return JPEG_SUSPENDED;
4052 }
4053
4054 /* OK, output from the virtual arrays. */
4055 for (ci = 0; ci < cinfo.num_components; ci++) {
4056 compptr = cinfo.comp_info[ci];
4057 /* Don't bother to IDCT an uninteresting component. */
4058 if (! compptr.component_needed)
4059 continue;
4060 /* Align the virtual buffer for this component. */
4061 buffer = coef.whole_image[ci];
4062 int buffer_offset = cinfo.output_iMCU_row * compptr.v_samp_factor;
4063 /* Count non-dummy DCT block rows in this iMCU row. */
4064 if (cinfo.output_iMCU_row < last_iMCU_row)
4065 block_rows = compptr.v_samp_factor;
4066 else {
4067 /* NB: can't use last_row_height here; it is input-side-dependent! */
4068 block_rows = (compptr.height_in_blocks % compptr.v_samp_factor);
4069 if (block_rows == 0) block_rows = compptr.v_samp_factor;
4070 }
4071 // inverse_DCT = cinfo.idct.inverse_DCT[ci];
4072 output_ptr = output_buf[ci];
4073 int output_ptr_offset = output_buf_offset[ci];
4074 /* Loop over all DCT blocks to be processed. */
4075 for (block_row = 0; block_row < block_rows; block_row++) {
4076 buffer_ptr = buffer[block_row+buffer_offset];
4077 int buffer_ptr_offset = 0;
4078 output_col = 0;
4079 for (block_num = 0; block_num < compptr.width_in_blocks; block_num++) {
4080 jpeg_idct_islow(cinfo, compptr, buffer_ptr[buffer_ptr_offset], output_ptr, output_ptr_offset, output_col);
4081
4082 buffer_ptr_offset++;
4083 output_col += compptr.DCT_scaled_size;
4084 }
4085 output_ptr_offset += compptr.DCT_scaled_size;
4086 }
4087 }
4088
4089 if (++(cinfo.output_iMCU_row) < cinfo.total_iMCU_rows)
4090 return JPEG_ROW_COMPLETED;
4091 return JPEG_SCAN_COMPLETED;
4092 }
4093
4094 static void post_process_data (jpeg_decompress_struct cinfo,
4095 byte[][][] input_buf, int[] input_buf_offset, int[] in_row_group_ctr,
4096 int in_row_groups_avail,
4097 byte[][] output_buf, int[] out_row_ctr,
4098 int out_rows_avail)
4099 {
4100 upsample(cinfo, input_buf, input_buf_offset, in_row_group_ctr, in_row_groups_avail, output_buf, out_row_ctr, out_rows_avail);
4101 }
4102
4103 static void set_bottom_pointers (jpeg_decompress_struct cinfo)
4104 /* Change the pointer lists to duplicate the last sample row at the bottom
4105 * of the image. whichptr indicates which xbuffer holds the final iMCU row.
4106 * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
4107 */
4108 {
4109 jpeg_d_main_controller main = cinfo.main;
4110 int ci, i, rgroup, iMCUheight, rows_left;
4111 jpeg_component_info compptr;
4112 byte[][] xbuf;
4113
4114 for (ci = 0; ci < cinfo.num_components; ci++) {
4115 compptr = cinfo.comp_info[ci];
4116 /* Count sample rows in one iMCU row and in one row group */
4117 iMCUheight = compptr.v_samp_factor * compptr.DCT_scaled_size;
4118 rgroup = iMCUheight / cinfo.min_DCT_scaled_size;
4119 /* Count nondummy sample rows remaining for this component */
4120 rows_left = (compptr.downsampled_height % iMCUheight);
4121 if (rows_left == 0) rows_left = iMCUheight;
4122 /* Count nondummy row groups. Should get same answer for each component,
4123 * so we need only do it once.
4124 */
4125 if (ci == 0) {
4126 main.rowgroups_avail = ((rows_left-1) / rgroup + 1);
4127 }
4128 /* Duplicate the last real sample row rgroup*2 times; this pads out the
4129 * last partial rowgroup and ensures at least one full rowgroup of context.
4130 */
4131 xbuf = main.xbuffer[main.whichptr][ci];
4132 int xbuf_offset = main.xbuffer_offset[main.whichptr][ci];
4133 for (i = 0; i < rgroup * 2; i++) {
4134 xbuf[rows_left + i + xbuf_offset] = xbuf[rows_left-1 + xbuf_offset];
4135 }
4136 }
4137 }
4138
4139 static void set_wraparound_pointers (jpeg_decompress_struct cinfo)
4140 /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
4141 * This changes the pointer list state from top-of-image to the normal state.
4142 */
4143 {
4144 jpeg_d_main_controller main = cinfo.main;
4145 int ci, i, rgroup;
4146 int M = cinfo.min_DCT_scaled_size;
4147 jpeg_component_info compptr;
4148 byte[][] xbuf0, xbuf1;
4149
4150 for (ci = 0; ci < cinfo.num_components; ci++) {
4151 compptr = cinfo.comp_info[ci];
4152 rgroup = (compptr.v_samp_factor * compptr.DCT_scaled_size) / cinfo.min_DCT_scaled_size; /* height of a row group of component */
4153 xbuf0 = main.xbuffer[0][ci];
4154 int xbuf0_offset = main.xbuffer_offset[0][ci];
4155 xbuf1 = main.xbuffer[1][ci];
4156 int xbuf1_offset = main.xbuffer_offset[1][ci];
4157 for (i = 0; i < rgroup; i++) {
4158 xbuf0[i - rgroup + xbuf0_offset] = xbuf0[rgroup*(M+1) + i + xbuf0_offset];
4159 xbuf1[i - rgroup + xbuf1_offset] = xbuf1[rgroup*(M+1) + i + xbuf1_offset];
4160 xbuf0[rgroup*(M+2) + i + xbuf0_offset] = xbuf0[i + xbuf0_offset];
4161 xbuf1[rgroup*(M+2) + i + xbuf1_offset] = xbuf1[i + xbuf1_offset];
4162 }
4163 }
4164 }
4165
4166 static void process_data_crank_post (jpeg_decompress_struct cinfo,
4167 byte[][] output_buf, int[] out_row_ctr,
4168 int out_rows_avail)
4169 {
4170 error();
4171 }
4172
4173 static void process_data_context_main (jpeg_decompress_struct cinfo,
4174 byte[][] output_buf, int[] out_row_ctr,
4175 int out_rows_avail)
4176 {
4177 jpeg_d_main_controller main = cinfo.main;
4178
4179 /* Read input data if we haven't filled the main buffer yet */
4180 if (! main.buffer_full) {
4181 int result;
4182 switch (cinfo.coef.decompress_data) {
4183 case DECOMPRESS_DATA:
4184 result = decompress_data(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]);
4185 break;
4186 case DECOMPRESS_SMOOTH_DATA:
4187 result = decompress_smooth_data(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]);
4188 break;
4189 case DECOMPRESS_ONEPASS:
4190 result = decompress_onepass(cinfo, main.xbuffer[main.whichptr], main.xbuffer_offset[main.whichptr]);
4191 break;
4192 default: result = 0;
4193 }
4194 if (result == 0)
4195 return; /* suspension forced, can do nothing more */
4196 main.buffer_full = true; /* OK, we have an iMCU row to work with */
4197 main.iMCU_row_ctr++; /* count rows received */
4198 }
4199
4200 /* Postprocessor typically will not swallow all the input data it is handed
4201 * in one call (due to filling the output buffer first). Must be prepared
4202 * to exit and restart. This switch lets us keep track of how far we got.
4203 * Note that each case falls through to the next on successful completion.
4204 */
4205 switch (main.context_state) {
4206 case CTX_POSTPONED_ROW:
4207 /* Call postprocessor using previously set pointers for postponed row */
4208 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);
4209 if (main.rowgroup_ctr[0] < main.rowgroups_avail)
4210 return; /* Need to suspend */
4211 main.context_state = CTX_PREPARE_FOR_IMCU;
4212 if (out_row_ctr[0] >= out_rows_avail)
4213 return; /* Postprocessor exactly filled output buf */
4214 /*FALLTHROUGH*/
4215 case CTX_PREPARE_FOR_IMCU:
4216 /* Prepare to process first M-1 row groups of this iMCU row */
4217 main.rowgroup_ctr[0] = 0;
4218 main.rowgroups_avail = (cinfo.min_DCT_scaled_size - 1);
4219 /* Check for bottom of image: if so, tweak pointers to "duplicate"
4220 * the last sample row, and adjust rowgroups_avail to ignore padding rows.
4221 */
4222 if (main.iMCU_row_ctr == cinfo.total_iMCU_rows)
4223 set_bottom_pointers(cinfo);
4224 main.context_state = CTX_PROCESS_IMCU;
4225 /*FALLTHROUGH*/
4226 case CTX_PROCESS_IMCU:
4227 /* Call postprocessor using previously set pointers */
4228 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);
4229 if (main.rowgroup_ctr[0] < main.rowgroups_avail)
4230 return; /* Need to suspend */
4231 /* After the first iMCU, change wraparound pointers to normal state */
4232 if (main.iMCU_row_ctr == 1)
4233 set_wraparound_pointers(cinfo);
4234 /* Prepare to load new iMCU row using other xbuffer list */
4235 main.whichptr ^= 1; /* 0=>1 or 1=>0 */
4236 main.buffer_full = false;
4237 /* Still need to process last row group of this iMCU row, */
4238 /* which is saved at index M+1 of the other xbuffer */
4239 main.rowgroup_ctr[0] = (cinfo.min_DCT_scaled_size + 1);
4240 main.rowgroups_avail = (cinfo.min_DCT_scaled_size + 2);
4241 main.context_state = CTX_POSTPONED_ROW;
4242 }
4243 }
4244
4245 static void process_data_simple_main (jpeg_decompress_struct cinfo, byte[][] output_buf, int[] out_row_ctr, int out_rows_avail) {
4246 jpeg_d_main_controller main = cinfo.main;
4247 int rowgroups_avail;
4248
4249 /* Read input data if we haven't filled the main buffer yet */
4250 if (! main.buffer_full) {
4251 int result;
4252 switch (cinfo.coef.decompress_data) {
4253 case DECOMPRESS_DATA:
4254 result = decompress_data(cinfo, main.buffer, main.buffer_offset);
4255 break;
4256 case DECOMPRESS_SMOOTH_DATA:
4257 result = decompress_smooth_data(cinfo, main.buffer, main.buffer_offset);
4258 break;
4259 case DECOMPRESS_ONEPASS:
4260 result = decompress_onepass(cinfo, main.buffer, main.buffer_offset);
4261 break;
4262 default: result = 0;
4263 }
4264 if (result == 0)
4265 return; /* suspension forced, can do nothing more */
4266 main.buffer_full = true; /* OK, we have an iMCU row to work with */
4267 }
4268
4269 /* There are always min_DCT_scaled_size row groups in an iMCU row. */
4270 rowgroups_avail = cinfo.min_DCT_scaled_size;
4271 /* Note: at the bottom of the image, we may pass extra garbage row groups
4272 * to the postprocessor. The postprocessor has to check for bottom
4273 * of image anyway (at row resolution), so no point in us doing it too.
4274 */
4275
4276 /* Feed the postprocessor */
4277 post_process_data (cinfo, main.buffer, main.buffer_offset, main.rowgroup_ctr, rowgroups_avail, output_buf, out_row_ctr, out_rows_avail);
4278
4279 /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
4280 if (main.rowgroup_ctr[0] >= rowgroups_avail) {
4281 main.buffer_full = false;
4282 main.rowgroup_ctr[0] = 0;
4283 }
4284 }
4285
4286 static int jpeg_read_scanlines (jpeg_decompress_struct cinfo, byte[][] scanlines, int max_lines) {
4287
4288 if (cinfo.global_state != DSTATE_SCANNING)
4289 error();
4290 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
4291 if (cinfo.output_scanline >= cinfo.output_height) {
4292 // WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
4293 return 0;
4294 }
4295
4296 /* Call progress monitor hook if present */
4297 // if (cinfo.progress != NULL) {
4298 // cinfo.progress.pass_counter = (long) cinfo.output_scanline;
4299 // cinfo.progress.pass_limit = (long) cinfo.output_height;
4300 // (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo);
4301 // }
4302
4303 /* Process some data */
4304 cinfo.row_ctr[0] = 0;
4305 switch (cinfo.main.process_data) {
4306 case PROCESS_DATA_SIMPLE_MAIN:
4307 process_data_simple_main (cinfo, scanlines, cinfo.row_ctr, max_lines);
4308 break;
4309 case PROCESS_DATA_CONTEXT_MAIN:
4310 process_data_context_main (cinfo, scanlines, cinfo.row_ctr, max_lines);
4311 break;
4312 case PROCESS_DATA_CRANK_POST:
4313 process_data_crank_post (cinfo, scanlines, cinfo.row_ctr, max_lines);
4314 break;
4315 default: error();
4316 }
4317 cinfo.output_scanline += cinfo.row_ctr[0];
4318 return cinfo.row_ctr[0];
4319 }
4320
4321
4322 static boolean output_pass_setup (jpeg_decompress_struct cinfo) {
4323 if (cinfo.global_state != DSTATE_PRESCAN) {
4324 /* First call: do pass setup */
4325 prepare_for_output_pass (cinfo);
4326 cinfo.output_scanline = 0;
4327 cinfo.global_state = DSTATE_PRESCAN;
4328 }
4329 /* Loop over any required dummy passes */
4330 while (cinfo.master.is_dummy_pass) {
4331 error();
4332 //#ifdef QUANT_2PASS_SUPPORTED
4333 // /* Crank through the dummy pass */
4334 // while (cinfo.output_scanline < cinfo.output_height) {
4335 // JDIMENSION last_scanline;
4336 // /* Call progress monitor hook if present */
4337 // if (cinfo.progress != NULL) {
4338 // cinfo.progress.pass_counter = (long) cinfo.output_scanline;
4339 // cinfo.progress.pass_limit = (long) cinfo.output_height;
4340 // (*cinfo.progress.progress_monitor) ((j_common_ptr) cinfo);
4341 // }
4342 // /* Process some data */
4343 // last_scanline = cinfo.output_scanline;
4344 // (*cinfo.main.process_data) (cinfo, (JSAMPARRAY) NULL,
4345 // &cinfo.output_scanline, (JDIMENSION) 0);
4346 // if (cinfo.output_scanline == last_scanline)
4347 // return FALSE; /* No progress made, must suspend */
4348 // }
4349 // /* Finish up dummy pass, and set up for another one */
4350 // (*cinfo.master.finish_output_pass) (cinfo);
4351 // (*cinfo.master.prepare_for_output_pass) (cinfo);
4352 // cinfo.output_scanline = 0;
4353 //#else
4354 // ERREXIT(cinfo, JERR_NOT_COMPILED);
4355 //#endif /* QUANT_2PASS_SUPPORTED */
4356 }
4357 /* Ready for application to drive output pass through
4358 * jpeg_read_scanlines or jpeg_read_raw_data.
4359 */
4360 cinfo.global_state = cinfo.raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
4361 return true;
4362 }
4363
4364 static boolean get_dht (jpeg_decompress_struct cinfo)
4365 /* Process a DHT marker */
4366 {
4367 int length;
4368 byte[] bits = new byte[17];
4369 byte[] huffval = new byte[256];
4370 int i, index, count;
4371 JHUFF_TBL htblptr;
4372
4373 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4374 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4375 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4376 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4377 length -= 2;
4378
4379 while (length > 16) {
4380 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4381 index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4382
4383 // TRACEMS1(cinfo, 1, JTRC_DHT, index);
4384
4385 bits[0] = 0;
4386 count = 0;
4387 for (i = 1; i <= 16; i++) {
4388 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4389 bits[i] = cinfo.buffer[cinfo.bytes_offset++];
4390 count += bits[i] & 0xFF;
4391 }
4392
4393 length -= 1 + 16;
4394
4395 // TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
4396 // bits[1], bits[2], bits[3], bits[4],
4397 // bits[5], bits[6], bits[7], bits[8]);
4398 // TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
4399 // bits[9], bits[10], bits[11], bits[12],
4400 // bits[13], bits[14], bits[15], bits[16]);
4401
4402 /* Here we just do minimal validation of the counts to avoid walking
4403 * off the end of our table space. jdhuff.c will check more carefully.
4404 */
4405 if (count > 256 || (count) > length)
4406 error();
4407 // ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
4408
4409 for (i = 0; i < count; i++) {
4410 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4411 huffval[i] = cinfo.buffer[cinfo.bytes_offset++];
4412 }
4413
4414 length -= count;
4415
4416 if ((index & 0x10) != 0) { /* AC table definition */
4417 index -= 0x10;
4418 htblptr = cinfo.ac_huff_tbl_ptrs[index] = new JHUFF_TBL();
4419 } else { /* DC table definition */
4420 htblptr = cinfo.dc_huff_tbl_ptrs[index] = new JHUFF_TBL();
4421 }
4422
4423 if (index < 0 || index >= NUM_HUFF_TBLS)
4424 error();
4425 // ERREXIT1(cinfo, JERR_DHT_INDEX, index);
4426
4427 System.arraycopy(bits, 0, htblptr.bits, 0, bits.length);
4428 System.arraycopy(huffval, 0, htblptr.huffval, 0, huffval.length);
4429 }
4430
4431 if (length != 0)
4432 error();
4433 // ERREXIT(cinfo, JERR_BAD_LENGTH);
4434
4435 return true;
4436 }
4437
4438
4439 static boolean get_dqt (jpeg_decompress_struct cinfo)
4440 /* Process a DQT marker */
4441 {
4442 int length;
4443 int n, i, prec;
4444 int tmp;
4445 JQUANT_TBL quant_ptr;
4446
4447 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4448 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4449 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4450 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4451 length -= 2;
4452
4453 while (length > 0) {
4454 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4455 n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4456 prec = n >> 4;
4457 n &= 0x0F;
4458
4459 // TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
4460
4461 if (n >= NUM_QUANT_TBLS)
4462 error();
4463 // ERREXIT1(cinfo, JERR_DQT_INDEX, n);
4464
4465 if (cinfo.quant_tbl_ptrs[n] == null)
4466 cinfo.quant_tbl_ptrs[n] = new JQUANT_TBL();
4467 quant_ptr = cinfo.quant_tbl_ptrs[n];
4468
4469 for (i = 0; i < DCTSIZE2; i++) {
4470 if (prec != 0) {
4471 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4472 tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4473 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4474 tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4475 } else {
4476 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4477 tmp = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4478 }
4479 /* We convert the zigzag-order table to natural array order. */
4480 quant_ptr.quantval[jpeg_natural_order[i]] = (short) tmp;
4481 }
4482
4483 // if (cinfo.err.trace_level >= 2) {
4484 // for (i = 0; i < DCTSIZE2; i += 8) {
4485 // TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
4486 // quant_ptr.quantval[i], quant_ptr.quantval[i+1],
4487 // quant_ptr.quantval[i+2], quant_ptr.quantval[i+3],
4488 // quant_ptr.quantval[i+4], quant_ptr.quantval[i+5],
4489 // quant_ptr.quantval[i+6], quant_ptr.quantval[i+7]);
4490 // }
4491 // }
4492
4493 length -= (DCTSIZE2+1);
4494 if (prec != 0) length -= DCTSIZE2;
4495 }
4496
4497 if (length != 0)
4498 error();
4499 // ERREXIT(cinfo, JERR_BAD_LENGTH);
4500
4501 return true;
4502 }
4503
4504 static boolean get_dri (jpeg_decompress_struct cinfo)
4505 /* Process a DRI marker */
4506 {
4507 int length;
4508 int tmp;
4509
4510 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4511 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4512 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4513 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4514
4515 if (length != 4)
4516 error();
4517 // ERREXIT(cinfo, JERR_BAD_LENGTH);
4518
4519 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4520 tmp = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4521 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4522 tmp |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4523
4524 // TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
4525
4526 cinfo.restart_interval = tmp;
4527
4528 return true;
4529 }
4530
4531 static boolean get_dac (jpeg_decompress_struct cinfo)
4532 /* Process a DAC marker */
4533 {
4534 int length;
4535 int index, val;
4536 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4537 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4538 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4539 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4540 length -= 2;
4541
4542 while (length > 0) {
4543 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4544 index = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4545 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4546 val = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4547
4548 length -= 2;
4549
4550 // TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
4551
4552 if (index < 0 || index >= (2*NUM_ARITH_TBLS))
4553 error();
4554 // ERREXIT1(cinfo, JERR_DAC_INDEX, index);
4555
4556 if (index >= NUM_ARITH_TBLS) { /* define AC table */
4557 cinfo.arith_ac_K[index-NUM_ARITH_TBLS] = (byte) val;
4558 } else { /* define DC table */
4559 cinfo.arith_dc_L[index] = (byte) (val & 0x0F);
4560 cinfo.arith_dc_U[index] = (byte) (val >> 4);
4561 if (cinfo.arith_dc_L[index] > cinfo.arith_dc_U[index])
4562 error();
4563 // ERREXIT1(cinfo, JERR_DAC_VALUE, val);
4564 }
4565 }
4566
4567 if (length != 0)
4568 error();
4569 // ERREXIT(cinfo, JERR_BAD_LENGTH);
4570
4571 return true;
4572 }
4573
4574
4575 static boolean get_sos (jpeg_decompress_struct cinfo)
4576 /* Process a SOS marker */
4577 {
4578 int length;
4579 int i, ci, n, c, cc;
4580 jpeg_component_info compptr = null;
4581
4582 if (! cinfo.marker.saw_SOF)
4583 error();
4584 // ERREXIT(cinfo, JERR_SOS_NO_SOF);
4585
4586 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4587 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4588 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4589 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4590
4591 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4592 n = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4593
4594 // TRACEMS1(cinfo, 1, JTRC_SOS, n);
4595
4596 if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
4597 error();
4598 // ERREXIT(cinfo, JERR_BAD_LENGTH);
4599
4600 cinfo.comps_in_scan = n;
4601
4602 /* Collect the component-spec parameters */
4603
4604 for (i = 0; i < n; i++) {
4605 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4606 cc = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4607 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4608 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4609
4610 for (ci = 0; ci < cinfo.num_components; ci++) {
4611 compptr = cinfo.comp_info[ci];
4612 if (cc == compptr.component_id)
4613 break;
4614 }
4615
4616 if (ci == cinfo.num_components)
4617 error();
4618 // ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
4619
4620 cinfo.cur_comp_info[i] = compptr;
4621 compptr.dc_tbl_no = (c >> 4) & 15;
4622 compptr.ac_tbl_no = (c ) & 15;
4623
4624 // TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc, compptr.dc_tbl_no, compptr.ac_tbl_no);
4625 }
4626
4627 /* Collect the additional scan parameters Ss, Se, Ah/Al. */
4628 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4629 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4630 cinfo.Ss = c;
4631 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4632 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4633 cinfo.Se = c;
4634 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4635 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4636 cinfo.Ah = (c >> 4) & 15;
4637 cinfo.Al = (c ) & 15;
4638
4639 // TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo.Ss, cinfo.Se, cinfo.Ah, cinfo.Al);
4640
4641 /* Prepare to scan data & restart markers */
4642 cinfo.marker.next_restart_num = 0;
4643
4644 /* Count another SOS marker */
4645 cinfo.input_scan_number++;
4646
4647 return true;
4648 }
4649
4650 static boolean get_sof (jpeg_decompress_struct cinfo, boolean is_prog, boolean is_arith) {
4651 int length;
4652 int c, ci;
4653
4654 cinfo.progressive_mode = is_prog;
4655 cinfo.arith_code = is_arith;
4656
4657 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4658 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4659 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4660 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4661
4662 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4663 cinfo.data_precision = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4664
4665 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4666 cinfo.image_height = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4667 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4668 cinfo.image_height |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4669
4670 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4671 cinfo.image_width = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
4672 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4673 cinfo.image_width |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4674
4675 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4676 cinfo.num_components = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4677
4678 length -= 8;
4679
4680 // TRACEMS4(cinfo, 1, JTRC_SOF, cinfo.unread_marker,
4681 // (int) cinfo.image_width, (int) cinfo.image_height,
4682 // cinfo.num_components);
4683
4684 if (cinfo.marker.saw_SOF)
4685 error();
4686 // ERREXIT(cinfo, JERR_SOF_DUPLICATE);
4687
4688 /* We don't support files in which the image height is initially specified */
4689 /* as 0 and is later redefined by DNL. As long as we have to check that, */
4690 /* might as well have a general sanity check. */
4691 if (cinfo.image_height <= 0 || cinfo.image_width <= 0 || cinfo.num_components <= 0)
4692 error();
4693 // ERREXIT(cinfo, JERR_EMPTY_IMAGE);
4694
4695 if (length != (cinfo.num_components * 3))
4696 error();
4697 // ERREXIT(cinfo, JERR_BAD_LENGTH);
4698
4699 if (cinfo.comp_info == null) /* do only once, even if suspend */
4700 cinfo.comp_info = new jpeg_component_info[cinfo.num_components];
4701
4702 for (ci = 0; ci < cinfo.num_components; ci++) {
4703 jpeg_component_info compptr = cinfo.comp_info[ci] = new jpeg_component_info();
4704 compptr.component_index = ci;
4705 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4706 compptr.component_id = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4707 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4708 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4709 compptr.h_samp_factor = (c >> 4) & 15;
4710 compptr.v_samp_factor = (c ) & 15;
4711 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
4712 compptr.quant_tbl_no = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
4713
4714 // TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
4715 // compptr.component_id, compptr.h_samp_factor,
4716 // compptr.v_samp_factor, compptr.quant_tbl_no);
4717 }
4718
4719 cinfo.marker.saw_SOF = true;
4720
4721 return true;
4722 }
4723
4724 static void sep_upsample (jpeg_decompress_struct cinfo, byte[][][] input_buf, int[] input_buf_offset,
4725 int[] in_row_group_ctr, int in_row_groups_avail,
4726 byte[][] output_buf, int[] out_row_ctr, int out_rows_avail)
4727 {
4728 jpeg_upsampler upsample = cinfo.upsample;
4729 int ci;
4730 jpeg_component_info compptr;
4731 int num_rows;
4732
4733 /* Fill the conversion buffer, if it's empty */
4734 if (upsample.next_row_out >= cinfo.max_v_samp_factor) {
4735 for (ci = 0; ci < cinfo.num_components; ci++) {
4736 compptr = cinfo.comp_info[ci];
4737 /* Invoke per-component upsample method. Notice we pass a POINTER
4738 * to color_buf[ci], so that fullsize_upsample can change it.
4739 */
4740 int offset = input_buf_offset[ci] + (in_row_group_ctr[0] * upsample.rowgroup_height[ci]);
4741 switch (upsample.methods[ci]) {
4742 case NOOP_UPSAMPLE: noop_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4743 case FULLSIZE_UPSAMPLE: fullsize_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4744 case H2V1_FANCY_UPSAMPLE: h2v1_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4745 case H2V1_UPSAMPLE: h2v1_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4746 case H2V2_FANCY_UPSAMPLE: h2v2_fancy_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4747 case H2V2_UPSAMPLE: h2v2_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4748 case INT_UPSAMPLE: int_upsample(cinfo, compptr, input_buf[ci], offset, upsample.color_buf, upsample.color_buf_offset, ci); break;
4749 }
4750 }
4751 upsample.next_row_out = 0;
4752 }
4753
4754 /* Color-convert and emit rows */
4755
4756 /* How many we have in the buffer: */
4757 num_rows = (cinfo.max_v_samp_factor - upsample.next_row_out);
4758 /* Not more than the distance to the end of the image. Need this test
4759 * in case the image height is not a multiple of max_v_samp_factor:
4760 */
4761 if (num_rows > upsample.rows_to_go)
4762 num_rows = upsample.rows_to_go;
4763 /* And not more than what the client can accept: */
4764 out_rows_avail -= out_row_ctr[0];
4765 if (num_rows > out_rows_avail)
4766 num_rows = out_rows_avail;
4767
4768 switch (cinfo.cconvert.color_convert) {
4769 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;
4770 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;
4771 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;
4772 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;
4773 case YCCK_CMYK_CONVERT: error(); break;
4774 }
4775
4776 /* Adjust counts */
4777 out_row_ctr[0] += num_rows;
4778 upsample.rows_to_go -= num_rows;
4779 upsample.next_row_out += num_rows;
4780 /* When the buffer is emptied, declare this input row group consumed */
4781 if (upsample.next_row_out >= cinfo.max_v_samp_factor) {
4782 in_row_group_ctr[0]++;
4783 }
4784 }
4785
4786 static void noop_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4787 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4788 {
4789 output_data_ptr[output_data_index] = null; /* safety check */
4790 }
4791
4792 static void fullsize_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4793 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4794 {
4795 output_data_ptr[output_data_index] = input_data;
4796 output_data_offset[output_data_index] = input_data_offset;
4797 }
4798
4799 static void h2v1_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4800 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4801 {
4802 byte[][] output_data = output_data_ptr[output_data_index];
4803 byte[] inptr, outptr;
4804 byte invalue;
4805 int outend;
4806 int inrow;
4807 output_data_offset[output_data_index] = 0;
4808
4809 for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) {
4810 inptr = input_data[inrow+input_data_offset];
4811 outptr = output_data[inrow];
4812 int inptr_offset = 0, outptr_offset = 0;
4813 outend = outptr_offset + cinfo.output_width;
4814 while (outptr_offset < outend) {
4815 invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */
4816 outptr[outptr_offset++] = invalue;
4817 outptr[outptr_offset++] = invalue;
4818 }
4819 }
4820 }
4821
4822 static void h2v2_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4823 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4824 {
4825 byte[][] output_data = output_data_ptr[output_data_index];
4826 byte[] inptr, outptr;
4827 byte invalue;
4828 int outend;
4829 int inrow, outrow;
4830 output_data_offset[output_data_index] = 0;
4831
4832 inrow = outrow = 0;
4833 while (outrow < cinfo.max_v_samp_factor) {
4834 inptr = input_data[inrow+input_data_offset];
4835 outptr = output_data[outrow];
4836 int inptr_offset = 0, outptr_offset = 0;
4837 outend = outptr_offset + cinfo.output_width;
4838 while (outptr_offset < outend) {
4839 invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */
4840 outptr[outptr_offset++] = invalue;
4841 outptr[outptr_offset++] = invalue;
4842 }
4843 jcopy_sample_rows(output_data, outrow, output_data, outrow+1, 1, cinfo.output_width);
4844 inrow++;
4845 outrow += 2;
4846 }
4847 }
4848
4849 static void h2v1_fancy_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4850 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4851 {
4852 byte[][] output_data = output_data_ptr[output_data_index];
4853 byte[] inptr, outptr;
4854 int invalue;
4855 int colctr;
4856 int inrow;
4857 output_data_offset[output_data_index] = 0;
4858
4859 for (inrow = 0; inrow < cinfo.max_v_samp_factor; inrow++) {
4860 inptr = input_data[inrow+input_data_offset];
4861 outptr = output_data[inrow];
4862 int inptr_offset = 0, outptr_offset = 0;
4863 /* Special case for first column */
4864 invalue = inptr[inptr_offset++] & 0xFF;
4865 outptr[outptr_offset++] = (byte) invalue;
4866 outptr[outptr_offset++] = (byte) ((invalue * 3 + (inptr[inptr_offset] & 0xFF) + 2) >> 2);
4867
4868 for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) {
4869 /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
4870 invalue = (inptr[inptr_offset++] & 0xFF) * 3;
4871 outptr[outptr_offset++] = (byte) ((invalue + (inptr[inptr_offset-2] & 0xFF) + 1) >> 2);
4872 outptr[outptr_offset++] = (byte) ((invalue + (inptr[inptr_offset] & 0xFF) + 2) >> 2);
4873 }
4874
4875 /* Special case for last column */
4876 invalue = (inptr[inptr_offset] & 0xFF);
4877 outptr[outptr_offset++] = (byte) ((invalue * 3 + (inptr[inptr_offset-1] & 0xFF) + 1) >> 2);
4878 outptr[outptr_offset++] = (byte) invalue;
4879 }
4880 }
4881
4882 static void h2v2_fancy_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4883 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4884 {
4885 byte[][] output_data = output_data_ptr[output_data_index];
4886 byte[] inptr0, inptr1, outptr;
4887 int thiscolsum, lastcolsum, nextcolsum;
4888 int colctr;
4889 int inrow, outrow, v;
4890 output_data_offset[output_data_index] = 0;
4891
4892 inrow = outrow = 0;
4893 while (outrow < cinfo.max_v_samp_factor) {
4894 for (v = 0; v < 2; v++) {
4895 /* inptr0 points to nearest input row, inptr1 points to next nearest */
4896 inptr0 = input_data[inrow+input_data_offset];
4897 if (v == 0) /* next nearest is row above */
4898 inptr1 = input_data[inrow-1+input_data_offset];
4899 else /* next nearest is row below */
4900 inptr1 = input_data[inrow+1+input_data_offset];
4901 outptr = output_data[outrow++];
4902
4903 int inptr0_offset = 0, inptr1_offset = 0, outptr_offset = 0;
4904
4905 /* Special case for first column */
4906 thiscolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF);
4907 nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF);
4908 outptr[outptr_offset++] = (byte) ((thiscolsum * 4 + 8) >> 4);
4909 outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
4910 lastcolsum = thiscolsum; thiscolsum = nextcolsum;
4911
4912 for (colctr = compptr.downsampled_width - 2; colctr > 0; colctr--) {
4913 /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
4914 /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
4915 nextcolsum = (inptr0[inptr0_offset++] & 0xFF) * 3 + (inptr1[inptr1_offset++] & 0xFF);
4916 outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
4917 outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
4918 lastcolsum = thiscolsum; thiscolsum = nextcolsum;
4919 }
4920
4921 /* Special case for last column */
4922 outptr[outptr_offset++] = (byte) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
4923 outptr[outptr_offset++] = (byte) ((thiscolsum * 4 + 7) >> 4);
4924 }
4925 inrow++;
4926 }
4927 }
4928
4929 static void int_upsample (jpeg_decompress_struct cinfo, jpeg_component_info compptr,
4930 byte[][] input_data, int input_data_offset, byte[][][] output_data_ptr, int[] output_data_offset, int output_data_index)
4931 {
4932 jpeg_upsampler upsample = cinfo.upsample;
4933 byte[][] output_data = output_data_ptr[output_data_index];
4934 byte[] inptr, outptr;
4935 byte invalue;
4936 int h;
4937 int outend;
4938 int h_expand, v_expand;
4939 int inrow, outrow;
4940 output_data_offset[output_data_index] = 0;
4941
4942 h_expand = upsample.h_expand[compptr.component_index];
4943 v_expand = upsample.v_expand[compptr.component_index];
4944
4945 inrow = outrow = 0;
4946 while (outrow < cinfo.max_v_samp_factor) {
4947 /* Generate one output row with proper horizontal expansion */
4948 inptr = input_data[inrow+input_data_offset];
4949 int inptr_offset = 0;
4950 outptr = output_data[outrow];
4951 int outptr_offset = 0;
4952 outend = outptr_offset + cinfo.output_width;
4953 while (outptr_offset < outend) {
4954 invalue = inptr[inptr_offset++]; /* don't need GETJSAMPLE() here */
4955 for (h = h_expand; h > 0; h--) {
4956 outptr[outptr_offset++] = invalue;
4957 }
4958 }
4959 /* Generate any additional output rows by duplicating the first one */
4960 if (v_expand > 1) {
4961 jcopy_sample_rows(output_data, outrow, output_data, outrow+1, v_expand-1, cinfo.output_width);
4962 }
4963 inrow++;
4964 outrow += v_expand;
4965 }
4966 }
4967
4968 static void null_convert (jpeg_decompress_struct cinfo,
4969 byte[][][] input_buf, int[] input_buf_offset, int input_row,
4970 byte[][] output_buf, int output_buf_offset, int num_rows)
4971 {
4972 byte[] inptr, outptr;
4973 int count;
4974 int num_components = cinfo.num_components;
4975 int num_cols = cinfo.output_width;
4976 int ci;
4977
4978 while (--num_rows >= 0) {
4979 for (ci = 0; ci < num_components; ci++) {
4980 inptr = input_buf[ci][input_row+input_buf_offset[0]];
4981 outptr = output_buf[output_buf_offset];
4982 /* BGR instead of RGB */
4983 int offset = 0;
4984 switch (ci) {
4985 case 2: offset = RGB_BLUE; break;
4986 case 1: offset = RGB_GREEN; break;
4987 case 0: offset = RGB_RED; break;
4988 }
4989 int outptr_offset = offset, inptr_offset = 0;
4990 for (count = num_cols; count > 0; count--) {
4991 outptr[outptr_offset] = inptr[inptr_offset++]; /* needn't bother with GETJSAMPLE() here */
4992 outptr_offset += num_components;
4993 }
4994 }
4995 input_row++;
4996 output_buf_offset++;
4997 }
4998 }
4999
5000 static void grayscale_convert (jpeg_decompress_struct cinfo,
5001 byte[][][] input_buf, int[] input_buf_offset, int input_row,
5002 byte[][] output_buf, int output_buf_offset, int num_rows)
5003 {
5004 jcopy_sample_rows(input_buf[0], input_row+input_buf_offset[0], output_buf, output_buf_offset,
5005 num_rows, cinfo.output_width);
5006 }
5007
5008 static void gray_rgb_convert (jpeg_decompress_struct cinfo,
5009 byte[][][] input_buf, int[] input_buf_offset, int input_row,
5010 byte[][] output_buf, int output_buf_offset, int num_rows)
5011 {
5012 byte[] inptr, outptr;
5013 int col;
5014 int num_cols = cinfo.output_width;
5015
5016 while (--num_rows >= 0) {
5017 inptr = input_buf[0][input_row+++input_buf_offset[0]];
5018 outptr = output_buf[output_buf_offset++];
5019 int outptr_offset = 0;
5020 for (col = 0; col < num_cols; col++) {
5021 /* We can dispense with GETJSAMPLE() here */
5022 outptr[RGB_RED+outptr_offset] = outptr[RGB_GREEN+outptr_offset] = outptr[RGB_BLUE+outptr_offset] = inptr[col];
5023 outptr_offset += RGB_PIXELSIZE;
5024 }
5025 }
5026 }
5027
5028 static void ycc_rgb_convert (jpeg_decompress_struct cinfo,
5029 byte[][][] input_buf, int[] input_buf_offset, int input_row,
5030 byte[][] output_buf, int output_buf_offset, int num_rows)
5031 {
5032 jpeg_color_deconverter cconvert = cinfo.cconvert;
5033 int y, cb, cr;
5034 byte[] outptr;
5035 byte[] inptr0, inptr1, inptr2;
5036 int col;
5037 int num_cols = cinfo.output_width;
5038 /* copy these pointers into registers if possible */
5039 byte[] range_limit = cinfo.sample_range_limit;
5040 int range_limit_offset = cinfo.sample_range_limit_offset;
5041 int[] Crrtab = cconvert.Cr_r_tab;
5042 int[] Cbbtab = cconvert.Cb_b_tab;
5043 int[] Crgtab = cconvert.Cr_g_tab;
5044 int[] Cbgtab = cconvert.Cb_g_tab;
5045 // SHIFT_TEMPS
5046
5047 while (--num_rows >= 0) {
5048 inptr0 = input_buf[0][input_row+input_buf_offset[0]];
5049 inptr1 = input_buf[1][input_row+input_buf_offset[1]];
5050 inptr2 = input_buf[2][input_row+input_buf_offset[2]];
5051 input_row++;
5052 outptr = output_buf[output_buf_offset++];
5053 int outptr_offset = 0;
5054 for (col = 0; col < num_cols; col++) {
5055 y = (inptr0[col] & 0xFF);
5056 cb = (inptr1[col] & 0xFF);
5057 cr = (inptr2[col] & 0xFF);
5058 /* Range-limiting is essential due to noise introduced by DCT losses. */
5059 outptr[outptr_offset + RGB_RED] = range_limit[y + Crrtab[cr] + range_limit_offset];
5060 outptr[outptr_offset + RGB_GREEN] = range_limit[y + ((Cbgtab[cb] + Crgtab[cr]>>SCALEBITS)) + range_limit_offset];
5061 outptr[outptr_offset + RGB_BLUE] = range_limit[y + Cbbtab[cb] + range_limit_offset];
5062 outptr_offset += RGB_PIXELSIZE;
5063 }
5064 }
5065 }
5066
5067 static boolean process_APPn(int n, jpeg_decompress_struct cinfo) {
5068 if (n == 0 || n == 14) {
5069 return get_interesting_appn(cinfo);
5070 }
5071 return skip_variable(cinfo);
5072 }
5073
5074 static boolean process_COM(jpeg_decompress_struct cinfo) {
5075 return skip_variable(cinfo);
5076 }
5077
5078 static void skip_input_data (jpeg_decompress_struct cinfo, int num_bytes) {
5079 if (num_bytes > 0) {
5080 while (num_bytes > cinfo.bytes_in_buffer - cinfo.bytes_offset) {
5081 num_bytes -= cinfo.bytes_in_buffer - cinfo.bytes_offset;
5082 if (!fill_input_buffer(cinfo)) error();
5083 /* note we assume that fill_input_buffer will never return FALSE,
5084 * so suspension need not be handled.
5085 */
5086 }
5087 cinfo.bytes_offset += num_bytes;
5088 }
5089 }
5090
5091 static boolean skip_variable (jpeg_decompress_struct cinfo)
5092 /* Skip over an unknown or uninteresting variable-length marker */
5093 {
5094 int length;
5095
5096 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5097 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
5098 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5099 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5100
5101 length -= 2;
5102
5103 // TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo.unread_marker, (int) length);
5104
5105 if (length > 0) {
5106 skip_input_data (cinfo, length);
5107 }
5108
5109 return true;
5110 }
5111
5112 static boolean get_interesting_appn (jpeg_decompress_struct cinfo)
5113 /* Process an APP0 or APP14 marker without saving it */
5114 {
5115 int length;
5116 byte[] b = new byte[APPN_DATA_LEN];
5117 int i, numtoread;
5118
5119 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5120 length = (cinfo.buffer[cinfo.bytes_offset++] & 0xFF) << 8;
5121 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5122 length |= cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5123 length -= 2;
5124
5125 /* get the interesting part of the marker data */
5126 if (length >= APPN_DATA_LEN)
5127 numtoread = APPN_DATA_LEN;
5128 else if (length > 0)
5129 numtoread = length;
5130 else
5131 numtoread = 0;
5132 for (i = 0; i < numtoread; i++) {
5133 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5134 b[i] = cinfo.buffer[cinfo.bytes_offset++];
5135 }
5136 length -= numtoread;
5137
5138 /* process it */
5139 switch (cinfo.unread_marker) {
5140 case M_APP0:
5141 examine_app0(cinfo, b, numtoread, length);
5142 break;
5143 case M_APP14:
5144 examine_app14(cinfo, b, numtoread, length);
5145 break;
5146 default:
5147 /* can't get here unless jpeg_save_markers chooses wrong processor */
5148 error();
5149 // ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker);
5150 break;
5151 }
5152
5153 /* skip any remaining data -- could be lots */
5154 if (length > 0)
5155 skip_input_data (cinfo, length);
5156
5157 return true;
5158 }
5159
5160 static void examine_app0 (jpeg_decompress_struct cinfo, byte[] data, int datalen, int remaining)
5161 /* Examine first few bytes from an APP0.
5162 * Take appropriate action if it is a JFIF marker.
5163 * datalen is # of bytes at data[], remaining is length of rest of marker data.
5164 */
5165 {
5166 int totallen = datalen + remaining;
5167
5168 if (datalen >= APP0_DATA_LEN &&
5169 (data[0] & 0xFF) == 0x4A &&
5170 (data[1] & 0xFF) == 0x46 &&
5171 (data[2] & 0xFF) == 0x49 &&
5172 (data[3] & 0xFF) == 0x46 &&
5173 (data[4] & 0xFF) == 0)
5174 {
5175 /* Found JFIF APP0 marker: save info */
5176 cinfo.saw_JFIF_marker = true;
5177 cinfo.JFIF_major_version = (data[5]);
5178 cinfo.JFIF_minor_version = (byte)(data[6] & 0xFF);
5179 cinfo.density_unit = (byte)(data[7] & 0xFF);
5180 cinfo.X_density = (short)(((data[8] & 0xFF) << 8) + (data[9] & 0xFF));
5181 cinfo.Y_density = (short)(((data[10] & 0xFF) << 8) + (data[11] & 0xFF));
5182 /* Check version.
5183 * Major version must be 1, anything else signals an incompatible change.
5184 * (We used to treat this as an error, but now it's a nonfatal warning,
5185 * because some bozo at Hijaak couldn't read the spec.)
5186 * Minor version should be 0..2, but process anyway if newer.
5187 */
5188 if (cinfo.JFIF_major_version != 1) {
5189 // WARNMS2(cinfo, JWRN_JFIF_MAJOR,
5190 // cinfo.JFIF_major_version, cinfo.JFIF_minor_version);
5191 }
5192 /* Generate trace messages */
5193 // TRACEMS5(cinfo, 1, JTRC_JFIF,
5194 // cinfo.JFIF_major_version, cinfo.JFIF_minor_version,
5195 // cinfo.X_density, cinfo.Y_density, cinfo.density_unit);
5196 /* Validate thumbnail dimensions and issue appropriate messages */
5197 if (((data[12] & 0xFF) | (data[13]) & 0xFF) != 0) {
5198 // TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
5199 // GETJOCTET(data[12]), GETJOCTET(data[13]));
5200 }
5201 totallen -= APP0_DATA_LEN;
5202 if (totallen != ((data[12] & 0xFF) * (data[13] & 0xFF) * 3)) {
5203 // TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
5204 }
5205 } else if (datalen >= 6 &&
5206 (data[0] & 0xFF) == 0x4A &&
5207 (data[1] & 0xFF) == 0x46 &&
5208 (data[2] & 0xFF) == 0x58 &&
5209 (data[3] & 0xFF) == 0x58 &&
5210 (data[4] & 0xFF) == 0)
5211 {
5212 /* Found JFIF "JFXX" extension APP0 marker */
5213 /* The library doesn't actually do anything with these,
5214 * but we try to produce a helpful trace message.
5215 */
5216 switch ((data[5]) & 0xFF) {
5217 case 0x10:
5218 // TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
5219 break;
5220 case 0x11:
5221 // TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
5222 break;
5223 case 0x13:
5224 // TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
5225 break;
5226 default:
5227 // TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION, GETJOCTET(data[5]), (int) totallen);
5228 break;
5229 }
5230 } else {
5231 /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
5232 // TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
5233 }
5234 }
5235
5236 static void examine_app14 (jpeg_decompress_struct cinfo, byte[] data, int datalen, int remaining)
5237 /* Examine first few bytes from an APP14.
5238 * Take appropriate action if it is an Adobe marker.
5239 * datalen is # of bytes at data[], remaining is length of rest of marker data.
5240 */
5241 {
5242 int /*version, flags0, flags1, */transform;
5243
5244 if (datalen >= APP14_DATA_LEN &&
5245 (data[0] & 0xFF) == 0x41 &&
5246 (data[1] & 0xFF) == 0x64 &&
5247 (data[2] & 0xFF) == 0x6F &&
5248 (data[3] & 0xFF) == 0x62 &&
5249 (data[4] & 0xFF) == 0x65)
5250 {
5251 /* Found Adobe APP14 marker */
5252 // version = ((data[5] & 0xFF) << 8) + (data[6] & 0xFF);
5253 // flags0 = ((data[7] & 0xFF) << 8) + (data[8] & 0xFF);
5254 // flags1 = ((data[9] & 0xFF) << 8) + (data[10] & 0xFF);
5255 transform = (data[11] & 0xFF);
5256 // TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
5257 cinfo.saw_Adobe_marker = true;
5258 cinfo.Adobe_transform = (byte) transform;
5259 } else {
5260 /* Start of APP14 does not match "Adobe", or too short */
5261 // TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
5262 }
5263 }
5264
5265 static boolean get_soi (jpeg_decompress_struct cinfo) /* Process an SOI marker */ {
5266 int i;
5267
5268 // TRACEMS(cinfo, 1, JTRC_SOI);
5269
5270 if (cinfo.marker.saw_SOI)
5271 error();
5272 // ERREXIT(cinfo, JERR_SOI_DUPLICATE);
5273
5274 /* Reset all parameters that are defined to be reset by SOI */
5275
5276 for (i = 0; i < NUM_ARITH_TBLS; i++) {
5277 cinfo.arith_dc_L[i] = 0;
5278 cinfo.arith_dc_U[i] = 1;
5279 cinfo.arith_ac_K[i] = 5;
5280 }
5281 cinfo.restart_interval = 0;
5282
5283 /* Set initial assumptions for colorspace etc */
5284
5285 cinfo.jpeg_color_space = JCS_UNKNOWN;
5286 cinfo.CCIR601_sampling = false; /* Assume non-CCIR sampling??? */
5287
5288 cinfo.saw_JFIF_marker = false;
5289 cinfo.JFIF_major_version = 1; /* set default JFIF APP0 values */
5290 cinfo.JFIF_minor_version = 1;
5291 cinfo.density_unit = 0;
5292 cinfo.X_density = 1;
5293 cinfo.Y_density = 1;
5294 cinfo.saw_Adobe_marker = false;
5295 cinfo.Adobe_transform = 0;
5296
5297 cinfo.marker.saw_SOI = true;
5298
5299 return true;
5300 }
5301
5302 static void jinit_input_controller (jpeg_decompress_struct cinfo)
5303 {
5304 /* Initialize state: can't use reset_input_controller since we don't
5305 * want to try to reset other modules yet.
5306 */
5307 jpeg_input_controller inputctl = cinfo.inputctl = new jpeg_input_controller();
5308 inputctl.has_multiple_scans = false; /* "unknown" would be better */
5309 inputctl.eoi_reached = false;
5310 inputctl.inheaders = true;
5311 }
5312
5313 static void reset_marker_reader (jpeg_decompress_struct cinfo) {
5314 jpeg_marker_reader marker = cinfo.marker;
5315
5316 cinfo.comp_info = null; /* until allocated by get_sof */
5317 cinfo.input_scan_number = 0; /* no SOS seen yet */
5318 cinfo.unread_marker = 0; /* no pending marker */
5319 marker.saw_SOI = false; /* set internal state too */
5320 marker.saw_SOF = false;
5321 marker.discarded_bytes = 0;
5322 // marker.cur_marker = null;
5323 }
5324
5325 static void reset_input_controller (jpeg_decompress_struct cinfo) {
5326 jpeg_input_controller inputctl = cinfo.inputctl;
5327
5328 inputctl.has_multiple_scans = false; /* "unknown" would be better */
5329 inputctl.eoi_reached = false;
5330 inputctl.inheaders = true;
5331 /* Reset other modules */
5332 reset_marker_reader (cinfo);
5333 /* Reset progression state -- would be cleaner if entropy decoder did this */
5334 cinfo.coef_bits = null;
5335 }
5336
5337 static void finish_output_pass (jpeg_decompress_struct cinfo) {
5338 jpeg_decomp_master master = cinfo.master;
5339
5340 if (cinfo.quantize_colors) {
5341 error(SWT.ERROR_NOT_IMPLEMENTED);
5342 // (*cinfo.cquantize.finish_pass) (cinfo);
5343 }
5344 master.pass_number++;
5345 }
5346
5347 static void jpeg_destroy (jpeg_decompress_struct cinfo) {
5348 /* We need only tell the memory manager to release everything. */
5349 /* NB: mem pointer is NULL if memory mgr failed to initialize. */
5350 // if (cinfo.mem != NULL)
5351 // (*cinfo.mem.self_destruct) (cinfo);
5352 // cinfo.mem = NULL; /* be safe if jpeg_destroy is called twice */
5353 cinfo.global_state = 0; /* mark it destroyed */
5354 }
5355
5356 static void jpeg_destroy_decompress (jpeg_decompress_struct cinfo) {
5357 jpeg_destroy(cinfo); /* use common routine */
5358 }
5359
5360 static boolean jpeg_input_complete (jpeg_decompress_struct cinfo) {
5361 /* Check for valid jpeg object */
5362 if (cinfo.global_state < DSTATE_START || cinfo.global_state > DSTATE_STOPPING)
5363 error();
5364 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5365 return cinfo.inputctl.eoi_reached;
5366 }
5367
5368 static boolean jpeg_start_output (jpeg_decompress_struct cinfo, int scan_number) {
5369 if (cinfo.global_state != DSTATE_BUFIMAGE && cinfo.global_state != DSTATE_PRESCAN)
5370 error();
5371 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5372 /* Limit scan number to valid range */
5373 if (scan_number <= 0)
5374 scan_number = 1;
5375 if (cinfo.inputctl.eoi_reached && scan_number > cinfo.input_scan_number)
5376 scan_number = cinfo.input_scan_number;
5377 cinfo.output_scan_number = scan_number;
5378 /* Perform any dummy output passes, and set up for the real pass */
5379 return output_pass_setup(cinfo);
5380 }
5381
5382 static boolean jpeg_finish_output (jpeg_decompress_struct cinfo) {
5383 if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && cinfo.buffered_image) {
5384 /* Terminate this pass. */
5385 /* We do not require the whole pass to have been completed. */
5386 finish_output_pass (cinfo);
5387 cinfo.global_state = DSTATE_BUFPOST;
5388 } else if (cinfo.global_state != DSTATE_BUFPOST) {
5389 /* BUFPOST = repeat call after a suspension, anything else is error */
5390 error();
5391 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5392 }
5393 /* Read markers looking for SOS or EOI */
5394 while (cinfo.input_scan_number <= cinfo.output_scan_number && !cinfo.inputctl.eoi_reached) {
5395 if (consume_input (cinfo) == JPEG_SUSPENDED)
5396 return false; /* Suspend, come back later */
5397 }
5398 cinfo.global_state = DSTATE_BUFIMAGE;
5399 return true;
5400 }
5401
5402 static boolean jpeg_finish_decompress (jpeg_decompress_struct cinfo) {
5403 if ((cinfo.global_state == DSTATE_SCANNING || cinfo.global_state == DSTATE_RAW_OK) && ! cinfo.buffered_image) {
5404 /* Terminate final pass of non-buffered mode */
5405 if (cinfo.output_scanline < cinfo.output_height)
5406 error();
5407 // ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
5408 finish_output_pass (cinfo);
5409 cinfo.global_state = DSTATE_STOPPING;
5410 } else if (cinfo.global_state == DSTATE_BUFIMAGE) {
5411 /* Finishing after a buffered-image operation */
5412 cinfo.global_state = DSTATE_STOPPING;
5413 } else if (cinfo.global_state != DSTATE_STOPPING) {
5414 /* STOPPING = repeat call after a suspension, anything else is error */
5415 error();
5416 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5417 }
5418 /* Read until EOI */
5419 while (! cinfo.inputctl.eoi_reached) {
5420 if (consume_input (cinfo) == JPEG_SUSPENDED)
5421 return false; /* Suspend, come back later */
5422 }
5423 /* Do final cleanup */
5424 // (*cinfo.src.term_source) (cinfo);
5425 /* We can use jpeg_abort to release memory and reset global_state */
5426 jpeg_abort(cinfo);
5427 return true;
5428 }
5429
5430
5431 static int jpeg_read_header (jpeg_decompress_struct cinfo, boolean require_image) {
5432 int retcode;
5433
5434 if (cinfo.global_state != DSTATE_START && cinfo.global_state != DSTATE_INHEADER)
5435 error();
5436 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
5437
5438 retcode = jpeg_consume_input(cinfo);
5439
5440 switch (retcode) {
5441 case JPEG_REACHED_SOS:
5442 retcode = JPEG_HEADER_OK;
5443 break;
5444 case JPEG_REACHED_EOI:
5445 if (require_image) /* Complain if application wanted an image */
5446 error();
5447 // ERREXIT(cinfo, JERR_NO_IMAGE);
5448 /* Reset to start state; it would be safer to require the application to
5449 * call jpeg_abort, but we can't change it now for compatibility reasons.
5450 * A side effect is to free any temporary memory (there shouldn't be any).
5451 */
5452 jpeg_abort(cinfo); /* sets state = DSTATE_START */
5453 retcode = JPEG_HEADER_TABLES_ONLY;
5454 break;
5455 case JPEG_SUSPENDED:
5456 /* no work */
5457 break;
5458 }
5459
5460 return retcode;
5461 }
5462
5463 static int dummy_consume_data (jpeg_decompress_struct cinfo) {
5464 return JPEG_SUSPENDED; /* Always indicate nothing was done */
5465 }
5466
5467 static int consume_data (jpeg_decompress_struct cinfo) {
5468 jpeg_d_coef_controller coef = cinfo.coef;
5469 int MCU_col_num; /* index of current MCU within row */
5470 int blkn, ci, xindex, yindex, yoffset;
5471 int start_col;
5472 // short[][][][] buffer = new short[MAX_COMPS_IN_SCAN][][][];
5473 short[][] buffer_ptr;
5474 jpeg_component_info compptr;
5475
5476 // /* Align the virtual buffers for the components used in this scan. */
5477 // for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5478 // compptr = cinfo.cur_comp_info[ci];
5479 // buffer[ci] = coef.whole_image[compptr.component_index];
5480 // /* Note: entropy decoder expects buffer to be zeroed,
5481 // * but this is handled automatically by the memory manager
5482 // * because we requested a pre-zeroed array.
5483 // */
5484 // }
5485
5486 /* Loop to process one whole iMCU row */
5487 for (yoffset = coef.MCU_vert_offset; yoffset < coef.MCU_rows_per_iMCU_row; yoffset++) {
5488 for (MCU_col_num = coef.MCU_ctr; MCU_col_num < cinfo.MCUs_per_row; MCU_col_num++) {
5489 /* Construct list of pointers to DCT blocks belonging to this MCU */
5490 blkn = 0; /* index of current DCT block within MCU */
5491 for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5492 compptr = cinfo.cur_comp_info[ci];
5493 start_col = MCU_col_num * compptr.MCU_width;
5494 for (yindex = 0; yindex < compptr.MCU_height; yindex++) {
5495 // buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
5496 buffer_ptr = coef.whole_image[compptr.component_index][yindex+yoffset+cinfo.input_iMCU_row*compptr.v_samp_factor];
5497 int buffer_ptr_offset = start_col;
5498 for (xindex = 0; xindex < compptr.MCU_width; xindex++) {
5499 coef.MCU_buffer[blkn++] = buffer_ptr[buffer_ptr_offset++];
5500 }
5501 }
5502 }
5503 /* Try to fetch the MCU. */
5504 if (! cinfo.entropy.decode_mcu (cinfo, coef.MCU_buffer)) {
5505 /* Suspension forced; update state counters and exit */
5506 coef.MCU_vert_offset = yoffset;
5507 coef.MCU_ctr = MCU_col_num;
5508 return JPEG_SUSPENDED;
5509 }
5510 }
5511 /* Completed an MCU row, but perhaps not an iMCU row */
5512 coef.MCU_ctr = 0;
5513 }
5514 /* Completed the iMCU row, advance counters for next one */
5515 if (++(cinfo.input_iMCU_row) < cinfo.total_iMCU_rows) {
5516 coef.start_iMCU_row(cinfo);
5517 return JPEG_ROW_COMPLETED;
5518 }
5519 /* Completed the scan */
5520 finish_input_pass (cinfo);
5521 return JPEG_SCAN_COMPLETED;
5522 }
5523
5524 static int consume_input (jpeg_decompress_struct cinfo) {
5525 switch (cinfo.inputctl.consume_input) {
5526 case COEF_CONSUME_INPUT:
5527 switch (cinfo.coef.consume_data) {
5528 case CONSUME_DATA: return consume_data(cinfo);
5529 case DUMMY_CONSUME_DATA: return dummy_consume_data(cinfo);
5530 default: error();
5531 }
5532 break;
5533 case INPUT_CONSUME_INPUT:
5534 return consume_markers(cinfo);
5535 default:
5536 error();
5537 }
5538 return 0;
5539 }
5540
5541 static boolean fill_input_buffer(jpeg_decompress_struct cinfo) {
5542 try {
5543 InputStream inputStream = cinfo.inputStream;
5544 int nbytes = inputStream.read(cinfo.buffer);
5545 if (nbytes <= 0) {
5546 if (cinfo.start_of_file) /* Treat empty input file as fatal error */
5547 error();
5548 // ERREXIT(cinfo, JERR_INPUT_EMPTY);
5549 // WARNMS(cinfo, JWRN_JPEG_EOF);
5550 /* Insert a fake EOI marker */
5551 cinfo.buffer[0] = (byte)0xFF;
5552 cinfo.buffer[1] = (byte)M_EOI;
5553 nbytes = 2;
5554 }
5555 cinfo.bytes_in_buffer = nbytes;
5556 cinfo.bytes_offset = 0;
5557 cinfo.start_of_file = false;
5558 } catch (IOException e) {
5559 error(SWT.ERROR_IO);
5560 return false;
5561 }
5562 return true;
5563 }
5564
5565 static boolean first_marker (jpeg_decompress_struct cinfo) {
5566 /* Like next_marker, but used to obtain the initial SOI marker. */
5567 /* For this marker, we do not allow preceding garbage or fill; otherwise,
5568 * we might well scan an entire input file before realizing it ain't JPEG.
5569 * If an application wants to process non-JFIF files, it must seek to the
5570 * SOI before calling the JPEG library.
5571 */
5572 int c, c2;
5573
5574 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5575 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5576 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5577 c2 = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5578 if (c != 0xFF || c2 != M_SOI)
5579 error();
5580 // ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
5581
5582 cinfo.unread_marker = c2;
5583
5584 return true;
5585 }
5586
5587 static boolean next_marker (jpeg_decompress_struct cinfo) {
5588 int c;
5589
5590 for (;;) {
5591 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5592 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5593 /* Skip any non-FF bytes.
5594 * This may look a bit inefficient, but it will not occur in a valid file.
5595 * We sync after each discarded byte so that a suspending data source
5596 * can discard the byte from its buffer.
5597 */
5598 while (c != 0xFF) {
5599 cinfo.marker.discarded_bytes++;
5600 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5601 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5602 }
5603 /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
5604 * pad bytes, so don't count them in discarded_bytes. We assume there
5605 * will not be so many consecutive FF bytes as to overflow a suspending
5606 * data source's input buffer.
5607 */
5608 do {
5609 if (cinfo.bytes_offset == cinfo.bytes_in_buffer) fill_input_buffer(cinfo);
5610 c = cinfo.buffer[cinfo.bytes_offset++] & 0xFF;
5611 } while (c == 0xFF);
5612 if (c != 0)
5613 break; /* found a valid marker, exit loop */
5614 /* Reach here if we found a stuffed-zero data sequence (FF/00).
5615 * Discard it and loop back to try again.
5616 */
5617 cinfo.marker.discarded_bytes += 2;
5618 }
5619
5620 if (cinfo.marker.discarded_bytes != 0) {
5621 // WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo.marker.discarded_bytes, c);
5622 cinfo.marker.discarded_bytes = 0;
5623 }
5624
5625 cinfo.unread_marker = c;
5626
5627 return true;
5628 }
5629
5630 static int read_markers (jpeg_decompress_struct cinfo) {
5631 /* Outer loop repeats once for each marker. */
5632 for (;;) {
5633 /* Collect the marker proper, unless we already did. */
5634 /* NB: first_marker() enforces the requirement that SOI appear first. */
5635 if (cinfo.unread_marker == 0) {
5636 if (! cinfo.marker.saw_SOI) {
5637 if (! first_marker(cinfo))
5638 return JPEG_SUSPENDED;
5639 } else {
5640 if (! next_marker(cinfo))
5641 return JPEG_SUSPENDED;
5642 }
5643 }
5644 /* At this point cinfo.unread_marker contains the marker code and the
5645 * input point is just past the marker proper, but before any parameters.
5646 * A suspension will cause us to return with this state still true.
5647 */
5648 switch (cinfo.unread_marker) {
5649 case M_SOI:
5650 if (! get_soi(cinfo))
5651 return JPEG_SUSPENDED;
5652 break;
5653
5654 case M_SOF0: /* Baseline */
5655 case M_SOF1: /* Extended sequential, Huffman */
5656 if (! get_sof(cinfo, false, false))
5657 return JPEG_SUSPENDED;
5658 break;
5659
5660 case M_SOF2: /* Progressive, Huffman */
5661 if (! get_sof(cinfo, true, false))
5662 return JPEG_SUSPENDED;
5663 break;
5664
5665 case M_SOF9: /* Extended sequential, arithmetic */
5666 if (! get_sof(cinfo, false, true))
5667 return JPEG_SUSPENDED;
5668 break;
5669
5670 case M_SOF10: /* Progressive, arithmetic */
5671 if (! get_sof(cinfo, true, true))
5672 return JPEG_SUSPENDED;
5673 break;
5674
5675 /* Currently unsupported SOFn types */
5676 case M_SOF3: /* Lossless, Huffman */
5677 case M_SOF5: /* Differential sequential, Huffman */
5678 case M_SOF6: /* Differential progressive, Huffman */
5679 case M_SOF7: /* Differential lossless, Huffman */
5680 case M_JPG: /* Reserved for JPEG extensions */
5681 case M_SOF11: /* Lossless, arithmetic */
5682 case M_SOF13: /* Differential sequential, arithmetic */
5683 case M_SOF14: /* Differential progressive, arithmetic */
5684 case M_SOF15: /* Differential lossless, arithmetic */
5685 error();
5686 // ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo.unread_marker);
5687 break;
5688
5689 case M_SOS:
5690 if (! get_sos(cinfo))
5691 return JPEG_SUSPENDED;
5692 cinfo.unread_marker = 0; /* processed the marker */
5693 return JPEG_REACHED_SOS;
5694
5695 case M_EOI:
5696 // TRACEMS(cinfo, 1, JTRC_EOI);
5697 cinfo.unread_marker = 0; /* processed the marker */
5698 return JPEG_REACHED_EOI;
5699
5700 case M_DAC:
5701 if (! get_dac(cinfo))
5702 return JPEG_SUSPENDED;
5703 break;
5704
5705 case M_DHT:
5706 if (! get_dht(cinfo))
5707 return JPEG_SUSPENDED;
5708 break;
5709
5710 case M_DQT:
5711 if (! get_dqt(cinfo))
5712 return JPEG_SUSPENDED;
5713 break;
5714
5715 case M_DRI:
5716 if (! get_dri(cinfo))
5717 return JPEG_SUSPENDED;
5718 break;
5719
5720 case M_APP0:
5721 case M_APP1:
5722 case M_APP2:
5723 case M_APP3:
5724 case M_APP4:
5725 case M_APP5:
5726 case M_APP6:
5727 case M_APP7:
5728 case M_APP8:
5729 case M_APP9:
5730 case M_APP10:
5731 case M_APP11:
5732 case M_APP12:
5733 case M_APP13:
5734 case M_APP14:
5735 case M_APP15:
5736 if (! process_APPn(cinfo.unread_marker - M_APP0, cinfo))
5737 return JPEG_SUSPENDED;
5738 break;
5739
5740 case M_COM:
5741 if (! process_COM(cinfo))
5742 return JPEG_SUSPENDED;
5743 break;
5744
5745 case M_RST0: /* these are all parameterless */
5746 case M_RST1:
5747 case M_RST2:
5748 case M_RST3:
5749 case M_RST4:
5750 case M_RST5:
5751 case M_RST6:
5752 case M_RST7:
5753 case M_TEM:
5754 // TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo.unread_marker);
5755 break;
5756
5757 case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
5758 if (! skip_variable(cinfo))
5759 return JPEG_SUSPENDED;
5760 break;
5761
5762 default: /* must be DHP, EXP, JPGn, or RESn */
5763 /* For now, we treat the reserved markers as fatal errors since they are
5764 * likely to be used to signal incompatible JPEG Part 3 extensions.
5765 * Once the JPEG 3 version-number marker is well defined, this code
5766 * ought to change!
5767 */
5768 error();
5769 // ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo.unread_marker);
5770 break;
5771 }
5772 /* Successfully processed marker, so reset state variable */
5773 cinfo.unread_marker = 0;
5774 } /* end loop */
5775 }
5776
5777 static long jdiv_round_up (long a, long b)
5778 /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
5779 /* Assumes a >= 0, b > 0 */
5780 {
5781 return (a + b - 1) / b;
5782 }
5783
5784 static void initial_setup (jpeg_decompress_struct cinfo)
5785 /* Called once, when first SOS marker is reached */
5786 {
5787 int ci;
5788 jpeg_component_info compptr;
5789
5790 /* Make sure image isn't bigger than I can handle */
5791 if (cinfo.image_height > JPEG_MAX_DIMENSION || cinfo.image_width > JPEG_MAX_DIMENSION)
5792 error();
5793 // ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
5794
5795 /* For now, precision must match compiled-in value... */
5796 if (cinfo.data_precision != BITS_IN_JSAMPLE)
5797 error(" [data precision=" + cinfo.data_precision + "]");
5798 // ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo.data_precision);
5799
5800 /* Check that number of components won't exceed internal array sizes */
5801 if (cinfo.num_components > MAX_COMPONENTS)
5802 error();
5803 // ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.num_components, MAX_COMPONENTS);
5804
5805 /* Compute maximum sampling factors; check factor validity */
5806 cinfo.max_h_samp_factor = 1;
5807 cinfo.max_v_samp_factor = 1;
5808 for (ci = 0; ci < cinfo.num_components; ci++) {
5809 compptr = cinfo.comp_info[ci];
5810 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)
5811 error();
5812 // ERREXIT(cinfo, JERR_BAD_SAMPLING);
5813 cinfo.max_h_samp_factor = Math.max(cinfo.max_h_samp_factor, compptr.h_samp_factor);
5814 cinfo.max_v_samp_factor = Math.max(cinfo.max_v_samp_factor, compptr.v_samp_factor);
5815 }
5816
5817 /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
5818 * In the full decompressor, this will be overridden by jdmaster.c;
5819 * but in the transcoder, jdmaster.c is not used, so we must do it here.
5820 */
5821 cinfo.min_DCT_scaled_size = DCTSIZE;
5822
5823 /* Compute dimensions of components */
5824 for (ci = 0; ci < cinfo.num_components; ci++) {
5825 compptr = cinfo.comp_info[ci];
5826 compptr.DCT_scaled_size = DCTSIZE;
5827 /* Size in DCT blocks */
5828 compptr.width_in_blocks = (int)jdiv_round_up((long) cinfo.image_width * (long) compptr.h_samp_factor, (cinfo.max_h_samp_factor * DCTSIZE));
5829 compptr.height_in_blocks = (int)jdiv_round_up((long) cinfo.image_height * (long) compptr.v_samp_factor, (cinfo.max_v_samp_factor * DCTSIZE));
5830 /* downsampled_width and downsampled_height will also be overridden by
5831 * jdmaster.c if we are doing full decompression. The transcoder library
5832 * doesn't use these values, but the calling application might.
5833 */
5834 /* Size in samples */
5835 compptr.downsampled_width = (int)jdiv_round_up((long) cinfo.image_width * (long) compptr.h_samp_factor, cinfo.max_h_samp_factor);
5836 compptr.downsampled_height = (int)jdiv_round_up((long) cinfo.image_height * (long) compptr.v_samp_factor, cinfo.max_v_samp_factor);
5837 /* Mark component needed, until color conversion says otherwise */
5838 compptr.component_needed = true;
5839 /* Mark no quantization table yet saved for component */
5840 compptr.quant_table = null;
5841 }
5842
5843 /* Compute number of fully interleaved MCU rows. */
5844 cinfo.total_iMCU_rows = (int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE));
5845
5846 /* Decide whether file contains multiple scans */
5847 if (cinfo.comps_in_scan < cinfo.num_components || cinfo.progressive_mode)
5848 cinfo.inputctl.has_multiple_scans = true;
5849 else
5850 cinfo.inputctl.has_multiple_scans = false;
5851 }
5852
5853
5854 static void per_scan_setup (jpeg_decompress_struct cinfo)
5855 /* Do computations that are needed before processing a JPEG scan */
5856 /* cinfo.comps_in_scan and cinfo.cur_comp_info[] were set from SOS marker */
5857 {
5858 int ci, mcublks, tmp = 0;
5859 jpeg_component_info compptr;
5860
5861 if (cinfo.comps_in_scan == 1) {
5862
5863 /* Noninterleaved (single-component) scan */
5864 compptr = cinfo.cur_comp_info[0];
5865
5866 /* Overall image size in MCUs */
5867 cinfo.MCUs_per_row = compptr.width_in_blocks;
5868 cinfo.MCU_rows_in_scan = compptr.height_in_blocks;
5869
5870 /* For noninterleaved scan, always one block per MCU */
5871 compptr.MCU_width = 1;
5872 compptr.MCU_height = 1;
5873 compptr.MCU_blocks = 1;
5874 compptr.MCU_sample_width = compptr.DCT_scaled_size;
5875 compptr.last_col_width = 1;
5876 /* For noninterleaved scans, it is convenient to define last_row_height
5877 * as the number of block rows present in the last iMCU row.
5878 */
5879 tmp = (compptr.height_in_blocks % compptr.v_samp_factor);
5880 if (tmp == 0) tmp = compptr.v_samp_factor;
5881 compptr.last_row_height = tmp;
5882
5883 /* Prepare array describing MCU composition */
5884 cinfo.blocks_in_MCU = 1;
5885 cinfo.MCU_membership[0] = 0;
5886
5887 } else {
5888
5889 /* Interleaved (multi-component) scan */
5890 if (cinfo.comps_in_scan <= 0 || cinfo.comps_in_scan > MAX_COMPS_IN_SCAN)
5891 error();
5892 // ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo.comps_in_scan, MAX_COMPS_IN_SCAN);
5893
5894 /* Overall image size in MCUs */
5895 cinfo.MCUs_per_row = (int)jdiv_round_up( cinfo.image_width, (cinfo.max_h_samp_factor*DCTSIZE));
5896 cinfo.MCU_rows_in_scan = (int)jdiv_round_up( cinfo.image_height, (cinfo.max_v_samp_factor*DCTSIZE));
5897
5898 cinfo.blocks_in_MCU = 0;
5899
5900 for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5901 compptr = cinfo.cur_comp_info[ci];
5902 /* Sampling factors give # of blocks of component in each MCU */
5903 compptr.MCU_width = compptr.h_samp_factor;
5904 compptr.MCU_height = compptr.v_samp_factor;
5905 compptr.MCU_blocks = compptr.MCU_width * compptr.MCU_height;
5906 compptr.MCU_sample_width = compptr.MCU_width * compptr.DCT_scaled_size;
5907 /* Figure number of non-dummy blocks in last MCU column & row */
5908 tmp = (compptr.width_in_blocks % compptr.MCU_width);
5909 if (tmp == 0) tmp = compptr.MCU_width;
5910 compptr.last_col_width = tmp;
5911 tmp = (compptr.height_in_blocks % compptr.MCU_height);
5912 if (tmp == 0) tmp = compptr.MCU_height;
5913 compptr.last_row_height = tmp;
5914 /* Prepare array describing MCU composition */
5915 mcublks = compptr.MCU_blocks;
5916 if (cinfo.blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
5917 error();
5918 // ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
5919 while (mcublks-- > 0) {
5920 cinfo.MCU_membership[cinfo.blocks_in_MCU++] = ci;
5921 }
5922 }
5923
5924 }
5925 }
5926
5927 static void latch_quant_tables (jpeg_decompress_struct cinfo) {
5928 int ci, qtblno;
5929 jpeg_component_info compptr;
5930 JQUANT_TBL qtbl;
5931
5932 for (ci = 0; ci < cinfo.comps_in_scan; ci++) {
5933 compptr = cinfo.cur_comp_info[ci];
5934 /* No work if we already saved Q-table for this component */
5935 if (compptr.quant_table != null)
5936 continue;
5937 /* Make sure specified quantization table is present */
5938 qtblno = compptr.quant_tbl_no;
5939 if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS || cinfo.quant_tbl_ptrs[qtblno] == null)
5940 error();
5941 // ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
5942 /* OK, save away the quantization table */
5943 qtbl = new JQUANT_TBL();
5944 System.arraycopy(cinfo.quant_tbl_ptrs[qtblno].quantval, 0, qtbl.quantval, 0, qtbl.quantval.length);
5945 qtbl.sent_table = cinfo.quant_tbl_ptrs[qtblno].sent_table;
5946 compptr.quant_table = qtbl;
5947 }
5948 }
5949
5950 static void jpeg_make_d_derived_tbl (jpeg_decompress_struct cinfo, boolean isDC, int tblno, d_derived_tbl dtbl) {
5951 JHUFF_TBL htbl;
5952 int p, i = 0, l, si, numsymbols;
5953 int lookbits, ctr;
5954 byte[] huffsize = new byte[257];
5955 int[] huffcode = new int[257];
5956 int code;
5957
5958 /* Note that huffsize[] and huffcode[] are filled in code-length order,
5959 * paralleling the order of the symbols themselves in htbl.huffval[].
5960 */
5961
5962 /* Find the input Huffman table */
5963 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
5964 error();
5965 // ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
5966 htbl = isDC ? cinfo.dc_huff_tbl_ptrs[tblno] : cinfo.ac_huff_tbl_ptrs[tblno];
5967 if (htbl == null)
5968 error();
5969 // ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
5970
5971 /* Allocate a workspace if we haven't already done so. */
5972 dtbl.pub = htbl; /* fill in back link */
5973
5974 /* Figure C.1: make table of Huffman code length for each symbol */
5975
5976 p = 0;
5977 for (l = 1; l <= 16; l++) {
5978 i = htbl.bits[l] & 0xFF;
5979 if (i < 0 || p + i > 256) /* protect against table overrun */
5980 error();
5981 // ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
5982 while (i-- != 0)
5983 huffsize[p++] = (byte) l;
5984 }
5985 huffsize[p] = 0;
5986 numsymbols = p;
5987
5988 /* Figure C.2: generate the codes themselves */
5989 /* We also validate that the counts represent a legal Huffman code tree. */
5990
5991 code = 0;
5992 si = huffsize[0];
5993 p = 0;
5994 while ((huffsize[p]) != 0) {
5995 while (( huffsize[p]) == si) {
5996 huffcode[p++] = code;
5997 code++;
5998 }
5999 /* code is now 1 more than the last code used for codelength si; but
6000 * it must still fit in si bits, since no code is allowed to be all ones.
6001 */
6002 if (( code) >= (( 1) << si))
6003 error();
6004 // ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
6005 code <<= 1;
6006 si++;
6007 }
6008
6009 /* Figure F.15: generate decoding tables for bit-sequential decoding */
6010
6011 p = 0;
6012 for (l = 1; l <= 16; l++) {
6013 if ((htbl.bits[l] & 0xFF) != 0) {
6014 /* valoffset[l] = huffval[] index of 1st symbol of code length l,
6015 * minus the minimum code of length l
6016 */
6017 dtbl.valoffset[l] = p - huffcode[p];
6018 p += (htbl.bits[l] & 0xFF);
6019 dtbl.maxcode[l] = huffcode[p-1]; /* maximum code of length l */
6020 } else {
6021 dtbl.maxcode[l] = -1; /* -1 if no codes of this length */
6022 }
6023 }
6024 dtbl.maxcode[17] = 0xFFFFF; /* ensures jpeg_huff_decode terminates */
6025
6026 /* Compute lookahead tables to speed up decoding.
6027 * First we set all the table entries to 0, indicating "too long";
6028 * then we iterate through the Huffman codes that are short enough and
6029 * fill in all the entries that correspond to bit sequences starting
6030 * with that code.
6031 */
6032
6033 for (int j = 0; j < dtbl.look_nbits.length; j++) {
6034 dtbl.look_nbits[j] = 0;
6035 }
6036
6037 p = 0;
6038 for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
6039 for (i = 1; i <= (htbl.bits[l] & 0xFF); i++, p++) {
6040 /* l = current code's length, p = its index in huffcode[] & huffval[]. */
6041 /* Generate left-justified code followed by all possible bit sequences */
6042 lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
6043 for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
6044 dtbl.look_nbits[lookbits] = l;
6045 dtbl.look_sym[lookbits] = htbl.huffval[p];
6046 lookbits++;
6047 }
6048 }
6049 }
6050
6051 /* Validate symbols as being reasonable.
6052 * For AC tables, we make no check, but accept all byte values 0..255.
6053 * For DC tables, we require the symbols to be in range 0..15.
6054 * (Tighter bounds could be applied depending on the data depth and mode,
6055 * but this is sufficient to ensure safe decoding.)
6056 */
6057 if (isDC) {
6058 for (i = 0; i < numsymbols; i++) {
6059 int sym = htbl.huffval[i] & 0xFF;
6060 if (sym < 0 || sym > 15)
6061 error();
6062 // ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
6063 }
6064 }
6065 }
6066
6067 static void start_input_pass (jpeg_decompress_struct cinfo) {
6068 per_scan_setup(cinfo);
6069 latch_quant_tables(cinfo);
6070 cinfo.entropy.start_pass(cinfo);
6071 cinfo.coef.start_input_pass (cinfo);
6072 cinfo.inputctl.consume_input = COEF_CONSUME_INPUT;
6073 }
6074
6075 static void finish_input_pass (jpeg_decompress_struct cinfo) {
6076 cinfo.inputctl.consume_input = INPUT_CONSUME_INPUT;
6077 }
6078
6079 static int consume_markers (jpeg_decompress_struct cinfo) {
6080 jpeg_input_controller inputctl = cinfo.inputctl;
6081 int val;
6082
6083 if (inputctl.eoi_reached) /* After hitting EOI, read no further */
6084 return JPEG_REACHED_EOI;
6085
6086 val = read_markers (cinfo);
6087
6088 switch (val) {
6089 case JPEG_REACHED_SOS: /* Found SOS */
6090 if (inputctl.inheaders) { /* 1st SOS */
6091 initial_setup(cinfo);
6092 inputctl.inheaders = false;
6093 /* Note: start_input_pass must be called by jdmaster.c
6094 * before any more input can be consumed. jdapimin.c is
6095 * responsible for enforcing this sequencing.
6096 */
6097 } else { /* 2nd or later SOS marker */
6098 if (! inputctl.has_multiple_scans)
6099 error();
6100 // ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
6101 start_input_pass(cinfo);
6102 }
6103 break;
6104 case JPEG_REACHED_EOI: /* Found EOI */
6105 inputctl.eoi_reached = true;
6106 if (inputctl.inheaders) { /* Tables-only datastream, apparently */
6107 if (cinfo.marker.saw_SOF)
6108 error();
6109 // ERREXIT(cinfo, JERR_SOF_NO_SOS);
6110 } else {
6111 /* Prevent infinite loop in coef ctlr's decompress_data routine
6112 * if user set output_scan_number larger than number of scans.
6113 */
6114 if (cinfo.output_scan_number > cinfo.input_scan_number)
6115 cinfo.output_scan_number = cinfo.input_scan_number;
6116 }
6117 break;
6118 case JPEG_SUSPENDED:
6119 break;
6120 }
6121
6122 return val;
6123 }
6124
6125 static void default_decompress_parms (jpeg_decompress_struct cinfo) {
6126 /* Guess the input colorspace, and set output colorspace accordingly. */
6127 /* (Wish JPEG committee had provided a real way to specify this...) */
6128 /* Note application may override our guesses. */
6129 switch (cinfo.num_components) {
6130 case 1:
6131 cinfo.jpeg_color_space = JCS_GRAYSCALE;
6132 cinfo.out_color_space = JCS_GRAYSCALE;
6133 break;
6134
6135 case 3:
6136 if (cinfo.saw_JFIF_marker) {
6137 cinfo.jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
6138 } else if (cinfo.saw_Adobe_marker) {
6139 switch (cinfo.Adobe_transform) {
6140 case 0:
6141 cinfo.jpeg_color_space = JCS_RGB;
6142 break;
6143 case 1:
6144 cinfo.jpeg_color_space = JCS_YCbCr;
6145 break;
6146 default:
6147 // WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform);
6148 cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
6149 break;
6150 }
6151 } else {
6152 /* Saw no special markers, try to guess from the component IDs */
6153 int cid0 = cinfo.comp_info[0].component_id;
6154 int cid1 = cinfo.comp_info[1].component_id;
6155 int cid2 = cinfo.comp_info[2].component_id;
6156
6157 if (cid0 == 1 && cid1 == 2 && cid2 == 3)
6158 cinfo.jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
6159 else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
6160 cinfo.jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
6161 else {
6162 // TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
6163 cinfo.jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
6164 }
6165 }
6166 /* Always guess RGB is proper output colorspace. */
6167 cinfo.out_color_space = JCS_RGB;
6168 break;
6169
6170 case 4:
6171 if (cinfo.saw_Adobe_marker) {
6172 switch (cinfo.Adobe_transform) {
6173 case 0:
6174 cinfo.jpeg_color_space = JCS_CMYK;
6175 break;
6176 case 2:
6177 cinfo.jpeg_color_space = JCS_YCCK;
6178 break;
6179 default:
6180 // WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo.Adobe_transform);
6181 cinfo.jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
6182 break;
6183 }
6184 } else {
6185 /* No special markers, assume straight CMYK. */
6186 cinfo.jpeg_color_space = JCS_CMYK;
6187 }
6188 cinfo.out_color_space = JCS_CMYK;
6189 break;
6190
6191 default:
6192 cinfo.jpeg_color_space = JCS_UNKNOWN;
6193 cinfo.out_color_space = JCS_UNKNOWN;
6194 break;
6195 }
6196
6197 /* Set defaults for other decompression parameters. */
6198 cinfo.scale_num = 1; /* 1:1 scaling */
6199 cinfo.scale_denom = 1;
6200 cinfo.output_gamma = 1.0;
6201 cinfo.buffered_image = false;
6202 cinfo.raw_data_out = false;
6203 cinfo.dct_method = JDCT_DEFAULT;
6204 cinfo.do_fancy_upsampling = true;
6205 cinfo.do_block_smoothing = true;
6206 cinfo.quantize_colors = false;
6207 /* We set these in case application only sets quantize_colors. */
6208 cinfo.dither_mode = JDITHER_FS;
6209 cinfo.two_pass_quantize = true;
6210 cinfo.desired_number_of_colors = 256;
6211 cinfo.colormap = null;
6212 /* Initialize for no mode change in buffered-image mode. */
6213 cinfo.enable_1pass_quant = false;
6214 cinfo.enable_external_quant = false;
6215 cinfo.enable_2pass_quant = false;
6216 }
6217
6218 static void init_source(jpeg_decompress_struct cinfo) {
6219 cinfo.buffer = new byte[INPUT_BUFFER_SIZE];
6220 cinfo.bytes_in_buffer = 0;
6221 cinfo.bytes_offset = 0;
6222 cinfo.start_of_file = true;
6223 }
6224
6225 static int jpeg_consume_input (jpeg_decompress_struct cinfo) {
6226 int retcode = JPEG_SUSPENDED;
6227
6228 /* NB: every possible DSTATE value should be listed in this switch */
6229 switch (cinfo.global_state) {
6230 case DSTATE_START:
6231 /* Start-of-datastream actions: reset appropriate modules */
6232 reset_input_controller(cinfo);
6233 /* Initialize application's data source module */
6234 init_source (cinfo);
6235 cinfo.global_state = DSTATE_INHEADER;
6236 /*FALLTHROUGH*/
6237 case DSTATE_INHEADER:
6238 retcode = consume_input(cinfo);
6239 if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
6240 /* Set up default parameters based on header data */
6241 default_decompress_parms(cinfo);
6242 /* Set global state: ready for start_decompress */
6243 cinfo.global_state = DSTATE_READY;
6244 }
6245 break;
6246 case DSTATE_READY:
6247 /* Can't advance past first SOS until start_decompress is called */
6248 retcode = JPEG_REACHED_SOS;
6249 break;
6250 case DSTATE_PRELOAD:
6251 case DSTATE_PRESCAN:
6252 case DSTATE_SCANNING:
6253 case DSTATE_RAW_OK:
6254 case DSTATE_BUFIMAGE:
6255 case DSTATE_BUFPOST:
6256 case DSTATE_STOPPING:
6257 retcode = consume_input (cinfo);
6258 break;
6259 default:
6260 error();
6261 // ERREXIT1(cinfo, JERR_BAD_STATE, cinfo.global_state);
6262 }
6263 return retcode;
6264 }
6265
6266
6267 static void jpeg_abort (jpeg_decompress_struct cinfo) {
6268 // int pool;
6269 //
6270 // /* Releasing pools in reverse order might help avoid fragmentation
6271 // * with some (brain-damaged) malloc libraries.
6272 // */
6273 // for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
6274 // (*cinfo.mem.free_pool) (cinfo, pool);
6275 // }
6276
6277 /* Reset overall state for possible reuse of object */
6278 if (cinfo.is_decompressor) {
6279 cinfo.global_state = DSTATE_START;
6280 /* Try to keep application from accessing now-deleted marker list.
6281 * A bit kludgy to do it here, but this is the most central place.
6282 */
6283 // ((j_decompress_ptr) cinfo).marker_list = null;
6284 } else {
6285 cinfo.global_state = CSTATE_START;
6286 }
6287 }
6288
6289
6290 static boolean isFileFormat(LEDataInputStream stream) {
6291 try {
6292 byte[] buffer = new byte[2];
6293 stream.read(buffer);
6294 stream.unread(buffer);
6295 return (buffer[0] & 0xFF) == 0xFF && (buffer[1] & 0xFF) == M_SOI;
6296 } catch (Exception e) {
6297 return false;
6298 }
6299 }
6300
6301 static ImageData[] loadFromByteStream(InputStream inputStream, ImageLoader loader) {
6302 jpeg_decompress_struct cinfo = new jpeg_decompress_struct();
6303 cinfo.inputStream = inputStream;
6304 jpeg_create_decompress(cinfo);
6305 jpeg_read_header(cinfo, true);
6306 cinfo.buffered_image = cinfo.progressive_mode && loader.hasListeners();
6307 jpeg_start_decompress(cinfo);
6308 PaletteData palette = null;
6309 switch (cinfo.out_color_space) {
6310 case JCS_RGB:
6311 palette = new PaletteData(0xFF, 0xFF00, 0xFF0000);
6312 break;
6313 case JCS_GRAYSCALE:
6314 RGB[] colors = new RGB[256];
6315 for (int i = 0; i < colors.length; i++) {
6316 colors[i] = new RGB(i, i, i);
6317 }
6318 palette = new PaletteData(colors);
6319 break;
6320 default:
6321 error();
6322 }
6323 int scanlinePad = 4;
6324 int row_stride = (((cinfo.output_width * cinfo.out_color_components * 8 + 7) / 8) + (scanlinePad - 1)) / scanlinePad * scanlinePad;
6325 byte[][] buffer = new byte[1][row_stride];
6326 byte[] data = new byte[row_stride * cinfo.output_height];
6327 ImageData imageData = ImageData.internal_new(
6328 cinfo.output_width, cinfo.output_height, palette.isDirect ? 24 : 8, palette, scanlinePad, data,
6329 0, null, null, -1, -1, SWT.IMAGE_JPEG, 0, 0, 0, 0);
6330 if (cinfo.buffered_image) {
6331 boolean done;
6332 do {
6333 int incrementCount = cinfo.input_scan_number - 1;
6334 jpeg_start_output(cinfo, cinfo.input_scan_number);
6335 while (cinfo.output_scanline < cinfo.output_height) {
6336 int offset = row_stride * cinfo.output_scanline;
6337 jpeg_read_scanlines(cinfo, buffer, 1);
6338 System.arraycopy(buffer[0], 0, data, offset, row_stride);
6339 }
6340 jpeg_finish_output(cinfo);
6341 loader.notifyListeners(new ImageLoaderEvent(loader, (ImageData)imageData.clone(), incrementCount, done = jpeg_input_complete(cinfo)));
6342 } while (!done);
6343 } else {
6344 while (cinfo.output_scanline < cinfo.output_height) {
6345 int offset = row_stride * cinfo.output_scanline;
6346 jpeg_read_scanlines(cinfo, buffer, 1);
6347 System.arraycopy(buffer[0], 0, data, offset, row_stride);
6348 }
6349 }
6350 jpeg_finish_decompress(cinfo);
6351 jpeg_destroy_decompress(cinfo);
6352 return new ImageData[]{imageData};
6353 }
6354
6355 }