jctrans.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * jctrans.c
  3. *
  4. * This file was part of the Independent JPEG Group's software:
  5. * Copyright (C) 1995-1998, Thomas G. Lane.
  6. * Modified 2000-2009 by Guido Vollbeding.
  7. * It was modified by The libjpeg-turbo Project to include only code relevant
  8. * to libjpeg-turbo.
  9. * mozjpeg Modifications:
  10. * Copyright (C) 2014, Mozilla Corporation.
  11. * For conditions of distribution and use, see the accompanying README file.
  12. *
  13. * This file contains library routines for transcoding compression,
  14. * that is, writing raw DCT coefficient arrays to an output JPEG file.
  15. * The routines in jcapimin.c will also be needed by a transcoder.
  16. */
  17. #define JPEG_INTERNALS
  18. #include "jinclude.h"
  19. #include "jpeglib.h"
  20. /* Forward declarations */
  21. LOCAL(void) transencode_master_selection(j_compress_ptr cinfo,
  22. jvirt_barray_ptr *coef_arrays);
  23. LOCAL(void) transencode_coef_controller(j_compress_ptr cinfo,
  24. jvirt_barray_ptr *coef_arrays);
  25. /*
  26. * Compression initialization for writing raw-coefficient data.
  27. * Before calling this, all parameters and a data destination must be set up.
  28. * Call jpeg_finish_compress() to actually write the data.
  29. *
  30. * The number of passed virtual arrays must match cinfo->num_components.
  31. * Note that the virtual arrays need not be filled or even realized at
  32. * the time write_coefficients is called; indeed, if the virtual arrays
  33. * were requested from this compression object's memory manager, they
  34. * typically will be realized during this routine and filled afterwards.
  35. */
  36. GLOBAL(void)
  37. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr *coef_arrays)
  38. {
  39. /* setting up scan optimisation pattern failed, disable scan optimisation */
  40. if (cinfo->master->num_scans_luma == 0)
  41. cinfo->master->optimize_scans = FALSE;
  42. if (cinfo->global_state != CSTATE_START)
  43. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  44. /* Mark all tables to be written */
  45. jpeg_suppress_tables(cinfo, FALSE);
  46. /* (Re)initialize error mgr and destination modules */
  47. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  48. (*cinfo->dest->init_destination) (cinfo);
  49. /* Perform master selection of active modules */
  50. transencode_master_selection(cinfo, coef_arrays);
  51. /* Wait for jpeg_finish_compress() call */
  52. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  53. cinfo->global_state = CSTATE_WRCOEFS;
  54. }
  55. /*
  56. * Initialize the compression object with default parameters,
  57. * then copy from the source object all parameters needed for lossless
  58. * transcoding. Parameters that can be varied without loss (such as
  59. * scan script and Huffman optimization) are left in their default states.
  60. */
  61. GLOBAL(void)
  62. jpeg_copy_critical_parameters (const j_decompress_ptr srcinfo, j_compress_ptr dstinfo)
  63. {
  64. JQUANT_TBL **qtblptr;
  65. jpeg_component_info *incomp, *outcomp;
  66. JQUANT_TBL *c_quant, *slot_quant;
  67. int tblno, ci, coefi;
  68. /* Safety check to ensure start_compress not called yet. */
  69. if (dstinfo->global_state != CSTATE_START)
  70. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  71. /* Copy fundamental image dimensions */
  72. dstinfo->image_width = srcinfo->image_width;
  73. dstinfo->image_height = srcinfo->image_height;
  74. dstinfo->input_components = srcinfo->num_components;
  75. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  76. #if JPEG_LIB_VERSION >= 70
  77. dstinfo->jpeg_width = srcinfo->output_width;
  78. dstinfo->jpeg_height = srcinfo->output_height;
  79. dstinfo->min_DCT_h_scaled_size = srcinfo->min_DCT_h_scaled_size;
  80. dstinfo->min_DCT_v_scaled_size = srcinfo->min_DCT_v_scaled_size;
  81. #endif
  82. /* Initialize all parameters to default values */
  83. jpeg_set_defaults(dstinfo);
  84. dstinfo->master->trellis_quant = FALSE;
  85. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  86. * Fix it to get the right header markers for the image colorspace.
  87. */
  88. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  89. dstinfo->data_precision = srcinfo->data_precision;
  90. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  91. /* Copy the source's quantization tables. */
  92. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  93. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  94. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  95. if (*qtblptr == NULL)
  96. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  97. MEMCOPY((*qtblptr)->quantval, srcinfo->quant_tbl_ptrs[tblno]->quantval,
  98. sizeof((*qtblptr)->quantval));
  99. (*qtblptr)->sent_table = FALSE;
  100. }
  101. }
  102. /* Copy the source's per-component info.
  103. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  104. */
  105. dstinfo->num_components = srcinfo->num_components;
  106. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  107. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  108. MAX_COMPONENTS);
  109. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  110. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  111. outcomp->component_id = incomp->component_id;
  112. outcomp->h_samp_factor = incomp->h_samp_factor;
  113. outcomp->v_samp_factor = incomp->v_samp_factor;
  114. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  115. /* Make sure saved quantization table for component matches the qtable
  116. * slot. If not, the input file re-used this qtable slot.
  117. * IJG encoder currently cannot duplicate this.
  118. */
  119. tblno = outcomp->quant_tbl_no;
  120. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  121. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  122. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  123. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  124. c_quant = incomp->quant_table;
  125. if (c_quant != NULL) {
  126. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  127. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  128. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  129. }
  130. }
  131. /* Note: we do not copy the source's Huffman table assignments;
  132. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  133. */
  134. }
  135. /* Also copy JFIF version and resolution information, if available.
  136. * Strictly speaking this isn't "critical" info, but it's nearly
  137. * always appropriate to copy it if available. In particular,
  138. * if the application chooses to copy JFIF 1.02 extension markers from
  139. * the source file, we need to copy the version to make sure we don't
  140. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  141. * We will *not*, however, copy version info from mislabeled "2.01" files.
  142. */
  143. if (srcinfo->saw_JFIF_marker) {
  144. if (srcinfo->JFIF_major_version == 1) {
  145. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  146. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  147. }
  148. dstinfo->density_unit = srcinfo->density_unit;
  149. dstinfo->X_density = srcinfo->X_density;
  150. dstinfo->Y_density = srcinfo->Y_density;
  151. }
  152. }
  153. /*
  154. * Master selection of compression modules for transcoding.
  155. * This substitutes for jcinit.c's initialization of the full compressor.
  156. */
  157. LOCAL(void)
  158. transencode_master_selection (j_compress_ptr cinfo,
  159. jvirt_barray_ptr *coef_arrays)
  160. {
  161. /* Although we don't actually use input_components for transcoding,
  162. * jcmaster.c's initial_setup will complain if input_components is 0.
  163. */
  164. cinfo->input_components = 1;
  165. /* Initialize master control (includes parameter checking/processing) */
  166. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167. /* Entropy encoding: either Huffman or arithmetic coding. */
  168. if (cinfo->arith_code) {
  169. #ifdef C_ARITH_CODING_SUPPORTED
  170. jinit_arith_encoder(cinfo);
  171. #else
  172. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173. #endif
  174. } else {
  175. if (cinfo->progressive_mode) {
  176. #ifdef C_PROGRESSIVE_SUPPORTED
  177. jinit_phuff_encoder(cinfo);
  178. #else
  179. ERREXIT(cinfo, JERR_NOT_COMPILED);
  180. #endif
  181. } else
  182. jinit_huff_encoder(cinfo);
  183. }
  184. /* We need a special coefficient buffer controller. */
  185. transencode_coef_controller(cinfo, coef_arrays);
  186. jinit_marker_writer(cinfo);
  187. /* We can now tell the memory manager to allocate virtual arrays. */
  188. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  189. /* Write the datastream header (SOI, JFIF) immediately.
  190. * Frame and scan headers are postponed till later.
  191. * This lets application insert special markers after the SOI.
  192. */
  193. (*cinfo->marker->write_file_header) (cinfo);
  194. }
  195. /*
  196. * The rest of this file is a special implementation of the coefficient
  197. * buffer controller. This is similar to jccoefct.c, but it handles only
  198. * output from presupplied virtual arrays. Furthermore, we generate any
  199. * dummy padding blocks on-the-fly rather than expecting them to be present
  200. * in the arrays.
  201. */
  202. /* Private buffer controller object */
  203. typedef struct {
  204. struct jpeg_c_coef_controller pub; /* public fields */
  205. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  206. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  207. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  208. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  209. /* Virtual block array for each component. */
  210. jvirt_barray_ptr *whole_image;
  211. /* Workspace for constructing dummy blocks at right/bottom edges. */
  212. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  213. } my_coef_controller;
  214. typedef my_coef_controller *my_coef_ptr;
  215. LOCAL(void)
  216. start_iMCU_row (j_compress_ptr cinfo)
  217. /* Reset within-iMCU-row counters for a new row */
  218. {
  219. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  220. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  221. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  222. * But at the bottom of the image, process only what's left.
  223. */
  224. if (cinfo->comps_in_scan > 1) {
  225. coef->MCU_rows_per_iMCU_row = 1;
  226. } else {
  227. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  228. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  229. else
  230. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  231. }
  232. coef->mcu_ctr = 0;
  233. coef->MCU_vert_offset = 0;
  234. }
  235. /*
  236. * Initialize for a processing pass.
  237. */
  238. METHODDEF(void)
  239. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  240. {
  241. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  242. if (pass_mode != JBUF_CRANK_DEST)
  243. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  244. coef->iMCU_row_num = 0;
  245. start_iMCU_row(cinfo);
  246. }
  247. /*
  248. * Process some data.
  249. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  250. * per call, ie, v_samp_factor block rows for each component in the scan.
  251. * The data is obtained from the virtual arrays and fed to the entropy coder.
  252. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  253. *
  254. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  255. */
  256. METHODDEF(boolean)
  257. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  258. {
  259. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  260. JDIMENSION MCU_col_num; /* index of current MCU within row */
  261. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  262. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  263. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  264. JDIMENSION start_col;
  265. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  266. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  267. JBLOCKROW buffer_ptr;
  268. jpeg_component_info *compptr;
  269. /* Align the virtual buffers for the components used in this scan. */
  270. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  271. compptr = cinfo->cur_comp_info[ci];
  272. buffer[ci] = (*cinfo->mem->access_virt_barray)
  273. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  274. coef->iMCU_row_num * compptr->v_samp_factor,
  275. (JDIMENSION) compptr->v_samp_factor, FALSE);
  276. }
  277. /* Loop to process one whole iMCU row */
  278. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  279. yoffset++) {
  280. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  281. MCU_col_num++) {
  282. /* Construct list of pointers to DCT blocks belonging to this MCU */
  283. blkn = 0; /* index of current DCT block within MCU */
  284. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  285. compptr = cinfo->cur_comp_info[ci];
  286. start_col = MCU_col_num * compptr->MCU_width;
  287. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width :
  288. compptr->last_col_width;
  289. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  290. if (coef->iMCU_row_num < last_iMCU_row ||
  291. yindex+yoffset < compptr->last_row_height) {
  292. /* Fill in pointers to real blocks in this row */
  293. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  294. for (xindex = 0; xindex < blockcnt; xindex++)
  295. MCU_buffer[blkn++] = buffer_ptr++;
  296. } else {
  297. /* At bottom of image, need a whole row of dummy blocks */
  298. xindex = 0;
  299. }
  300. /* Fill in any dummy blocks needed in this row.
  301. * Dummy blocks are filled in the same way as in jccoefct.c:
  302. * all zeroes in the AC entries, DC entries equal to previous
  303. * block's DC value. The init routine has already zeroed the
  304. * AC entries, so we need only set the DC entries correctly.
  305. */
  306. for (; xindex < compptr->MCU_width; xindex++) {
  307. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  308. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  309. blkn++;
  310. }
  311. }
  312. }
  313. /* Try to write the MCU. */
  314. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  315. /* Suspension forced; update state counters and exit */
  316. coef->MCU_vert_offset = yoffset;
  317. coef->mcu_ctr = MCU_col_num;
  318. return FALSE;
  319. }
  320. }
  321. /* Completed an MCU row, but perhaps not an iMCU row */
  322. coef->mcu_ctr = 0;
  323. }
  324. /* Completed the iMCU row, advance counters for next one */
  325. coef->iMCU_row_num++;
  326. start_iMCU_row(cinfo);
  327. return TRUE;
  328. }
  329. /*
  330. * Initialize coefficient buffer controller.
  331. *
  332. * Each passed coefficient array must be the right size for that
  333. * coefficient: width_in_blocks wide and height_in_blocks high,
  334. * with unitheight at least v_samp_factor.
  335. */
  336. LOCAL(void)
  337. transencode_coef_controller (j_compress_ptr cinfo,
  338. jvirt_barray_ptr *coef_arrays)
  339. {
  340. my_coef_ptr coef;
  341. JBLOCKROW buffer;
  342. int i;
  343. coef = (my_coef_ptr)
  344. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  345. sizeof(my_coef_controller));
  346. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  347. coef->pub.start_pass = start_pass_coef;
  348. coef->pub.compress_data = compress_output;
  349. /* Save pointer to virtual arrays */
  350. coef->whole_image = coef_arrays;
  351. /* Allocate and pre-zero space for dummy DCT blocks. */
  352. buffer = (JBLOCKROW)
  353. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  354. C_MAX_BLOCKS_IN_MCU * sizeof(JBLOCK));
  355. jzero_far((void *) buffer, C_MAX_BLOCKS_IN_MCU * sizeof(JBLOCK));
  356. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  357. coef->dummy_buffer[i] = buffer + i;
  358. }
  359. }