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