/src/FreeImage/Source/LibJPEG/jdmaster.c

https://bitbucket.org/cabalistic/ogredeps/ · C · 531 lines · 309 code · 64 blank · 158 comment · 88 complexity · a6962ca4b811117b92e6503230a8bfac MD5 · raw file

  1. /*
  2. * jdmaster.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2002-2011 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 decompressor.
  10. * These routines are concerned with selecting the modules to be executed
  11. * and with determining the number of passes and the work to be done in each
  12. * pass.
  13. */
  14. #define JPEG_INTERNALS
  15. #include "jinclude.h"
  16. #include "jpeglib.h"
  17. /* Private state */
  18. typedef struct {
  19. struct jpeg_decomp_master pub; /* public fields */
  20. int pass_number; /* # of passes completed */
  21. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  22. /* Saved references to initialized quantizer modules,
  23. * in case we need to switch modes.
  24. */
  25. struct jpeg_color_quantizer * quantizer_1pass;
  26. struct jpeg_color_quantizer * quantizer_2pass;
  27. } my_decomp_master;
  28. typedef my_decomp_master * my_master_ptr;
  29. /*
  30. * Determine whether merged upsample/color conversion should be used.
  31. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  32. */
  33. LOCAL(boolean)
  34. use_merged_upsample (j_decompress_ptr cinfo)
  35. {
  36. #ifdef UPSAMPLE_MERGING_SUPPORTED
  37. /* Merging is the equivalent of plain box-filter upsampling */
  38. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  39. return FALSE;
  40. /* jdmerge.c only supports YCC=>RGB color conversion */
  41. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  42. cinfo->out_color_space != JCS_RGB ||
  43. cinfo->out_color_components != RGB_PIXELSIZE)
  44. return FALSE;
  45. /* and it only handles 2h1v or 2h2v sampling ratios */
  46. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  47. cinfo->comp_info[1].h_samp_factor != 1 ||
  48. cinfo->comp_info[2].h_samp_factor != 1 ||
  49. cinfo->comp_info[0].v_samp_factor > 2 ||
  50. cinfo->comp_info[1].v_samp_factor != 1 ||
  51. cinfo->comp_info[2].v_samp_factor != 1)
  52. return FALSE;
  53. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  54. if (cinfo->comp_info[0].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
  55. cinfo->comp_info[1].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
  56. cinfo->comp_info[2].DCT_h_scaled_size != cinfo->min_DCT_h_scaled_size ||
  57. cinfo->comp_info[0].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size ||
  58. cinfo->comp_info[1].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size ||
  59. cinfo->comp_info[2].DCT_v_scaled_size != cinfo->min_DCT_v_scaled_size)
  60. return FALSE;
  61. /* ??? also need to test for upsample-time rescaling, when & if supported */
  62. return TRUE; /* by golly, it'll work... */
  63. #else
  64. return FALSE;
  65. #endif
  66. }
  67. /*
  68. * Compute output image dimensions and related values.
  69. * NOTE: this is exported for possible use by application.
  70. * Hence it mustn't do anything that can't be done twice.
  71. * Also note that it may be called before the master module is initialized!
  72. */
  73. GLOBAL(void)
  74. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  75. /* Do computations that are needed before master selection phase.
  76. * This function is used for full decompression.
  77. */
  78. {
  79. #ifdef IDCT_SCALING_SUPPORTED
  80. int ci;
  81. jpeg_component_info *compptr;
  82. #endif
  83. /* Prevent application from calling me at wrong times */
  84. if (cinfo->global_state != DSTATE_READY)
  85. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  86. /* Compute core output image dimensions and DCT scaling choices. */
  87. jpeg_core_output_dimensions(cinfo);
  88. #ifdef IDCT_SCALING_SUPPORTED
  89. /* In selecting the actual DCT scaling for each component, we try to
  90. * scale up the chroma components via IDCT scaling rather than upsampling.
  91. * This saves time if the upsampler gets to use 1:1 scaling.
  92. * Note this code adapts subsampling ratios which are powers of 2.
  93. */
  94. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  95. ci++, compptr++) {
  96. int ssize = 1;
  97. while (cinfo->min_DCT_h_scaled_size * ssize <=
  98. (cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) &&
  99. (cinfo->max_h_samp_factor % (compptr->h_samp_factor * ssize * 2)) == 0) {
  100. ssize = ssize * 2;
  101. }
  102. compptr->DCT_h_scaled_size = cinfo->min_DCT_h_scaled_size * ssize;
  103. ssize = 1;
  104. while (cinfo->min_DCT_v_scaled_size * ssize <=
  105. (cinfo->do_fancy_upsampling ? DCTSIZE : DCTSIZE / 2) &&
  106. (cinfo->max_v_samp_factor % (compptr->v_samp_factor * ssize * 2)) == 0) {
  107. ssize = ssize * 2;
  108. }
  109. compptr->DCT_v_scaled_size = cinfo->min_DCT_v_scaled_size * ssize;
  110. /* We don't support IDCT ratios larger than 2. */
  111. if (compptr->DCT_h_scaled_size > compptr->DCT_v_scaled_size * 2)
  112. compptr->DCT_h_scaled_size = compptr->DCT_v_scaled_size * 2;
  113. else if (compptr->DCT_v_scaled_size > compptr->DCT_h_scaled_size * 2)
  114. compptr->DCT_v_scaled_size = compptr->DCT_h_scaled_size * 2;
  115. }
  116. /* Recompute downsampled dimensions of components;
  117. * application needs to know these if using raw downsampled data.
  118. */
  119. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  120. ci++, compptr++) {
  121. /* Size in samples, after IDCT scaling */
  122. compptr->downsampled_width = (JDIMENSION)
  123. jdiv_round_up((long) cinfo->image_width *
  124. (long) (compptr->h_samp_factor * compptr->DCT_h_scaled_size),
  125. (long) (cinfo->max_h_samp_factor * cinfo->block_size));
  126. compptr->downsampled_height = (JDIMENSION)
  127. jdiv_round_up((long) cinfo->image_height *
  128. (long) (compptr->v_samp_factor * compptr->DCT_v_scaled_size),
  129. (long) (cinfo->max_v_samp_factor * cinfo->block_size));
  130. }
  131. #endif /* IDCT_SCALING_SUPPORTED */
  132. /* Report number of components in selected colorspace. */
  133. /* Probably this should be in the color conversion module... */
  134. switch (cinfo->out_color_space) {
  135. case JCS_GRAYSCALE:
  136. cinfo->out_color_components = 1;
  137. break;
  138. case JCS_RGB:
  139. cinfo->out_color_components = RGB_PIXELSIZE;
  140. break;
  141. case JCS_YCbCr:
  142. cinfo->out_color_components = 3;
  143. break;
  144. case JCS_CMYK:
  145. case JCS_YCCK:
  146. cinfo->out_color_components = 4;
  147. break;
  148. default: /* else must be same colorspace as in file */
  149. cinfo->out_color_components = cinfo->num_components;
  150. break;
  151. }
  152. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  153. cinfo->out_color_components);
  154. /* See if upsampler will want to emit more than one row at a time */
  155. if (use_merged_upsample(cinfo))
  156. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  157. else
  158. cinfo->rec_outbuf_height = 1;
  159. }
  160. /*
  161. * Several decompression processes need to range-limit values to the range
  162. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  163. * due to noise introduced by quantization, roundoff error, etc. These
  164. * processes are inner loops and need to be as fast as possible. On most
  165. * machines, particularly CPUs with pipelines or instruction prefetch,
  166. * a (subscript-check-less) C table lookup
  167. * x = sample_range_limit[x];
  168. * is faster than explicit tests
  169. * if (x < 0) x = 0;
  170. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  171. * These processes all use a common table prepared by the routine below.
  172. *
  173. * For most steps we can mathematically guarantee that the initial value
  174. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  175. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  176. * limiting step (just after the IDCT), a wildly out-of-range value is
  177. * possible if the input data is corrupt. To avoid any chance of indexing
  178. * off the end of memory and getting a bad-pointer trap, we perform the
  179. * post-IDCT limiting thus:
  180. * x = range_limit[x & MASK];
  181. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  182. * samples. Under normal circumstances this is more than enough range and
  183. * a correct output will be generated; with bogus input data the mask will
  184. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  185. * For the post-IDCT step, we want to convert the data from signed to unsigned
  186. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  187. * So the post-IDCT limiting table ends up looking like this:
  188. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  189. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  190. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  191. * 0,1,...,CENTERJSAMPLE-1
  192. * Negative inputs select values from the upper half of the table after
  193. * masking.
  194. *
  195. * We can save some space by overlapping the start of the post-IDCT table
  196. * with the simpler range limiting table. The post-IDCT table begins at
  197. * sample_range_limit + CENTERJSAMPLE.
  198. *
  199. * Note that the table is allocated in near data space on PCs; it's small
  200. * enough and used often enough to justify this.
  201. */
  202. LOCAL(void)
  203. prepare_range_limit_table (j_decompress_ptr cinfo)
  204. /* Allocate and fill in the sample_range_limit table */
  205. {
  206. JSAMPLE * table;
  207. int i;
  208. table = (JSAMPLE *)
  209. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  210. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  211. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  212. cinfo->sample_range_limit = table;
  213. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  214. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  215. /* Main part of "simple" table: limit[x] = x */
  216. for (i = 0; i <= MAXJSAMPLE; i++)
  217. table[i] = (JSAMPLE) i;
  218. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  219. /* End of simple table, rest of first half of post-IDCT table */
  220. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  221. table[i] = MAXJSAMPLE;
  222. /* Second half of post-IDCT table */
  223. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  224. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  225. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  226. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  227. }
  228. /*
  229. * Master selection of decompression modules.
  230. * This is done once at jpeg_start_decompress time. We determine
  231. * which modules will be used and give them appropriate initialization calls.
  232. * We also initialize the decompressor input side to begin consuming data.
  233. *
  234. * Since jpeg_read_header has finished, we know what is in the SOF
  235. * and (first) SOS markers. We also have all the application parameter
  236. * settings.
  237. */
  238. LOCAL(void)
  239. master_selection (j_decompress_ptr cinfo)
  240. {
  241. my_master_ptr master = (my_master_ptr) cinfo->master;
  242. boolean use_c_buffer;
  243. long samplesperrow;
  244. JDIMENSION jd_samplesperrow;
  245. /* Initialize dimensions and other stuff */
  246. jpeg_calc_output_dimensions(cinfo);
  247. prepare_range_limit_table(cinfo);
  248. /* Width of an output scanline must be representable as JDIMENSION. */
  249. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  250. jd_samplesperrow = (JDIMENSION) samplesperrow;
  251. if ((long) jd_samplesperrow != samplesperrow)
  252. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  253. /* Initialize my private state */
  254. master->pass_number = 0;
  255. master->using_merged_upsample = use_merged_upsample(cinfo);
  256. /* Color quantizer selection */
  257. master->quantizer_1pass = NULL;
  258. master->quantizer_2pass = NULL;
  259. /* No mode changes if not using buffered-image mode. */
  260. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  261. cinfo->enable_1pass_quant = FALSE;
  262. cinfo->enable_external_quant = FALSE;
  263. cinfo->enable_2pass_quant = FALSE;
  264. }
  265. if (cinfo->quantize_colors) {
  266. if (cinfo->raw_data_out)
  267. ERREXIT(cinfo, JERR_NOTIMPL);
  268. /* 2-pass quantizer only works in 3-component color space. */
  269. if (cinfo->out_color_components != 3) {
  270. cinfo->enable_1pass_quant = TRUE;
  271. cinfo->enable_external_quant = FALSE;
  272. cinfo->enable_2pass_quant = FALSE;
  273. cinfo->colormap = NULL;
  274. } else if (cinfo->colormap != NULL) {
  275. cinfo->enable_external_quant = TRUE;
  276. } else if (cinfo->two_pass_quantize) {
  277. cinfo->enable_2pass_quant = TRUE;
  278. } else {
  279. cinfo->enable_1pass_quant = TRUE;
  280. }
  281. if (cinfo->enable_1pass_quant) {
  282. #ifdef QUANT_1PASS_SUPPORTED
  283. jinit_1pass_quantizer(cinfo);
  284. master->quantizer_1pass = cinfo->cquantize;
  285. #else
  286. ERREXIT(cinfo, JERR_NOT_COMPILED);
  287. #endif
  288. }
  289. /* We use the 2-pass code to map to external colormaps. */
  290. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  291. #ifdef QUANT_2PASS_SUPPORTED
  292. jinit_2pass_quantizer(cinfo);
  293. master->quantizer_2pass = cinfo->cquantize;
  294. #else
  295. ERREXIT(cinfo, JERR_NOT_COMPILED);
  296. #endif
  297. }
  298. /* If both quantizers are initialized, the 2-pass one is left active;
  299. * this is necessary for starting with quantization to an external map.
  300. */
  301. }
  302. /* Post-processing: in particular, color conversion first */
  303. if (! cinfo->raw_data_out) {
  304. if (master->using_merged_upsample) {
  305. #ifdef UPSAMPLE_MERGING_SUPPORTED
  306. jinit_merged_upsampler(cinfo); /* does color conversion too */
  307. #else
  308. ERREXIT(cinfo, JERR_NOT_COMPILED);
  309. #endif
  310. } else {
  311. jinit_color_deconverter(cinfo);
  312. jinit_upsampler(cinfo);
  313. }
  314. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  315. }
  316. /* Inverse DCT */
  317. jinit_inverse_dct(cinfo);
  318. /* Entropy decoding: either Huffman or arithmetic coding. */
  319. if (cinfo->arith_code)
  320. jinit_arith_decoder(cinfo);
  321. else {
  322. jinit_huff_decoder(cinfo);
  323. }
  324. /* Initialize principal buffer controllers. */
  325. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  326. jinit_d_coef_controller(cinfo, use_c_buffer);
  327. if (! cinfo->raw_data_out)
  328. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  329. /* We can now tell the memory manager to allocate virtual arrays. */
  330. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  331. /* Initialize input side of decompressor to consume first scan. */
  332. (*cinfo->inputctl->start_input_pass) (cinfo);
  333. #ifdef D_MULTISCAN_FILES_SUPPORTED
  334. /* If jpeg_start_decompress will read the whole file, initialize
  335. * progress monitoring appropriately. The input step is counted
  336. * as one pass.
  337. */
  338. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  339. cinfo->inputctl->has_multiple_scans) {
  340. int nscans;
  341. /* Estimate number of scans to set pass_limit. */
  342. if (cinfo->progressive_mode) {
  343. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  344. nscans = 2 + 3 * cinfo->num_components;
  345. } else {
  346. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  347. nscans = cinfo->num_components;
  348. }
  349. cinfo->progress->pass_counter = 0L;
  350. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  351. cinfo->progress->completed_passes = 0;
  352. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  353. /* Count the input pass as done */
  354. master->pass_number++;
  355. }
  356. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  357. }
  358. /*
  359. * Per-pass setup.
  360. * This is called at the beginning of each output pass. We determine which
  361. * modules will be active during this pass and give them appropriate
  362. * start_pass calls. We also set is_dummy_pass to indicate whether this
  363. * is a "real" output pass or a dummy pass for color quantization.
  364. * (In the latter case, jdapistd.c will crank the pass to completion.)
  365. */
  366. METHODDEF(void)
  367. prepare_for_output_pass (j_decompress_ptr cinfo)
  368. {
  369. my_master_ptr master = (my_master_ptr) cinfo->master;
  370. if (master->pub.is_dummy_pass) {
  371. #ifdef QUANT_2PASS_SUPPORTED
  372. /* Final pass of 2-pass quantization */
  373. master->pub.is_dummy_pass = FALSE;
  374. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  375. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  376. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  377. #else
  378. ERREXIT(cinfo, JERR_NOT_COMPILED);
  379. #endif /* QUANT_2PASS_SUPPORTED */
  380. } else {
  381. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  382. /* Select new quantization method */
  383. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  384. cinfo->cquantize = master->quantizer_2pass;
  385. master->pub.is_dummy_pass = TRUE;
  386. } else if (cinfo->enable_1pass_quant) {
  387. cinfo->cquantize = master->quantizer_1pass;
  388. } else {
  389. ERREXIT(cinfo, JERR_MODE_CHANGE);
  390. }
  391. }
  392. (*cinfo->idct->start_pass) (cinfo);
  393. (*cinfo->coef->start_output_pass) (cinfo);
  394. if (! cinfo->raw_data_out) {
  395. if (! master->using_merged_upsample)
  396. (*cinfo->cconvert->start_pass) (cinfo);
  397. (*cinfo->upsample->start_pass) (cinfo);
  398. if (cinfo->quantize_colors)
  399. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  400. (*cinfo->post->start_pass) (cinfo,
  401. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  402. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  403. }
  404. }
  405. /* Set up progress monitor's pass info if present */
  406. if (cinfo->progress != NULL) {
  407. cinfo->progress->completed_passes = master->pass_number;
  408. cinfo->progress->total_passes = master->pass_number +
  409. (master->pub.is_dummy_pass ? 2 : 1);
  410. /* In buffered-image mode, we assume one more output pass if EOI not
  411. * yet reached, but no more passes if EOI has been reached.
  412. */
  413. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  414. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  415. }
  416. }
  417. }
  418. /*
  419. * Finish up at end of an output pass.
  420. */
  421. METHODDEF(void)
  422. finish_output_pass (j_decompress_ptr cinfo)
  423. {
  424. my_master_ptr master = (my_master_ptr) cinfo->master;
  425. if (cinfo->quantize_colors)
  426. (*cinfo->cquantize->finish_pass) (cinfo);
  427. master->pass_number++;
  428. }
  429. #ifdef D_MULTISCAN_FILES_SUPPORTED
  430. /*
  431. * Switch to a new external colormap between output passes.
  432. */
  433. GLOBAL(void)
  434. jpeg_new_colormap (j_decompress_ptr cinfo)
  435. {
  436. my_master_ptr master = (my_master_ptr) cinfo->master;
  437. /* Prevent application from calling me at wrong times */
  438. if (cinfo->global_state != DSTATE_BUFIMAGE)
  439. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  440. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  441. cinfo->colormap != NULL) {
  442. /* Select 2-pass quantizer for external colormap use */
  443. cinfo->cquantize = master->quantizer_2pass;
  444. /* Notify quantizer of colormap change */
  445. (*cinfo->cquantize->new_color_map) (cinfo);
  446. master->pub.is_dummy_pass = FALSE; /* just in case */
  447. } else
  448. ERREXIT(cinfo, JERR_MODE_CHANGE);
  449. }
  450. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  451. /*
  452. * Initialize master decompression control and select active modules.
  453. * This is performed at the start of jpeg_start_decompress.
  454. */
  455. GLOBAL(void)
  456. jinit_master_decompress (j_decompress_ptr cinfo)
  457. {
  458. my_master_ptr master;
  459. master = (my_master_ptr)
  460. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  461. SIZEOF(my_decomp_master));
  462. cinfo->master = (struct jpeg_decomp_master *) master;
  463. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  464. master->pub.finish_output_pass = finish_output_pass;
  465. master->pub.is_dummy_pass = FALSE;
  466. master_selection(cinfo);
  467. }