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