Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
38918 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324// This file is available under and governed by the GNU General Public25// License version 2 only, as published by the Free Software Foundation.26// However, the following notice accompanied the original version of this27// file:28//29//---------------------------------------------------------------------------------30//31// Little Color Management System32// Copyright (c) 1998-2020 Marti Maria Saguer33//34// Permission is hereby granted, free of charge, to any person obtaining35// a copy of this software and associated documentation files (the "Software"),36// to deal in the Software without restriction, including without limitation37// the rights to use, copy, modify, merge, publish, distribute, sublicense,38// and/or sell copies of the Software, and to permit persons to whom the Software39// is furnished to do so, subject to the following conditions:40//41// The above copyright notice and this permission notice shall be included in42// all copies or substantial portions of the Software.43//44// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,45// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO46// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND47// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE48// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION49// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION50// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.51//52//---------------------------------------------------------------------------------53//5455#include "lcms2_internal.h"565758//----------------------------------------------------------------------------------5960// Optimization for 8 bits, Shaper-CLUT (3 inputs only)61typedef struct {6263cmsContext ContextID;6465const cmsInterpParams* p; // Tetrahedrical interpolation parameters. This is a not-owned pointer.6667cmsUInt16Number rx[256], ry[256], rz[256];68cmsUInt32Number X0[256], Y0[256], Z0[256]; // Precomputed nodes and offsets for 8-bit input data697071} Prelin8Data;727374// Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs)75typedef struct {7677cmsContext ContextID;7879// Number of channels80cmsUInt32Number nInputs;81cmsUInt32Number nOutputs;8283_cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS]; // The maximum number of input channels is known in advance84cmsInterpParams* ParamsCurveIn16[MAX_INPUT_DIMENSIONS];8586_cmsInterpFn16 EvalCLUT; // The evaluator for 3D grid87const cmsInterpParams* CLUTparams; // (not-owned pointer)888990_cmsInterpFn16* EvalCurveOut16; // Points to an array of curve evaluators in 16 bits (not-owned pointer)91cmsInterpParams** ParamsCurveOut16; // Points to an array of references to interpolation params (not-owned pointer)929394} Prelin16Data;959697// Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed9899typedef cmsInt32Number cmsS1Fixed14Number; // Note that this may hold more than 16 bits!100101#define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5))102103typedef struct {104105cmsContext ContextID;106107cmsS1Fixed14Number Shaper1R[256]; // from 0..255 to 1.14 (0.0...1.0)108cmsS1Fixed14Number Shaper1G[256];109cmsS1Fixed14Number Shaper1B[256];110111cmsS1Fixed14Number Mat[3][3]; // n.14 to n.14 (needs a saturation after that)112cmsS1Fixed14Number Off[3];113114cmsUInt16Number Shaper2R[16385]; // 1.14 to 0..255115cmsUInt16Number Shaper2G[16385];116cmsUInt16Number Shaper2B[16385];117118} MatShaper8Data;119120// Curves, optimization is shared between 8 and 16 bits121typedef struct {122123cmsContext ContextID;124125cmsUInt32Number nCurves; // Number of curves126cmsUInt32Number nElements; // Elements in curves127cmsUInt16Number** Curves; // Points to a dynamically allocated array128129} Curves16Data;130131132// Simple optimizations ----------------------------------------------------------------------------------------------------------133134135// Remove an element in linked chain136static137void _RemoveElement(cmsStage** head)138{139cmsStage* mpe = *head;140cmsStage* next = mpe ->Next;141*head = next;142cmsStageFree(mpe);143}144145// Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer.146static147cmsBool _Remove1Op(cmsPipeline* Lut, cmsStageSignature UnaryOp)148{149cmsStage** pt = &Lut ->Elements;150cmsBool AnyOpt = FALSE;151152while (*pt != NULL) {153154if ((*pt) ->Implements == UnaryOp) {155_RemoveElement(pt);156AnyOpt = TRUE;157}158else159pt = &((*pt) -> Next);160}161162return AnyOpt;163}164165// Same, but only if two adjacent elements are found166static167cmsBool _Remove2Op(cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2)168{169cmsStage** pt1;170cmsStage** pt2;171cmsBool AnyOpt = FALSE;172173pt1 = &Lut ->Elements;174if (*pt1 == NULL) return AnyOpt;175176while (*pt1 != NULL) {177178pt2 = &((*pt1) -> Next);179if (*pt2 == NULL) return AnyOpt;180181if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) {182_RemoveElement(pt2);183_RemoveElement(pt1);184AnyOpt = TRUE;185}186else187pt1 = &((*pt1) -> Next);188}189190return AnyOpt;191}192193194static195cmsBool CloseEnoughFloat(cmsFloat64Number a, cmsFloat64Number b)196{197return fabs(b - a) < 0.00001f;198}199200static201cmsBool isFloatMatrixIdentity(const cmsMAT3* a)202{203cmsMAT3 Identity;204int i, j;205206_cmsMAT3identity(&Identity);207208for (i = 0; i < 3; i++)209for (j = 0; j < 3; j++)210if (!CloseEnoughFloat(a->v[i].n[j], Identity.v[i].n[j])) return FALSE;211212return TRUE;213}214// if two adjacent matrices are found, multiply them.215static216cmsBool _MultiplyMatrix(cmsPipeline* Lut)217{218cmsStage** pt1;219cmsStage** pt2;220cmsStage* chain;221cmsBool AnyOpt = FALSE;222223pt1 = &Lut->Elements;224if (*pt1 == NULL) return AnyOpt;225226while (*pt1 != NULL) {227228pt2 = &((*pt1)->Next);229if (*pt2 == NULL) return AnyOpt;230231if ((*pt1)->Implements == cmsSigMatrixElemType && (*pt2)->Implements == cmsSigMatrixElemType) {232233// Get both matrices234_cmsStageMatrixData* m1 = (_cmsStageMatrixData*) cmsStageData(*pt1);235_cmsStageMatrixData* m2 = (_cmsStageMatrixData*) cmsStageData(*pt2);236cmsMAT3 res;237238// Input offset and output offset should be zero to use this optimization239if (m1->Offset != NULL || m2 ->Offset != NULL ||240cmsStageInputChannels(*pt1) != 3 || cmsStageOutputChannels(*pt1) != 3 ||241cmsStageInputChannels(*pt2) != 3 || cmsStageOutputChannels(*pt2) != 3)242return FALSE;243244// Multiply both matrices to get the result245_cmsMAT3per(&res, (cmsMAT3*)m2->Double, (cmsMAT3*)m1->Double);246247// Get the next in chain after the matrices248chain = (*pt2)->Next;249250// Remove both matrices251_RemoveElement(pt2);252_RemoveElement(pt1);253254// Now what if the result is a plain identity?255if (!isFloatMatrixIdentity(&res)) {256257// We can not get rid of full matrix258cmsStage* Multmat = cmsStageAllocMatrix(Lut->ContextID, 3, 3, (const cmsFloat64Number*) &res, NULL);259if (Multmat == NULL) return FALSE; // Should never happen260261// Recover the chain262Multmat->Next = chain;263*pt1 = Multmat;264}265266AnyOpt = TRUE;267}268else269pt1 = &((*pt1)->Next);270}271272return AnyOpt;273}274275276// Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed277// by a v4 to v2 and vice-versa. The elements are then discarded.278static279cmsBool PreOptimize(cmsPipeline* Lut)280{281cmsBool AnyOpt = FALSE, Opt;282283do {284285Opt = FALSE;286287// Remove all identities288Opt |= _Remove1Op(Lut, cmsSigIdentityElemType);289290// Remove XYZ2Lab followed by Lab2XYZ291Opt |= _Remove2Op(Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType);292293// Remove Lab2XYZ followed by XYZ2Lab294Opt |= _Remove2Op(Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType);295296// Remove V4 to V2 followed by V2 to V4297Opt |= _Remove2Op(Lut, cmsSigLabV4toV2, cmsSigLabV2toV4);298299// Remove V2 to V4 followed by V4 to V2300Opt |= _Remove2Op(Lut, cmsSigLabV2toV4, cmsSigLabV4toV2);301302// Remove float pcs Lab conversions303Opt |= _Remove2Op(Lut, cmsSigLab2FloatPCS, cmsSigFloatPCS2Lab);304305// Remove float pcs Lab conversions306Opt |= _Remove2Op(Lut, cmsSigXYZ2FloatPCS, cmsSigFloatPCS2XYZ);307308// Simplify matrix.309Opt |= _MultiplyMatrix(Lut);310311if (Opt) AnyOpt = TRUE;312313} while (Opt);314315return AnyOpt;316}317318static319void Eval16nop1D(CMSREGISTER const cmsUInt16Number Input[],320CMSREGISTER cmsUInt16Number Output[],321CMSREGISTER const struct _cms_interp_struc* p)322{323Output[0] = Input[0];324325cmsUNUSED_PARAMETER(p);326}327328static329void PrelinEval16(CMSREGISTER const cmsUInt16Number Input[],330CMSREGISTER cmsUInt16Number Output[],331CMSREGISTER const void* D)332{333Prelin16Data* p16 = (Prelin16Data*) D;334cmsUInt16Number StageABC[MAX_INPUT_DIMENSIONS];335cmsUInt16Number StageDEF[cmsMAXCHANNELS];336cmsUInt32Number i;337338for (i=0; i < p16 ->nInputs; i++) {339340p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);341}342343p16 ->EvalCLUT(StageABC, StageDEF, p16 ->CLUTparams);344345for (i=0; i < p16 ->nOutputs; i++) {346347p16 ->EvalCurveOut16[i](&StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);348}349}350351352static353void PrelinOpt16free(cmsContext ContextID, void* ptr)354{355Prelin16Data* p16 = (Prelin16Data*) ptr;356357_cmsFree(ContextID, p16 ->EvalCurveOut16);358_cmsFree(ContextID, p16 ->ParamsCurveOut16);359360_cmsFree(ContextID, p16);361}362363static364void* Prelin16dup(cmsContext ContextID, const void* ptr)365{366Prelin16Data* p16 = (Prelin16Data*) ptr;367Prelin16Data* Duped = (Prelin16Data*) _cmsDupMem(ContextID, p16, sizeof(Prelin16Data));368369if (Duped == NULL) return NULL;370371Duped->EvalCurveOut16 = (_cmsInterpFn16*) _cmsDupMem(ContextID, p16->EvalCurveOut16, p16->nOutputs * sizeof(_cmsInterpFn16));372Duped->ParamsCurveOut16 = (cmsInterpParams**)_cmsDupMem(ContextID, p16->ParamsCurveOut16, p16->nOutputs * sizeof(cmsInterpParams*));373374return Duped;375}376377378static379Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,380const cmsInterpParams* ColorMap,381cmsUInt32Number nInputs, cmsToneCurve** In,382cmsUInt32Number nOutputs, cmsToneCurve** Out )383{384cmsUInt32Number i;385Prelin16Data* p16 = (Prelin16Data*)_cmsMallocZero(ContextID, sizeof(Prelin16Data));386if (p16 == NULL) return NULL;387388p16 ->nInputs = nInputs;389p16 ->nOutputs = nOutputs;390391392for (i=0; i < nInputs; i++) {393394if (In == NULL) {395p16 -> ParamsCurveIn16[i] = NULL;396p16 -> EvalCurveIn16[i] = Eval16nop1D;397398}399else {400p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams;401p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16;402}403}404405p16 ->CLUTparams = ColorMap;406p16 ->EvalCLUT = ColorMap ->Interpolation.Lerp16;407408409p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));410p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));411412for (i=0; i < nOutputs; i++) {413414if (Out == NULL) {415p16 ->ParamsCurveOut16[i] = NULL;416p16 -> EvalCurveOut16[i] = Eval16nop1D;417}418else {419420p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;421p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;422}423}424425return p16;426}427428429430// Resampling ---------------------------------------------------------------------------------431432#define PRELINEARIZATION_POINTS 4096433434// Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for435// almost any transform. We use floating point precision and then convert from floating point to 16 bits.436static437cmsInt32Number XFormSampler16(CMSREGISTER const cmsUInt16Number In[], CMSREGISTER cmsUInt16Number Out[], CMSREGISTER void* Cargo)438{439cmsPipeline* Lut = (cmsPipeline*) Cargo;440cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];441cmsUInt32Number i;442443_cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);444_cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);445446// From 16 bit to floating point447for (i=0; i < Lut ->InputChannels; i++)448InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);449450// Evaluate in floating point451cmsPipelineEvalFloat(InFloat, OutFloat, Lut);452453// Back to 16 bits representation454for (i=0; i < Lut ->OutputChannels; i++)455Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);456457// Always succeed458return TRUE;459}460461// Try to see if the curves of a given MPE are linear462static463cmsBool AllCurvesAreLinear(cmsStage* mpe)464{465cmsToneCurve** Curves;466cmsUInt32Number i, n;467468Curves = _cmsStageGetPtrToCurveSet(mpe);469if (Curves == NULL) return FALSE;470471n = cmsStageOutputChannels(mpe);472473for (i=0; i < n; i++) {474if (!cmsIsToneCurveLinear(Curves[i])) return FALSE;475}476477return TRUE;478}479480// This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose481// is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels482static483cmsBool PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],484cmsUInt32Number nChannelsOut, cmsUInt32Number nChannelsIn)485{486_cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;487cmsInterpParams* p16 = Grid ->Params;488cmsFloat64Number px, py, pz, pw;489int x0, y0, z0, w0;490int i, index;491492if (CLUT -> Type != cmsSigCLutElemType) {493cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage");494return FALSE;495}496497if (nChannelsIn == 4) {498499px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;500py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;501pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;502pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;503504x0 = (int) floor(px);505y0 = (int) floor(py);506z0 = (int) floor(pz);507w0 = (int) floor(pw);508509if (((px - x0) != 0) ||510((py - y0) != 0) ||511((pz - z0) != 0) ||512((pw - w0) != 0)) return FALSE; // Not on exact node513514index = (int) p16 -> opta[3] * x0 +515(int) p16 -> opta[2] * y0 +516(int) p16 -> opta[1] * z0 +517(int) p16 -> opta[0] * w0;518}519else520if (nChannelsIn == 3) {521522px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;523py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;524pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;525526x0 = (int) floor(px);527y0 = (int) floor(py);528z0 = (int) floor(pz);529530if (((px - x0) != 0) ||531((py - y0) != 0) ||532((pz - z0) != 0)) return FALSE; // Not on exact node533534index = (int) p16 -> opta[2] * x0 +535(int) p16 -> opta[1] * y0 +536(int) p16 -> opta[0] * z0;537}538else539if (nChannelsIn == 1) {540541px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;542543x0 = (int) floor(px);544545if (((px - x0) != 0)) return FALSE; // Not on exact node546547index = (int) p16 -> opta[0] * x0;548}549else {550cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);551return FALSE;552}553554for (i = 0; i < (int) nChannelsOut; i++)555Grid->Tab.T[index + i] = Value[i];556557return TRUE;558}559560// Auxiliary, to see if two values are equal or very different561static562cmsBool WhitesAreEqual(cmsUInt32Number n, cmsUInt16Number White1[], cmsUInt16Number White2[] )563{564cmsUInt32Number i;565566for (i=0; i < n; i++) {567568if (abs(White1[i] - White2[i]) > 0xf000) return TRUE; // Values are so extremely different that the fixup should be avoided569if (White1[i] != White2[i]) return FALSE;570}571return TRUE;572}573574575// Locate the node for the white point and fix it to pure white in order to avoid scum dot.576static577cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)578{579cmsUInt16Number *WhitePointIn, *WhitePointOut;580cmsUInt16Number WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];581cmsUInt32Number i, nOuts, nIns;582cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;583584if (!_cmsEndPointsBySpace(EntryColorSpace,585&WhitePointIn, NULL, &nIns)) return FALSE;586587if (!_cmsEndPointsBySpace(ExitColorSpace,588&WhitePointOut, NULL, &nOuts)) return FALSE;589590// It needs to be fixed?591if (Lut ->InputChannels != nIns) return FALSE;592if (Lut ->OutputChannels != nOuts) return FALSE;593594cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut);595596if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match597598// Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations599if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))600if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))601if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))602if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT))603return FALSE;604605// We need to interpolate white points of both, pre and post curves606if (PreLin) {607608cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);609610for (i=0; i < nIns; i++) {611WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]);612}613}614else {615for (i=0; i < nIns; i++)616WhiteIn[i] = WhitePointIn[i];617}618619// If any post-linearization, we need to find how is represented white before the curve, do620// a reverse interpolation in this case.621if (PostLin) {622623cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);624625for (i=0; i < nOuts; i++) {626627cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);628if (InversePostLin == NULL) {629WhiteOut[i] = WhitePointOut[i];630631} else {632633WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);634cmsFreeToneCurve(InversePostLin);635}636}637}638else {639for (i=0; i < nOuts; i++)640WhiteOut[i] = WhitePointOut[i];641}642643// Ok, proceed with patching. May fail and we don't care if it fails644PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns);645646return TRUE;647}648649// -----------------------------------------------------------------------------------------------------------------------------------------------650// This function creates simple LUT from complex ones. The generated LUT has an optional set of651// prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.652// These curves have to exist in the original LUT in order to be used in the simplified output.653// Caller may also use the flags to allow this feature.654// LUTS with all curves will be simplified to a single curve. Parametric curves are lost.655// This function should be used on 16-bits LUTS only, as floating point losses precision when simplified656// -----------------------------------------------------------------------------------------------------------------------------------------------657658static659cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)660{661cmsPipeline* Src = NULL;662cmsPipeline* Dest = NULL;663cmsStage* mpe;664cmsStage* CLUT;665cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;666cmsUInt32Number nGridPoints;667cmsColorSpaceSignature ColorSpace, OutputColorSpace;668cmsStage *NewPreLin = NULL;669cmsStage *NewPostLin = NULL;670_cmsStageCLutData* DataCLUT;671cmsToneCurve** DataSetIn;672cmsToneCurve** DataSetOut;673Prelin16Data* p16;674675// This is a lossy optimization! does not apply in floating-point cases676if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;677678ColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*InputFormat));679OutputColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*OutputFormat));680681// Color space must be specified682if (ColorSpace == (cmsColorSpaceSignature)0 ||683OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;684685nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);686687// For empty LUTs, 2 points are enough688if (cmsPipelineStageCount(*Lut) == 0)689nGridPoints = 2;690691Src = *Lut;692693// Named color pipelines cannot be optimized either694for (mpe = cmsPipelineGetPtrToFirstStage(Src);695mpe != NULL;696mpe = cmsStageNext(mpe)) {697if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;698}699700// Allocate an empty LUT701Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);702if (!Dest) return FALSE;703704// Prelinearization tables are kept unless indicated by flags705if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {706707// Get a pointer to the prelinearization element708cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);709710// Check if suitable711if (PreLin && PreLin ->Type == cmsSigCurveSetElemType) {712713// Maybe this is a linear tram, so we can avoid the whole stuff714if (!AllCurvesAreLinear(PreLin)) {715716// All seems ok, proceed.717NewPreLin = cmsStageDup(PreLin);718if(!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin))719goto Error;720721// Remove prelinearization. Since we have duplicated the curve722// in destination LUT, the sampling should be applied after this stage.723cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin);724}725}726}727728// Allocate the CLUT729CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);730if (CLUT == NULL) goto Error;731732// Add the CLUT to the destination LUT733if (!cmsPipelineInsertStage(Dest, cmsAT_END, CLUT)) {734goto Error;735}736737// Postlinearization tables are kept unless indicated by flags738if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {739740// Get a pointer to the postlinearization if present741cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);742743// Check if suitable744if (PostLin && cmsStageType(PostLin) == cmsSigCurveSetElemType) {745746// Maybe this is a linear tram, so we can avoid the whole stuff747if (!AllCurvesAreLinear(PostLin)) {748749// All seems ok, proceed.750NewPostLin = cmsStageDup(PostLin);751if (!cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin))752goto Error;753754// In destination LUT, the sampling should be applied after this stage.755cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);756}757}758}759760// Now its time to do the sampling. We have to ignore pre/post linearization761// The source LUT without pre/post curves is passed as parameter.762if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {763Error:764// Ops, something went wrong, Restore stages765if (KeepPreLin != NULL) {766if (!cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin)) {767_cmsAssert(0); // This never happens768}769}770if (KeepPostLin != NULL) {771if (!cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin)) {772_cmsAssert(0); // This never happens773}774}775cmsPipelineFree(Dest);776return FALSE;777}778779// Done.780781if (KeepPreLin != NULL) cmsStageFree(KeepPreLin);782if (KeepPostLin != NULL) cmsStageFree(KeepPostLin);783cmsPipelineFree(Src);784785DataCLUT = (_cmsStageCLutData*) CLUT ->Data;786787if (NewPreLin == NULL) DataSetIn = NULL;788else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;789790if (NewPostLin == NULL) DataSetOut = NULL;791else DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;792793794if (DataSetIn == NULL && DataSetOut == NULL) {795796_cmsPipelineSetOptimizationParameters(Dest, (_cmsOPTeval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);797}798else {799800p16 = PrelinOpt16alloc(Dest ->ContextID,801DataCLUT ->Params,802Dest ->InputChannels,803DataSetIn,804Dest ->OutputChannels,805DataSetOut);806807_cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);808}809810811// Don't fix white on absolute colorimetric812if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)813*dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;814815if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {816817FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace);818}819820*Lut = Dest;821return TRUE;822823cmsUNUSED_PARAMETER(Intent);824}825826827// -----------------------------------------------------------------------------------------------------------------------------------------------828// Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on829// Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works830// for RGB transforms. See the paper for more details831// -----------------------------------------------------------------------------------------------------------------------------------------------832833834// Normalize endpoints by slope limiting max and min. This assures endpoints as well.835// Descending curves are handled as well.836static837void SlopeLimiting(cmsToneCurve* g)838{839int BeginVal, EndVal;840int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5); // Cutoff at 2%841int AtEnd = (int) g ->nEntries - AtBegin - 1; // And 98%842cmsFloat64Number Val, Slope, beta;843int i;844845if (cmsIsToneCurveDescending(g)) {846BeginVal = 0xffff; EndVal = 0;847}848else {849BeginVal = 0; EndVal = 0xffff;850}851852// Compute slope and offset for begin of curve853Val = g ->Table16[AtBegin];854Slope = (Val - BeginVal) / AtBegin;855beta = Val - Slope * AtBegin;856857for (i=0; i < AtBegin; i++)858g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);859860// Compute slope and offset for the end861Val = g ->Table16[AtEnd];862Slope = (EndVal - Val) / AtBegin; // AtBegin holds the X interval, which is same in both cases863beta = Val - Slope * AtEnd;864865for (i = AtEnd; i < (int) g ->nEntries; i++)866g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);867}868869870// Precomputes tables for 8-bit on input devicelink.871static872Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])873{874int i;875cmsUInt16Number Input[3];876cmsS15Fixed16Number v1, v2, v3;877Prelin8Data* p8;878879p8 = (Prelin8Data*)_cmsMallocZero(ContextID, sizeof(Prelin8Data));880if (p8 == NULL) return NULL;881882// Since this only works for 8 bit input, values comes always as x * 257,883// we can safely take msb byte (x << 8 + x)884885for (i=0; i < 256; i++) {886887if (G != NULL) {888889// Get 16-bit representation890Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i));891Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i));892Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i));893}894else {895Input[0] = FROM_8_TO_16(i);896Input[1] = FROM_8_TO_16(i);897Input[2] = FROM_8_TO_16(i);898}899900901// Move to 0..1.0 in fixed domain902v1 = _cmsToFixedDomain((int) (Input[0] * p -> Domain[0]));903v2 = _cmsToFixedDomain((int) (Input[1] * p -> Domain[1]));904v3 = _cmsToFixedDomain((int) (Input[2] * p -> Domain[2]));905906// Store the precalculated table of nodes907p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));908p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));909p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));910911// Store the precalculated table of offsets912p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);913p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);914p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);915}916917p8 ->ContextID = ContextID;918p8 ->p = p;919920return p8;921}922923static924void Prelin8free(cmsContext ContextID, void* ptr)925{926_cmsFree(ContextID, ptr);927}928929static930void* Prelin8dup(cmsContext ContextID, const void* ptr)931{932return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));933}934935936937// A optimized interpolation for 8-bit input.938#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])939static CMS_NO_SANITIZE940void PrelinEval8(CMSREGISTER const cmsUInt16Number Input[],941CMSREGISTER cmsUInt16Number Output[],942CMSREGISTER const void* D)943{944945cmsUInt8Number r, g, b;946cmsS15Fixed16Number rx, ry, rz;947cmsS15Fixed16Number c0, c1, c2, c3, Rest;948int OutChan;949CMSREGISTER cmsS15Fixed16Number X0, X1, Y0, Y1, Z0, Z1;950Prelin8Data* p8 = (Prelin8Data*) D;951CMSREGISTER const cmsInterpParams* p = p8 ->p;952int TotalOut = (int) p -> nOutputs;953const cmsUInt16Number* LutTable = (const cmsUInt16Number*) p->Table;954955r = (cmsUInt8Number) (Input[0] >> 8);956g = (cmsUInt8Number) (Input[1] >> 8);957b = (cmsUInt8Number) (Input[2] >> 8);958959X0 = X1 = (cmsS15Fixed16Number) p8->X0[r];960Y0 = Y1 = (cmsS15Fixed16Number) p8->Y0[g];961Z0 = Z1 = (cmsS15Fixed16Number) p8->Z0[b];962963rx = p8 ->rx[r];964ry = p8 ->ry[g];965rz = p8 ->rz[b];966967X1 = X0 + (cmsS15Fixed16Number)((rx == 0) ? 0 : p ->opta[2]);968Y1 = Y0 + (cmsS15Fixed16Number)((ry == 0) ? 0 : p ->opta[1]);969Z1 = Z0 + (cmsS15Fixed16Number)((rz == 0) ? 0 : p ->opta[0]);970971972// These are the 6 Tetrahedral973for (OutChan=0; OutChan < TotalOut; OutChan++) {974975c0 = DENS(X0, Y0, Z0);976977if (rx >= ry && ry >= rz)978{979c1 = DENS(X1, Y0, Z0) - c0;980c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);981c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);982}983else984if (rx >= rz && rz >= ry)985{986c1 = DENS(X1, Y0, Z0) - c0;987c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);988c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);989}990else991if (rz >= rx && rx >= ry)992{993c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);994c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);995c3 = DENS(X0, Y0, Z1) - c0;996}997else998if (ry >= rx && rx >= rz)999{1000c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);1001c2 = DENS(X0, Y1, Z0) - c0;1002c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);1003}1004else1005if (ry >= rz && rz >= rx)1006{1007c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);1008c2 = DENS(X0, Y1, Z0) - c0;1009c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);1010}1011else1012if (rz >= ry && ry >= rx)1013{1014c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);1015c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);1016c3 = DENS(X0, Y0, Z1) - c0;1017}1018else {1019c1 = c2 = c3 = 0;1020}10211022Rest = c1 * rx + c2 * ry + c3 * rz + 0x8001;1023Output[OutChan] = (cmsUInt16Number) (c0 + ((Rest + (Rest >> 16)) >> 16));10241025}1026}10271028#undef DENS102910301031// Curves that contain wide empty areas are not optimizeable1032static1033cmsBool IsDegenerated(const cmsToneCurve* g)1034{1035cmsUInt32Number i, Zeros = 0, Poles = 0;1036cmsUInt32Number nEntries = g ->nEntries;10371038for (i=0; i < nEntries; i++) {10391040if (g ->Table16[i] == 0x0000) Zeros++;1041if (g ->Table16[i] == 0xffff) Poles++;1042}10431044if (Zeros == 1 && Poles == 1) return FALSE; // For linear tables1045if (Zeros > (nEntries / 20)) return TRUE; // Degenerated, many zeros1046if (Poles > (nEntries / 20)) return TRUE; // Degenerated, many poles10471048return FALSE;1049}10501051// --------------------------------------------------------------------------------------------------------------1052// We need xput over here10531054static1055cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)1056{1057cmsPipeline* OriginalLut;1058cmsUInt32Number nGridPoints;1059cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];1060cmsUInt32Number t, i;1061cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];1062cmsBool lIsSuitable, lIsLinear;1063cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;1064cmsStage* OptimizedCLUTmpe;1065cmsColorSpaceSignature ColorSpace, OutputColorSpace;1066cmsStage* OptimizedPrelinMpe;1067cmsStage* mpe;1068cmsToneCurve** OptimizedPrelinCurves;1069_cmsStageCLutData* OptimizedPrelinCLUT;107010711072// This is a lossy optimization! does not apply in floating-point cases1073if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;10741075// Only on chunky RGB1076if (T_COLORSPACE(*InputFormat) != PT_RGB) return FALSE;1077if (T_PLANAR(*InputFormat)) return FALSE;10781079if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;1080if (T_PLANAR(*OutputFormat)) return FALSE;10811082// On 16 bits, user has to specify the feature1083if (!_cmsFormatterIs8bit(*InputFormat)) {1084if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;1085}10861087OriginalLut = *Lut;10881089// Named color pipelines cannot be optimized either1090for (mpe = cmsPipelineGetPtrToFirstStage(OriginalLut);1091mpe != NULL;1092mpe = cmsStageNext(mpe)) {1093if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;1094}10951096ColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*InputFormat));1097OutputColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*OutputFormat));10981099// Color space must be specified1100if (ColorSpace == (cmsColorSpaceSignature)0 ||1101OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;11021103nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);11041105// Empty gamma containers1106memset(Trans, 0, sizeof(Trans));1107memset(TransReverse, 0, sizeof(TransReverse));11081109// If the last stage of the original lut are curves, and those curves are1110// degenerated, it is likely the transform is squeezing and clipping1111// the output from previous CLUT. We cannot optimize this case1112{1113cmsStage* last = cmsPipelineGetPtrToLastStage(OriginalLut);11141115if (last == NULL) goto Error;1116if (cmsStageType(last) == cmsSigCurveSetElemType) {11171118_cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*)cmsStageData(last);1119for (i = 0; i < Data->nCurves; i++) {1120if (IsDegenerated(Data->TheCurves[i]))1121goto Error;1122}1123}1124}11251126for (t = 0; t < OriginalLut ->InputChannels; t++) {1127Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);1128if (Trans[t] == NULL) goto Error;1129}11301131// Populate the curves1132for (i=0; i < PRELINEARIZATION_POINTS; i++) {11331134v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));11351136// Feed input with a gray ramp1137for (t=0; t < OriginalLut ->InputChannels; t++)1138In[t] = v;11391140// Evaluate the gray value1141cmsPipelineEvalFloat(In, Out, OriginalLut);11421143// Store result in curve1144for (t=0; t < OriginalLut ->InputChannels; t++)1145Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);1146}11471148// Slope-limit the obtained curves1149for (t = 0; t < OriginalLut ->InputChannels; t++)1150SlopeLimiting(Trans[t]);11511152// Check for validity1153lIsSuitable = TRUE;1154lIsLinear = TRUE;1155for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {11561157// Exclude if already linear1158if (!cmsIsToneCurveLinear(Trans[t]))1159lIsLinear = FALSE;11601161// Exclude if non-monotonic1162if (!cmsIsToneCurveMonotonic(Trans[t]))1163lIsSuitable = FALSE;11641165if (IsDegenerated(Trans[t]))1166lIsSuitable = FALSE;1167}11681169// If it is not suitable, just quit1170if (!lIsSuitable) goto Error;11711172// Invert curves if possible1173for (t = 0; t < OriginalLut ->InputChannels; t++) {1174TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]);1175if (TransReverse[t] == NULL) goto Error;1176}11771178// Now inset the reversed curves at the begin of transform1179LutPlusCurves = cmsPipelineDup(OriginalLut);1180if (LutPlusCurves == NULL) goto Error;11811182if (!cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse)))1183goto Error;11841185// Create the result LUT1186OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);1187if (OptimizedLUT == NULL) goto Error;11881189OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);11901191// Create and insert the curves at the beginning1192if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe))1193goto Error;11941195// Allocate the CLUT for result1196OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);11971198// Add the CLUT to the destination LUT1199if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe))1200goto Error;12011202// Resample the LUT1203if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;12041205// Free resources1206for (t = 0; t < OriginalLut ->InputChannels; t++) {12071208if (Trans[t]) cmsFreeToneCurve(Trans[t]);1209if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);1210}12111212cmsPipelineFree(LutPlusCurves);121312141215OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);1216OptimizedPrelinCLUT = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;12171218// Set the evaluator if 8-bit1219if (_cmsFormatterIs8bit(*InputFormat)) {12201221Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID,1222OptimizedPrelinCLUT ->Params,1223OptimizedPrelinCurves);1224if (p8 == NULL) return FALSE;12251226_cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);12271228}1229else1230{1231Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID,1232OptimizedPrelinCLUT ->Params,12333, OptimizedPrelinCurves, 3, NULL);1234if (p16 == NULL) return FALSE;12351236_cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);12371238}12391240// Don't fix white on absolute colorimetric1241if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)1242*dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;12431244if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {12451246if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) {12471248return FALSE;1249}1250}12511252// And return the obtained LUT12531254cmsPipelineFree(OriginalLut);1255*Lut = OptimizedLUT;1256return TRUE;12571258Error:12591260for (t = 0; t < OriginalLut ->InputChannels; t++) {12611262if (Trans[t]) cmsFreeToneCurve(Trans[t]);1263if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);1264}12651266if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves);1267if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT);12681269return FALSE;12701271cmsUNUSED_PARAMETER(Intent);1272cmsUNUSED_PARAMETER(lIsLinear);1273}127412751276// Curves optimizer ------------------------------------------------------------------------------------------------------------------12771278static1279void CurvesFree(cmsContext ContextID, void* ptr)1280{1281Curves16Data* Data = (Curves16Data*) ptr;1282cmsUInt32Number i;12831284for (i=0; i < Data -> nCurves; i++) {12851286_cmsFree(ContextID, Data ->Curves[i]);1287}12881289_cmsFree(ContextID, Data ->Curves);1290_cmsFree(ContextID, ptr);1291}12921293static1294void* CurvesDup(cmsContext ContextID, const void* ptr)1295{1296Curves16Data* Data = (Curves16Data*)_cmsDupMem(ContextID, ptr, sizeof(Curves16Data));1297cmsUInt32Number i;12981299if (Data == NULL) return NULL;13001301Data->Curves = (cmsUInt16Number**) _cmsDupMem(ContextID, Data->Curves, Data->nCurves * sizeof(cmsUInt16Number*));13021303for (i=0; i < Data -> nCurves; i++) {1304Data->Curves[i] = (cmsUInt16Number*) _cmsDupMem(ContextID, Data->Curves[i], Data->nElements * sizeof(cmsUInt16Number));1305}13061307return (void*) Data;1308}13091310// Precomputes tables for 8-bit on input devicelink.1311static1312Curves16Data* CurvesAlloc(cmsContext ContextID, cmsUInt32Number nCurves, cmsUInt32Number nElements, cmsToneCurve** G)1313{1314cmsUInt32Number i, j;1315Curves16Data* c16;13161317c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));1318if (c16 == NULL) return NULL;13191320c16 ->nCurves = nCurves;1321c16 ->nElements = nElements;13221323c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));1324if (c16->Curves == NULL) {1325_cmsFree(ContextID, c16);1326return NULL;1327}13281329for (i=0; i < nCurves; i++) {13301331c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));13321333if (c16->Curves[i] == NULL) {13341335for (j=0; j < i; j++) {1336_cmsFree(ContextID, c16->Curves[j]);1337}1338_cmsFree(ContextID, c16->Curves);1339_cmsFree(ContextID, c16);1340return NULL;1341}13421343if (nElements == 256U) {13441345for (j=0; j < nElements; j++) {13461347c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));1348}1349}1350else {13511352for (j=0; j < nElements; j++) {1353c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);1354}1355}1356}13571358return c16;1359}13601361static1362void FastEvaluateCurves8(CMSREGISTER const cmsUInt16Number In[],1363CMSREGISTER cmsUInt16Number Out[],1364CMSREGISTER const void* D)1365{1366Curves16Data* Data = (Curves16Data*) D;1367int x;1368cmsUInt32Number i;13691370for (i=0; i < Data ->nCurves; i++) {13711372x = (In[i] >> 8);1373Out[i] = Data -> Curves[i][x];1374}1375}137613771378static1379void FastEvaluateCurves16(CMSREGISTER const cmsUInt16Number In[],1380CMSREGISTER cmsUInt16Number Out[],1381CMSREGISTER const void* D)1382{1383Curves16Data* Data = (Curves16Data*) D;1384cmsUInt32Number i;13851386for (i=0; i < Data ->nCurves; i++) {1387Out[i] = Data -> Curves[i][In[i]];1388}1389}139013911392static1393void FastIdentity16(CMSREGISTER const cmsUInt16Number In[],1394CMSREGISTER cmsUInt16Number Out[],1395CMSREGISTER const void* D)1396{1397cmsPipeline* Lut = (cmsPipeline*) D;1398cmsUInt32Number i;13991400for (i=0; i < Lut ->InputChannels; i++) {1401Out[i] = In[i];1402}1403}140414051406// If the target LUT holds only curves, the optimization procedure is to join all those1407// curves together. That only works on curves and does not work on matrices.1408static1409cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)1410{1411cmsToneCurve** GammaTables = NULL;1412cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];1413cmsUInt32Number i, j;1414cmsPipeline* Src = *Lut;1415cmsPipeline* Dest = NULL;1416cmsStage* mpe;1417cmsStage* ObtainedCurves = NULL;141814191420// This is a lossy optimization! does not apply in floating-point cases1421if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;14221423// Only curves in this LUT?1424for (mpe = cmsPipelineGetPtrToFirstStage(Src);1425mpe != NULL;1426mpe = cmsStageNext(mpe)) {1427if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE;1428}14291430// Allocate an empty LUT1431Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);1432if (Dest == NULL) return FALSE;14331434// Create target curves1435GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));1436if (GammaTables == NULL) goto Error;14371438for (i=0; i < Src ->InputChannels; i++) {1439GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL);1440if (GammaTables[i] == NULL) goto Error;1441}14421443// Compute 16 bit result by using floating point1444for (i=0; i < PRELINEARIZATION_POINTS; i++) {14451446for (j=0; j < Src ->InputChannels; j++)1447InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));14481449cmsPipelineEvalFloat(InFloat, OutFloat, Src);14501451for (j=0; j < Src ->InputChannels; j++)1452GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);1453}14541455ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables);1456if (ObtainedCurves == NULL) goto Error;14571458for (i=0; i < Src ->InputChannels; i++) {1459cmsFreeToneCurve(GammaTables[i]);1460GammaTables[i] = NULL;1461}14621463if (GammaTables != NULL) {1464_cmsFree(Src->ContextID, GammaTables);1465GammaTables = NULL;1466}14671468// Maybe the curves are linear at the end1469if (!AllCurvesAreLinear(ObtainedCurves)) {1470_cmsStageToneCurvesData* Data;14711472if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves))1473goto Error;1474Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);1475ObtainedCurves = NULL;14761477// If the curves are to be applied in 8 bits, we can save memory1478if (_cmsFormatterIs8bit(*InputFormat)) {1479Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);14801481if (c16 == NULL) goto Error;1482*dwFlags |= cmsFLAGS_NOCACHE;1483_cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);14841485}1486else {1487Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);14881489if (c16 == NULL) goto Error;1490*dwFlags |= cmsFLAGS_NOCACHE;1491_cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);1492}1493}1494else {14951496// LUT optimizes to nothing. Set the identity LUT1497cmsStageFree(ObtainedCurves);1498ObtainedCurves = NULL;14991500if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels)))1501goto Error;15021503*dwFlags |= cmsFLAGS_NOCACHE;1504_cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);1505}15061507// We are done.1508cmsPipelineFree(Src);1509*Lut = Dest;1510return TRUE;15111512Error:15131514if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves);1515if (GammaTables != NULL) {1516for (i=0; i < Src ->InputChannels; i++) {1517if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]);1518}15191520_cmsFree(Src ->ContextID, GammaTables);1521}15221523if (Dest != NULL) cmsPipelineFree(Dest);1524return FALSE;15251526cmsUNUSED_PARAMETER(Intent);1527cmsUNUSED_PARAMETER(InputFormat);1528cmsUNUSED_PARAMETER(OutputFormat);1529cmsUNUSED_PARAMETER(dwFlags);1530}15311532// -------------------------------------------------------------------------------------------------------------------------------------1533// LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles153415351536static1537void FreeMatShaper(cmsContext ContextID, void* Data)1538{1539if (Data != NULL) _cmsFree(ContextID, Data);1540}15411542static1543void* DupMatShaper(cmsContext ContextID, const void* Data)1544{1545return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));1546}154715481549// A fast matrix-shaper evaluator for 8 bits. This is a bit ticky since I'm using 1.14 signed fixed point1550// to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,1551// in total about 50K, and the performance boost is huge!1552static1553void MatShaperEval16(CMSREGISTER const cmsUInt16Number In[],1554CMSREGISTER cmsUInt16Number Out[],1555CMSREGISTER const void* D)1556{1557MatShaper8Data* p = (MatShaper8Data*) D;1558cmsS1Fixed14Number l1, l2, l3, r, g, b;1559cmsUInt32Number ri, gi, bi;15601561// In this case (and only in this case!) we can use this simplification since1562// In[] is assured to come from a 8 bit number. (a << 8 | a)1563ri = In[0] & 0xFFU;1564gi = In[1] & 0xFFU;1565bi = In[2] & 0xFFU;15661567// Across first shaper, which also converts to 1.14 fixed point1568r = p->Shaper1R[ri];1569g = p->Shaper1G[gi];1570b = p->Shaper1B[bi];15711572// Evaluate the matrix in 1.14 fixed point1573l1 = (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;1574l2 = (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;1575l3 = (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;15761577// Now we have to clip to 0..1.0 range1578ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384U : (cmsUInt32Number) l1);1579gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384U : (cmsUInt32Number) l2);1580bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384U : (cmsUInt32Number) l3);15811582// And across second shaper,1583Out[0] = p->Shaper2R[ri];1584Out[1] = p->Shaper2G[gi];1585Out[2] = p->Shaper2B[bi];15861587}15881589// This table converts from 8 bits to 1.14 after applying the curve1590static1591void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve)1592{1593int i;1594cmsFloat32Number R, y;15951596for (i=0; i < 256; i++) {15971598R = (cmsFloat32Number) (i / 255.0);1599y = cmsEvalToneCurveFloat(Curve, R);16001601if (y < 131072.0)1602Table[i] = DOUBLE_TO_1FIXED14(y);1603else1604Table[i] = 0x7fffffff;1605}1606}16071608// This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve1609static1610void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)1611{1612int i;1613cmsFloat32Number R, Val;16141615for (i=0; i < 16385; i++) {16161617R = (cmsFloat32Number) (i / 16384.0);1618Val = cmsEvalToneCurveFloat(Curve, R); // Val comes 0..1.016191620if (Val < 0)1621Val = 0;16221623if (Val > 1.0)1624Val = 1.0;16251626if (Is8BitsOutput) {16271628// If 8 bits output, we can optimize further by computing the / 257 part.1629// first we compute the resulting byte and then we store the byte times1630// 257. This quantization allows to round very quick by doing a >> 8, but1631// since the low byte is always equal to msb, we can do a & 0xff and this works!1632cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0);1633cmsUInt8Number b = FROM_16_TO_8(w);16341635Table[i] = FROM_8_TO_16(b);1636}1637else Table[i] = _cmsQuickSaturateWord(Val * 65535.0);1638}1639}16401641// Compute the matrix-shaper structure1642static1643cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)1644{1645MatShaper8Data* p;1646int i, j;1647cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);16481649// Allocate a big chuck of memory to store precomputed tables1650p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));1651if (p == NULL) return FALSE;16521653p -> ContextID = Dest -> ContextID;16541655// Precompute tables1656FillFirstShaper(p ->Shaper1R, Curve1[0]);1657FillFirstShaper(p ->Shaper1G, Curve1[1]);1658FillFirstShaper(p ->Shaper1B, Curve1[2]);16591660FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits);1661FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits);1662FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits);16631664// Convert matrix to nFixed14. Note that those values may take more than 16 bits1665for (i=0; i < 3; i++) {1666for (j=0; j < 3; j++) {1667p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);1668}1669}16701671for (i=0; i < 3; i++) {16721673if (Off == NULL) {1674p ->Off[i] = 0;1675}1676else {1677p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);1678}1679}16801681// Mark as optimized for faster formatter1682if (Is8Bits)1683*OutputFormat |= OPTIMIZED_SH(1);16841685// Fill function pointers1686_cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);1687return TRUE;1688}16891690// 8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!1691static1692cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)1693{1694cmsStage* Curve1, *Curve2;1695cmsStage* Matrix1, *Matrix2;1696cmsMAT3 res;1697cmsBool IdentityMat;1698cmsPipeline* Dest, *Src;1699cmsFloat64Number* Offset;17001701// Only works on RGB to RGB1702if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;17031704// Only works on 8 bit input1705if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;17061707// Seems suitable, proceed1708Src = *Lut;17091710// Check for:1711//1712// shaper-matrix-matrix-shaper1713// shaper-matrix-shaper1714//1715// Both of those constructs are possible (first because abs. colorimetric).1716// additionally, In the first case, the input matrix offset should be zero.17171718IdentityMat = FALSE;1719if (cmsPipelineCheckAndRetreiveStages(Src, 4,1720cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,1721&Curve1, &Matrix1, &Matrix2, &Curve2)) {17221723// Get both matrices1724_cmsStageMatrixData* Data1 = (_cmsStageMatrixData*)cmsStageData(Matrix1);1725_cmsStageMatrixData* Data2 = (_cmsStageMatrixData*)cmsStageData(Matrix2);17261727// Input offset should be zero1728if (Data1->Offset != NULL) return FALSE;17291730// Multiply both matrices to get the result1731_cmsMAT3per(&res, (cmsMAT3*)Data2->Double, (cmsMAT3*)Data1->Double);17321733// Only 2nd matrix has offset, or it is zero1734Offset = Data2->Offset;17351736// Now the result is in res + Data2 -> Offset. Maybe is a plain identity?1737if (_cmsMAT3isIdentity(&res) && Offset == NULL) {17381739// We can get rid of full matrix1740IdentityMat = TRUE;1741}17421743}1744else {17451746if (cmsPipelineCheckAndRetreiveStages(Src, 3,1747cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,1748&Curve1, &Matrix1, &Curve2)) {17491750_cmsStageMatrixData* Data = (_cmsStageMatrixData*)cmsStageData(Matrix1);17511752// Copy the matrix to our result1753memcpy(&res, Data->Double, sizeof(res));17541755// Preserve the Odffset (may be NULL as a zero offset)1756Offset = Data->Offset;17571758if (_cmsMAT3isIdentity(&res) && Offset == NULL) {17591760// We can get rid of full matrix1761IdentityMat = TRUE;1762}1763}1764else1765return FALSE; // Not optimizeable this time17661767}17681769// Allocate an empty LUT1770Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);1771if (!Dest) return FALSE;17721773// Assamble the new LUT1774if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1)))1775goto Error;17761777if (!IdentityMat) {17781779if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest->ContextID, 3, 3, (const cmsFloat64Number*)&res, Offset)))1780goto Error;1781}17821783if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2)))1784goto Error;17851786// If identity on matrix, we can further optimize the curves, so call the join curves routine1787if (IdentityMat) {17881789OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags);1790}1791else {1792_cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1);1793_cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2);17941795// In this particular optimization, cache does not help as it takes more time to deal with1796// the cache that with the pixel handling1797*dwFlags |= cmsFLAGS_NOCACHE;17981799// Setup the optimizarion routines1800SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Offset, mpeC2->TheCurves, OutputFormat);1801}18021803cmsPipelineFree(Src);1804*Lut = Dest;1805return TRUE;1806Error:1807// Leave Src unchanged1808cmsPipelineFree(Dest);1809return FALSE;1810}181118121813// -------------------------------------------------------------------------------------------------------------------------------------1814// Optimization plug-ins18151816// List of optimizations1817typedef struct _cmsOptimizationCollection_st {18181819_cmsOPToptimizeFn OptimizePtr;18201821struct _cmsOptimizationCollection_st *Next;18221823} _cmsOptimizationCollection;182418251826// The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling1827static _cmsOptimizationCollection DefaultOptimization[] = {18281829{ OptimizeByJoiningCurves, &DefaultOptimization[1] },1830{ OptimizeMatrixShaper, &DefaultOptimization[2] },1831{ OptimizeByComputingLinearization, &DefaultOptimization[3] },1832{ OptimizeByResampling, NULL }1833};18341835// The linked list head1836_cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL };183718381839// Duplicates the zone of memory used by the plug-in in the new context1840static1841void DupPluginOptimizationList(struct _cmsContext_struct* ctx,1842const struct _cmsContext_struct* src)1843{1844_cmsOptimizationPluginChunkType newHead = { NULL };1845_cmsOptimizationCollection* entry;1846_cmsOptimizationCollection* Anterior = NULL;1847_cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin];18481849_cmsAssert(ctx != NULL);1850_cmsAssert(head != NULL);18511852// Walk the list copying all nodes1853for (entry = head->OptimizationCollection;1854entry != NULL;1855entry = entry ->Next) {18561857_cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection));18581859if (newEntry == NULL)1860return;18611862// We want to keep the linked list order, so this is a little bit tricky1863newEntry -> Next = NULL;1864if (Anterior)1865Anterior -> Next = newEntry;18661867Anterior = newEntry;18681869if (newHead.OptimizationCollection == NULL)1870newHead.OptimizationCollection = newEntry;1871}18721873ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType));1874}18751876void _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx,1877const struct _cmsContext_struct* src)1878{1879if (src != NULL) {18801881// Copy all linked list1882DupPluginOptimizationList(ctx, src);1883}1884else {1885static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL };1886ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType));1887}1888}188918901891// Register new ways to optimize1892cmsBool _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data)1893{1894cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;1895_cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);1896_cmsOptimizationCollection* fl;18971898if (Data == NULL) {18991900ctx->OptimizationCollection = NULL;1901return TRUE;1902}19031904// Optimizer callback is required1905if (Plugin ->OptimizePtr == NULL) return FALSE;19061907fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection));1908if (fl == NULL) return FALSE;19091910// Copy the parameters1911fl ->OptimizePtr = Plugin ->OptimizePtr;19121913// Keep linked list1914fl ->Next = ctx->OptimizationCollection;19151916// Set the head1917ctx ->OptimizationCollection = fl;19181919// All is ok1920return TRUE;1921}19221923// The entry point for LUT optimization1924cmsBool _cmsOptimizePipeline(cmsContext ContextID,1925cmsPipeline** PtrLut,1926cmsUInt32Number Intent,1927cmsUInt32Number* InputFormat,1928cmsUInt32Number* OutputFormat,1929cmsUInt32Number* dwFlags)1930{1931_cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);1932_cmsOptimizationCollection* Opts;1933cmsBool AnySuccess = FALSE;19341935// A CLUT is being asked, so force this specific optimization1936if (*dwFlags & cmsFLAGS_FORCE_CLUT) {19371938PreOptimize(*PtrLut);1939return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags);1940}19411942// Anything to optimize?1943if ((*PtrLut) ->Elements == NULL) {1944_cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);1945return TRUE;1946}19471948// Try to get rid of identities and trivial conversions.1949AnySuccess = PreOptimize(*PtrLut);19501951// After removal do we end with an identity?1952if ((*PtrLut) ->Elements == NULL) {1953_cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);1954return TRUE;1955}19561957// Do not optimize, keep all precision1958if (*dwFlags & cmsFLAGS_NOOPTIMIZE)1959return FALSE;19601961// Try plug-in optimizations1962for (Opts = ctx->OptimizationCollection;1963Opts != NULL;1964Opts = Opts ->Next) {19651966// If one schema succeeded, we are done1967if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {19681969return TRUE; // Optimized!1970}1971}19721973// Try built-in optimizations1974for (Opts = DefaultOptimization;1975Opts != NULL;1976Opts = Opts ->Next) {19771978if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {19791980return TRUE;1981}1982}19831984// Only simple optimizations succeeded1985return AnySuccess;1986}198719881989199019911992