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