1/*
2 * reserved comment block
3 * DO NOT REMOVE OR ALTER!
4 */
5/*
6 * jdmaster.c
7 *
8 * Copyright (C) 1991-1997, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
11 *
12 * This file contains master control logic for the JPEG decompressor.
13 * These routines are concerned with selecting the modules to be executed
14 * and with determining the number of passes and the work to be done in each
15 * pass.
16 */
17
18#define JPEG_INTERNALS
19#include "jinclude.h"
20#include "jpeglib.h"
21
22
23/* Private state */
24
25typedef struct {
26 struct jpeg_decomp_master pub; /* public fields */
27
28 int pass_number; /* # of passes completed */
29
30 boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
31
32 /* Saved references to initialized quantizer modules,
33 * in case we need to switch modes.
34 */
35 struct jpeg_color_quantizer * quantizer_1pass;
36 struct jpeg_color_quantizer * quantizer_2pass;
37} my_decomp_master;
38
39typedef my_decomp_master * my_master_ptr;
40
41
42/*
43 * Determine whether merged upsample/color conversion should be used.
44 * CRUCIAL: this must match the actual capabilities of jdmerge.c!
45 */
46
47LOCAL(boolean)
48use_merged_upsample (j_decompress_ptr cinfo)
49{
50#ifdef UPSAMPLE_MERGING_SUPPORTED
51 /* Merging is the equivalent of plain box-filter upsampling */
52 if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
53 return FALSE;
54 /* jdmerge.c only supports YCC=>RGB color conversion */
55 if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
56 cinfo->out_color_space != JCS_RGB ||
57 cinfo->out_color_components != RGB_PIXELSIZE)
58 return FALSE;
59 /* and it only handles 2h1v or 2h2v sampling ratios */
60 if (cinfo->comp_info[0].h_samp_factor != 2 ||
61 cinfo->comp_info[1].h_samp_factor != 1 ||
62 cinfo->comp_info[2].h_samp_factor != 1 ||
63 cinfo->comp_info[0].v_samp_factor > 2 ||
64 cinfo->comp_info[1].v_samp_factor != 1 ||
65 cinfo->comp_info[2].v_samp_factor != 1)
66 return FALSE;
67 /* furthermore, it doesn't work if we've scaled the IDCTs differently */
68 if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
69 cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
70 cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
71 return FALSE;
72 /* ??? also need to test for upsample-time rescaling, when & if supported */
73 return TRUE; /* by golly, it'll work... */
74#else
75 return FALSE;
76#endif
77}
78
79
80/*
81 * Compute output image dimensions and related values.
82 * NOTE: this is exported for possible use by application.
83 * Hence it mustn't do anything that can't be done twice.
84 * Also note that it may be called before the master module is initialized!
85 */
86
87GLOBAL(void)
88jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
89/* Do computations that are needed before master selection phase */
90{
91#ifdef IDCT_SCALING_SUPPORTED
92 int ci;
93 jpeg_component_info *compptr;
94#endif
95
96 /* Prevent application from calling me at wrong times */
97 if (cinfo->global_state != DSTATE_READY)
98 ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
99
100#ifdef IDCT_SCALING_SUPPORTED
101
102 /* Compute actual output image dimensions and DCT scaling choices. */
103 if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
104 /* Provide 1/8 scaling */
105 cinfo->output_width = (JDIMENSION)
106 jdiv_round_up((long) cinfo->image_width, 8L);
107 cinfo->output_height = (JDIMENSION)
108 jdiv_round_up((long) cinfo->image_height, 8L);
109 cinfo->min_DCT_scaled_size = 1;
110 } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
111 /* Provide 1/4 scaling */
112 cinfo->output_width = (JDIMENSION)
113 jdiv_round_up((long) cinfo->image_width, 4L);
114 cinfo->output_height = (JDIMENSION)
115 jdiv_round_up((long) cinfo->image_height, 4L);
116 cinfo->min_DCT_scaled_size = 2;
117 } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
118 /* Provide 1/2 scaling */
119 cinfo->output_width = (JDIMENSION)
120 jdiv_round_up((long) cinfo->image_width, 2L);
121 cinfo->output_height = (JDIMENSION)
122 jdiv_round_up((long) cinfo->image_height, 2L);
123 cinfo->min_DCT_scaled_size = 4;
124 } else {
125 /* Provide 1/1 scaling */
126 cinfo->output_width = cinfo->image_width;
127 cinfo->output_height = cinfo->image_height;
128 cinfo->min_DCT_scaled_size = DCTSIZE;
129 }
130 /* In selecting the actual DCT scaling for each component, we try to
131 * scale up the chroma components via IDCT scaling rather than upsampling.
132 * This saves time if the upsampler gets to use 1:1 scaling.
133 * Note this code assumes that the supported DCT scalings are powers of 2.
134 */
135 for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
136 ci++, compptr++) {
137 int ssize = cinfo->min_DCT_scaled_size;
138 while (ssize < DCTSIZE &&
139 (compptr->h_samp_factor * ssize * 2 <=
140 cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
141 (compptr->v_samp_factor * ssize * 2 <=
142 cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
143 ssize = ssize * 2;
144 }
145 compptr->DCT_scaled_size = ssize;
146 }
147
148 /* Recompute downsampled dimensions of components;
149 * application needs to know these if using raw downsampled data.
150 */
151 for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
152 ci++, compptr++) {
153 /* Size in samples, after IDCT scaling */
154 compptr->downsampled_width = (JDIMENSION)
155 jdiv_round_up((long) cinfo->image_width *
156 (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
157 (long) (cinfo->max_h_samp_factor * DCTSIZE));
158 compptr->downsampled_height = (JDIMENSION)
159 jdiv_round_up((long) cinfo->image_height *
160 (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
161 (long) (cinfo->max_v_samp_factor * DCTSIZE));
162 }
163
164#else /* !IDCT_SCALING_SUPPORTED */
165
166 /* Hardwire it to "no scaling" */
167 cinfo->output_width = cinfo->image_width;
168 cinfo->output_height = cinfo->image_height;
169 /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
170 * and has computed unscaled downsampled_width and downsampled_height.
171 */
172
173#endif /* IDCT_SCALING_SUPPORTED */
174
175 /* Report number of components in selected colorspace. */
176 /* Probably this should be in the color conversion module... */
177 switch (cinfo->out_color_space) {
178 case JCS_GRAYSCALE:
179 cinfo->out_color_components = 1;
180 break;
181 case JCS_RGB:
182#if RGB_PIXELSIZE != 3
183 cinfo->out_color_components = RGB_PIXELSIZE;
184 break;
185#endif /* else share code with YCbCr */
186 case JCS_YCbCr:
187 cinfo->out_color_components = 3;
188 break;
189 case JCS_CMYK:
190 case JCS_YCCK:
191 cinfo->out_color_components = 4;
192 break;
193 default: /* else must be same colorspace as in file */
194 cinfo->out_color_components = cinfo->num_components;
195 break;
196 }
197 cinfo->output_components = (cinfo->quantize_colors ? 1 :
198 cinfo->out_color_components);
199
200 /* See if upsampler will want to emit more than one row at a time */
201 if (use_merged_upsample(cinfo))
202 cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
203 else
204 cinfo->rec_outbuf_height = 1;
205}
206
207
208/*
209 * Several decompression processes need to range-limit values to the range
210 * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
211 * due to noise introduced by quantization, roundoff error, etc. These
212 * processes are inner loops and need to be as fast as possible. On most
213 * machines, particularly CPUs with pipelines or instruction prefetch,
214 * a (subscript-check-less) C table lookup
215 * x = sample_range_limit[x];
216 * is faster than explicit tests
217 * if (x < 0) x = 0;
218 * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
219 * These processes all use a common table prepared by the routine below.
220 *
221 * For most steps we can mathematically guarantee that the initial value
222 * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
223 * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
224 * limiting step (just after the IDCT), a wildly out-of-range value is
225 * possible if the input data is corrupt. To avoid any chance of indexing
226 * off the end of memory and getting a bad-pointer trap, we perform the
227 * post-IDCT limiting thus:
228 * x = range_limit[x & MASK];
229 * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
230 * samples. Under normal circumstances this is more than enough range and
231 * a correct output will be generated; with bogus input data the mask will
232 * cause wraparound, and we will safely generate a bogus-but-in-range output.
233 * For the post-IDCT step, we want to convert the data from signed to unsigned
234 * representation by adding CENTERJSAMPLE at the same time that we limit it.
235 * So the post-IDCT limiting table ends up looking like this:
236 * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
237 * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
238 * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
239 * 0,1,...,CENTERJSAMPLE-1
240 * Negative inputs select values from the upper half of the table after
241 * masking.
242 *
243 * We can save some space by overlapping the start of the post-IDCT table
244 * with the simpler range limiting table. The post-IDCT table begins at
245 * sample_range_limit + CENTERJSAMPLE.
246 *
247 * Note that the table is allocated in near data space on PCs; it's small
248 * enough and used often enough to justify this.
249 */
250
251LOCAL(void)
252prepare_range_limit_table (j_decompress_ptr cinfo)
253/* Allocate and fill in the sample_range_limit table */
254{
255 JSAMPLE * table;
256 int i;
257
258 table = (JSAMPLE *)
259 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
260 (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
261 table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
262 cinfo->sample_range_limit = table;
263 /* First segment of "simple" table: limit[x] = 0 for x < 0 */
264 MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
265 /* Main part of "simple" table: limit[x] = x */
266 for (i = 0; i <= MAXJSAMPLE; i++)
267 table[i] = (JSAMPLE) i;
268 table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
269 /* End of simple table, rest of first half of post-IDCT table */
270 for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
271 table[i] = MAXJSAMPLE;
272 /* Second half of post-IDCT table */
273 MEMZERO(table + (2 * (MAXJSAMPLE+1)),
274 (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
275 MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
276 cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
277}
278
279
280/*
281 * Master selection of decompression modules.
282 * This is done once at jpeg_start_decompress time. We determine
283 * which modules will be used and give them appropriate initialization calls.
284 * We also initialize the decompressor input side to begin consuming data.
285 *
286 * Since jpeg_read_header has finished, we know what is in the SOF
287 * and (first) SOS markers. We also have all the application parameter
288 * settings.
289 */
290
291LOCAL(void)
292master_selection (j_decompress_ptr cinfo)
293{
294 my_master_ptr master = (my_master_ptr) cinfo->master;
295 boolean use_c_buffer;
296 long samplesperrow;
297 JDIMENSION jd_samplesperrow;
298
299 /* Initialize dimensions and other stuff */
300 jpeg_calc_output_dimensions(cinfo);
301 prepare_range_limit_table(cinfo);
302
303 /* Width of an output scanline must be representable as JDIMENSION. */
304 samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
305 jd_samplesperrow = (JDIMENSION) samplesperrow;
306 if ((long) jd_samplesperrow != samplesperrow)
307 ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
308
309 /* Initialize my private state */
310 master->pass_number = 0;
311 master->using_merged_upsample = use_merged_upsample(cinfo);
312
313 /* Color quantizer selection */
314 master->quantizer_1pass = NULL;
315 master->quantizer_2pass = NULL;
316 /* No mode changes if not using buffered-image mode. */
317 if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
318 cinfo->enable_1pass_quant = FALSE;
319 cinfo->enable_external_quant = FALSE;
320 cinfo->enable_2pass_quant = FALSE;
321 }
322 if (cinfo->quantize_colors) {
323 if (cinfo->raw_data_out)
324 ERREXIT(cinfo, JERR_NOTIMPL);
325 /* 2-pass quantizer only works in 3-component color space. */
326 if (cinfo->out_color_components != 3) {
327 cinfo->enable_1pass_quant = TRUE;
328 cinfo->enable_external_quant = FALSE;
329 cinfo->enable_2pass_quant = FALSE;
330 cinfo->colormap = NULL;
331 } else if (cinfo->colormap != NULL) {
332 cinfo->enable_external_quant = TRUE;
333 } else if (cinfo->two_pass_quantize) {
334 cinfo->enable_2pass_quant = TRUE;
335 } else {
336 cinfo->enable_1pass_quant = TRUE;
337 }
338
339 if (cinfo->enable_1pass_quant) {
340#ifdef QUANT_1PASS_SUPPORTED
341 jinit_1pass_quantizer(cinfo);
342 master->quantizer_1pass = cinfo->cquantize;
343#else
344 ERREXIT(cinfo, JERR_NOT_COMPILED);
345#endif
346 }
347
348 /* We use the 2-pass code to map to external colormaps. */
349 if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
350#ifdef QUANT_2PASS_SUPPORTED
351 jinit_2pass_quantizer(cinfo);
352 master->quantizer_2pass = cinfo->cquantize;
353#else
354 ERREXIT(cinfo, JERR_NOT_COMPILED);
355#endif
356 }
357 /* If both quantizers are initialized, the 2-pass one is left active;
358 * this is necessary for starting with quantization to an external map.
359 */
360 }
361
362 /* Post-processing: in particular, color conversion first */
363 if (! cinfo->raw_data_out) {
364 if (master->using_merged_upsample) {
365#ifdef UPSAMPLE_MERGING_SUPPORTED
366 jinit_merged_upsampler(cinfo); /* does color conversion too */
367#else
368 ERREXIT(cinfo, JERR_NOT_COMPILED);
369#endif
370 } else {
371 jinit_color_deconverter(cinfo);
372 jinit_upsampler(cinfo);
373 }
374 jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
375 }
376 /* Inverse DCT */
377 jinit_inverse_dct(cinfo);
378 /* Entropy decoding: either Huffman or arithmetic coding. */
379 if (cinfo->arith_code) {
380 ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
381 } else {
382 if (cinfo->progressive_mode) {
383#ifdef D_PROGRESSIVE_SUPPORTED
384 jinit_phuff_decoder(cinfo);
385#else
386 ERREXIT(cinfo, JERR_NOT_COMPILED);
387#endif
388 } else
389 jinit_huff_decoder(cinfo);
390 }
391
392 /* Initialize principal buffer controllers. */
393 use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
394 jinit_d_coef_controller(cinfo, use_c_buffer);
395
396 if (! cinfo->raw_data_out)
397 jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
398
399 /* We can now tell the memory manager to allocate virtual arrays. */
400 (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
401
402 /* Initialize input side of decompressor to consume first scan. */
403 (*cinfo->inputctl->start_input_pass) (cinfo);
404
405#ifdef D_MULTISCAN_FILES_SUPPORTED
406 /* If jpeg_start_decompress will read the whole file, initialize
407 * progress monitoring appropriately. The input step is counted
408 * as one pass.
409 */
410 if (cinfo->progress != NULL && ! cinfo->buffered_image &&
411 cinfo->inputctl->has_multiple_scans) {
412 int nscans;
413 /* Estimate number of scans to set pass_limit. */
414 if (cinfo->progressive_mode) {
415 /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
416 nscans = 2 + 3 * cinfo->num_components;
417 } else {
418 /* For a nonprogressive multiscan file, estimate 1 scan per component. */
419 nscans = cinfo->num_components;
420 }
421 cinfo->progress->pass_counter = 0L;
422 cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
423 cinfo->progress->completed_passes = 0;
424 cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
425 /* Count the input pass as done */
426 master->pass_number++;
427 }
428#endif /* D_MULTISCAN_FILES_SUPPORTED */
429}
430
431
432/*
433 * Per-pass setup.
434 * This is called at the beginning of each output pass. We determine which
435 * modules will be active during this pass and give them appropriate
436 * start_pass calls. We also set is_dummy_pass to indicate whether this
437 * is a "real" output pass or a dummy pass for color quantization.
438 * (In the latter case, jdapistd.c will crank the pass to completion.)
439 */
440
441METHODDEF(void)
442prepare_for_output_pass (j_decompress_ptr cinfo)
443{
444 my_master_ptr master = (my_master_ptr) cinfo->master;
445
446 if (master->pub.is_dummy_pass) {
447#ifdef QUANT_2PASS_SUPPORTED
448 /* Final pass of 2-pass quantization */
449 master->pub.is_dummy_pass = FALSE;
450 (*cinfo->cquantize->start_pass) (cinfo, FALSE);
451 (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
452 (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
453#else
454 ERREXIT(cinfo, JERR_NOT_COMPILED);
455#endif /* QUANT_2PASS_SUPPORTED */
456 } else {
457 if (cinfo->quantize_colors && cinfo->colormap == NULL) {
458 /* Select new quantization method */
459 if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
460 cinfo->cquantize = master->quantizer_2pass;
461 master->pub.is_dummy_pass = TRUE;
462 } else if (cinfo->enable_1pass_quant) {
463 cinfo->cquantize = master->quantizer_1pass;
464 } else {
465 ERREXIT(cinfo, JERR_MODE_CHANGE);
466 }
467 }
468 (*cinfo->idct->start_pass) (cinfo);
469 (*cinfo->coef->start_output_pass) (cinfo);
470 if (! cinfo->raw_data_out) {
471 if (! master->using_merged_upsample)
472 (*cinfo->cconvert->start_pass) (cinfo);
473 (*cinfo->upsample->start_pass) (cinfo);
474 if (cinfo->quantize_colors)
475 (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
476 (*cinfo->post->start_pass) (cinfo,
477 (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
478 (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
479 }
480 }
481
482 /* Set up progress monitor's pass info if present */
483 if (cinfo->progress != NULL) {
484 cinfo->progress->completed_passes = master->pass_number;
485 cinfo->progress->total_passes = master->pass_number +
486 (master->pub.is_dummy_pass ? 2 : 1);
487 /* In buffered-image mode, we assume one more output pass if EOI not
488 * yet reached, but no more passes if EOI has been reached.
489 */
490 if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
491 cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
492 }
493 }
494}
495
496
497/*
498 * Finish up at end of an output pass.
499 */
500
501METHODDEF(void)
502finish_output_pass (j_decompress_ptr cinfo)
503{
504 my_master_ptr master = (my_master_ptr) cinfo->master;
505
506 if (cinfo->quantize_colors)
507 (*cinfo->cquantize->finish_pass) (cinfo);
508 master->pass_number++;
509}
510
511
512#ifdef D_MULTISCAN_FILES_SUPPORTED
513
514/*
515 * Switch to a new external colormap between output passes.
516 */
517
518GLOBAL(void)
519jpeg_new_colormap (j_decompress_ptr cinfo)
520{
521 my_master_ptr master = (my_master_ptr) cinfo->master;
522
523 /* Prevent application from calling me at wrong times */
524 if (cinfo->global_state != DSTATE_BUFIMAGE)
525 ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
526
527 if (cinfo->quantize_colors && cinfo->enable_external_quant &&
528 cinfo->colormap != NULL) {
529 /* Select 2-pass quantizer for external colormap use */
530 cinfo->cquantize = master->quantizer_2pass;
531 /* Notify quantizer of colormap change */
532 (*cinfo->cquantize->new_color_map) (cinfo);
533 master->pub.is_dummy_pass = FALSE; /* just in case */
534 } else
535 ERREXIT(cinfo, JERR_MODE_CHANGE);
536}
537
538#endif /* D_MULTISCAN_FILES_SUPPORTED */
539
540
541/*
542 * Initialize master decompression control and select active modules.
543 * This is performed at the start of jpeg_start_decompress.
544 */
545
546GLOBAL(void)
547jinit_master_decompress (j_decompress_ptr cinfo)
548{
549 my_master_ptr master;
550
551 master = (my_master_ptr)
552 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
553 SIZEOF(my_decomp_master));
554 cinfo->master = (struct jpeg_decomp_master *) master;
555 master->pub.prepare_for_output_pass = prepare_for_output_pass;
556 master->pub.finish_output_pass = finish_output_pass;
557
558 master->pub.is_dummy_pass = FALSE;
559
560 master_selection(cinfo);
561}
562