4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * Modified 2002-2015 by Guido Vollbeding.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
9 * This file contains master control logic for the JPEG decompressor.
10 * These routines are concerned with selecting the modules to be executed
11 * and with determining the number of passes and the work to be done in each
15 #define JPEG_INTERNALS
23 struct jpeg_decomp_master pub; /* public fields */
25 int pass_number; /* # of passes completed */
27 boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
29 /* Saved references to initialized quantizer modules,
30 * in case we need to switch modes.
32 struct jpeg_color_quantizer * quantizer_1pass;
33 struct jpeg_color_quantizer * quantizer_2pass;
36 typedef my_decomp_master * my_master_ptr;
40 * Determine whether merged upsample/color conversion should be used.
41 * CRUCIAL: this must match the actual capabilities of jdmerge.c!
45 use_merged_upsample (j_decompress_ptr cinfo)
47 #ifdef UPSAMPLE_MERGING_SUPPORTED
48 /* Merging is the equivalent of plain box-filter upsampling. */
49 /* The following condition is only needed if fancy shall select
50 * a different upsampling method. In our current implementation
51 * fancy only affects the DCT scaling, thus we can use fancy
52 * upsampling and merged upsample simultaneously, in particular
53 * with scaled DCT sizes larger than the default DCTSIZE.
56 if (cinfo->do_fancy_upsampling)
59 if (cinfo->CCIR601_sampling)
61 /* jdmerge.c only supports YCC=>RGB color conversion */
62 if ((cinfo->jpeg_color_space != JCS_YCbCr &&
63 cinfo->jpeg_color_space != JCS_BG_YCC) ||
64 cinfo->num_components != 3 ||
65 cinfo->out_color_space != JCS_RGB ||
66 cinfo->out_color_components != RGB_PIXELSIZE ||
67 cinfo->color_transform)
69 /* and it only handles 2h1v or 2h2v sampling ratios */
70 if (cinfo->comp_info[0].h_samp_factor != 2 ||
71 cinfo->comp_info[1].h_samp_factor != 1 ||
72 cinfo->comp_info[2].h_samp_factor != 1 ||
73 cinfo->comp_info[0].v_samp_factor > 2 ||
74 cinfo->comp_info[1].v_samp_factor != 1 ||
75 cinfo->comp_info[2].v_samp_factor != 1)
77 /* furthermore, it doesn't work if we've scaled the IDCTs differently */
78 if (cinfo->comp_info[0].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
79 cinfo->comp_info[1].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
80 cinfo->comp_info[2].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
81 cinfo->comp_info[0].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size ||
82 cinfo->comp_info[1].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size ||
83 cinfo->comp_info[2].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size)
85 /* ??? also need to test for upsample-time rescaling, when & if supported */
86 return TRUE; /* by golly, it'll work... */
94 * Compute output image dimensions and related values.
95 * NOTE: this is exported for possible use by application.
96 * Hence it mustn't do anything that can't be done twice.
97 * Also note that it may be called before the master module is initialized!
101 jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
102 /* Do computations that are needed before master selection phase.
103 * This function is used for full decompression.
106 #ifdef IDCT_SCALING_SUPPORTED
108 jpeg_component_info *compptr;
111 /* Prevent application from calling me at wrong times */
112 if (cinfo->global_state != DSTATE_READY)
113 ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
115 /* Compute core output image dimensions and DCT scaling choices. */
116 jpeg_core_output_dimensions(cinfo);
118 #ifdef IDCT_SCALING_SUPPORTED
120 /* In selecting the actual DCT scaling for each component, we try to
121 * scale up the chroma components via IDCT scaling rather than upsampling.
122 * This saves time if the upsampler gets to use 1:1 scaling.
123 * Note this code adapts subsampling ratios which are powers of 2.
125 for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
128 while (cinfo->min_DCT_h_scaled_size * ssize <=
129 (cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) &&
130 (cinfo->max_h_samp_factor % (compptr->h_samp_factor * ssize * 2)) == 0) {
133 compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size * ssize;
135 while (cinfo->min_DCT_v_scaled_size * ssize <=
136 (cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) &&
137 (cinfo->max_v_samp_factor % (compptr->v_samp_factor * ssize * 2)) == 0) {
140 compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size * ssize;
142 /* We don't support IDCT ratios larger than 2. */
143 if (compptr->DCT_h_scaled_size > compptr->DCT_v_scaled_size * 2)
144 compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size * 2;
145 else if (compptr->DCT_v_scaled_size > compptr->DCT_h_scaled_size * 2)
146 compptr->DCT_v_scaled_size = compptr->DCT_h_scaled_size * 2;
149 /* Recompute downsampled dimensions of components;
150 * application needs to know these if using raw downsampled data.
152 for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
154 /* Size in samples, after IDCT scaling */
155 compptr->downsampled_width = (JDIMENSION)
156 jdiv_round_up((long) cinfo->image_width *
157 (long) (compptr->h_samp_factor * compptr->DCT_h_scaled_size),
158 (long) (cinfo->max_h_samp_factor * cinfo->block_size));
159 compptr->downsampled_height = (JDIMENSION)
160 jdiv_round_up((long) cinfo->image_height *
161 (long) (compptr->v_samp_factor * compptr->DCT_v_scaled_size),
162 (long) (cinfo->max_v_samp_factor * cinfo->block_size));
165 #endif /* IDCT_SCALING_SUPPORTED */
167 /* Report number of components in selected colorspace. */
168 /* Probably this should be in the color conversion module... */
169 switch (cinfo->out_color_space) {
171 cinfo->out_color_components = 1;
175 cinfo->out_color_components = RGB_PIXELSIZE;
179 cinfo->out_color_components = 3;
183 cinfo->out_color_components = 4;
185 default: /* else must be same colorspace as in file */
186 cinfo->out_color_components = cinfo->num_components;
189 cinfo->output_components = (cinfo->quantize_colors ? 1 :
190 cinfo->out_color_components);
192 /* See if upsampler will want to emit more than one row at a time */
193 if (use_merged_upsample(cinfo))
194 cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
196 cinfo->rec_outbuf_height = 1;
201 * Several decompression processes need to range-limit values to the range
202 * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
203 * due to noise introduced by quantization, roundoff error, etc. These
204 * processes are inner loops and need to be as fast as possible. On most
205 * machines, particularly CPUs with pipelines or instruction prefetch,
206 * a (subscript-check-less) C table lookup
207 * x = sample_range_limit[x];
208 * is faster than explicit tests
210 * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
211 * These processes all use a common table prepared by the routine below.
213 * For most steps we can mathematically guarantee that the initial value
214 * of x is within 2*(MAXJSAMPLE+1) of the legal range, so a table running
215 * from -2*(MAXJSAMPLE+1) to 3*MAXJSAMPLE+2 is sufficient. But for the
216 * initial limiting step (just after the IDCT), a wildly out-of-range value
217 * is possible if the input data is corrupt. To avoid any chance of indexing
218 * off the end of memory and getting a bad-pointer trap, we perform the
219 * post-IDCT limiting thus:
220 * x = (sample_range_limit - SUBSET)[(x + CENTER) & MASK];
221 * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
222 * samples. Under normal circumstances this is more than enough range and
223 * a correct output will be generated; with bogus input data the mask will
224 * cause wraparound, and we will safely generate a bogus-but-in-range output.
225 * For the post-IDCT step, we want to convert the data from signed to unsigned
226 * representation by adding CENTERJSAMPLE at the same time that we limit it.
227 * This is accomplished with SUBSET = CENTER - CENTERJSAMPLE.
229 * Note that the table is allocated in near data space on PCs; it's small
230 * enough and used often enough to justify this.
234 prepare_range_limit_table (j_decompress_ptr cinfo)
235 /* Allocate and fill in the sample_range_limit table */
241 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
242 5 * (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
243 /* First segment of range limit table: limit[x] = 0 for x < 0 */
244 MEMZERO(table, 2 * (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
245 table += 2 * (MAXJSAMPLE+1); /* allow negative subscripts of table */
246 cinfo->sample_range_limit = table;
247 /* Main part of range limit table: limit[x] = x */
248 for (i = 0; i <= MAXJSAMPLE; i++)
249 table[i] = (JSAMPLE) i;
250 /* End of range limit table: limit[x] = MAXJSAMPLE for x > MAXJSAMPLE */
251 for (; i < 3 * (MAXJSAMPLE+1); i++)
252 table[i] = MAXJSAMPLE;
257 * Master selection of decompression modules.
258 * This is done once at jpeg_start_decompress time. We determine
259 * which modules will be used and give them appropriate initialization calls.
260 * We also initialize the decompressor input side to begin consuming data.
262 * Since jpeg_read_header has finished, we know what is in the SOF
263 * and (first) SOS markers. We also have all the application parameter
268 master_selection (j_decompress_ptr cinfo)
270 my_master_ptr master = (my_master_ptr) cinfo->master;
271 boolean use_c_buffer;
273 JDIMENSION jd_samplesperrow;
275 /* For now, precision must match compiled-in value... */
276 if (cinfo->data_precision != BITS_IN_JSAMPLE)
277 ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
279 /* Initialize dimensions and other stuff */
280 jpeg_calc_output_dimensions(cinfo);
281 prepare_range_limit_table(cinfo);
283 /* Sanity check on image dimensions */
284 if (cinfo->output_height <= 0 || cinfo->output_width <= 0 ||
285 cinfo->out_color_components <= 0)
286 ERREXIT(cinfo, JERR_EMPTY_IMAGE);
288 /* Width of an output scanline must be representable as JDIMENSION. */
289 samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
290 jd_samplesperrow = (JDIMENSION) samplesperrow;
291 if ((long) jd_samplesperrow != samplesperrow)
292 ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
294 /* Initialize my private state */
295 master->pass_number = 0;
296 master->using_merged_upsample = use_merged_upsample(cinfo);
298 /* Color quantizer selection */
299 master->quantizer_1pass = NULL;
300 master->quantizer_2pass = NULL;
301 /* No mode changes if not using buffered-image mode. */
302 if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
303 cinfo->enable_1pass_quant = FALSE;
304 cinfo->enable_external_quant = FALSE;
305 cinfo->enable_2pass_quant = FALSE;
307 if (cinfo->quantize_colors) {
308 if (cinfo->raw_data_out)
309 ERREXIT(cinfo, JERR_NOTIMPL);
310 /* 2-pass quantizer only works in 3-component color space. */
311 if (cinfo->out_color_components != 3) {
312 cinfo->enable_1pass_quant = TRUE;
313 cinfo->enable_external_quant = FALSE;
314 cinfo->enable_2pass_quant = FALSE;
315 cinfo->colormap = NULL;
316 } else if (cinfo->colormap != NULL) {
317 cinfo->enable_external_quant = TRUE;
318 } else if (cinfo->two_pass_quantize) {
319 cinfo->enable_2pass_quant = TRUE;
321 cinfo->enable_1pass_quant = TRUE;
324 if (cinfo->enable_1pass_quant) {
325 #ifdef QUANT_1PASS_SUPPORTED
326 jinit_1pass_quantizer(cinfo);
327 master->quantizer_1pass = cinfo->cquantize;
329 ERREXIT(cinfo, JERR_NOT_COMPILED);
333 /* We use the 2-pass code to map to external colormaps. */
334 if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
335 #ifdef QUANT_2PASS_SUPPORTED
336 jinit_2pass_quantizer(cinfo);
337 master->quantizer_2pass = cinfo->cquantize;
339 ERREXIT(cinfo, JERR_NOT_COMPILED);
342 /* If both quantizers are initialized, the 2-pass one is left active;
343 * this is necessary for starting with quantization to an external map.
347 /* Post-processing: in particular, color conversion first */
348 if (! cinfo->raw_data_out) {
349 if (master->using_merged_upsample) {
350 #ifdef UPSAMPLE_MERGING_SUPPORTED
351 jinit_merged_upsampler(cinfo); /* does color conversion too */
353 ERREXIT(cinfo, JERR_NOT_COMPILED);
356 jinit_color_deconverter(cinfo);
357 jinit_upsampler(cinfo);
359 jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
362 jinit_inverse_dct(cinfo);
363 /* Entropy decoding: either Huffman or arithmetic coding. */
364 if (cinfo->arith_code)
365 jinit_arith_decoder(cinfo);
367 jinit_huff_decoder(cinfo);
370 /* Initialize principal buffer controllers. */
371 use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
372 jinit_d_coef_controller(cinfo, use_c_buffer);
374 if (! cinfo->raw_data_out)
375 jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
377 /* We can now tell the memory manager to allocate virtual arrays. */
378 (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
380 /* Initialize input side of decompressor to consume first scan. */
381 (*cinfo->inputctl->start_input_pass) (cinfo);
383 #ifdef D_MULTISCAN_FILES_SUPPORTED
384 /* If jpeg_start_decompress will read the whole file, initialize
385 * progress monitoring appropriately. The input step is counted
388 if (cinfo->progress != NULL && ! cinfo->buffered_image &&
389 cinfo->inputctl->has_multiple_scans) {
391 /* Estimate number of scans to set pass_limit. */
392 if (cinfo->progressive_mode) {
393 /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
394 nscans = 2 + 3 * cinfo->num_components;
396 /* For a nonprogressive multiscan file, estimate 1 scan per component. */
397 nscans = cinfo->num_components;
399 cinfo->progress->pass_counter = 0L;
400 cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
401 cinfo->progress->completed_passes = 0;
402 cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
403 /* Count the input pass as done */
404 master->pass_number++;
406 #endif /* D_MULTISCAN_FILES_SUPPORTED */
412 * This is called at the beginning of each output pass. We determine which
413 * modules will be active during this pass and give them appropriate
414 * start_pass calls. We also set is_dummy_pass to indicate whether this
415 * is a "real" output pass or a dummy pass for color quantization.
416 * (In the latter case, jdapistd.c will crank the pass to completion.)
420 prepare_for_output_pass (j_decompress_ptr cinfo)
422 my_master_ptr master = (my_master_ptr) cinfo->master;
424 if (master->pub.is_dummy_pass) {
425 #ifdef QUANT_2PASS_SUPPORTED
426 /* Final pass of 2-pass quantization */
427 master->pub.is_dummy_pass = FALSE;
428 (*cinfo->cquantize->start_pass) (cinfo, FALSE);
429 (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
430 (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
432 ERREXIT(cinfo, JERR_NOT_COMPILED);
433 #endif /* QUANT_2PASS_SUPPORTED */
435 if (cinfo->quantize_colors && cinfo->colormap == NULL) {
436 /* Select new quantization method */
437 if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
438 cinfo->cquantize = master->quantizer_2pass;
439 master->pub.is_dummy_pass = TRUE;
440 } else if (cinfo->enable_1pass_quant) {
441 cinfo->cquantize = master->quantizer_1pass;
443 ERREXIT(cinfo, JERR_MODE_CHANGE);
446 (*cinfo->idct->start_pass) (cinfo);
447 (*cinfo->coef->start_output_pass) (cinfo);
448 if (! cinfo->raw_data_out) {
449 if (! master->using_merged_upsample)
450 (*cinfo->cconvert->start_pass) (cinfo);
451 (*cinfo->upsample->start_pass) (cinfo);
452 if (cinfo->quantize_colors)
453 (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
454 (*cinfo->post->start_pass) (cinfo,
455 (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
456 (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
460 /* Set up progress monitor's pass info if present */
461 if (cinfo->progress != NULL) {
462 cinfo->progress->completed_passes = master->pass_number;
463 cinfo->progress->total_passes = master->pass_number +
464 (master->pub.is_dummy_pass ? 2 : 1);
465 /* In buffered-image mode, we assume one more output pass if EOI not
466 * yet reached, but no more passes if EOI has been reached.
468 if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
469 cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
476 * Finish up at end of an output pass.
480 finish_output_pass (j_decompress_ptr cinfo)
482 my_master_ptr master = (my_master_ptr) cinfo->master;
484 if (cinfo->quantize_colors)
485 (*cinfo->cquantize->finish_pass) (cinfo);
486 master->pass_number++;
490 #ifdef D_MULTISCAN_FILES_SUPPORTED
493 * Switch to a new external colormap between output passes.
497 jpeg_new_colormap (j_decompress_ptr cinfo)
499 my_master_ptr master = (my_master_ptr) cinfo->master;
501 /* Prevent application from calling me at wrong times */
502 if (cinfo->global_state != DSTATE_BUFIMAGE)
503 ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
505 if (cinfo->quantize_colors && cinfo->enable_external_quant &&
506 cinfo->colormap != NULL) {
507 /* Select 2-pass quantizer for external colormap use */
508 cinfo->cquantize = master->quantizer_2pass;
509 /* Notify quantizer of colormap change */
510 (*cinfo->cquantize->new_color_map) (cinfo);
511 master->pub.is_dummy_pass = FALSE; /* just in case */
513 ERREXIT(cinfo, JERR_MODE_CHANGE);
516 #endif /* D_MULTISCAN_FILES_SUPPORTED */
520 * Initialize master decompression control and select active modules.
521 * This is performed at the start of jpeg_start_decompress.
525 jinit_master_decompress (j_decompress_ptr cinfo)
527 my_master_ptr master;
529 master = (my_master_ptr)
530 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
531 SIZEOF(my_decomp_master));
532 cinfo->master = &master->pub;
533 master->pub.prepare_for_output_pass = prepare_for_output_pass;
534 master->pub.finish_output_pass = finish_output_pass;
536 master->pub.is_dummy_pass = FALSE;
538 master_selection(cinfo);