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