1 /*
2  * jcmaster.c
3  *
4  * Copyright (C) 1991-1997, Thomas G. Lane.
5  * Modified 2003-2009 by Guido Vollbeding.
6  * This file is part of the Independent JPEG Group's software.
7  * For conditions of distribution and use, see the accompanying README file.
8  *
9  * This file contains master control logic for the JPEG compressor.
10  * These routines are concerned with parameter validation, initial setup,
11  * and inter-pass control (determining the number of passes and the work
12  * to be done in each pass).
13  */
14 
15 #define JPEG_INTERNALS
16 #include "jinclude.h"
17 #include "jpeglib.h"
18 
19 
20 /* Private state */
21 
22 typedef enum {
23 	main_pass,		/* input data, also do first output step */
24 	huff_opt_pass,		/* Huffman code optimization pass */
25 	output_pass		/* data output pass */
26 } c_pass_type;
27 
28 typedef struct {
29   struct jpeg_comp_master pub;	/* public fields */
30 
31   c_pass_type pass_type;	/* the type of the current pass */
32 
33   int pass_number;		/* # of passes completed */
34   int total_passes;		/* total # of passes needed */
35 
36   int scan_number;		/* current index in scan_info[] */
37 } my_comp_master;
38 
39 typedef my_comp_master * my_master_ptr;
40 
41 
42 /*
43  * Support routines that do various essential calculations.
44  */
45 
46 /*
47  * Compute JPEG image dimensions and related values.
48  * NOTE: this is exported for possible use by application.
49  * Hence it mustn't do anything that can't be done twice.
50  */
51 
52 GLOBAL(void)
jpeg_calc_jpeg_dimensions(j_compress_ptr cinfo)53 jpeg_calc_jpeg_dimensions (j_compress_ptr cinfo)
54 /* Do computations that are needed before master selection phase */
55 {
56 #ifdef DCT_SCALING_SUPPORTED
57 
58   /* Compute actual JPEG image dimensions and DCT scaling choices. */
59   if (cinfo->scale_num >= cinfo->scale_denom * 8) {
60     /* Provide 8/1 scaling */
61     cinfo->jpeg_width = cinfo->image_width << 3;
62     cinfo->jpeg_height = cinfo->image_height << 3;
63     cinfo->min_DCT_h_scaled_size = 1;
64     cinfo->min_DCT_v_scaled_size = 1;
65   } else if (cinfo->scale_num >= cinfo->scale_denom * 4) {
66     /* Provide 4/1 scaling */
67     cinfo->jpeg_width = cinfo->image_width << 2;
68     cinfo->jpeg_height = cinfo->image_height << 2;
69     cinfo->min_DCT_h_scaled_size = 2;
70     cinfo->min_DCT_v_scaled_size = 2;
71   } else if (cinfo->scale_num * 3 >= cinfo->scale_denom * 8) {
72     /* Provide 8/3 scaling */
73     cinfo->jpeg_width = (cinfo->image_width << 1) + (JDIMENSION)
74       jdiv_round_up((long) cinfo->image_width * 2, 3L);
75     cinfo->jpeg_height = (cinfo->image_height << 1) + (JDIMENSION)
76       jdiv_round_up((long) cinfo->image_height * 2, 3L);
77     cinfo->min_DCT_h_scaled_size = 3;
78     cinfo->min_DCT_v_scaled_size = 3;
79   } else if (cinfo->scale_num >= cinfo->scale_denom * 2) {
80     /* Provide 2/1 scaling */
81     cinfo->jpeg_width = cinfo->image_width << 1;
82     cinfo->jpeg_height = cinfo->image_height << 1;
83     cinfo->min_DCT_h_scaled_size = 4;
84     cinfo->min_DCT_v_scaled_size = 4;
85   } else if (cinfo->scale_num * 5 >= cinfo->scale_denom * 8) {
86     /* Provide 8/5 scaling */
87     cinfo->jpeg_width = cinfo->image_width + (JDIMENSION)
88       jdiv_round_up((long) cinfo->image_width * 3, 5L);
89     cinfo->jpeg_height = cinfo->image_height + (JDIMENSION)
90       jdiv_round_up((long) cinfo->image_height * 3, 5L);
91     cinfo->min_DCT_h_scaled_size = 5;
92     cinfo->min_DCT_v_scaled_size = 5;
93   } else if (cinfo->scale_num * 3 >= cinfo->scale_denom * 4) {
94     /* Provide 4/3 scaling */
95     cinfo->jpeg_width = cinfo->image_width + (JDIMENSION)
96       jdiv_round_up((long) cinfo->image_width, 3L);
97     cinfo->jpeg_height = cinfo->image_height + (JDIMENSION)
98       jdiv_round_up((long) cinfo->image_height, 3L);
99     cinfo->min_DCT_h_scaled_size = 6;
100     cinfo->min_DCT_v_scaled_size = 6;
101   } else if (cinfo->scale_num * 7 >= cinfo->scale_denom * 8) {
102     /* Provide 8/7 scaling */
103     cinfo->jpeg_width = cinfo->image_width + (JDIMENSION)
104       jdiv_round_up((long) cinfo->image_width, 7L);
105     cinfo->jpeg_height = cinfo->image_height + (JDIMENSION)
106       jdiv_round_up((long) cinfo->image_height, 7L);
107     cinfo->min_DCT_h_scaled_size = 7;
108     cinfo->min_DCT_v_scaled_size = 7;
109   } else if (cinfo->scale_num >= cinfo->scale_denom) {
110     /* Provide 1/1 scaling */
111     cinfo->jpeg_width = cinfo->image_width;
112     cinfo->jpeg_height = cinfo->image_height;
113     cinfo->min_DCT_h_scaled_size = DCTSIZE;
114     cinfo->min_DCT_v_scaled_size = DCTSIZE;
115   } else if (cinfo->scale_num * 9 >= cinfo->scale_denom * 8) {
116     /* Provide 8/9 scaling */
117     cinfo->jpeg_width = (JDIMENSION)
118       jdiv_round_up((long) cinfo->image_width * 8, 9L);
119     cinfo->jpeg_height = (JDIMENSION)
120       jdiv_round_up((long) cinfo->image_height * 8, 9L);
121     cinfo->min_DCT_h_scaled_size = 9;
122     cinfo->min_DCT_v_scaled_size = 9;
123   } else if (cinfo->scale_num * 5 >= cinfo->scale_denom * 4) {
124     /* Provide 4/5 scaling */
125     cinfo->jpeg_width = (JDIMENSION)
126       jdiv_round_up((long) cinfo->image_width * 4, 5L);
127     cinfo->jpeg_height = (JDIMENSION)
128       jdiv_round_up((long) cinfo->image_height * 4, 5L);
129     cinfo->min_DCT_h_scaled_size = 10;
130     cinfo->min_DCT_v_scaled_size = 10;
131   } else if (cinfo->scale_num * 11 >= cinfo->scale_denom * 8) {
132     /* Provide 8/11 scaling */
133     cinfo->jpeg_width = (JDIMENSION)
134       jdiv_round_up((long) cinfo->image_width * 8, 11L);
135     cinfo->jpeg_height = (JDIMENSION)
136       jdiv_round_up((long) cinfo->image_height * 8, 11L);
137     cinfo->min_DCT_h_scaled_size = 11;
138     cinfo->min_DCT_v_scaled_size = 11;
139   } else if (cinfo->scale_num * 3 >= cinfo->scale_denom * 2) {
140     /* Provide 2/3 scaling */
141     cinfo->jpeg_width = (JDIMENSION)
142       jdiv_round_up((long) cinfo->image_width * 2, 3L);
143     cinfo->jpeg_height = (JDIMENSION)
144       jdiv_round_up((long) cinfo->image_height * 2, 3L);
145     cinfo->min_DCT_h_scaled_size = 12;
146     cinfo->min_DCT_v_scaled_size = 12;
147   } else if (cinfo->scale_num * 13 >= cinfo->scale_denom * 8) {
148     /* Provide 8/13 scaling */
149     cinfo->jpeg_width = (JDIMENSION)
150       jdiv_round_up((long) cinfo->image_width * 8, 13L);
151     cinfo->jpeg_height = (JDIMENSION)
152       jdiv_round_up((long) cinfo->image_height * 8, 13L);
153     cinfo->min_DCT_h_scaled_size = 13;
154     cinfo->min_DCT_v_scaled_size = 13;
155   } else if (cinfo->scale_num * 7 >= cinfo->scale_denom * 4) {
156     /* Provide 4/7 scaling */
157     cinfo->jpeg_width = (JDIMENSION)
158       jdiv_round_up((long) cinfo->image_width * 4, 7L);
159     cinfo->jpeg_height = (JDIMENSION)
160       jdiv_round_up((long) cinfo->image_height * 4, 7L);
161     cinfo->min_DCT_h_scaled_size = 14;
162     cinfo->min_DCT_v_scaled_size = 14;
163   } else if (cinfo->scale_num * 15 >= cinfo->scale_denom * 8) {
164     /* Provide 8/15 scaling */
165     cinfo->jpeg_width = (JDIMENSION)
166       jdiv_round_up((long) cinfo->image_width * 8, 15L);
167     cinfo->jpeg_height = (JDIMENSION)
168       jdiv_round_up((long) cinfo->image_height * 8, 15L);
169     cinfo->min_DCT_h_scaled_size = 15;
170     cinfo->min_DCT_v_scaled_size = 15;
171   } else {
172     /* Provide 1/2 scaling */
173     cinfo->jpeg_width = (JDIMENSION)
174       jdiv_round_up((long) cinfo->image_width, 2L);
175     cinfo->jpeg_height = (JDIMENSION)
176       jdiv_round_up((long) cinfo->image_height, 2L);
177     cinfo->min_DCT_h_scaled_size = 16;
178     cinfo->min_DCT_v_scaled_size = 16;
179   }
180 
181 #else /* !DCT_SCALING_SUPPORTED */
182 
183   /* Hardwire it to "no scaling" */
184   cinfo->jpeg_width = cinfo->image_width;
185   cinfo->jpeg_height = cinfo->image_height;
186   cinfo->min_DCT_h_scaled_size = DCTSIZE;
187   cinfo->min_DCT_v_scaled_size = DCTSIZE;
188 
189 #endif /* DCT_SCALING_SUPPORTED */
190 }
191 
192 
193 LOCAL(void)
initial_setup(j_compress_ptr cinfo)194 initial_setup (j_compress_ptr cinfo)
195 /* Do computations that are needed before master selection phase */
196 {
197   int ci, ssize;
198   jpeg_component_info *compptr;
199   long samplesperrow;
200   JDIMENSION jd_samplesperrow;
201 
202   jpeg_calc_jpeg_dimensions(cinfo);
203 
204   /* Sanity check on image dimensions */
205   if (cinfo->jpeg_height <= 0 || cinfo->jpeg_width <= 0
206       || cinfo->num_components <= 0 || cinfo->input_components <= 0)
207     ERREXIT(cinfo, JERR_EMPTY_IMAGE);
208 
209   /* Make sure image isn't bigger than I can handle */
210   if ((long) cinfo->jpeg_height > (long) JPEG_MAX_DIMENSION ||
211       (long) cinfo->jpeg_width > (long) JPEG_MAX_DIMENSION)
212     ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
213 
214   /* Width of an input scanline must be representable as JDIMENSION. */
215   samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
216   jd_samplesperrow = (JDIMENSION) samplesperrow;
217   if ((long) jd_samplesperrow != samplesperrow)
218     ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
219 
220   /* For now, precision must match compiled-in value... */
221   if (cinfo->data_precision != BITS_IN_JSAMPLE)
222     ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
223 
224   /* Check that number of components won't exceed internal array sizes */
225   if (cinfo->num_components > MAX_COMPONENTS)
226     ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
227 	     MAX_COMPONENTS);
228 
229   /* Compute maximum sampling factors; check factor validity */
230   cinfo->max_h_samp_factor = 1;
231   cinfo->max_v_samp_factor = 1;
232   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
233        ci++, compptr++) {
234     if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
235 	compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
236       ERREXIT(cinfo, JERR_BAD_SAMPLING);
237     cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
238 				   compptr->h_samp_factor);
239     cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
240 				   compptr->v_samp_factor);
241   }
242 
243   /* Compute dimensions of components */
244   for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
245        ci++, compptr++) {
246     /* Fill in the correct component_index value; don't rely on application */
247     compptr->component_index = ci;
248     /* In selecting the actual DCT scaling for each component, we try to
249      * scale down the chroma components via DCT scaling rather than downsampling.
250      * This saves time if the downsampler gets to use 1:1 scaling.
251      * Note this code adapts subsampling ratios which are powers of 2.
252      */
253     ssize = 1;
254 #ifdef DCT_SCALING_SUPPORTED
255     while (cinfo->min_DCT_h_scaled_size * ssize <=
256 	   (cinfo->do_fancy_downsampling ? DCTSIZE : DCTSIZE / 2) &&
257 	   (cinfo->max_h_samp_factor % (compptr->h_samp_factor * ssize * 2)) == 0) {
258       ssize = ssize * 2;
259     }
260 #endif
261     compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size * ssize;
262     ssize = 1;
263 #ifdef DCT_SCALING_SUPPORTED
264     while (cinfo->min_DCT_v_scaled_size * ssize <=
265 	   (cinfo->do_fancy_downsampling ? DCTSIZE : DCTSIZE / 2) &&
266 	   (cinfo->max_v_samp_factor % (compptr->v_samp_factor * ssize * 2)) == 0) {
267       ssize = ssize * 2;
268     }
269 #endif
270     compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size * ssize;
271 
272     /* We don't support DCT ratios larger than 2. */
273     if (compptr->DCT_h_scaled_size > compptr->DCT_v_scaled_size * 2)
274 	compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size * 2;
275     else if (compptr->DCT_v_scaled_size > compptr->DCT_h_scaled_size * 2)
276 	compptr->DCT_v_scaled_size = compptr->DCT_h_scaled_size * 2;
277 
278     /* Size in DCT blocks */
279     compptr->width_in_blocks = (JDIMENSION)
280       jdiv_round_up((long) cinfo->jpeg_width * (long) compptr->h_samp_factor,
281 		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
282     compptr->height_in_blocks = (JDIMENSION)
283       jdiv_round_up((long) cinfo->jpeg_height * (long) compptr->v_samp_factor,
284 		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
285     /* Size in samples */
286     compptr->downsampled_width = (JDIMENSION)
287       jdiv_round_up((long) cinfo->jpeg_width *
288 		    (long) (compptr->h_samp_factor * compptr->DCT_h_scaled_size),
289 		    (long) (cinfo->max_h_samp_factor * DCTSIZE));
290     compptr->downsampled_height = (JDIMENSION)
291       jdiv_round_up((long) cinfo->jpeg_height *
292 		    (long) (compptr->v_samp_factor * compptr->DCT_v_scaled_size),
293 		    (long) (cinfo->max_v_samp_factor * DCTSIZE));
294     /* Mark component needed (this flag isn't actually used for compression) */
295     compptr->component_needed = TRUE;
296   }
297 
298   /* Compute number of fully interleaved MCU rows (number of times that
299    * main controller will call coefficient controller).
300    */
301   cinfo->total_iMCU_rows = (JDIMENSION)
302     jdiv_round_up((long) cinfo->jpeg_height,
303 		  (long) (cinfo->max_v_samp_factor*DCTSIZE));
304 }
305 
306 
307 #ifdef C_MULTISCAN_FILES_SUPPORTED
308 
309 LOCAL(void)
validate_script(j_compress_ptr cinfo)310 validate_script (j_compress_ptr cinfo)
311 /* Verify that the scan script in cinfo->scan_info[] is valid; also
312  * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
313  */
314 {
315   const jpeg_scan_info * scanptr;
316   int scanno, ncomps, ci, coefi, thisi;
317   int Ss, Se, Ah, Al;
318   boolean component_sent[MAX_COMPONENTS];
319 #ifdef C_PROGRESSIVE_SUPPORTED
320   int * last_bitpos_ptr;
321   int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
322   /* -1 until that coefficient has been seen; then last Al for it */
323 #endif
324 
325   if (cinfo->num_scans <= 0)
326     ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
327 
328   /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
329    * for progressive JPEG, no scan can have this.
330    */
331   scanptr = cinfo->scan_info;
332   if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
333 #ifdef C_PROGRESSIVE_SUPPORTED
334     cinfo->progressive_mode = TRUE;
335     last_bitpos_ptr = & last_bitpos[0][0];
336     for (ci = 0; ci < cinfo->num_components; ci++)
337       for (coefi = 0; coefi < DCTSIZE2; coefi++)
338 	*last_bitpos_ptr++ = -1;
339 #else
340     ERREXIT(cinfo, JERR_NOT_COMPILED);
341 #endif
342   } else {
343     cinfo->progressive_mode = FALSE;
344     for (ci = 0; ci < cinfo->num_components; ci++)
345       component_sent[ci] = FALSE;
346   }
347 
348   for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
349     /* Validate component indexes */
350     ncomps = scanptr->comps_in_scan;
351     if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
352       ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
353     for (ci = 0; ci < ncomps; ci++) {
354       thisi = scanptr->component_index[ci];
355       if (thisi < 0 || thisi >= cinfo->num_components)
356 	ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
357       /* Components must appear in SOF order within each scan */
358       if (ci > 0 && thisi <= scanptr->component_index[ci-1])
359 	ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
360     }
361     /* Validate progression parameters */
362     Ss = scanptr->Ss;
363     Se = scanptr->Se;
364     Ah = scanptr->Ah;
365     Al = scanptr->Al;
366     if (cinfo->progressive_mode) {
367 #ifdef C_PROGRESSIVE_SUPPORTED
368       /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
369        * seems wrong: the upper bound ought to depend on data precision.
370        * Perhaps they really meant 0..N+1 for N-bit precision.
371        * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
372        * out-of-range reconstructed DC values during the first DC scan,
373        * which might cause problems for some decoders.
374        */
375 #if BITS_IN_JSAMPLE == 8
376 #define MAX_AH_AL 10
377 #else
378 #define MAX_AH_AL 13
379 #endif
380       if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
381 	  Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
382 	ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
383       if (Ss == 0) {
384 	if (Se != 0)		/* DC and AC together not OK */
385 	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
386       } else {
387 	if (ncomps != 1)	/* AC scans must be for only one component */
388 	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
389       }
390       for (ci = 0; ci < ncomps; ci++) {
391 	last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
392 	if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
393 	  ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
394 	for (coefi = Ss; coefi <= Se; coefi++) {
395 	  if (last_bitpos_ptr[coefi] < 0) {
396 	    /* first scan of this coefficient */
397 	    if (Ah != 0)
398 	      ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
399 	  } else {
400 	    /* not first scan */
401 	    if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
402 	      ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
403 	  }
404 	  last_bitpos_ptr[coefi] = Al;
405 	}
406       }
407 #endif
408     } else {
409       /* For sequential JPEG, all progression parameters must be these: */
410       if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
411 	ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
412       /* Make sure components are not sent twice */
413       for (ci = 0; ci < ncomps; ci++) {
414 	thisi = scanptr->component_index[ci];
415 	if (component_sent[thisi])
416 	  ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
417 	component_sent[thisi] = TRUE;
418       }
419     }
420   }
421 
422   /* Now verify that everything got sent. */
423   if (cinfo->progressive_mode) {
424 #ifdef C_PROGRESSIVE_SUPPORTED
425     /* For progressive mode, we only check that at least some DC data
426      * got sent for each component; the spec does not require that all bits
427      * of all coefficients be transmitted.  Would it be wiser to enforce
428      * transmission of all coefficient bits??
429      */
430     for (ci = 0; ci < cinfo->num_components; ci++) {
431       if (last_bitpos[ci][0] < 0)
432 	ERREXIT(cinfo, JERR_MISSING_DATA);
433     }
434 #endif
435   } else {
436     for (ci = 0; ci < cinfo->num_components; ci++) {
437       if (! component_sent[ci])
438 	ERREXIT(cinfo, JERR_MISSING_DATA);
439     }
440   }
441 }
442 
443 #endif /* C_MULTISCAN_FILES_SUPPORTED */
444 
445 
446 LOCAL(void)
select_scan_parameters(j_compress_ptr cinfo)447 select_scan_parameters (j_compress_ptr cinfo)
448 /* Set up the scan parameters for the current scan */
449 {
450   int ci;
451 
452 #ifdef C_MULTISCAN_FILES_SUPPORTED
453   if (cinfo->scan_info != NULL) {
454     /* Prepare for current scan --- the script is already validated */
455     my_master_ptr master = (my_master_ptr) cinfo->master;
456     const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
457 
458     cinfo->comps_in_scan = scanptr->comps_in_scan;
459     for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
460       cinfo->cur_comp_info[ci] =
461 	&cinfo->comp_info[scanptr->component_index[ci]];
462     }
463     cinfo->Ss = scanptr->Ss;
464     cinfo->Se = scanptr->Se;
465     cinfo->Ah = scanptr->Ah;
466     cinfo->Al = scanptr->Al;
467   }
468   else
469 #endif
470   {
471     /* Prepare for single sequential-JPEG scan containing all components */
472     if (cinfo->num_components > MAX_COMPS_IN_SCAN)
473       ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
474 	       MAX_COMPS_IN_SCAN);
475     cinfo->comps_in_scan = cinfo->num_components;
476     for (ci = 0; ci < cinfo->num_components; ci++) {
477       cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
478     }
479     cinfo->Ss = 0;
480     cinfo->Se = DCTSIZE2-1;
481     cinfo->Ah = 0;
482     cinfo->Al = 0;
483   }
484 }
485 
486 
487 LOCAL(void)
per_scan_setup(j_compress_ptr cinfo)488 per_scan_setup (j_compress_ptr cinfo)
489 /* Do computations that are needed before processing a JPEG scan */
490 /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
491 {
492   int ci, mcublks, tmp;
493   jpeg_component_info *compptr;
494 
495   if (cinfo->comps_in_scan == 1) {
496 
497     /* Noninterleaved (single-component) scan */
498     compptr = cinfo->cur_comp_info[0];
499 
500     /* Overall image size in MCUs */
501     cinfo->MCUs_per_row = compptr->width_in_blocks;
502     cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
503 
504     /* For noninterleaved scan, always one block per MCU */
505     compptr->MCU_width = 1;
506     compptr->MCU_height = 1;
507     compptr->MCU_blocks = 1;
508     compptr->MCU_sample_width = compptr->DCT_h_scaled_size;
509     compptr->last_col_width = 1;
510     /* For noninterleaved scans, it is convenient to define last_row_height
511      * as the number of block rows present in the last iMCU row.
512      */
513     tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
514     if (tmp == 0) tmp = compptr->v_samp_factor;
515     compptr->last_row_height = tmp;
516 
517     /* Prepare array describing MCU composition */
518     cinfo->blocks_in_MCU = 1;
519     cinfo->MCU_membership[0] = 0;
520 
521   } else {
522 
523     /* Interleaved (multi-component) scan */
524     if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
525       ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
526 	       MAX_COMPS_IN_SCAN);
527 
528     /* Overall image size in MCUs */
529     cinfo->MCUs_per_row = (JDIMENSION)
530       jdiv_round_up((long) cinfo->jpeg_width,
531 		    (long) (cinfo->max_h_samp_factor*DCTSIZE));
532     cinfo->MCU_rows_in_scan = (JDIMENSION)
533       jdiv_round_up((long) cinfo->jpeg_height,
534 		    (long) (cinfo->max_v_samp_factor*DCTSIZE));
535 
536     cinfo->blocks_in_MCU = 0;
537 
538     for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
539       compptr = cinfo->cur_comp_info[ci];
540       /* Sampling factors give # of blocks of component in each MCU */
541       compptr->MCU_width = compptr->h_samp_factor;
542       compptr->MCU_height = compptr->v_samp_factor;
543       compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
544       compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_h_scaled_size;
545       /* Figure number of non-dummy blocks in last MCU column & row */
546       tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
547       if (tmp == 0) tmp = compptr->MCU_width;
548       compptr->last_col_width = tmp;
549       tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
550       if (tmp == 0) tmp = compptr->MCU_height;
551       compptr->last_row_height = tmp;
552       /* Prepare array describing MCU composition */
553       mcublks = compptr->MCU_blocks;
554       if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
555 	ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
556       while (mcublks-- > 0) {
557 	cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
558       }
559     }
560 
561   }
562 
563   /* Convert restart specified in rows to actual MCU count. */
564   /* Note that count must fit in 16 bits, so we provide limiting. */
565   if (cinfo->restart_in_rows > 0) {
566     long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
567     cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
568   }
569 }
570 
571 
572 /*
573  * Per-pass setup.
574  * This is called at the beginning of each pass.  We determine which modules
575  * will be active during this pass and give them appropriate start_pass calls.
576  * We also set is_last_pass to indicate whether any more passes will be
577  * required.
578  */
579 
580 METHODDEF(void)
prepare_for_pass(j_compress_ptr cinfo)581 prepare_for_pass (j_compress_ptr cinfo)
582 {
583   my_master_ptr master = (my_master_ptr) cinfo->master;
584 
585   switch (master->pass_type) {
586   case main_pass:
587     /* Initial pass: will collect input data, and do either Huffman
588      * optimization or data output for the first scan.
589      */
590     select_scan_parameters(cinfo);
591     per_scan_setup(cinfo);
592     if (! cinfo->raw_data_in) {
593       (*cinfo->cconvert->start_pass) (cinfo);
594       (*cinfo->downsample->start_pass) (cinfo);
595       (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
596     }
597     (*cinfo->fdct->start_pass) (cinfo);
598     (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
599     (*cinfo->coef->start_pass) (cinfo,
600 				(master->total_passes > 1 ?
601 				 JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
602     (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
603     if (cinfo->optimize_coding) {
604       /* No immediate data output; postpone writing frame/scan headers */
605       master->pub.call_pass_startup = FALSE;
606     } else {
607       /* Will write frame/scan headers at first jpeg_write_scanlines call */
608       master->pub.call_pass_startup = TRUE;
609     }
610     break;
611 #ifdef ENTROPY_OPT_SUPPORTED
612   case huff_opt_pass:
613     /* Do Huffman optimization for a scan after the first one. */
614     select_scan_parameters(cinfo);
615     per_scan_setup(cinfo);
616     if (cinfo->Ss != 0 || cinfo->Ah == 0) {
617       (*cinfo->entropy->start_pass) (cinfo, TRUE);
618       (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
619       master->pub.call_pass_startup = FALSE;
620       break;
621     }
622     /* Special case: Huffman DC refinement scans need no Huffman table
623      * and therefore we can skip the optimization pass for them.
624      */
625     master->pass_type = output_pass;
626     master->pass_number++;
627     /*FALLTHROUGH*/
628 #endif
629   case output_pass:
630     /* Do a data-output pass. */
631     /* We need not repeat per-scan setup if prior optimization pass did it. */
632     if (! cinfo->optimize_coding) {
633       select_scan_parameters(cinfo);
634       per_scan_setup(cinfo);
635     }
636     (*cinfo->entropy->start_pass) (cinfo, FALSE);
637     (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
638     /* We emit frame/scan headers now */
639     if (master->scan_number == 0)
640       (*cinfo->marker->write_frame_header) (cinfo);
641     (*cinfo->marker->write_scan_header) (cinfo);
642     master->pub.call_pass_startup = FALSE;
643     break;
644   default:
645     ERREXIT(cinfo, JERR_NOT_COMPILED);
646   }
647 
648   master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
649 
650   /* Set up progress monitor's pass info if present */
651   if (cinfo->progress != NULL) {
652     cinfo->progress->completed_passes = master->pass_number;
653     cinfo->progress->total_passes = master->total_passes;
654   }
655 }
656 
657 
658 /*
659  * Special start-of-pass hook.
660  * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
661  * In single-pass processing, we need this hook because we don't want to
662  * write frame/scan headers during jpeg_start_compress; we want to let the
663  * application write COM markers etc. between jpeg_start_compress and the
664  * jpeg_write_scanlines loop.
665  * In multi-pass processing, this routine is not used.
666  */
667 
668 METHODDEF(void)
pass_startup(j_compress_ptr cinfo)669 pass_startup (j_compress_ptr cinfo)
670 {
671   cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
672 
673   (*cinfo->marker->write_frame_header) (cinfo);
674   (*cinfo->marker->write_scan_header) (cinfo);
675 }
676 
677 
678 /*
679  * Finish up at end of pass.
680  */
681 
682 METHODDEF(void)
finish_pass_master(j_compress_ptr cinfo)683 finish_pass_master (j_compress_ptr cinfo)
684 {
685   my_master_ptr master = (my_master_ptr) cinfo->master;
686 
687   /* The entropy coder always needs an end-of-pass call,
688    * either to analyze statistics or to flush its output buffer.
689    */
690   (*cinfo->entropy->finish_pass) (cinfo);
691 
692   /* Update state for next pass */
693   switch (master->pass_type) {
694   case main_pass:
695     /* next pass is either output of scan 0 (after optimization)
696      * or output of scan 1 (if no optimization).
697      */
698     master->pass_type = output_pass;
699     if (! cinfo->optimize_coding)
700       master->scan_number++;
701     break;
702   case huff_opt_pass:
703     /* next pass is always output of current scan */
704     master->pass_type = output_pass;
705     break;
706   case output_pass:
707     /* next pass is either optimization or output of next scan */
708     if (cinfo->optimize_coding)
709       master->pass_type = huff_opt_pass;
710     master->scan_number++;
711     break;
712   }
713 
714   master->pass_number++;
715 }
716 
717 
718 /*
719  * Initialize master compression control.
720  */
721 
722 GLOBAL(void)
jinit_c_master_control(j_compress_ptr cinfo,boolean transcode_only)723 jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
724 {
725   my_master_ptr master;
726 
727   master = (my_master_ptr)
728       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
729 				  SIZEOF(my_comp_master));
730   cinfo->master = (struct jpeg_comp_master *) master;
731   master->pub.prepare_for_pass = prepare_for_pass;
732   master->pub.pass_startup = pass_startup;
733   master->pub.finish_pass = finish_pass_master;
734   master->pub.is_last_pass = FALSE;
735 
736   /* Validate parameters, determine derived values */
737   initial_setup(cinfo);
738 
739   if (cinfo->scan_info != NULL) {
740 #ifdef C_MULTISCAN_FILES_SUPPORTED
741     validate_script(cinfo);
742 #else
743     ERREXIT(cinfo, JERR_NOT_COMPILED);
744 #endif
745   } else {
746     cinfo->progressive_mode = FALSE;
747     cinfo->num_scans = 1;
748   }
749 
750   if (cinfo->progressive_mode && cinfo->arith_code == 0)	/*  TEMPORARY HACK ??? */
751     cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
752 
753   /* Initialize my private state */
754   if (transcode_only) {
755     /* no main pass in transcoding */
756     if (cinfo->optimize_coding)
757       master->pass_type = huff_opt_pass;
758     else
759       master->pass_type = output_pass;
760   } else {
761     /* for normal compression, first pass is always this type: */
762     master->pass_type = main_pass;
763   }
764   master->scan_number = 0;
765   master->pass_number = 0;
766   if (cinfo->optimize_coding)
767     master->total_passes = cinfo->num_scans * 2;
768   else
769     master->total_passes = cinfo->num_scans;
770 }
771