Path: blob/master/thirdparty/libjpeg-turbo/src/jctrans.c
9904 views
/*1* jctrans.c2*3* This file was part of the Independent JPEG Group's software:4* Copyright (C) 1995-1998, Thomas G. Lane.5* Modified 2000-2009 by Guido Vollbeding.6* libjpeg-turbo Modifications:7* Copyright (C) 2020, 2022, D. R. Commander.8* For conditions of distribution and use, see the accompanying README.ijg9* file.10*11* This file contains library routines for transcoding compression,12* that is, writing raw DCT coefficient arrays to an output JPEG file.13* The routines in jcapimin.c will also be needed by a transcoder.14*/1516#define JPEG_INTERNALS17#include "jinclude.h"18#include "jpeglib.h"19#include "jpegapicomp.h"202122/* Forward declarations */23LOCAL(void) transencode_master_selection(j_compress_ptr cinfo,24jvirt_barray_ptr *coef_arrays);25LOCAL(void) transencode_coef_controller(j_compress_ptr cinfo,26jvirt_barray_ptr *coef_arrays);272829/*30* Compression initialization for writing raw-coefficient data.31* Before calling this, all parameters and a data destination must be set up.32* Call jpeg_finish_compress() to actually write the data.33*34* The number of passed virtual arrays must match cinfo->num_components.35* Note that the virtual arrays need not be filled or even realized at36* the time write_coefficients is called; indeed, if the virtual arrays37* were requested from this compression object's memory manager, they38* typically will be realized during this routine and filled afterwards.39*/4041GLOBAL(void)42jpeg_write_coefficients(j_compress_ptr cinfo, jvirt_barray_ptr *coef_arrays)43{44if (cinfo->master->lossless)45ERREXIT(cinfo, JERR_NOTIMPL);4647if (cinfo->global_state != CSTATE_START)48ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);49/* Mark all tables to be written */50jpeg_suppress_tables(cinfo, FALSE);51/* (Re)initialize error mgr and destination modules */52(*cinfo->err->reset_error_mgr) ((j_common_ptr)cinfo);53(*cinfo->dest->init_destination) (cinfo);54/* Perform master selection of active modules */55transencode_master_selection(cinfo, coef_arrays);56/* Wait for jpeg_finish_compress() call */57cinfo->next_scanline = 0; /* so jpeg_write_marker works */58cinfo->global_state = CSTATE_WRCOEFS;59}606162/*63* Initialize the compression object with default parameters,64* then copy from the source object all parameters needed for lossless65* transcoding. Parameters that can be varied without loss (such as66* scan script and Huffman optimization) are left in their default states.67*/6869GLOBAL(void)70jpeg_copy_critical_parameters(j_decompress_ptr srcinfo, j_compress_ptr dstinfo)71{72JQUANT_TBL **qtblptr;73jpeg_component_info *incomp, *outcomp;74JQUANT_TBL *c_quant, *slot_quant;75int tblno, ci, coefi;7677if (srcinfo->master->lossless)78ERREXIT(dstinfo, JERR_NOTIMPL);7980/* Safety check to ensure start_compress not called yet. */81if (dstinfo->global_state != CSTATE_START)82ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);83/* Copy fundamental image dimensions */84dstinfo->image_width = srcinfo->image_width;85dstinfo->image_height = srcinfo->image_height;86dstinfo->input_components = srcinfo->num_components;87dstinfo->in_color_space = srcinfo->jpeg_color_space;88#if JPEG_LIB_VERSION >= 7089dstinfo->jpeg_width = srcinfo->output_width;90dstinfo->jpeg_height = srcinfo->output_height;91dstinfo->min_DCT_h_scaled_size = srcinfo->min_DCT_h_scaled_size;92dstinfo->min_DCT_v_scaled_size = srcinfo->min_DCT_v_scaled_size;93#endif94/* Initialize all parameters to default values */95jpeg_set_defaults(dstinfo);96/* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.97* Fix it to get the right header markers for the image colorspace.98*/99jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);100dstinfo->data_precision = srcinfo->data_precision;101dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;102/* Copy the source's quantization tables. */103for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {104if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {105qtblptr = &dstinfo->quant_tbl_ptrs[tblno];106if (*qtblptr == NULL)107*qtblptr = jpeg_alloc_quant_table((j_common_ptr)dstinfo);108memcpy((*qtblptr)->quantval, srcinfo->quant_tbl_ptrs[tblno]->quantval,109sizeof((*qtblptr)->quantval));110(*qtblptr)->sent_table = FALSE;111}112}113/* Copy the source's per-component info.114* Note we assume jpeg_set_defaults has allocated the dest comp_info array.115*/116dstinfo->num_components = srcinfo->num_components;117if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)118ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,119MAX_COMPONENTS);120for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;121ci < dstinfo->num_components; ci++, incomp++, outcomp++) {122outcomp->component_id = incomp->component_id;123outcomp->h_samp_factor = incomp->h_samp_factor;124outcomp->v_samp_factor = incomp->v_samp_factor;125outcomp->quant_tbl_no = incomp->quant_tbl_no;126/* Make sure saved quantization table for component matches the qtable127* slot. If not, the input file re-used this qtable slot.128* IJG encoder currently cannot duplicate this.129*/130tblno = outcomp->quant_tbl_no;131if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||132srcinfo->quant_tbl_ptrs[tblno] == NULL)133ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);134slot_quant = srcinfo->quant_tbl_ptrs[tblno];135c_quant = incomp->quant_table;136if (c_quant != NULL) {137for (coefi = 0; coefi < DCTSIZE2; coefi++) {138if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])139ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);140}141}142/* Note: we do not copy the source's Huffman table assignments;143* instead we rely on jpeg_set_colorspace to have made a suitable choice.144*/145}146/* Also copy JFIF version and resolution information, if available.147* Strictly speaking this isn't "critical" info, but it's nearly148* always appropriate to copy it if available. In particular,149* if the application chooses to copy JFIF 1.02 extension markers from150* the source file, we need to copy the version to make sure we don't151* emit a file that has 1.02 extensions but a claimed version of 1.01.152* We will *not*, however, copy version info from mislabeled "2.01" files.153*/154if (srcinfo->saw_JFIF_marker) {155if (srcinfo->JFIF_major_version == 1) {156dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;157dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;158}159dstinfo->density_unit = srcinfo->density_unit;160dstinfo->X_density = srcinfo->X_density;161dstinfo->Y_density = srcinfo->Y_density;162}163}164165166/*167* Master selection of compression modules for transcoding.168* This substitutes for jcinit.c's initialization of the full compressor.169*/170171LOCAL(void)172transencode_master_selection(j_compress_ptr cinfo,173jvirt_barray_ptr *coef_arrays)174{175/* Although we don't actually use input_components for transcoding,176* jcmaster.c's initial_setup will complain if input_components is 0.177*/178cinfo->input_components = 1;179/* Initialize master control (includes parameter checking/processing) */180jinit_c_master_control(cinfo, TRUE /* transcode only */);181182/* Entropy encoding: either Huffman or arithmetic coding. */183if (cinfo->arith_code) {184#ifdef C_ARITH_CODING_SUPPORTED185jinit_arith_encoder(cinfo);186#else187ERREXIT(cinfo, JERR_ARITH_NOTIMPL);188#endif189} else {190if (cinfo->progressive_mode) {191#ifdef C_PROGRESSIVE_SUPPORTED192jinit_phuff_encoder(cinfo);193#else194ERREXIT(cinfo, JERR_NOT_COMPILED);195#endif196} else197jinit_huff_encoder(cinfo);198}199200/* We need a special coefficient buffer controller. */201transencode_coef_controller(cinfo, coef_arrays);202203jinit_marker_writer(cinfo);204205/* We can now tell the memory manager to allocate virtual arrays. */206(*cinfo->mem->realize_virt_arrays) ((j_common_ptr)cinfo);207208/* Write the datastream header (SOI, JFIF) immediately.209* Frame and scan headers are postponed till later.210* This lets application insert special markers after the SOI.211*/212(*cinfo->marker->write_file_header) (cinfo);213}214215216/*217* The rest of this file is a special implementation of the coefficient218* buffer controller. This is similar to jccoefct.c, but it handles only219* output from presupplied virtual arrays. Furthermore, we generate any220* dummy padding blocks on-the-fly rather than expecting them to be present221* in the arrays.222*/223224/* Private buffer controller object */225226typedef struct {227struct jpeg_c_coef_controller pub; /* public fields */228229JDIMENSION iMCU_row_num; /* iMCU row # within image */230JDIMENSION mcu_ctr; /* counts MCUs processed in current row */231int MCU_vert_offset; /* counts MCU rows within iMCU row */232int MCU_rows_per_iMCU_row; /* number of such rows needed */233234/* Virtual block array for each component. */235jvirt_barray_ptr *whole_image;236237/* Workspace for constructing dummy blocks at right/bottom edges. */238JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];239} my_coef_controller;240241typedef my_coef_controller *my_coef_ptr;242243244LOCAL(void)245start_iMCU_row(j_compress_ptr cinfo)246/* Reset within-iMCU-row counters for a new row */247{248my_coef_ptr coef = (my_coef_ptr)cinfo->coef;249250/* In an interleaved scan, an MCU row is the same as an iMCU row.251* In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.252* But at the bottom of the image, process only what's left.253*/254if (cinfo->comps_in_scan > 1) {255coef->MCU_rows_per_iMCU_row = 1;256} else {257if (coef->iMCU_row_num < (cinfo->total_iMCU_rows - 1))258coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;259else260coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;261}262263coef->mcu_ctr = 0;264coef->MCU_vert_offset = 0;265}266267268/*269* Initialize for a processing pass.270*/271272METHODDEF(void)273start_pass_coef(j_compress_ptr cinfo, J_BUF_MODE pass_mode)274{275my_coef_ptr coef = (my_coef_ptr)cinfo->coef;276277if (pass_mode != JBUF_CRANK_DEST)278ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);279280coef->iMCU_row_num = 0;281start_iMCU_row(cinfo);282}283284285/*286* Process some data.287* We process the equivalent of one fully interleaved MCU row ("iMCU" row)288* per call, ie, v_samp_factor block rows for each component in the scan.289* The data is obtained from the virtual arrays and fed to the entropy coder.290* Returns TRUE if the iMCU row is completed, FALSE if suspended.291*292* NB: input_buf is ignored; it is likely to be a NULL pointer.293*/294295METHODDEF(boolean)296compress_output(j_compress_ptr cinfo, JSAMPIMAGE input_buf)297{298my_coef_ptr coef = (my_coef_ptr)cinfo->coef;299JDIMENSION MCU_col_num; /* index of current MCU within row */300JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;301JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;302int blkn, ci, xindex, yindex, yoffset, blockcnt;303JDIMENSION start_col;304JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];305JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];306JBLOCKROW buffer_ptr;307jpeg_component_info *compptr;308309/* Align the virtual buffers for the components used in this scan. */310for (ci = 0; ci < cinfo->comps_in_scan; ci++) {311compptr = cinfo->cur_comp_info[ci];312buffer[ci] = (*cinfo->mem->access_virt_barray)313((j_common_ptr)cinfo, coef->whole_image[compptr->component_index],314coef->iMCU_row_num * compptr->v_samp_factor,315(JDIMENSION)compptr->v_samp_factor, FALSE);316}317318/* Loop to process one whole iMCU row */319for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;320yoffset++) {321for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;322MCU_col_num++) {323/* Construct list of pointers to DCT blocks belonging to this MCU */324blkn = 0; /* index of current DCT block within MCU */325for (ci = 0; ci < cinfo->comps_in_scan; ci++) {326compptr = cinfo->cur_comp_info[ci];327start_col = MCU_col_num * compptr->MCU_width;328blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width :329compptr->last_col_width;330for (yindex = 0; yindex < compptr->MCU_height; yindex++) {331if (coef->iMCU_row_num < last_iMCU_row ||332yindex + yoffset < compptr->last_row_height) {333/* Fill in pointers to real blocks in this row */334buffer_ptr = buffer[ci][yindex + yoffset] + start_col;335for (xindex = 0; xindex < blockcnt; xindex++)336MCU_buffer[blkn++] = buffer_ptr++;337} else {338/* At bottom of image, need a whole row of dummy blocks */339xindex = 0;340}341/* Fill in any dummy blocks needed in this row.342* Dummy blocks are filled in the same way as in jccoefct.c:343* all zeroes in the AC entries, DC entries equal to previous344* block's DC value. The init routine has already zeroed the345* AC entries, so we need only set the DC entries correctly.346*/347for (; xindex < compptr->MCU_width; xindex++) {348MCU_buffer[blkn] = coef->dummy_buffer[blkn];349MCU_buffer[blkn][0][0] = MCU_buffer[blkn - 1][0][0];350blkn++;351}352}353}354/* Try to write the MCU. */355if (!(*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {356/* Suspension forced; update state counters and exit */357coef->MCU_vert_offset = yoffset;358coef->mcu_ctr = MCU_col_num;359return FALSE;360}361}362/* Completed an MCU row, but perhaps not an iMCU row */363coef->mcu_ctr = 0;364}365/* Completed the iMCU row, advance counters for next one */366coef->iMCU_row_num++;367start_iMCU_row(cinfo);368return TRUE;369}370371372METHODDEF(boolean)373compress_output_12(j_compress_ptr cinfo, J12SAMPIMAGE input_buf)374{375return compress_output(cinfo, (JSAMPIMAGE)input_buf);376}377378379/*380* Initialize coefficient buffer controller.381*382* Each passed coefficient array must be the right size for that383* coefficient: width_in_blocks wide and height_in_blocks high,384* with unitheight at least v_samp_factor.385*/386387LOCAL(void)388transencode_coef_controller(j_compress_ptr cinfo,389jvirt_barray_ptr *coef_arrays)390{391my_coef_ptr coef;392JBLOCKROW buffer;393int i;394395coef = (my_coef_ptr)396(*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,397sizeof(my_coef_controller));398cinfo->coef = (struct jpeg_c_coef_controller *)coef;399coef->pub.start_pass = start_pass_coef;400coef->pub.compress_data = compress_output;401coef->pub.compress_data_12 = compress_output_12;402403/* Save pointer to virtual arrays */404coef->whole_image = coef_arrays;405406/* Allocate and pre-zero space for dummy DCT blocks. */407buffer = (JBLOCKROW)408(*cinfo->mem->alloc_large) ((j_common_ptr)cinfo, JPOOL_IMAGE,409C_MAX_BLOCKS_IN_MCU * sizeof(JBLOCK));410jzero_far((void *)buffer, C_MAX_BLOCKS_IN_MCU * sizeof(JBLOCK));411for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {412coef->dummy_buffer[i] = buffer + i;413}414}415416417