Path: blob/master/src/java.desktop/share/native/liblcms/cmsopt.c
41149 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));410if (p16->EvalCurveOut16 == NULL)411{412_cmsFree(ContextID, p16);413return NULL;414}415416p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));417if (p16->ParamsCurveOut16 == NULL)418{419420_cmsFree(ContextID, p16->EvalCurveOut16);421_cmsFree(ContextID, p16);422return NULL;423}424425for (i=0; i < nOutputs; i++) {426427if (Out == NULL) {428p16 ->ParamsCurveOut16[i] = NULL;429p16 -> EvalCurveOut16[i] = Eval16nop1D;430}431else {432433p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;434p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;435}436}437438return p16;439}440441442443// Resampling ---------------------------------------------------------------------------------444445#define PRELINEARIZATION_POINTS 4096446447// Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for448// almost any transform. We use floating point precision and then convert from floating point to 16 bits.449static450cmsInt32Number XFormSampler16(CMSREGISTER const cmsUInt16Number In[],451CMSREGISTER cmsUInt16Number Out[],452CMSREGISTER void* Cargo)453{454cmsPipeline* Lut = (cmsPipeline*) Cargo;455cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];456cmsUInt32Number i;457458_cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);459_cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);460461// From 16 bit to floating point462for (i=0; i < Lut ->InputChannels; i++)463InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);464465// Evaluate in floating point466cmsPipelineEvalFloat(InFloat, OutFloat, Lut);467468// Back to 16 bits representation469for (i=0; i < Lut ->OutputChannels; i++)470Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);471472// Always succeed473return TRUE;474}475476// Try to see if the curves of a given MPE are linear477static478cmsBool AllCurvesAreLinear(cmsStage* mpe)479{480cmsToneCurve** Curves;481cmsUInt32Number i, n;482483Curves = _cmsStageGetPtrToCurveSet(mpe);484if (Curves == NULL) return FALSE;485486n = cmsStageOutputChannels(mpe);487488for (i=0; i < n; i++) {489if (!cmsIsToneCurveLinear(Curves[i])) return FALSE;490}491492return TRUE;493}494495// This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose496// is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels497static498cmsBool PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],499cmsUInt32Number nChannelsOut, cmsUInt32Number nChannelsIn)500{501_cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;502cmsInterpParams* p16 = Grid ->Params;503cmsFloat64Number px, py, pz, pw;504int x0, y0, z0, w0;505int i, index;506507if (CLUT -> Type != cmsSigCLutElemType) {508cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage");509return FALSE;510}511512if (nChannelsIn == 4) {513514px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;515py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;516pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;517pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;518519x0 = (int) floor(px);520y0 = (int) floor(py);521z0 = (int) floor(pz);522w0 = (int) floor(pw);523524if (((px - x0) != 0) ||525((py - y0) != 0) ||526((pz - z0) != 0) ||527((pw - w0) != 0)) return FALSE; // Not on exact node528529index = (int) p16 -> opta[3] * x0 +530(int) p16 -> opta[2] * y0 +531(int) p16 -> opta[1] * z0 +532(int) p16 -> opta[0] * w0;533}534else535if (nChannelsIn == 3) {536537px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;538py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;539pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;540541x0 = (int) floor(px);542y0 = (int) floor(py);543z0 = (int) floor(pz);544545if (((px - x0) != 0) ||546((py - y0) != 0) ||547((pz - z0) != 0)) return FALSE; // Not on exact node548549index = (int) p16 -> opta[2] * x0 +550(int) p16 -> opta[1] * y0 +551(int) p16 -> opta[0] * z0;552}553else554if (nChannelsIn == 1) {555556px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;557558x0 = (int) floor(px);559560if (((px - x0) != 0)) return FALSE; // Not on exact node561562index = (int) p16 -> opta[0] * x0;563}564else {565cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);566return FALSE;567}568569for (i = 0; i < (int) nChannelsOut; i++)570Grid->Tab.T[index + i] = Value[i];571572return TRUE;573}574575// Auxiliary, to see if two values are equal or very different576static577cmsBool WhitesAreEqual(cmsUInt32Number n, cmsUInt16Number White1[], cmsUInt16Number White2[] )578{579cmsUInt32Number i;580581for (i=0; i < n; i++) {582583if (abs(White1[i] - White2[i]) > 0xf000) return TRUE; // Values are so extremely different that the fixup should be avoided584if (White1[i] != White2[i]) return FALSE;585}586return TRUE;587}588589590// Locate the node for the white point and fix it to pure white in order to avoid scum dot.591static592cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)593{594cmsUInt16Number *WhitePointIn, *WhitePointOut;595cmsUInt16Number WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];596cmsUInt32Number i, nOuts, nIns;597cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;598599if (!_cmsEndPointsBySpace(EntryColorSpace,600&WhitePointIn, NULL, &nIns)) return FALSE;601602if (!_cmsEndPointsBySpace(ExitColorSpace,603&WhitePointOut, NULL, &nOuts)) return FALSE;604605// It needs to be fixed?606if (Lut ->InputChannels != nIns) return FALSE;607if (Lut ->OutputChannels != nOuts) return FALSE;608609cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut);610611if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match612613// Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations614if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))615if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))616if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))617if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT))618return FALSE;619620// We need to interpolate white points of both, pre and post curves621if (PreLin) {622623cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);624625for (i=0; i < nIns; i++) {626WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]);627}628}629else {630for (i=0; i < nIns; i++)631WhiteIn[i] = WhitePointIn[i];632}633634// If any post-linearization, we need to find how is represented white before the curve, do635// a reverse interpolation in this case.636if (PostLin) {637638cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);639640for (i=0; i < nOuts; i++) {641642cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);643if (InversePostLin == NULL) {644WhiteOut[i] = WhitePointOut[i];645646} else {647648WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);649cmsFreeToneCurve(InversePostLin);650}651}652}653else {654for (i=0; i < nOuts; i++)655WhiteOut[i] = WhitePointOut[i];656}657658// Ok, proceed with patching. May fail and we don't care if it fails659PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns);660661return TRUE;662}663664// -----------------------------------------------------------------------------------------------------------------------------------------------665// This function creates simple LUT from complex ones. The generated LUT has an optional set of666// prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.667// These curves have to exist in the original LUT in order to be used in the simplified output.668// Caller may also use the flags to allow this feature.669// LUTS with all curves will be simplified to a single curve. Parametric curves are lost.670// This function should be used on 16-bits LUTS only, as floating point losses precision when simplified671// -----------------------------------------------------------------------------------------------------------------------------------------------672673static674cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)675{676cmsPipeline* Src = NULL;677cmsPipeline* Dest = NULL;678cmsStage* mpe;679cmsStage* CLUT;680cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;681cmsUInt32Number nGridPoints;682cmsColorSpaceSignature ColorSpace, OutputColorSpace;683cmsStage *NewPreLin = NULL;684cmsStage *NewPostLin = NULL;685_cmsStageCLutData* DataCLUT;686cmsToneCurve** DataSetIn;687cmsToneCurve** DataSetOut;688Prelin16Data* p16;689690// This is a lossy optimization! does not apply in floating-point cases691if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;692693ColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*InputFormat));694OutputColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*OutputFormat));695696// Color space must be specified697if (ColorSpace == (cmsColorSpaceSignature)0 ||698OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;699700nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);701702// For empty LUTs, 2 points are enough703if (cmsPipelineStageCount(*Lut) == 0)704nGridPoints = 2;705706Src = *Lut;707708// Named color pipelines cannot be optimized either709for (mpe = cmsPipelineGetPtrToFirstStage(Src);710mpe != NULL;711mpe = cmsStageNext(mpe)) {712if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;713}714715// Allocate an empty LUT716Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);717if (!Dest) return FALSE;718719// Prelinearization tables are kept unless indicated by flags720if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {721722// Get a pointer to the prelinearization element723cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);724725// Check if suitable726if (PreLin && PreLin ->Type == cmsSigCurveSetElemType) {727728// Maybe this is a linear tram, so we can avoid the whole stuff729if (!AllCurvesAreLinear(PreLin)) {730731// All seems ok, proceed.732NewPreLin = cmsStageDup(PreLin);733if(!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin))734goto Error;735736// Remove prelinearization. Since we have duplicated the curve737// in destination LUT, the sampling should be applied after this stage.738cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin);739}740}741}742743// Allocate the CLUT744CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);745if (CLUT == NULL) goto Error;746747// Add the CLUT to the destination LUT748if (!cmsPipelineInsertStage(Dest, cmsAT_END, CLUT)) {749goto Error;750}751752// Postlinearization tables are kept unless indicated by flags753if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {754755// Get a pointer to the postlinearization if present756cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);757758// Check if suitable759if (PostLin && cmsStageType(PostLin) == cmsSigCurveSetElemType) {760761// Maybe this is a linear tram, so we can avoid the whole stuff762if (!AllCurvesAreLinear(PostLin)) {763764// All seems ok, proceed.765NewPostLin = cmsStageDup(PostLin);766if (!cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin))767goto Error;768769// In destination LUT, the sampling should be applied after this stage.770cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);771}772}773}774775// Now its time to do the sampling. We have to ignore pre/post linearization776// The source LUT without pre/post curves is passed as parameter.777if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {778Error:779// Ops, something went wrong, Restore stages780if (KeepPreLin != NULL) {781if (!cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin)) {782_cmsAssert(0); // This never happens783}784}785if (KeepPostLin != NULL) {786if (!cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin)) {787_cmsAssert(0); // This never happens788}789}790cmsPipelineFree(Dest);791return FALSE;792}793794// Done.795796if (KeepPreLin != NULL) cmsStageFree(KeepPreLin);797if (KeepPostLin != NULL) cmsStageFree(KeepPostLin);798cmsPipelineFree(Src);799800DataCLUT = (_cmsStageCLutData*) CLUT ->Data;801802if (NewPreLin == NULL) DataSetIn = NULL;803else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;804805if (NewPostLin == NULL) DataSetOut = NULL;806else DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;807808809if (DataSetIn == NULL && DataSetOut == NULL) {810811_cmsPipelineSetOptimizationParameters(Dest, (_cmsPipelineEval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);812}813else {814815p16 = PrelinOpt16alloc(Dest ->ContextID,816DataCLUT ->Params,817Dest ->InputChannels,818DataSetIn,819Dest ->OutputChannels,820DataSetOut);821822_cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);823}824825826// Don't fix white on absolute colorimetric827if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)828*dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;829830if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {831832FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace);833}834835*Lut = Dest;836return TRUE;837838cmsUNUSED_PARAMETER(Intent);839}840841842// -----------------------------------------------------------------------------------------------------------------------------------------------843// Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on844// Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works845// for RGB transforms. See the paper for more details846// -----------------------------------------------------------------------------------------------------------------------------------------------847848849// Normalize endpoints by slope limiting max and min. This assures endpoints as well.850// Descending curves are handled as well.851static852void SlopeLimiting(cmsToneCurve* g)853{854int BeginVal, EndVal;855int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5); // Cutoff at 2%856int AtEnd = (int) g ->nEntries - AtBegin - 1; // And 98%857cmsFloat64Number Val, Slope, beta;858int i;859860if (cmsIsToneCurveDescending(g)) {861BeginVal = 0xffff; EndVal = 0;862}863else {864BeginVal = 0; EndVal = 0xffff;865}866867// Compute slope and offset for begin of curve868Val = g ->Table16[AtBegin];869Slope = (Val - BeginVal) / AtBegin;870beta = Val - Slope * AtBegin;871872for (i=0; i < AtBegin; i++)873g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);874875// Compute slope and offset for the end876Val = g ->Table16[AtEnd];877Slope = (EndVal - Val) / AtBegin; // AtBegin holds the X interval, which is same in both cases878beta = Val - Slope * AtEnd;879880for (i = AtEnd; i < (int) g ->nEntries; i++)881g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);882}883884885// Precomputes tables for 8-bit on input devicelink.886static887Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])888{889int i;890cmsUInt16Number Input[3];891cmsS15Fixed16Number v1, v2, v3;892Prelin8Data* p8;893894p8 = (Prelin8Data*)_cmsMallocZero(ContextID, sizeof(Prelin8Data));895if (p8 == NULL) return NULL;896897// Since this only works for 8 bit input, values comes always as x * 257,898// we can safely take msb byte (x << 8 + x)899900for (i=0; i < 256; i++) {901902if (G != NULL) {903904// Get 16-bit representation905Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i));906Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i));907Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i));908}909else {910Input[0] = FROM_8_TO_16(i);911Input[1] = FROM_8_TO_16(i);912Input[2] = FROM_8_TO_16(i);913}914915916// Move to 0..1.0 in fixed domain917v1 = _cmsToFixedDomain((int) (Input[0] * p -> Domain[0]));918v2 = _cmsToFixedDomain((int) (Input[1] * p -> Domain[1]));919v3 = _cmsToFixedDomain((int) (Input[2] * p -> Domain[2]));920921// Store the precalculated table of nodes922p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));923p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));924p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));925926// Store the precalculated table of offsets927p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);928p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);929p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);930}931932p8 ->ContextID = ContextID;933p8 ->p = p;934935return p8;936}937938static939void Prelin8free(cmsContext ContextID, void* ptr)940{941_cmsFree(ContextID, ptr);942}943944static945void* Prelin8dup(cmsContext ContextID, const void* ptr)946{947return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));948}949950951952// A optimized interpolation for 8-bit input.953#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])954static CMS_NO_SANITIZE955void PrelinEval8(CMSREGISTER const cmsUInt16Number Input[],956CMSREGISTER cmsUInt16Number Output[],957CMSREGISTER const void* D)958{959960cmsUInt8Number r, g, b;961cmsS15Fixed16Number rx, ry, rz;962cmsS15Fixed16Number c0, c1, c2, c3, Rest;963int OutChan;964CMSREGISTER cmsS15Fixed16Number X0, X1, Y0, Y1, Z0, Z1;965Prelin8Data* p8 = (Prelin8Data*) D;966CMSREGISTER const cmsInterpParams* p = p8 ->p;967int TotalOut = (int) p -> nOutputs;968const cmsUInt16Number* LutTable = (const cmsUInt16Number*) p->Table;969970r = (cmsUInt8Number) (Input[0] >> 8);971g = (cmsUInt8Number) (Input[1] >> 8);972b = (cmsUInt8Number) (Input[2] >> 8);973974X0 = (cmsS15Fixed16Number) p8->X0[r];975Y0 = (cmsS15Fixed16Number) p8->Y0[g];976Z0 = (cmsS15Fixed16Number) p8->Z0[b];977978rx = p8 ->rx[r];979ry = p8 ->ry[g];980rz = p8 ->rz[b];981982X1 = X0 + (cmsS15Fixed16Number)((rx == 0) ? 0 : p ->opta[2]);983Y1 = Y0 + (cmsS15Fixed16Number)((ry == 0) ? 0 : p ->opta[1]);984Z1 = Z0 + (cmsS15Fixed16Number)((rz == 0) ? 0 : p ->opta[0]);985986987// These are the 6 Tetrahedral988for (OutChan=0; OutChan < TotalOut; OutChan++) {989990c0 = DENS(X0, Y0, Z0);991992if (rx >= ry && ry >= rz)993{994c1 = DENS(X1, Y0, Z0) - c0;995c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);996c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);997}998else999if (rx >= rz && rz >= ry)1000{1001c1 = DENS(X1, Y0, Z0) - c0;1002c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);1003c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);1004}1005else1006if (rz >= rx && rx >= ry)1007{1008c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);1009c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);1010c3 = DENS(X0, Y0, Z1) - c0;1011}1012else1013if (ry >= rx && rx >= rz)1014{1015c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);1016c2 = DENS(X0, Y1, Z0) - c0;1017c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);1018}1019else1020if (ry >= rz && rz >= rx)1021{1022c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);1023c2 = DENS(X0, Y1, Z0) - c0;1024c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);1025}1026else1027if (rz >= ry && ry >= rx)1028{1029c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);1030c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);1031c3 = DENS(X0, Y0, Z1) - c0;1032}1033else {1034c1 = c2 = c3 = 0;1035}10361037Rest = c1 * rx + c2 * ry + c3 * rz + 0x8001;1038Output[OutChan] = (cmsUInt16Number) (c0 + ((Rest + (Rest >> 16)) >> 16));10391040}1041}10421043#undef DENS104410451046// Curves that contain wide empty areas are not optimizeable1047static1048cmsBool IsDegenerated(const cmsToneCurve* g)1049{1050cmsUInt32Number i, Zeros = 0, Poles = 0;1051cmsUInt32Number nEntries = g ->nEntries;10521053for (i=0; i < nEntries; i++) {10541055if (g ->Table16[i] == 0x0000) Zeros++;1056if (g ->Table16[i] == 0xffff) Poles++;1057}10581059if (Zeros == 1 && Poles == 1) return FALSE; // For linear tables1060if (Zeros > (nEntries / 20)) return TRUE; // Degenerated, many zeros1061if (Poles > (nEntries / 20)) return TRUE; // Degenerated, many poles10621063return FALSE;1064}10651066// --------------------------------------------------------------------------------------------------------------1067// We need xput over here10681069static1070cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)1071{1072cmsPipeline* OriginalLut;1073cmsUInt32Number nGridPoints;1074cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];1075cmsUInt32Number t, i;1076cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];1077cmsBool lIsSuitable, lIsLinear;1078cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;1079cmsStage* OptimizedCLUTmpe;1080cmsColorSpaceSignature ColorSpace, OutputColorSpace;1081cmsStage* OptimizedPrelinMpe;1082cmsStage* mpe;1083cmsToneCurve** OptimizedPrelinCurves;1084_cmsStageCLutData* OptimizedPrelinCLUT;108510861087// This is a lossy optimization! does not apply in floating-point cases1088if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;10891090// Only on chunky RGB1091if (T_COLORSPACE(*InputFormat) != PT_RGB) return FALSE;1092if (T_PLANAR(*InputFormat)) return FALSE;10931094if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;1095if (T_PLANAR(*OutputFormat)) return FALSE;10961097// On 16 bits, user has to specify the feature1098if (!_cmsFormatterIs8bit(*InputFormat)) {1099if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;1100}11011102OriginalLut = *Lut;11031104// Named color pipelines cannot be optimized either1105for (mpe = cmsPipelineGetPtrToFirstStage(OriginalLut);1106mpe != NULL;1107mpe = cmsStageNext(mpe)) {1108if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;1109}11101111ColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*InputFormat));1112OutputColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*OutputFormat));11131114// Color space must be specified1115if (ColorSpace == (cmsColorSpaceSignature)0 ||1116OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;11171118nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);11191120// Empty gamma containers1121memset(Trans, 0, sizeof(Trans));1122memset(TransReverse, 0, sizeof(TransReverse));11231124// If the last stage of the original lut are curves, and those curves are1125// degenerated, it is likely the transform is squeezing and clipping1126// the output from previous CLUT. We cannot optimize this case1127{1128cmsStage* last = cmsPipelineGetPtrToLastStage(OriginalLut);11291130if (last == NULL) goto Error;1131if (cmsStageType(last) == cmsSigCurveSetElemType) {11321133_cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*)cmsStageData(last);1134for (i = 0; i < Data->nCurves; i++) {1135if (IsDegenerated(Data->TheCurves[i]))1136goto Error;1137}1138}1139}11401141for (t = 0; t < OriginalLut ->InputChannels; t++) {1142Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);1143if (Trans[t] == NULL) goto Error;1144}11451146// Populate the curves1147for (i=0; i < PRELINEARIZATION_POINTS; i++) {11481149v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));11501151// Feed input with a gray ramp1152for (t=0; t < OriginalLut ->InputChannels; t++)1153In[t] = v;11541155// Evaluate the gray value1156cmsPipelineEvalFloat(In, Out, OriginalLut);11571158// Store result in curve1159for (t=0; t < OriginalLut ->InputChannels; t++)1160Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);1161}11621163// Slope-limit the obtained curves1164for (t = 0; t < OriginalLut ->InputChannels; t++)1165SlopeLimiting(Trans[t]);11661167// Check for validity1168lIsSuitable = TRUE;1169lIsLinear = TRUE;1170for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {11711172// Exclude if already linear1173if (!cmsIsToneCurveLinear(Trans[t]))1174lIsLinear = FALSE;11751176// Exclude if non-monotonic1177if (!cmsIsToneCurveMonotonic(Trans[t]))1178lIsSuitable = FALSE;11791180if (IsDegenerated(Trans[t]))1181lIsSuitable = FALSE;1182}11831184// If it is not suitable, just quit1185if (!lIsSuitable) goto Error;11861187// Invert curves if possible1188for (t = 0; t < OriginalLut ->InputChannels; t++) {1189TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]);1190if (TransReverse[t] == NULL) goto Error;1191}11921193// Now inset the reversed curves at the begin of transform1194LutPlusCurves = cmsPipelineDup(OriginalLut);1195if (LutPlusCurves == NULL) goto Error;11961197if (!cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse)))1198goto Error;11991200// Create the result LUT1201OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);1202if (OptimizedLUT == NULL) goto Error;12031204OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);12051206// Create and insert the curves at the beginning1207if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe))1208goto Error;12091210// Allocate the CLUT for result1211OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);12121213// Add the CLUT to the destination LUT1214if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe))1215goto Error;12161217// Resample the LUT1218if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;12191220// Free resources1221for (t = 0; t < OriginalLut ->InputChannels; t++) {12221223if (Trans[t]) cmsFreeToneCurve(Trans[t]);1224if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);1225}12261227cmsPipelineFree(LutPlusCurves);122812291230OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);1231OptimizedPrelinCLUT = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;12321233// Set the evaluator if 8-bit1234if (_cmsFormatterIs8bit(*InputFormat)) {12351236Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID,1237OptimizedPrelinCLUT ->Params,1238OptimizedPrelinCurves);1239if (p8 == NULL) return FALSE;12401241_cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);12421243}1244else1245{1246Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID,1247OptimizedPrelinCLUT ->Params,12483, OptimizedPrelinCurves, 3, NULL);1249if (p16 == NULL) return FALSE;12501251_cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);12521253}12541255// Don't fix white on absolute colorimetric1256if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)1257*dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;12581259if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {12601261if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) {12621263return FALSE;1264}1265}12661267// And return the obtained LUT12681269cmsPipelineFree(OriginalLut);1270*Lut = OptimizedLUT;1271return TRUE;12721273Error:12741275for (t = 0; t < OriginalLut ->InputChannels; t++) {12761277if (Trans[t]) cmsFreeToneCurve(Trans[t]);1278if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);1279}12801281if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves);1282if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT);12831284return FALSE;12851286cmsUNUSED_PARAMETER(Intent);1287cmsUNUSED_PARAMETER(lIsLinear);1288}128912901291// Curves optimizer ------------------------------------------------------------------------------------------------------------------12921293static1294void CurvesFree(cmsContext ContextID, void* ptr)1295{1296Curves16Data* Data = (Curves16Data*) ptr;1297cmsUInt32Number i;12981299for (i=0; i < Data -> nCurves; i++) {13001301_cmsFree(ContextID, Data ->Curves[i]);1302}13031304_cmsFree(ContextID, Data ->Curves);1305_cmsFree(ContextID, ptr);1306}13071308static1309void* CurvesDup(cmsContext ContextID, const void* ptr)1310{1311Curves16Data* Data = (Curves16Data*)_cmsDupMem(ContextID, ptr, sizeof(Curves16Data));1312cmsUInt32Number i;13131314if (Data == NULL) return NULL;13151316Data->Curves = (cmsUInt16Number**) _cmsDupMem(ContextID, Data->Curves, Data->nCurves * sizeof(cmsUInt16Number*));13171318for (i=0; i < Data -> nCurves; i++) {1319Data->Curves[i] = (cmsUInt16Number*) _cmsDupMem(ContextID, Data->Curves[i], Data->nElements * sizeof(cmsUInt16Number));1320}13211322return (void*) Data;1323}13241325// Precomputes tables for 8-bit on input devicelink.1326static1327Curves16Data* CurvesAlloc(cmsContext ContextID, cmsUInt32Number nCurves, cmsUInt32Number nElements, cmsToneCurve** G)1328{1329cmsUInt32Number i, j;1330Curves16Data* c16;13311332c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));1333if (c16 == NULL) return NULL;13341335c16 ->nCurves = nCurves;1336c16 ->nElements = nElements;13371338c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));1339if (c16->Curves == NULL) {1340_cmsFree(ContextID, c16);1341return NULL;1342}13431344for (i=0; i < nCurves; i++) {13451346c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));13471348if (c16->Curves[i] == NULL) {13491350for (j=0; j < i; j++) {1351_cmsFree(ContextID, c16->Curves[j]);1352}1353_cmsFree(ContextID, c16->Curves);1354_cmsFree(ContextID, c16);1355return NULL;1356}13571358if (nElements == 256U) {13591360for (j=0; j < nElements; j++) {13611362c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));1363}1364}1365else {13661367for (j=0; j < nElements; j++) {1368c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);1369}1370}1371}13721373return c16;1374}13751376static1377void FastEvaluateCurves8(CMSREGISTER const cmsUInt16Number In[],1378CMSREGISTER cmsUInt16Number Out[],1379CMSREGISTER const void* D)1380{1381Curves16Data* Data = (Curves16Data*) D;1382int x;1383cmsUInt32Number i;13841385for (i=0; i < Data ->nCurves; i++) {13861387x = (In[i] >> 8);1388Out[i] = Data -> Curves[i][x];1389}1390}139113921393static1394void FastEvaluateCurves16(CMSREGISTER const cmsUInt16Number In[],1395CMSREGISTER cmsUInt16Number Out[],1396CMSREGISTER const void* D)1397{1398Curves16Data* Data = (Curves16Data*) D;1399cmsUInt32Number i;14001401for (i=0; i < Data ->nCurves; i++) {1402Out[i] = Data -> Curves[i][In[i]];1403}1404}140514061407static1408void FastIdentity16(CMSREGISTER const cmsUInt16Number In[],1409CMSREGISTER cmsUInt16Number Out[],1410CMSREGISTER const void* D)1411{1412cmsPipeline* Lut = (cmsPipeline*) D;1413cmsUInt32Number i;14141415for (i=0; i < Lut ->InputChannels; i++) {1416Out[i] = In[i];1417}1418}141914201421// If the target LUT holds only curves, the optimization procedure is to join all those1422// curves together. That only works on curves and does not work on matrices.1423static1424cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)1425{1426cmsToneCurve** GammaTables = NULL;1427cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];1428cmsUInt32Number i, j;1429cmsPipeline* Src = *Lut;1430cmsPipeline* Dest = NULL;1431cmsStage* mpe;1432cmsStage* ObtainedCurves = NULL;143314341435// This is a lossy optimization! does not apply in floating-point cases1436if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;14371438// Only curves in this LUT?1439for (mpe = cmsPipelineGetPtrToFirstStage(Src);1440mpe != NULL;1441mpe = cmsStageNext(mpe)) {1442if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE;1443}14441445// Allocate an empty LUT1446Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);1447if (Dest == NULL) return FALSE;14481449// Create target curves1450GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));1451if (GammaTables == NULL) goto Error;14521453for (i=0; i < Src ->InputChannels; i++) {1454GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL);1455if (GammaTables[i] == NULL) goto Error;1456}14571458// Compute 16 bit result by using floating point1459for (i=0; i < PRELINEARIZATION_POINTS; i++) {14601461for (j=0; j < Src ->InputChannels; j++)1462InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));14631464cmsPipelineEvalFloat(InFloat, OutFloat, Src);14651466for (j=0; j < Src ->InputChannels; j++)1467GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);1468}14691470ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables);1471if (ObtainedCurves == NULL) goto Error;14721473for (i=0; i < Src ->InputChannels; i++) {1474cmsFreeToneCurve(GammaTables[i]);1475GammaTables[i] = NULL;1476}14771478if (GammaTables != NULL) {1479_cmsFree(Src->ContextID, GammaTables);1480GammaTables = NULL;1481}14821483// Maybe the curves are linear at the end1484if (!AllCurvesAreLinear(ObtainedCurves)) {1485_cmsStageToneCurvesData* Data;14861487if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves))1488goto Error;1489Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);1490ObtainedCurves = NULL;14911492// If the curves are to be applied in 8 bits, we can save memory1493if (_cmsFormatterIs8bit(*InputFormat)) {1494Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);14951496if (c16 == NULL) goto Error;1497*dwFlags |= cmsFLAGS_NOCACHE;1498_cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);14991500}1501else {1502Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);15031504if (c16 == NULL) goto Error;1505*dwFlags |= cmsFLAGS_NOCACHE;1506_cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);1507}1508}1509else {15101511// LUT optimizes to nothing. Set the identity LUT1512cmsStageFree(ObtainedCurves);1513ObtainedCurves = NULL;15141515if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels)))1516goto Error;15171518*dwFlags |= cmsFLAGS_NOCACHE;1519_cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);1520}15211522// We are done.1523cmsPipelineFree(Src);1524*Lut = Dest;1525return TRUE;15261527Error:15281529if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves);1530if (GammaTables != NULL) {1531for (i=0; i < Src ->InputChannels; i++) {1532if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]);1533}15341535_cmsFree(Src ->ContextID, GammaTables);1536}15371538if (Dest != NULL) cmsPipelineFree(Dest);1539return FALSE;15401541cmsUNUSED_PARAMETER(Intent);1542cmsUNUSED_PARAMETER(InputFormat);1543cmsUNUSED_PARAMETER(OutputFormat);1544cmsUNUSED_PARAMETER(dwFlags);1545}15461547// -------------------------------------------------------------------------------------------------------------------------------------1548// LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles154915501551static1552void FreeMatShaper(cmsContext ContextID, void* Data)1553{1554if (Data != NULL) _cmsFree(ContextID, Data);1555}15561557static1558void* DupMatShaper(cmsContext ContextID, const void* Data)1559{1560return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));1561}156215631564// A fast matrix-shaper evaluator for 8 bits. This is a bit ticky since I'm using 1.14 signed fixed point1565// to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,1566// in total about 50K, and the performance boost is huge!1567static1568void MatShaperEval16(CMSREGISTER const cmsUInt16Number In[],1569CMSREGISTER cmsUInt16Number Out[],1570CMSREGISTER const void* D)1571{1572MatShaper8Data* p = (MatShaper8Data*) D;1573cmsS1Fixed14Number l1, l2, l3, r, g, b;1574cmsUInt32Number ri, gi, bi;15751576// In this case (and only in this case!) we can use this simplification since1577// In[] is assured to come from a 8 bit number. (a << 8 | a)1578ri = In[0] & 0xFFU;1579gi = In[1] & 0xFFU;1580bi = In[2] & 0xFFU;15811582// Across first shaper, which also converts to 1.14 fixed point1583r = p->Shaper1R[ri];1584g = p->Shaper1G[gi];1585b = p->Shaper1B[bi];15861587// Evaluate the matrix in 1.14 fixed point1588l1 = (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;1589l2 = (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;1590l3 = (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;15911592// Now we have to clip to 0..1.0 range1593ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384U : (cmsUInt32Number) l1);1594gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384U : (cmsUInt32Number) l2);1595bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384U : (cmsUInt32Number) l3);15961597// And across second shaper,1598Out[0] = p->Shaper2R[ri];1599Out[1] = p->Shaper2G[gi];1600Out[2] = p->Shaper2B[bi];16011602}16031604// This table converts from 8 bits to 1.14 after applying the curve1605static1606void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve)1607{1608int i;1609cmsFloat32Number R, y;16101611for (i=0; i < 256; i++) {16121613R = (cmsFloat32Number) (i / 255.0);1614y = cmsEvalToneCurveFloat(Curve, R);16151616if (y < 131072.0)1617Table[i] = DOUBLE_TO_1FIXED14(y);1618else1619Table[i] = 0x7fffffff;1620}1621}16221623// This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve1624static1625void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)1626{1627int i;1628cmsFloat32Number R, Val;16291630for (i=0; i < 16385; i++) {16311632R = (cmsFloat32Number) (i / 16384.0);1633Val = cmsEvalToneCurveFloat(Curve, R); // Val comes 0..1.016341635if (Val < 0)1636Val = 0;16371638if (Val > 1.0)1639Val = 1.0;16401641if (Is8BitsOutput) {16421643// If 8 bits output, we can optimize further by computing the / 257 part.1644// first we compute the resulting byte and then we store the byte times1645// 257. This quantization allows to round very quick by doing a >> 8, but1646// since the low byte is always equal to msb, we can do a & 0xff and this works!1647cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0);1648cmsUInt8Number b = FROM_16_TO_8(w);16491650Table[i] = FROM_8_TO_16(b);1651}1652else Table[i] = _cmsQuickSaturateWord(Val * 65535.0);1653}1654}16551656// Compute the matrix-shaper structure1657static1658cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)1659{1660MatShaper8Data* p;1661int i, j;1662cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);16631664// Allocate a big chuck of memory to store precomputed tables1665p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));1666if (p == NULL) return FALSE;16671668p -> ContextID = Dest -> ContextID;16691670// Precompute tables1671FillFirstShaper(p ->Shaper1R, Curve1[0]);1672FillFirstShaper(p ->Shaper1G, Curve1[1]);1673FillFirstShaper(p ->Shaper1B, Curve1[2]);16741675FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits);1676FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits);1677FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits);16781679// Convert matrix to nFixed14. Note that those values may take more than 16 bits1680for (i=0; i < 3; i++) {1681for (j=0; j < 3; j++) {1682p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);1683}1684}16851686for (i=0; i < 3; i++) {16871688if (Off == NULL) {1689p ->Off[i] = 0;1690}1691else {1692p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);1693}1694}16951696// Mark as optimized for faster formatter1697if (Is8Bits)1698*OutputFormat |= OPTIMIZED_SH(1);16991700// Fill function pointers1701_cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);1702return TRUE;1703}17041705// 8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!1706static1707cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)1708{1709cmsStage* Curve1, *Curve2;1710cmsStage* Matrix1, *Matrix2;1711cmsMAT3 res;1712cmsBool IdentityMat;1713cmsPipeline* Dest, *Src;1714cmsFloat64Number* Offset;17151716// Only works on RGB to RGB1717if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;17181719// Only works on 8 bit input1720if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;17211722// Seems suitable, proceed1723Src = *Lut;17241725// Check for:1726//1727// shaper-matrix-matrix-shaper1728// shaper-matrix-shaper1729//1730// Both of those constructs are possible (first because abs. colorimetric).1731// additionally, In the first case, the input matrix offset should be zero.17321733IdentityMat = FALSE;1734if (cmsPipelineCheckAndRetreiveStages(Src, 4,1735cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,1736&Curve1, &Matrix1, &Matrix2, &Curve2)) {17371738// Get both matrices1739_cmsStageMatrixData* Data1 = (_cmsStageMatrixData*)cmsStageData(Matrix1);1740_cmsStageMatrixData* Data2 = (_cmsStageMatrixData*)cmsStageData(Matrix2);17411742// Input offset should be zero1743if (Data1->Offset != NULL) return FALSE;17441745// Multiply both matrices to get the result1746_cmsMAT3per(&res, (cmsMAT3*)Data2->Double, (cmsMAT3*)Data1->Double);17471748// Only 2nd matrix has offset, or it is zero1749Offset = Data2->Offset;17501751// Now the result is in res + Data2 -> Offset. Maybe is a plain identity?1752if (_cmsMAT3isIdentity(&res) && Offset == NULL) {17531754// We can get rid of full matrix1755IdentityMat = TRUE;1756}17571758}1759else {17601761if (cmsPipelineCheckAndRetreiveStages(Src, 3,1762cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,1763&Curve1, &Matrix1, &Curve2)) {17641765_cmsStageMatrixData* Data = (_cmsStageMatrixData*)cmsStageData(Matrix1);17661767// Copy the matrix to our result1768memcpy(&res, Data->Double, sizeof(res));17691770// Preserve the Odffset (may be NULL as a zero offset)1771Offset = Data->Offset;17721773if (_cmsMAT3isIdentity(&res) && Offset == NULL) {17741775// We can get rid of full matrix1776IdentityMat = TRUE;1777}1778}1779else1780return FALSE; // Not optimizeable this time17811782}17831784// Allocate an empty LUT1785Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);1786if (!Dest) return FALSE;17871788// Assamble the new LUT1789if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1)))1790goto Error;17911792if (!IdentityMat) {17931794if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest->ContextID, 3, 3, (const cmsFloat64Number*)&res, Offset)))1795goto Error;1796}17971798if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2)))1799goto Error;18001801// If identity on matrix, we can further optimize the curves, so call the join curves routine1802if (IdentityMat) {18031804OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags);1805}1806else {1807_cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1);1808_cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2);18091810// In this particular optimization, cache does not help as it takes more time to deal with1811// the cache that with the pixel handling1812*dwFlags |= cmsFLAGS_NOCACHE;18131814// Setup the optimizarion routines1815SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Offset, mpeC2->TheCurves, OutputFormat);1816}18171818cmsPipelineFree(Src);1819*Lut = Dest;1820return TRUE;1821Error:1822// Leave Src unchanged1823cmsPipelineFree(Dest);1824return FALSE;1825}182618271828// -------------------------------------------------------------------------------------------------------------------------------------1829// Optimization plug-ins18301831// List of optimizations1832typedef struct _cmsOptimizationCollection_st {18331834_cmsOPToptimizeFn OptimizePtr;18351836struct _cmsOptimizationCollection_st *Next;18371838} _cmsOptimizationCollection;183918401841// The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling1842static _cmsOptimizationCollection DefaultOptimization[] = {18431844{ OptimizeByJoiningCurves, &DefaultOptimization[1] },1845{ OptimizeMatrixShaper, &DefaultOptimization[2] },1846{ OptimizeByComputingLinearization, &DefaultOptimization[3] },1847{ OptimizeByResampling, NULL }1848};18491850// The linked list head1851_cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL };185218531854// Duplicates the zone of memory used by the plug-in in the new context1855static1856void DupPluginOptimizationList(struct _cmsContext_struct* ctx,1857const struct _cmsContext_struct* src)1858{1859_cmsOptimizationPluginChunkType newHead = { NULL };1860_cmsOptimizationCollection* entry;1861_cmsOptimizationCollection* Anterior = NULL;1862_cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin];18631864_cmsAssert(ctx != NULL);1865_cmsAssert(head != NULL);18661867// Walk the list copying all nodes1868for (entry = head->OptimizationCollection;1869entry != NULL;1870entry = entry ->Next) {18711872_cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection));18731874if (newEntry == NULL)1875return;18761877// We want to keep the linked list order, so this is a little bit tricky1878newEntry -> Next = NULL;1879if (Anterior)1880Anterior -> Next = newEntry;18811882Anterior = newEntry;18831884if (newHead.OptimizationCollection == NULL)1885newHead.OptimizationCollection = newEntry;1886}18871888ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType));1889}18901891void _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx,1892const struct _cmsContext_struct* src)1893{1894if (src != NULL) {18951896// Copy all linked list1897DupPluginOptimizationList(ctx, src);1898}1899else {1900static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL };1901ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType));1902}1903}190419051906// Register new ways to optimize1907cmsBool _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data)1908{1909cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;1910_cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);1911_cmsOptimizationCollection* fl;19121913if (Data == NULL) {19141915ctx->OptimizationCollection = NULL;1916return TRUE;1917}19181919// Optimizer callback is required1920if (Plugin ->OptimizePtr == NULL) return FALSE;19211922fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection));1923if (fl == NULL) return FALSE;19241925// Copy the parameters1926fl ->OptimizePtr = Plugin ->OptimizePtr;19271928// Keep linked list1929fl ->Next = ctx->OptimizationCollection;19301931// Set the head1932ctx ->OptimizationCollection = fl;19331934// All is ok1935return TRUE;1936}19371938// The entry point for LUT optimization1939cmsBool CMSEXPORT _cmsOptimizePipeline(cmsContext ContextID,1940cmsPipeline** PtrLut,1941cmsUInt32Number Intent,1942cmsUInt32Number* InputFormat,1943cmsUInt32Number* OutputFormat,1944cmsUInt32Number* dwFlags)1945{1946_cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);1947_cmsOptimizationCollection* Opts;1948cmsBool AnySuccess = FALSE;19491950// A CLUT is being asked, so force this specific optimization1951if (*dwFlags & cmsFLAGS_FORCE_CLUT) {19521953PreOptimize(*PtrLut);1954return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags);1955}19561957// Anything to optimize?1958if ((*PtrLut) ->Elements == NULL) {1959_cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);1960return TRUE;1961}19621963// Try to get rid of identities and trivial conversions.1964AnySuccess = PreOptimize(*PtrLut);19651966// After removal do we end with an identity?1967if ((*PtrLut) ->Elements == NULL) {1968_cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);1969return TRUE;1970}19711972// Do not optimize, keep all precision1973if (*dwFlags & cmsFLAGS_NOOPTIMIZE)1974return FALSE;19751976// Try plug-in optimizations1977for (Opts = ctx->OptimizationCollection;1978Opts != NULL;1979Opts = Opts ->Next) {19801981// If one schema succeeded, we are done1982if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {19831984return TRUE; // Optimized!1985}1986}19871988// Try built-in optimizations1989for (Opts = DefaultOptimization;1990Opts != NULL;1991Opts = Opts ->Next) {19921993if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {19941995return TRUE;1996}1997}19981999// Only simple optimizations succeeded2000return AnySuccess;2001}200220032004200520062007