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