1 /*
2  * jdpipe.c
3  *
4  * Copyright (C) 1991, 1992, 1993, 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 decompression pipeline controllers.
9  * These routines are invoked via the d_pipeline_controller method.
10  *
11  * There are two basic pipeline controllers.  The simpler one handles a
12  * single-scan JPEG file (single component or fully interleaved) with no
13  * color quantization or 1-pass quantization.  In this case, the file can
14  * be processed in one top-to-bottom pass.  The more complex controller is
15  * used when 2-pass color quantization is requested and/or the JPEG file
16  * has multiple scans (noninterleaved or partially interleaved).  In this
17  * case, the entire image must be buffered up in a "big" array.
18  *
19  * If you need to make a minimal implementation, the more complex controller
20  * can be compiled out by disabling the appropriate configuration options.
21  * We don't recommend this, since then you can't handle all legal JPEG files.
22  */
23 
24 #include "jinclude.h"
25 
26 
27 #ifdef D_MULTISCAN_FILES_SUPPORTED /* wish we could assume ANSI's defined() */
28 #define NEED_COMPLEX_CONTROLLER
29 #else
30 #ifdef QUANT_2PASS_SUPPORTED
31 #define NEED_COMPLEX_CONTROLLER
32 #endif
33 #endif
34 
35 
36 /*
37  * About the data structures:
38  *
39  * The processing chunk size for upsampling is referred to in this file as
40  * a "row group": a row group is defined as Vk (v_samp_factor) sample rows of
41  * any component while downsampled, or Vmax (max_v_samp_factor) unsubsampled
42  * rows.  In an interleaved scan each MCU row contains exactly DCTSIZE row
43  * groups of each component in the scan.  In a noninterleaved scan an MCU row
44  * is one row of blocks, which might not be an integral number of row groups;
45  * therefore, we read in Vk MCU rows to obtain the same amount of data as we'd
46  * have in an interleaved scan.
47  * To provide context for the upsampling step, we have to retain the last
48  * two row groups of the previous MCU row while reading in the next MCU row
49  * (or set of Vk MCU rows).  To do this without copying data about, we create
50  * a rather strange data structure.  Exactly DCTSIZE+2 row groups of samples
51  * are allocated, but we create two different sets of pointers to this array.
52  * The second set swaps the last two pairs of row groups.  By working
53  * alternately with the two sets of pointers, we can access the data in the
54  * desired order.
55  *
56  * Cross-block smoothing also needs context above and below the "current" row.
57  * Since this is an optional feature, I've implemented it in a way that is
58  * much simpler but requires more than the minimum amount of memory.  We
59  * simply allocate three extra MCU rows worth of coefficient blocks and use
60  * them to "read ahead" one MCU row in the file.  For a typical 1000-pixel-wide
61  * image with 2x2,1x1,1x1 sampling, each MCU row is about 50Kb; an 80x86
62  * machine may be unable to apply cross-block smoothing to wider images.
63  */
64 
65 
66 /*
67  * These variables are logically local to the pipeline controller,
68  * but we make them static so that scan_big_image can use them
69  * without having to pass them through the quantization routines.
70  */
71 
72 static int rows_in_mem;		/* # of sample rows in full-size buffers */
73 /* Work buffer for data being passed to output module. */
74 /* This has color_out_comps components if not quantizing, */
75 /* but only one component when quantizing. */
76 static JSAMPIMAGE output_workspace;
77 
78 #ifdef NEED_COMPLEX_CONTROLLER
79 /* Full-size image array holding upsampled, but not color-processed data. */
80 static big_sarray_ptr *fullsize_image;
81 static JSAMPIMAGE fullsize_ptrs; /* workspace for access_big_sarray() result */
82 #endif
83 
84 
85 /*
86  * Utility routines: common code for pipeline controllers
87  */
88 
89 LOCAL void
interleaved_scan_setup(decompress_info_ptr cinfo)90 interleaved_scan_setup (decompress_info_ptr cinfo)
91 /* Compute all derived info for an interleaved (multi-component) scan */
92 /* On entry, cinfo->comps_in_scan and cinfo->cur_comp_info[] are set up */
93 {
94   short ci, mcublks;
95   jpeg_component_info *compptr;
96 
97   if (cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
98     ERREXIT(cinfo->emethods, "Too many components for interleaved scan");
99 
100   cinfo->MCUs_per_row = (cinfo->image_width
101 			 + cinfo->max_h_samp_factor*DCTSIZE - 1)
102 			/ (cinfo->max_h_samp_factor*DCTSIZE);
103 
104   cinfo->MCU_rows_in_scan = (cinfo->image_height
105 			     + cinfo->max_v_samp_factor*DCTSIZE - 1)
106 			    / (cinfo->max_v_samp_factor*DCTSIZE);
107 
108   cinfo->blocks_in_MCU = 0;
109 
110   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
111     compptr = cinfo->cur_comp_info[ci];
112     /* for interleaved scan, sampling factors give # of blocks per component */
113     compptr->MCU_width = compptr->h_samp_factor;
114     compptr->MCU_height = compptr->v_samp_factor;
115     compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
116     /* compute physical dimensions of component */
117     compptr->downsampled_width = jround_up(compptr->true_comp_width,
118 					   (long) (compptr->MCU_width*DCTSIZE));
119     compptr->downsampled_height = jround_up(compptr->true_comp_height,
120 					    (long) (compptr->MCU_height*DCTSIZE));
121     /* Sanity check */
122     if (compptr->downsampled_width !=
123 	(cinfo->MCUs_per_row * (compptr->MCU_width*DCTSIZE)))
124       ERREXIT(cinfo->emethods, "I'm confused about the image width");
125     /* Prepare array describing MCU composition */
126     mcublks = compptr->MCU_blocks;
127     if (cinfo->blocks_in_MCU + mcublks > MAX_BLOCKS_IN_MCU)
128       ERREXIT(cinfo->emethods, "Sampling factors too large for interleaved scan");
129     while (mcublks-- > 0) {
130       cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
131     }
132   }
133 
134   (*cinfo->methods->d_per_scan_method_selection) (cinfo);
135 }
136 
137 
138 LOCAL void
noninterleaved_scan_setup(decompress_info_ptr cinfo)139 noninterleaved_scan_setup (decompress_info_ptr cinfo)
140 /* Compute all derived info for a noninterleaved (single-component) scan */
141 /* On entry, cinfo->comps_in_scan = 1 and cinfo->cur_comp_info[0] is set up */
142 {
143   jpeg_component_info *compptr = cinfo->cur_comp_info[0];
144 
145   /* for noninterleaved scan, always one block per MCU */
146   compptr->MCU_width = 1;
147   compptr->MCU_height = 1;
148   compptr->MCU_blocks = 1;
149   /* compute physical dimensions of component */
150   compptr->downsampled_width = jround_up(compptr->true_comp_width,
151 					 (long) DCTSIZE);
152   compptr->downsampled_height = jround_up(compptr->true_comp_height,
153 					  (long) DCTSIZE);
154 
155   cinfo->MCUs_per_row = compptr->downsampled_width / DCTSIZE;
156   cinfo->MCU_rows_in_scan = compptr->downsampled_height / DCTSIZE;
157 
158   /* Prepare array describing MCU composition */
159   cinfo->blocks_in_MCU = 1;
160   cinfo->MCU_membership[0] = 0;
161 
162   (*cinfo->methods->d_per_scan_method_selection) (cinfo);
163 }
164 
165 
166 
167 LOCAL JSAMPIMAGE
alloc_sampimage(decompress_info_ptr cinfo,int num_comps,long num_rows,long num_cols)168 alloc_sampimage (decompress_info_ptr cinfo,
169 		 int num_comps, long num_rows, long num_cols)
170 /* Allocate an in-memory sample image (all components same size) */
171 {
172   JSAMPIMAGE image;
173   int ci;
174 
175   image = (JSAMPIMAGE) (*cinfo->emethods->alloc_small)
176 				(num_comps * SIZEOF(JSAMPARRAY));
177   for (ci = 0; ci < num_comps; ci++) {
178     image[ci] = (*cinfo->emethods->alloc_small_sarray) (num_cols, num_rows);
179   }
180   return image;
181 }
182 
183 
184 #if 0				/* this routine not currently needed */
185 
186 LOCAL void
187 free_sampimage (decompress_info_ptr cinfo, JSAMPIMAGE image, int num_comps)
188 /* Release a sample image created by alloc_sampimage */
189 {
190   int ci;
191 
192   for (ci = 0; ci < num_comps; ci++) {
193       (*cinfo->emethods->free_small_sarray) (image[ci]);
194   }
195   (*cinfo->emethods->free_small) ((void *) image);
196 }
197 
198 #endif
199 
200 
201 LOCAL JBLOCKIMAGE
alloc_MCU_row(decompress_info_ptr cinfo)202 alloc_MCU_row (decompress_info_ptr cinfo)
203 /* Allocate one MCU row's worth of coefficient blocks */
204 {
205   JBLOCKIMAGE image;
206   int ci;
207 
208   image = (JBLOCKIMAGE) (*cinfo->emethods->alloc_small)
209 				(cinfo->comps_in_scan * SIZEOF(JBLOCKARRAY));
210   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
211     image[ci] = (*cinfo->emethods->alloc_small_barray)
212 			(cinfo->cur_comp_info[ci]->downsampled_width / DCTSIZE,
213 			 (long) cinfo->cur_comp_info[ci]->MCU_height);
214   }
215   return image;
216 }
217 
218 
219 #ifdef NEED_COMPLEX_CONTROLLER	/* not used by simple controller */
220 
221 LOCAL void
free_MCU_row(decompress_info_ptr cinfo,JBLOCKIMAGE image)222 free_MCU_row (decompress_info_ptr cinfo, JBLOCKIMAGE image)
223 /* Release a coefficient block array created by alloc_MCU_row */
224 {
225   int ci;
226 
227   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
228     (*cinfo->emethods->free_small_barray) (image[ci]);
229   }
230   (*cinfo->emethods->free_small) ((void *) image);
231 }
232 
233 #endif
234 
235 
236 LOCAL void
alloc_sampling_buffer(decompress_info_ptr cinfo,JSAMPIMAGE sampled_data[2])237 alloc_sampling_buffer (decompress_info_ptr cinfo, JSAMPIMAGE sampled_data[2])
238 /* Create a downsampled-data buffer having the desired structure */
239 /* (see comments at head of file) */
240 {
241   short ci, vs, i;
242 
243   /* Get top-level space for array pointers */
244   sampled_data[0] = (JSAMPIMAGE) (*cinfo->emethods->alloc_small)
245 				(cinfo->comps_in_scan * SIZEOF(JSAMPARRAY));
246   sampled_data[1] = (JSAMPIMAGE) (*cinfo->emethods->alloc_small)
247 				(cinfo->comps_in_scan * SIZEOF(JSAMPARRAY));
248 
249   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
250     vs = cinfo->cur_comp_info[ci]->v_samp_factor; /* row group height */
251     /* Allocate the real storage */
252     sampled_data[0][ci] = (*cinfo->emethods->alloc_small_sarray)
253 				(cinfo->cur_comp_info[ci]->downsampled_width,
254 				(long) (vs * (DCTSIZE+2)));
255     /* Create space for the scrambled-order pointers */
256     sampled_data[1][ci] = (JSAMPARRAY) (*cinfo->emethods->alloc_small)
257 				(vs * (DCTSIZE+2) * SIZEOF(JSAMPROW));
258     /* Duplicate the first DCTSIZE-2 row groups */
259     for (i = 0; i < vs * (DCTSIZE-2); i++) {
260       sampled_data[1][ci][i] = sampled_data[0][ci][i];
261     }
262     /* Copy the last four row groups in swapped order */
263     for (i = 0; i < vs * 2; i++) {
264       sampled_data[1][ci][vs*DCTSIZE + i] = sampled_data[0][ci][vs*(DCTSIZE-2) + i];
265       sampled_data[1][ci][vs*(DCTSIZE-2) + i] = sampled_data[0][ci][vs*DCTSIZE + i];
266     }
267   }
268 }
269 
270 
271 #ifdef NEED_COMPLEX_CONTROLLER	/* not used by simple controller */
272 
273 LOCAL void
free_sampling_buffer(decompress_info_ptr cinfo,JSAMPIMAGE sampled_data[2])274 free_sampling_buffer (decompress_info_ptr cinfo, JSAMPIMAGE sampled_data[2])
275 /* Release a sampling buffer created by alloc_sampling_buffer */
276 {
277   short ci;
278 
279   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
280     /* Free the real storage */
281     (*cinfo->emethods->free_small_sarray) (sampled_data[0][ci]);
282     /* Free the scrambled-order pointers */
283     (*cinfo->emethods->free_small) ((void *) sampled_data[1][ci]);
284   }
285 
286   /* Free the top-level space */
287   (*cinfo->emethods->free_small) ((void *) sampled_data[0]);
288   (*cinfo->emethods->free_small) ((void *) sampled_data[1]);
289 }
290 
291 #endif
292 
293 
294 /*
295  * Several decompression processes need to range-limit values to the range
296  * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
297  * due to noise introduced by quantization, roundoff error, etc.  These
298  * processes are inner loops and need to be as fast as possible.  On most
299  * machines, particularly CPUs with pipelines or instruction prefetch,
300  * a (range-check-less) C table lookup
301  *		x = sample_range_limit[x];
302  * is faster than explicit tests
303  *		if (x < 0)  x = 0;
304  *		else if (x > MAXJSAMPLE)  x = MAXJSAMPLE;
305  * These processes all use a common table prepared by the routine below.
306  *
307  * The table will work correctly for x within MAXJSAMPLE+1 of the legal
308  * range.  This is a much wider range than is needed for most cases,
309  * but the wide range is handy for color quantization.
310  * Note that the table is allocated in near data space on PCs; it's small
311  * enough and used often enough to justify this.
312  */
313 
314 LOCAL void
prepare_range_limit_table(decompress_info_ptr cinfo)315 prepare_range_limit_table (decompress_info_ptr cinfo)
316 /* Allocate and fill in the sample_range_limit table */
317 {
318   JSAMPLE * table;
319   int i;
320 
321   table = (JSAMPLE *) (*cinfo->emethods->alloc_small)
322 			(3 * (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
323   cinfo->sample_range_limit = table + (MAXJSAMPLE+1);
324   for (i = 0; i <= MAXJSAMPLE; i++) {
325     table[i] = 0;			/* sample_range_limit[x] = 0 for x<0 */
326     table[i+(MAXJSAMPLE+1)] = (JSAMPLE) i;	/* sample_range_limit[x] = x */
327     table[i+(MAXJSAMPLE+1)*2] = MAXJSAMPLE;	/* x beyond MAXJSAMPLE */
328   }
329 }
330 
331 
332 LOCAL void
duplicate_row(JSAMPARRAY image_data,long num_cols,int source_row,int num_rows)333 duplicate_row (JSAMPARRAY image_data,
334 	       long num_cols, int source_row, int num_rows)
335 /* Duplicate the source_row at source_row+1 .. source_row+num_rows */
336 /* This happens only at the bottom of the image, */
337 /* so it needn't be super-efficient */
338 {
339   register int row;
340 
341   for (row = 1; row <= num_rows; row++) {
342     jcopy_sample_rows(image_data, source_row, image_data, source_row + row,
343 		      1, num_cols);
344   }
345 }
346 
347 
348 LOCAL void
expand(decompress_info_ptr cinfo,JSAMPIMAGE sampled_data,JSAMPIMAGE fullsize_data,long fullsize_width,short above,short current,short below,short out)349 expand (decompress_info_ptr cinfo,
350 	JSAMPIMAGE sampled_data, JSAMPIMAGE fullsize_data,
351 	long fullsize_width,
352 	short above, short current, short below, short out)
353 /* Do upsampling expansion of a single row group (of each component). */
354 /* above, current, below are indexes of row groups in sampled_data;       */
355 /* out is the index of the target row group in fullsize_data.             */
356 /* Special case: above, below can be -1 to indicate top, bottom of image. */
357 {
358   jpeg_component_info *compptr;
359   JSAMPARRAY above_ptr, below_ptr;
360   JSAMPROW dummy[MAX_SAMP_FACTOR]; /* for downsample expansion at top/bottom */
361   short ci, vs, i;
362 
363   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
364     compptr = cinfo->cur_comp_info[ci];
365     /* don't bother to upsample an uninteresting component */
366     if (! compptr->component_needed)
367       continue;
368 
369     vs = compptr->v_samp_factor; /* row group height */
370 
371     if (above >= 0)
372       above_ptr = sampled_data[ci] + above * vs;
373     else {
374       /* Top of image: make a dummy above-context with copies of 1st row */
375       /* We assume current=0 in this case */
376       for (i = 0; i < vs; i++)
377 	dummy[i] = sampled_data[ci][0];
378       above_ptr = (JSAMPARRAY) dummy; /* possible near->far pointer conv */
379     }
380 
381     if (below >= 0)
382       below_ptr = sampled_data[ci] + below * vs;
383     else {
384       /* Bot of image: make a dummy below-context with copies of last row */
385       for (i = 0; i < vs; i++)
386 	dummy[i] = sampled_data[ci][(current+1)*vs-1];
387       below_ptr = (JSAMPARRAY) dummy; /* possible near->far pointer conv */
388     }
389 
390     (*cinfo->methods->upsample[ci])
391 		(cinfo, (int) ci,
392 		 compptr->downsampled_width, (int) vs,
393 		 fullsize_width, (int) cinfo->max_v_samp_factor,
394 		 above_ptr,
395 		 sampled_data[ci] + current * vs,
396 		 below_ptr,
397 		 fullsize_data[ci] + out * cinfo->max_v_samp_factor);
398   }
399 }
400 
401 
402 LOCAL void
emit_1pass(decompress_info_ptr cinfo,int num_rows,JSAMPIMAGE fullsize_data,JSAMPARRAY dummy)403 emit_1pass (decompress_info_ptr cinfo, int num_rows, JSAMPIMAGE fullsize_data,
404 	    JSAMPARRAY dummy)
405 /* Do color processing and output of num_rows full-size rows. */
406 /* This is not used when doing 2-pass color quantization. */
407 /* The dummy argument simply lets this be called via scan_big_image. */
408 {
409   if (cinfo->quantize_colors) {
410     (*cinfo->methods->color_quantize) (cinfo, num_rows, fullsize_data,
411 				       output_workspace[0]);
412   } else {
413     (*cinfo->methods->color_convert) (cinfo, num_rows, cinfo->image_width,
414 				      fullsize_data, output_workspace);
415   }
416 
417   (*cinfo->methods->put_pixel_rows) (cinfo, num_rows, output_workspace);
418 }
419 
420 
421 /*
422  * Support routines for complex controller.
423  */
424 
425 #ifdef NEED_COMPLEX_CONTROLLER
426 
427 METHODDEF void
scan_big_image(decompress_info_ptr cinfo,quantize_method_ptr quantize_method)428 scan_big_image (decompress_info_ptr cinfo, quantize_method_ptr quantize_method)
429 /* Apply quantize_method to entire image stored in fullsize_image[]. */
430 /* This is the "iterator" routine used by the 2-pass color quantizer. */
431 /* We also use it directly in some cases. */
432 {
433   long pixel_rows_output;
434   short ci;
435 
436   for (pixel_rows_output = 0; pixel_rows_output < cinfo->image_height;
437        pixel_rows_output += rows_in_mem) {
438     (*cinfo->methods->progress_monitor) (cinfo, pixel_rows_output,
439 					 cinfo->image_height);
440     /* Realign the big buffers */
441     for (ci = 0; ci < cinfo->num_components; ci++) {
442       fullsize_ptrs[ci] = (*cinfo->emethods->access_big_sarray)
443 	(fullsize_image[ci], pixel_rows_output, FALSE);
444     }
445     /* Let the quantizer have its way with the data.
446      * Note that output_workspace is simply workspace for the quantizer;
447      * when it's ready to output, it must call put_pixel_rows itself.
448      */
449     (*quantize_method) (cinfo,
450 			(int) MIN((long) rows_in_mem,
451 				  cinfo->image_height - pixel_rows_output),
452 			fullsize_ptrs, output_workspace[0]);
453   }
454 
455   cinfo->completed_passes++;
456 }
457 
458 #endif /* NEED_COMPLEX_CONTROLLER */
459 
460 
461 /*
462  * Support routines for cross-block smoothing.
463  */
464 
465 #ifdef BLOCK_SMOOTHING_SUPPORTED
466 
467 
468 LOCAL void
smooth_mcu_row(decompress_info_ptr cinfo,JBLOCKIMAGE above,JBLOCKIMAGE input,JBLOCKIMAGE below,JBLOCKIMAGE output)469 smooth_mcu_row (decompress_info_ptr cinfo,
470 		JBLOCKIMAGE above, JBLOCKIMAGE input, JBLOCKIMAGE below,
471 		JBLOCKIMAGE output)
472 /* Apply cross-block smoothing to one MCU row's worth of coefficient blocks. */
473 /* above,below are NULL if at top/bottom of image. */
474 {
475   jpeg_component_info *compptr;
476   short ci, ri, last;
477   JBLOCKROW prev;
478 
479   for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
480     compptr = cinfo->cur_comp_info[ci];
481     /* don't bother to smooth an uninteresting component */
482     if (! compptr->component_needed)
483       continue;
484 
485     last = compptr->MCU_height - 1;
486 
487     if (above == NULL)
488       prev = NULL;
489     else
490       prev = above[ci][last];
491 
492     for (ri = 0; ri < last; ri++) {
493       (*cinfo->methods->smooth_coefficients) (cinfo, compptr,
494 				prev, input[ci][ri], input[ci][ri+1],
495 				output[ci][ri]);
496       prev = input[ci][ri];
497     }
498 
499     if (below == NULL)
500       (*cinfo->methods->smooth_coefficients) (cinfo, compptr,
501 				prev, input[ci][last], (JBLOCKROW) NULL,
502 				output[ci][last]);
503     else
504       (*cinfo->methods->smooth_coefficients) (cinfo, compptr,
505 				prev, input[ci][last], below[ci][0],
506 				output[ci][last]);
507   }
508 }
509 
510 
511 LOCAL void
get_smoothed_row(decompress_info_ptr cinfo,JBLOCKIMAGE coeff_data,JBLOCKIMAGE bsmooth[3],int * whichb,long cur_mcu_row)512 get_smoothed_row (decompress_info_ptr cinfo, JBLOCKIMAGE coeff_data,
513 		  JBLOCKIMAGE bsmooth[3], int * whichb, long cur_mcu_row)
514 /* Get an MCU row of coefficients, applying cross-block smoothing. */
515 /* The output row is placed in coeff_data.  bsmooth and whichb hold */
516 /* working state, and cur_row is needed to check for image top/bottom. */
517 /* This routine just takes care of the buffering logic. */
518 {
519   int prev, cur, next;
520 
521   /* Special case for top of image: need to pre-fetch a row & init whichb */
522   if (cur_mcu_row == 0) {
523     (*cinfo->methods->disassemble_MCU) (cinfo, bsmooth[0]);
524     if (cinfo->MCU_rows_in_scan > 1) {
525       (*cinfo->methods->disassemble_MCU) (cinfo, bsmooth[1]);
526       smooth_mcu_row(cinfo, (JBLOCKIMAGE) NULL, bsmooth[0], bsmooth[1],
527 		     coeff_data);
528     } else {
529       smooth_mcu_row(cinfo, (JBLOCKIMAGE) NULL, bsmooth[0], (JBLOCKIMAGE) NULL,
530 		     coeff_data);
531     }
532     *whichb = 1;		/* points to next bsmooth[] element to use */
533     return;
534   }
535 
536   cur = *whichb;		/* set up references */
537   prev = (cur == 0 ? 2 : cur - 1);
538   next = (cur == 2 ? 0 : cur + 1);
539   *whichb = next;		/* advance whichb for next time */
540 
541   /* Special case for bottom of image: don't read another row */
542   if (cur_mcu_row >= cinfo->MCU_rows_in_scan - 1) {
543     smooth_mcu_row(cinfo, bsmooth[prev], bsmooth[cur], (JBLOCKIMAGE) NULL,
544 		   coeff_data);
545     return;
546   }
547 
548   /* Normal case: read ahead a new row, smooth the one I got before */
549   (*cinfo->methods->disassemble_MCU) (cinfo, bsmooth[next]);
550   smooth_mcu_row(cinfo, bsmooth[prev], bsmooth[cur], bsmooth[next],
551 		 coeff_data);
552 }
553 
554 
555 #endif /* BLOCK_SMOOTHING_SUPPORTED */
556 
557 
558 
559 /*
560  * Decompression pipeline controller used for single-scan files
561  * without 2-pass color quantization.
562  */
563 
564 METHODDEF void
simple_dcontroller(decompress_info_ptr cinfo)565 simple_dcontroller (decompress_info_ptr cinfo)
566 {
567   long fullsize_width;		/* # of samples per row in full-size buffers */
568   long cur_mcu_row;		/* counts # of MCU rows processed */
569   long pixel_rows_output;	/* # of pixel rows actually emitted */
570   int mcu_rows_per_loop;	/* # of MCU rows processed per outer loop */
571   /* Work buffer for dequantized coefficients (IDCT input) */
572   JBLOCKIMAGE coeff_data;
573   /* Work buffer for cross-block smoothing input */
574 #ifdef BLOCK_SMOOTHING_SUPPORTED
575   JBLOCKIMAGE bsmooth[3];	/* this is optional */
576   int whichb;
577 #endif
578   /* Work buffer for downsampled image data (see comments at head of file) */
579   JSAMPIMAGE sampled_data[2];
580   /* Work buffer for upsampled data */
581   JSAMPIMAGE fullsize_data;
582   int whichss, ri;
583   short i;
584 
585   /* Compute dimensions of full-size pixel buffers */
586   /* Note these are the same whether interleaved or not. */
587   rows_in_mem = cinfo->max_v_samp_factor * DCTSIZE;
588   fullsize_width = jround_up(cinfo->image_width,
589 			     (long) (cinfo->max_h_samp_factor * DCTSIZE));
590 
591   /* Prepare for single scan containing all components */
592   if (cinfo->comps_in_scan == 1) {
593     noninterleaved_scan_setup(cinfo);
594     /* Need to read Vk MCU rows to obtain Vk block rows */
595     mcu_rows_per_loop = cinfo->cur_comp_info[0]->v_samp_factor;
596   } else {
597     interleaved_scan_setup(cinfo);
598     /* in an interleaved scan, one MCU row provides Vk block rows */
599     mcu_rows_per_loop = 1;
600   }
601   cinfo->total_passes++;
602 
603   /* Allocate working memory: */
604   prepare_range_limit_table(cinfo);
605   /* coeff_data holds a single MCU row of coefficient blocks */
606   coeff_data = alloc_MCU_row(cinfo);
607   /* if doing cross-block smoothing, need extra space for its input */
608 #ifdef BLOCK_SMOOTHING_SUPPORTED
609   if (cinfo->do_block_smoothing) {
610     bsmooth[0] = alloc_MCU_row(cinfo);
611     bsmooth[1] = alloc_MCU_row(cinfo);
612     bsmooth[2] = alloc_MCU_row(cinfo);
613   }
614 #endif
615   /* sampled_data is sample data before upsampling */
616   alloc_sampling_buffer(cinfo, sampled_data);
617   /* fullsize_data is sample data after upsampling */
618   fullsize_data = alloc_sampimage(cinfo, (int) cinfo->num_components,
619 				  (long) rows_in_mem, fullsize_width);
620   /* output_workspace is the color-processed data */
621   output_workspace = alloc_sampimage(cinfo, (int) cinfo->final_out_comps,
622 				     (long) rows_in_mem, fullsize_width);
623 
624   /* Tell the memory manager to instantiate big arrays.
625    * We don't need any big arrays in this controller,
626    * but some other module (like the output file writer) may need one.
627    */
628   (*cinfo->emethods->alloc_big_arrays)
629 	((long) 0,				/* no more small sarrays */
630 	 (long) 0,				/* no more small barrays */
631 	 (long) 0);				/* no more "medium" objects */
632   /* NB: if quantizer needs any "medium" size objects, it must get them */
633   /* at color_quant_init time */
634 
635   /* Initialize to read scan data */
636 
637   (*cinfo->methods->entropy_decode_init) (cinfo);
638   (*cinfo->methods->upsample_init) (cinfo);
639   (*cinfo->methods->disassemble_init) (cinfo);
640 
641   /* Loop over scan's data: rows_in_mem pixel rows are processed per loop */
642 
643   pixel_rows_output = 0;
644   whichss = 1;			/* arrange to start with sampled_data[0] */
645 
646   for (cur_mcu_row = 0; cur_mcu_row < cinfo->MCU_rows_in_scan;
647        cur_mcu_row += mcu_rows_per_loop) {
648     (*cinfo->methods->progress_monitor) (cinfo, cur_mcu_row,
649 					 cinfo->MCU_rows_in_scan);
650 
651     whichss ^= 1;		/* switch to other downsampled-data buffer */
652 
653     /* Obtain v_samp_factor block rows of each component in the scan. */
654     /* This is a single MCU row if interleaved, multiple MCU rows if not. */
655     /* In the noninterleaved case there might be fewer than v_samp_factor */
656     /* block rows remaining; if so, pad with copies of the last pixel row */
657     /* so that upsampling doesn't have to treat it as a special case. */
658 
659     for (ri = 0; ri < mcu_rows_per_loop; ri++) {
660       if (cur_mcu_row + ri < cinfo->MCU_rows_in_scan) {
661 	/* OK to actually read an MCU row. */
662 #ifdef BLOCK_SMOOTHING_SUPPORTED
663 	if (cinfo->do_block_smoothing)
664 	  get_smoothed_row(cinfo, coeff_data,
665 			   bsmooth, &whichb, cur_mcu_row + ri);
666 	else
667 #endif
668 	  (*cinfo->methods->disassemble_MCU) (cinfo, coeff_data);
669 
670 	(*cinfo->methods->reverse_DCT) (cinfo, coeff_data,
671 					sampled_data[whichss],
672 					ri * DCTSIZE);
673       } else {
674 	/* Need to pad out with copies of the last downsampled row. */
675 	/* This can only happen if there is just one component. */
676 	duplicate_row(sampled_data[whichss][0],
677 		      cinfo->cur_comp_info[0]->downsampled_width,
678 		      ri * DCTSIZE - 1, DCTSIZE);
679       }
680     }
681 
682     /* Upsample the data */
683     /* First time through is a special case */
684 
685     if (cur_mcu_row) {
686       /* Expand last row group of previous set */
687       expand(cinfo, sampled_data[whichss], fullsize_data, fullsize_width,
688 	     (short) DCTSIZE, (short) (DCTSIZE+1), (short) 0,
689 	     (short) (DCTSIZE-1));
690       /* and dump the previous set's expanded data */
691       emit_1pass (cinfo, rows_in_mem, fullsize_data, (JSAMPARRAY) NULL);
692       pixel_rows_output += rows_in_mem;
693       /* Expand first row group of this set */
694       expand(cinfo, sampled_data[whichss], fullsize_data, fullsize_width,
695 	     (short) (DCTSIZE+1), (short) 0, (short) 1,
696 	     (short) 0);
697     } else {
698       /* Expand first row group with dummy above-context */
699       expand(cinfo, sampled_data[whichss], fullsize_data, fullsize_width,
700 	     (short) (-1), (short) 0, (short) 1,
701 	     (short) 0);
702     }
703     /* Expand second through next-to-last row groups of this set */
704     for (i = 1; i <= DCTSIZE-2; i++) {
705       expand(cinfo, sampled_data[whichss], fullsize_data, fullsize_width,
706 	     (short) (i-1), (short) i, (short) (i+1),
707 	     (short) i);
708     }
709   } /* end of outer loop */
710 
711   /* Expand the last row group with dummy below-context */
712   /* Note whichss points to last buffer side used */
713   expand(cinfo, sampled_data[whichss], fullsize_data, fullsize_width,
714 	 (short) (DCTSIZE-2), (short) (DCTSIZE-1), (short) (-1),
715 	 (short) (DCTSIZE-1));
716   /* and dump the remaining data (may be less than full height) */
717   emit_1pass (cinfo, (int) (cinfo->image_height - pixel_rows_output),
718 	      fullsize_data, (JSAMPARRAY) NULL);
719 
720   /* Clean up after the scan */
721   (*cinfo->methods->disassemble_term) (cinfo);
722   (*cinfo->methods->upsample_term) (cinfo);
723   (*cinfo->methods->entropy_decode_term) (cinfo);
724   (*cinfo->methods->read_scan_trailer) (cinfo);
725   cinfo->completed_passes++;
726 
727   /* Verify that we've seen the whole input file */
728   if ((*cinfo->methods->read_scan_header) (cinfo))
729     WARNMS(cinfo->emethods, "Didn't expect more than one scan");
730 
731   /* Release working memory */
732   /* (no work -- we let free_all release what's needful) */
733 }
734 
735 
736 /*
737  * Decompression pipeline controller used for multiple-scan files
738  * and/or 2-pass color quantization.
739  *
740  * The current implementation places the "big" buffer at the stage of
741  * upsampled, non-color-processed data.  This is the only place that
742  * makes sense when doing 2-pass quantization.  For processing multiple-scan
743  * files without 2-pass quantization, it would be possible to develop another
744  * controller that buffers the downsampled data instead, thus reducing the size
745  * of the temp files (by about a factor of 2 in typical cases).  However,
746  * our present upsampling logic is dependent on the assumption that
747  * upsampling occurs during a scan, so it's much easier to do the
748  * enlargement as the JPEG file is read.  This also simplifies life for the
749  * memory manager, which would otherwise have to deal with overlapping
750  * access_big_sarray() requests.
751  * At present it appears that most JPEG files will be single-scan,
752  * so it doesn't seem worthwhile to worry about this optimization.
753  */
754 
755 #ifdef NEED_COMPLEX_CONTROLLER
756 
757 METHODDEF void
complex_dcontroller(decompress_info_ptr cinfo)758 complex_dcontroller (decompress_info_ptr cinfo)
759 {
760   long fullsize_width;		/* # of samples per row in full-size buffers */
761   long cur_mcu_row;		/* counts # of MCU rows processed */
762   long pixel_rows_output;	/* # of pixel rows actually emitted */
763   int mcu_rows_per_loop;	/* # of MCU rows processed per outer loop */
764   /* Work buffer for dequantized coefficients (IDCT input) */
765   JBLOCKIMAGE coeff_data;
766   /* Work buffer for cross-block smoothing input */
767 #ifdef BLOCK_SMOOTHING_SUPPORTED
768   JBLOCKIMAGE bsmooth[3];	/* this is optional */
769   int whichb;
770 #endif
771   /* Work buffer for downsampled image data (see comments at head of file) */
772   JSAMPIMAGE sampled_data[2];
773   int whichss, ri;
774   short ci, i;
775   boolean single_scan;
776 
777   /* Compute dimensions of full-size pixel buffers */
778   /* Note these are the same whether interleaved or not. */
779   rows_in_mem = cinfo->max_v_samp_factor * DCTSIZE;
780   fullsize_width = jround_up(cinfo->image_width,
781 			     (long) (cinfo->max_h_samp_factor * DCTSIZE));
782 
783   /* Allocate all working memory that doesn't depend on scan info */
784   prepare_range_limit_table(cinfo);
785   /* output_workspace is the color-processed data */
786   output_workspace = alloc_sampimage(cinfo, (int) cinfo->final_out_comps,
787 				     (long) rows_in_mem, fullsize_width);
788 
789   /* Get a big image: fullsize_image is sample data after upsampling. */
790   fullsize_image = (big_sarray_ptr *) (*cinfo->emethods->alloc_small)
791 			(cinfo->num_components * SIZEOF(big_sarray_ptr));
792   for (ci = 0; ci < cinfo->num_components; ci++) {
793     fullsize_image[ci] = (*cinfo->emethods->request_big_sarray)
794 			(fullsize_width,
795 			 jround_up(cinfo->image_height, (long) rows_in_mem),
796 			 (long) rows_in_mem);
797   }
798   /* Also get an area for pointers to currently accessible chunks */
799   fullsize_ptrs = (JSAMPIMAGE) (*cinfo->emethods->alloc_small)
800 				(cinfo->num_components * SIZEOF(JSAMPARRAY));
801 
802   /* Tell the memory manager to instantiate big arrays */
803   (*cinfo->emethods->alloc_big_arrays)
804 	 /* extra sarray space is for downsampled-data buffers: */
805 	((long) (fullsize_width			/* max width in samples */
806 	 * cinfo->max_v_samp_factor*(DCTSIZE+2)	/* max height */
807 	 * cinfo->num_components),		/* max components per scan */
808 	 /* extra barray space is for MCU-row buffers: */
809 	 (long) ((fullsize_width / DCTSIZE)	/* max width in blocks */
810 	 * cinfo->max_v_samp_factor		/* max height */
811 	 * cinfo->num_components		/* max components per scan */
812 	 * (cinfo->do_block_smoothing ? 4 : 1)),/* how many of these we need */
813 	 /* no extra "medium"-object space */
814 	 (long) 0);
815   /* NB: if quantizer needs any "medium" size objects, it must get them */
816   /* at color_quant_init time */
817 
818   /* If file is single-scan, we can do color quantization prescan on-the-fly
819    * during the scan (we must be doing 2-pass quantization, else this method
820    * would not have been selected).  If it is multiple scans, we have to make
821    * a separate pass after we've collected all the components.  (We could save
822    * some I/O by doing CQ prescan during the last scan, but the extra logic
823    * doesn't seem worth the trouble.)
824    */
825 
826   single_scan = (cinfo->comps_in_scan == cinfo->num_components);
827 
828   /* Account for passes needed (color quantizer adds its passes separately).
829    * If multiscan file, we guess that each component has its own scan,
830    * and increment completed_passes by the number of components in the scan.
831    */
832 
833   if (single_scan)
834     cinfo->total_passes++;	/* the single scan */
835   else {
836     cinfo->total_passes += cinfo->num_components; /* guessed # of scans */
837     if (cinfo->two_pass_quantize)
838       cinfo->total_passes++;	/* account for separate CQ prescan pass */
839   }
840   if (! cinfo->two_pass_quantize)
841     cinfo->total_passes++;	/* count output pass unless quantizer does it */
842 
843   /* Loop over scans in file */
844 
845   do {
846 
847     /* Prepare for this scan */
848     if (cinfo->comps_in_scan == 1) {
849       noninterleaved_scan_setup(cinfo);
850       /* Need to read Vk MCU rows to obtain Vk block rows */
851       mcu_rows_per_loop = cinfo->cur_comp_info[0]->v_samp_factor;
852     } else {
853       interleaved_scan_setup(cinfo);
854       /* in an interleaved scan, one MCU row provides Vk block rows */
855       mcu_rows_per_loop = 1;
856     }
857 
858     /* Allocate scan-local working memory */
859     /* coeff_data holds a single MCU row of coefficient blocks */
860     coeff_data = alloc_MCU_row(cinfo);
861     /* if doing cross-block smoothing, need extra space for its input */
862 #ifdef BLOCK_SMOOTHING_SUPPORTED
863     if (cinfo->do_block_smoothing) {
864       bsmooth[0] = alloc_MCU_row(cinfo);
865       bsmooth[1] = alloc_MCU_row(cinfo);
866       bsmooth[2] = alloc_MCU_row(cinfo);
867     }
868 #endif
869     /* sampled_data is sample data before upsampling */
870     alloc_sampling_buffer(cinfo, sampled_data);
871 
872     /* line up the big buffers for components in this scan */
873     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
874       fullsize_ptrs[ci] = (*cinfo->emethods->access_big_sarray)
875 	(fullsize_image[cinfo->cur_comp_info[ci]->component_index],
876 	 (long) 0, TRUE);
877     }
878 
879     /* Initialize to read scan data */
880 
881     (*cinfo->methods->entropy_decode_init) (cinfo);
882     (*cinfo->methods->upsample_init) (cinfo);
883     (*cinfo->methods->disassemble_init) (cinfo);
884 
885     /* Loop over scan's data: rows_in_mem pixel rows are processed per loop */
886 
887     pixel_rows_output = 0;
888     whichss = 1;		/* arrange to start with sampled_data[0] */
889 
890     for (cur_mcu_row = 0; cur_mcu_row < cinfo->MCU_rows_in_scan;
891 	 cur_mcu_row += mcu_rows_per_loop) {
892       (*cinfo->methods->progress_monitor) (cinfo, cur_mcu_row,
893 					   cinfo->MCU_rows_in_scan);
894 
895       whichss ^= 1;		/* switch to other downsampled-data buffer */
896 
897       /* Obtain v_samp_factor block rows of each component in the scan. */
898       /* This is a single MCU row if interleaved, multiple MCU rows if not. */
899       /* In the noninterleaved case there might be fewer than v_samp_factor */
900       /* block rows remaining; if so, pad with copies of the last pixel row */
901       /* so that upsampling doesn't have to treat it as a special case. */
902 
903       for (ri = 0; ri < mcu_rows_per_loop; ri++) {
904 	if (cur_mcu_row + ri < cinfo->MCU_rows_in_scan) {
905 	  /* OK to actually read an MCU row. */
906 #ifdef BLOCK_SMOOTHING_SUPPORTED
907 	  if (cinfo->do_block_smoothing)
908 	    get_smoothed_row(cinfo, coeff_data,
909 			     bsmooth, &whichb, cur_mcu_row + ri);
910 	  else
911 #endif
912 	    (*cinfo->methods->disassemble_MCU) (cinfo, coeff_data);
913 
914 	  (*cinfo->methods->reverse_DCT) (cinfo, coeff_data,
915 					  sampled_data[whichss],
916 					  ri * DCTSIZE);
917 	} else {
918 	  /* Need to pad out with copies of the last downsampled row. */
919 	  /* This can only happen if there is just one component. */
920 	  duplicate_row(sampled_data[whichss][0],
921 			cinfo->cur_comp_info[0]->downsampled_width,
922 			ri * DCTSIZE - 1, DCTSIZE);
923 	}
924       }
925 
926       /* Upsample the data */
927       /* First time through is a special case */
928 
929       if (cur_mcu_row) {
930 	/* Expand last row group of previous set */
931 	expand(cinfo, sampled_data[whichss], fullsize_ptrs, fullsize_width,
932 	       (short) DCTSIZE, (short) (DCTSIZE+1), (short) 0,
933 	       (short) (DCTSIZE-1));
934 	/* If single scan, can do color quantization prescan on-the-fly */
935 	if (single_scan)
936 	  (*cinfo->methods->color_quant_prescan) (cinfo, rows_in_mem,
937 						  fullsize_ptrs,
938 						  output_workspace[0]);
939 	/* Realign the big buffers */
940 	pixel_rows_output += rows_in_mem;
941 	for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
942 	  fullsize_ptrs[ci] = (*cinfo->emethods->access_big_sarray)
943 	    (fullsize_image[cinfo->cur_comp_info[ci]->component_index],
944 	     pixel_rows_output, TRUE);
945 	}
946 	/* Expand first row group of this set */
947 	expand(cinfo, sampled_data[whichss], fullsize_ptrs, fullsize_width,
948 	       (short) (DCTSIZE+1), (short) 0, (short) 1,
949 	       (short) 0);
950       } else {
951 	/* Expand first row group with dummy above-context */
952 	expand(cinfo, sampled_data[whichss], fullsize_ptrs, fullsize_width,
953 	       (short) (-1), (short) 0, (short) 1,
954 	       (short) 0);
955       }
956       /* Expand second through next-to-last row groups of this set */
957       for (i = 1; i <= DCTSIZE-2; i++) {
958 	expand(cinfo, sampled_data[whichss], fullsize_ptrs, fullsize_width,
959 	       (short) (i-1), (short) i, (short) (i+1),
960 	       (short) i);
961       }
962     } /* end of loop over scan's data */
963 
964     /* Expand the last row group with dummy below-context */
965     /* Note whichss points to last buffer side used */
966     expand(cinfo, sampled_data[whichss], fullsize_ptrs, fullsize_width,
967 	   (short) (DCTSIZE-2), (short) (DCTSIZE-1), (short) (-1),
968 	   (short) (DCTSIZE-1));
969     /* If single scan, finish on-the-fly color quantization prescan */
970     if (single_scan)
971       (*cinfo->methods->color_quant_prescan) (cinfo,
972 			(int) (cinfo->image_height - pixel_rows_output),
973 			fullsize_ptrs, output_workspace[0]);
974 
975     /* Clean up after the scan */
976     (*cinfo->methods->disassemble_term) (cinfo);
977     (*cinfo->methods->upsample_term) (cinfo);
978     (*cinfo->methods->entropy_decode_term) (cinfo);
979     (*cinfo->methods->read_scan_trailer) (cinfo);
980     if (single_scan)
981       cinfo->completed_passes++;
982     else
983       cinfo->completed_passes += cinfo->comps_in_scan;
984 
985     /* Release scan-local working memory */
986     free_MCU_row(cinfo, coeff_data);
987 #ifdef BLOCK_SMOOTHING_SUPPORTED
988     if (cinfo->do_block_smoothing) {
989       free_MCU_row(cinfo, bsmooth[0]);
990       free_MCU_row(cinfo, bsmooth[1]);
991       free_MCU_row(cinfo, bsmooth[2]);
992     }
993 #endif
994     free_sampling_buffer(cinfo, sampled_data);
995 
996     /* Repeat if there is another scan */
997   } while ((!single_scan) && (*cinfo->methods->read_scan_header) (cinfo));
998 
999   if (single_scan) {
1000     /* If we expected just one scan, make SURE there's just one */
1001     if ((*cinfo->methods->read_scan_header) (cinfo))
1002       WARNMS(cinfo->emethods, "Didn't expect more than one scan");
1003     /* We did the CQ prescan on-the-fly, so we are all set. */
1004   } else {
1005     /* For multiple-scan file, do the CQ prescan as a separate pass. */
1006     /* The main reason why prescan is passed the output_workspace is */
1007     /* so that we can use scan_big_image to call it... */
1008     if (cinfo->two_pass_quantize)
1009       scan_big_image(cinfo, cinfo->methods->color_quant_prescan);
1010   }
1011 
1012   /* Now that we've collected the data, do color processing and output */
1013   if (cinfo->two_pass_quantize)
1014     (*cinfo->methods->color_quant_doit) (cinfo, scan_big_image);
1015   else
1016     scan_big_image(cinfo, emit_1pass);
1017 
1018   /* Release working memory */
1019   /* (no work -- we let free_all release what's needful) */
1020 }
1021 
1022 #endif /* NEED_COMPLEX_CONTROLLER */
1023 
1024 
1025 /*
1026  * The method selection routine for decompression pipeline controllers.
1027  * Note that at this point we've already read the JPEG header and first SOS,
1028  * so we can tell whether the input is one scan or not.
1029  */
1030 
1031 GLOBAL void
jseldpipeline(decompress_info_ptr cinfo)1032 jseldpipeline (decompress_info_ptr cinfo)
1033 {
1034   /* simplify subsequent tests on color quantization */
1035   if (! cinfo->quantize_colors)
1036     cinfo->two_pass_quantize = FALSE;
1037 
1038   if (cinfo->comps_in_scan == cinfo->num_components) {
1039     /* It's a single-scan file */
1040     if (cinfo->two_pass_quantize) {
1041 #ifdef NEED_COMPLEX_CONTROLLER
1042       cinfo->methods->d_pipeline_controller = complex_dcontroller;
1043 #else
1044       ERREXIT(cinfo->emethods, "2-pass quantization support was not compiled");
1045 #endif
1046     } else
1047       cinfo->methods->d_pipeline_controller = simple_dcontroller;
1048   } else {
1049     /* It's a multiple-scan file */
1050 #ifdef NEED_COMPLEX_CONTROLLER
1051     cinfo->methods->d_pipeline_controller = complex_dcontroller;
1052 #else
1053     ERREXIT(cinfo->emethods, "Multiple-scan support was not compiled");
1054 #endif
1055   }
1056 }
1057