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