/*1* jctrans.c2*3* Copyright (C) 1995-1998, Thomas G. Lane.4* Modified 2000-2013 by Guido Vollbeding.5* This file is part of the Independent JPEG Group's software.6* For conditions of distribution and use, see the accompanying README file.7*8* This file contains library routines for transcoding compression,9* that is, writing raw DCT coefficient arrays to an output JPEG file.10* The routines in jcapimin.c will also be needed by a transcoder.11*/1213#define JPEG_INTERNALS14#include "jinclude.h"15#include "jpeglib.h"161718/* Forward declarations */19LOCAL(void) transencode_master_selection20JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));21LOCAL(void) transencode_coef_controller22JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));232425/*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 at32* the time write_coefficients is called; indeed, if the virtual arrays33* were requested from this compression object's memory manager, they34* typically will be realized during this routine and filled afterwards.35*/3637GLOBAL(void)38jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)39{40if (cinfo->global_state != CSTATE_START)41ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);42/* Mark all tables to be written */43jpeg_suppress_tables(cinfo, FALSE);44/* (Re)initialize error mgr and destination modules */45(*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);46(*cinfo->dest->init_destination) (cinfo);47/* Perform master selection of active modules */48transencode_master_selection(cinfo, coef_arrays);49/* Wait for jpeg_finish_compress() call */50cinfo->next_scanline = 0; /* so jpeg_write_marker works */51cinfo->global_state = CSTATE_WRCOEFS;52}535455/*56* Initialize the compression object with default parameters,57* then copy from the source object all parameters needed for lossless58* transcoding. Parameters that can be varied without loss (such as59* scan script and Huffman optimization) are left in their default states.60*/6162GLOBAL(void)63jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,64j_compress_ptr dstinfo)65{66JQUANT_TBL ** qtblptr;67jpeg_component_info *incomp, *outcomp;68JQUANT_TBL *c_quant, *slot_quant;69int tblno, ci, coefi;7071/* Safety check to ensure start_compress not called yet. */72if (dstinfo->global_state != CSTATE_START)73ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);74/* Copy fundamental image dimensions */75dstinfo->image_width = srcinfo->image_width;76dstinfo->image_height = srcinfo->image_height;77dstinfo->input_components = srcinfo->num_components;78dstinfo->in_color_space = srcinfo->jpeg_color_space;79dstinfo->jpeg_width = srcinfo->output_width;80dstinfo->jpeg_height = srcinfo->output_height;81dstinfo->min_DCT_h_scaled_size = srcinfo->min_DCT_h_scaled_size;82dstinfo->min_DCT_v_scaled_size = srcinfo->min_DCT_v_scaled_size;83/* Initialize all parameters to default values */84jpeg_set_defaults(dstinfo);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* Note: Entropy table assignment in jpeg_set_colorspace depends88* on color_transform.89*/90dstinfo->color_transform = srcinfo->color_transform;91jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);92dstinfo->data_precision = srcinfo->data_precision;93dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;94/* Copy the source's quantization tables. */95for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {96if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {97qtblptr = & dstinfo->quant_tbl_ptrs[tblno];98if (*qtblptr == NULL)99*qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);100MEMCOPY((*qtblptr)->quantval,101srcinfo->quant_tbl_ptrs[tblno]->quantval,102SIZEOF((*qtblptr)->quantval));103(*qtblptr)->sent_table = FALSE;104}105}106/* Copy the source's per-component info.107* Note we assume jpeg_set_defaults has allocated the dest comp_info array.108*/109dstinfo->num_components = srcinfo->num_components;110if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)111ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,112MAX_COMPONENTS);113for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;114ci < dstinfo->num_components; ci++, incomp++, outcomp++) {115outcomp->component_id = incomp->component_id;116outcomp->h_samp_factor = incomp->h_samp_factor;117outcomp->v_samp_factor = incomp->v_samp_factor;118outcomp->quant_tbl_no = incomp->quant_tbl_no;119/* Make sure saved quantization table for component matches the qtable120* slot. If not, the input file re-used this qtable slot.121* IJG encoder currently cannot duplicate this.122*/123tblno = outcomp->quant_tbl_no;124if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||125srcinfo->quant_tbl_ptrs[tblno] == NULL)126ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);127slot_quant = srcinfo->quant_tbl_ptrs[tblno];128c_quant = incomp->quant_table;129if (c_quant != NULL) {130for (coefi = 0; coefi < DCTSIZE2; coefi++) {131if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])132ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);133}134}135/* Note: we do not copy the source's entropy table assignments;136* instead we rely on jpeg_set_colorspace to have made a suitable choice.137*/138}139/* Also copy JFIF version and resolution information, if available.140* Strictly speaking this isn't "critical" info, but it's nearly141* always appropriate to copy it if available. In particular,142* if the application chooses to copy JFIF 1.02 extension markers from143* the source file, we need to copy the version to make sure we don't144* emit a file that has 1.02 extensions but a claimed version of 1.01.145*/146if (srcinfo->saw_JFIF_marker) {147if (srcinfo->JFIF_major_version == 1 ||148srcinfo->JFIF_major_version == 2) {149dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;150dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;151}152dstinfo->density_unit = srcinfo->density_unit;153dstinfo->X_density = srcinfo->X_density;154dstinfo->Y_density = srcinfo->Y_density;155}156}157158159/*160* Master selection of compression modules for transcoding.161* This substitutes for jcinit.c's initialization of the full compressor.162*/163164LOCAL(void)165transencode_master_selection (j_compress_ptr cinfo,166jvirt_barray_ptr * coef_arrays)167{168/* Initialize master control (includes parameter checking/processing) */169jinit_c_master_control(cinfo, TRUE /* transcode only */);170171/* Entropy encoding: either Huffman or arithmetic coding. */172if (cinfo->arith_code)173jinit_arith_encoder(cinfo);174else {175jinit_huff_encoder(cinfo);176}177178/* We need a special coefficient buffer controller. */179transencode_coef_controller(cinfo, coef_arrays);180181jinit_marker_writer(cinfo);182183/* We can now tell the memory manager to allocate virtual arrays. */184(*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);185186/* Write the datastream header (SOI, JFIF) immediately.187* Frame and scan headers are postponed till later.188* This lets application insert special markers after the SOI.189*/190(*cinfo->marker->write_file_header) (cinfo);191}192193194/*195* The rest of this file is a special implementation of the coefficient196* buffer controller. This is similar to jccoefct.c, but it handles only197* output from presupplied virtual arrays. Furthermore, we generate any198* dummy padding blocks on-the-fly rather than expecting them to be present199* in the arrays.200*/201202/* Private buffer controller object */203204typedef struct {205struct jpeg_c_coef_controller pub; /* public fields */206207JDIMENSION iMCU_row_num; /* iMCU row # within image */208JDIMENSION mcu_ctr; /* counts MCUs processed in current row */209int MCU_vert_offset; /* counts MCU rows within iMCU row */210int MCU_rows_per_iMCU_row; /* number of such rows needed */211212/* Virtual block array for each component. */213jvirt_barray_ptr * whole_image;214215/* Workspace for constructing dummy blocks at right/bottom edges. */216JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];217} my_coef_controller;218219typedef my_coef_controller * my_coef_ptr;220221222LOCAL(void)223start_iMCU_row (j_compress_ptr cinfo)224/* Reset within-iMCU-row counters for a new row */225{226my_coef_ptr coef = (my_coef_ptr) cinfo->coef;227228/* In an interleaved scan, an MCU row is the same as an iMCU row.229* In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.230* But at the bottom of the image, process only what's left.231*/232if (cinfo->comps_in_scan > 1) {233coef->MCU_rows_per_iMCU_row = 1;234} else {235if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))236coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;237else238coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;239}240241coef->mcu_ctr = 0;242coef->MCU_vert_offset = 0;243}244245246/*247* Initialize for a processing pass.248*/249250METHODDEF(void)251start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)252{253my_coef_ptr coef = (my_coef_ptr) cinfo->coef;254255if (pass_mode != JBUF_CRANK_DEST)256ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);257258coef->iMCU_row_num = 0;259start_iMCU_row(cinfo);260}261262263/*264* Process some data.265* We process the equivalent of one fully interleaved MCU row ("iMCU" row)266* per call, ie, v_samp_factor block rows for each component in the scan.267* The data is obtained from the virtual arrays and fed to the entropy coder.268* Returns TRUE if the iMCU row is completed, FALSE if suspended.269*270* NB: input_buf is ignored; it is likely to be a NULL pointer.271*/272273METHODDEF(boolean)274compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)275{276my_coef_ptr coef = (my_coef_ptr) cinfo->coef;277JDIMENSION MCU_col_num; /* index of current MCU within row */278JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;279JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;280int blkn, ci, xindex, yindex, yoffset, blockcnt;281JDIMENSION start_col;282JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];283JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];284JBLOCKROW buffer_ptr;285jpeg_component_info *compptr;286287/* Align the virtual buffers for the components used in this scan. */288for (ci = 0; ci < cinfo->comps_in_scan; ci++) {289compptr = cinfo->cur_comp_info[ci];290buffer[ci] = (*cinfo->mem->access_virt_barray)291((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],292coef->iMCU_row_num * compptr->v_samp_factor,293(JDIMENSION) compptr->v_samp_factor, FALSE);294}295296/* Loop to process one whole iMCU row */297for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;298yoffset++) {299for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;300MCU_col_num++) {301/* Construct list of pointers to DCT blocks belonging to this MCU */302blkn = 0; /* index of current DCT block within MCU */303for (ci = 0; ci < cinfo->comps_in_scan; ci++) {304compptr = cinfo->cur_comp_info[ci];305start_col = MCU_col_num * compptr->MCU_width;306blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width307: compptr->last_col_width;308for (yindex = 0; yindex < compptr->MCU_height; yindex++) {309if (coef->iMCU_row_num < last_iMCU_row ||310yindex+yoffset < compptr->last_row_height) {311/* Fill in pointers to real blocks in this row */312buffer_ptr = buffer[ci][yindex+yoffset] + start_col;313for (xindex = 0; xindex < blockcnt; xindex++)314MCU_buffer[blkn++] = buffer_ptr++;315} else {316/* At bottom of image, need a whole row of dummy blocks */317xindex = 0;318}319/* Fill in any dummy blocks needed in this row.320* Dummy blocks are filled in the same way as in jccoefct.c:321* all zeroes in the AC entries, DC entries equal to previous322* block's DC value. The init routine has already zeroed the323* AC entries, so we need only set the DC entries correctly.324*/325for (; xindex < compptr->MCU_width; xindex++) {326MCU_buffer[blkn] = coef->dummy_buffer[blkn];327MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];328blkn++;329}330}331}332/* Try to write the MCU. */333if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {334/* Suspension forced; update state counters and exit */335coef->MCU_vert_offset = yoffset;336coef->mcu_ctr = MCU_col_num;337return FALSE;338}339}340/* Completed an MCU row, but perhaps not an iMCU row */341coef->mcu_ctr = 0;342}343/* Completed the iMCU row, advance counters for next one */344coef->iMCU_row_num++;345start_iMCU_row(cinfo);346return TRUE;347}348349350/*351* Initialize coefficient buffer controller.352*353* Each passed coefficient array must be the right size for that354* coefficient: width_in_blocks wide and height_in_blocks high,355* with unitheight at least v_samp_factor.356*/357358LOCAL(void)359transencode_coef_controller (j_compress_ptr cinfo,360jvirt_barray_ptr * coef_arrays)361{362my_coef_ptr coef;363JBLOCKROW buffer;364int i;365366coef = (my_coef_ptr)367(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,368SIZEOF(my_coef_controller));369cinfo->coef = &coef->pub;370coef->pub.start_pass = start_pass_coef;371coef->pub.compress_data = compress_output;372373/* Save pointer to virtual arrays */374coef->whole_image = coef_arrays;375376/* Allocate and pre-zero space for dummy DCT blocks. */377buffer = (JBLOCKROW)378(*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,379C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));380FMEMZERO((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));381for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {382coef->dummy_buffer[i] = buffer + i;383}384}385386387