1 //---------------------------------------------------------------------------------
3 // Little Color Management System
4 // Copyright (c) 1998-2023 Marti Maria Saguer
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 //---------------------------------------------------------------------------------
27 #include "lcms2_internal.h"
30 //----------------------------------------------------------------------------------
32 // Optimization for 8 bits, Shaper-CLUT (3 inputs only)
37 const cmsInterpParams* p; // Tetrahedrical interpolation parameters. This is a not-owned pointer.
39 cmsUInt16Number rx[256], ry[256], rz[256];
40 cmsUInt32Number X0[256], Y0[256], Z0[256]; // Precomputed nodes and offsets for 8-bit input data
46 // Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs)
52 cmsUInt32Number nInputs;
53 cmsUInt32Number nOutputs;
55 _cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS]; // The maximum number of input channels is known in advance
56 cmsInterpParams* ParamsCurveIn16[MAX_INPUT_DIMENSIONS];
58 _cmsInterpFn16 EvalCLUT; // The evaluator for 3D grid
59 const cmsInterpParams* CLUTparams; // (not-owned pointer)
62 _cmsInterpFn16* EvalCurveOut16; // Points to an array of curve evaluators in 16 bits (not-owned pointer)
63 cmsInterpParams** ParamsCurveOut16; // Points to an array of references to interpolation params (not-owned pointer)
69 // Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed
71 typedef cmsInt32Number cmsS1Fixed14Number; // Note that this may hold more than 16 bits!
73 #define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5))
79 cmsS1Fixed14Number Shaper1R[256]; // from 0..255 to 1.14 (0.0...1.0)
80 cmsS1Fixed14Number Shaper1G[256];
81 cmsS1Fixed14Number Shaper1B[256];
83 cmsS1Fixed14Number Mat[3][3]; // n.14 to n.14 (needs a saturation after that)
84 cmsS1Fixed14Number Off[3];
86 cmsUInt16Number Shaper2R[16385]; // 1.14 to 0..255
87 cmsUInt16Number Shaper2G[16385];
88 cmsUInt16Number Shaper2B[16385];
92 // Curves, optimization is shared between 8 and 16 bits
97 cmsUInt32Number nCurves; // Number of curves
98 cmsUInt32Number nElements; // Elements in curves
99 cmsUInt16Number** Curves; // Points to a dynamically allocated array
104 // Simple optimizations ----------------------------------------------------------------------------------------------------------
107 // Remove an element in linked chain
109 void _RemoveElement(cmsStage** head)
111 cmsStage* mpe = *head;
112 cmsStage* next = mpe ->Next;
117 // Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer.
119 cmsBool _Remove1Op(cmsPipeline* Lut, cmsStageSignature UnaryOp)
121 cmsStage** pt = &Lut ->Elements;
122 cmsBool AnyOpt = FALSE;
124 while (*pt != NULL) {
126 if ((*pt) ->Implements == UnaryOp) {
131 pt = &((*pt) -> Next);
137 // Same, but only if two adjacent elements are found
139 cmsBool _Remove2Op(cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2)
143 cmsBool AnyOpt = FALSE;
145 pt1 = &Lut ->Elements;
146 if (*pt1 == NULL) return AnyOpt;
148 while (*pt1 != NULL) {
150 pt2 = &((*pt1) -> Next);
151 if (*pt2 == NULL) return AnyOpt;
153 if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) {
159 pt1 = &((*pt1) -> Next);
167 cmsBool CloseEnoughFloat(cmsFloat64Number a, cmsFloat64Number b)
169 return fabs(b - a) < 0.00001f;
173 cmsBool isFloatMatrixIdentity(const cmsMAT3* a)
178 _cmsMAT3identity(&Identity);
180 for (i = 0; i < 3; i++)
181 for (j = 0; j < 3; j++)
182 if (!CloseEnoughFloat(a->v[i].n[j], Identity.v[i].n[j])) return FALSE;
187 // if two adjacent matrices are found, multiply them.
189 cmsBool _MultiplyMatrix(cmsPipeline* Lut)
194 cmsBool AnyOpt = FALSE;
196 pt1 = &Lut->Elements;
197 if (*pt1 == NULL) return AnyOpt;
199 while (*pt1 != NULL) {
201 pt2 = &((*pt1)->Next);
202 if (*pt2 == NULL) return AnyOpt;
204 if ((*pt1)->Implements == cmsSigMatrixElemType && (*pt2)->Implements == cmsSigMatrixElemType) {
207 _cmsStageMatrixData* m1 = (_cmsStageMatrixData*) cmsStageData(*pt1);
208 _cmsStageMatrixData* m2 = (_cmsStageMatrixData*) cmsStageData(*pt2);
211 // Input offset and output offset should be zero to use this optimization
212 if (m1->Offset != NULL || m2 ->Offset != NULL ||
213 cmsStageInputChannels(*pt1) != 3 || cmsStageOutputChannels(*pt1) != 3 ||
214 cmsStageInputChannels(*pt2) != 3 || cmsStageOutputChannels(*pt2) != 3)
217 // Multiply both matrices to get the result
218 _cmsMAT3per(&res, (cmsMAT3*)m2->Double, (cmsMAT3*)m1->Double);
220 // Get the next in chain after the matrices
221 chain = (*pt2)->Next;
223 // Remove both matrices
227 // Now what if the result is a plain identity?
228 if (!isFloatMatrixIdentity(&res)) {
230 // We can not get rid of full matrix
231 cmsStage* Multmat = cmsStageAllocMatrix(Lut->ContextID, 3, 3, (const cmsFloat64Number*) &res, NULL);
232 if (Multmat == NULL) return FALSE; // Should never happen
235 Multmat->Next = chain;
242 pt1 = &((*pt1)->Next);
249 // Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed
250 // by a v4 to v2 and vice-versa. The elements are then discarded.
252 cmsBool PreOptimize(cmsPipeline* Lut)
254 cmsBool AnyOpt = FALSE, Opt;
260 // Remove all identities
261 Opt |= _Remove1Op(Lut, cmsSigIdentityElemType);
263 // Remove XYZ2Lab followed by Lab2XYZ
264 Opt |= _Remove2Op(Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType);
266 // Remove Lab2XYZ followed by XYZ2Lab
267 Opt |= _Remove2Op(Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType);
269 // Remove V4 to V2 followed by V2 to V4
270 Opt |= _Remove2Op(Lut, cmsSigLabV4toV2, cmsSigLabV2toV4);
272 // Remove V2 to V4 followed by V4 to V2
273 Opt |= _Remove2Op(Lut, cmsSigLabV2toV4, cmsSigLabV4toV2);
275 // Remove float pcs Lab conversions
276 Opt |= _Remove2Op(Lut, cmsSigLab2FloatPCS, cmsSigFloatPCS2Lab);
278 // Remove float pcs Lab conversions
279 Opt |= _Remove2Op(Lut, cmsSigXYZ2FloatPCS, cmsSigFloatPCS2XYZ);
282 Opt |= _MultiplyMatrix(Lut);
284 if (Opt) AnyOpt = TRUE;
292 void Eval16nop1D(CMSREGISTER const cmsUInt16Number Input[],
293 CMSREGISTER cmsUInt16Number Output[],
294 CMSREGISTER const struct _cms_interp_struc* p)
296 Output[0] = Input[0];
298 cmsUNUSED_PARAMETER(p);
302 void PrelinEval16(CMSREGISTER const cmsUInt16Number Input[],
303 CMSREGISTER cmsUInt16Number Output[],
304 CMSREGISTER const void* D)
306 Prelin16Data* p16 = (Prelin16Data*) D;
307 cmsUInt16Number StageABC[MAX_INPUT_DIMENSIONS];
308 cmsUInt16Number StageDEF[cmsMAXCHANNELS];
311 for (i=0; i < p16 ->nInputs; i++) {
313 p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);
316 p16 ->EvalCLUT(StageABC, StageDEF, p16 ->CLUTparams);
318 for (i=0; i < p16 ->nOutputs; i++) {
320 p16 ->EvalCurveOut16[i](&StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
326 void PrelinOpt16free(cmsContext ContextID, void* ptr)
328 Prelin16Data* p16 = (Prelin16Data*) ptr;
330 _cmsFree(ContextID, p16 ->EvalCurveOut16);
331 _cmsFree(ContextID, p16 ->ParamsCurveOut16);
333 _cmsFree(ContextID, p16);
337 void* Prelin16dup(cmsContext ContextID, const void* ptr)
339 Prelin16Data* p16 = (Prelin16Data*) ptr;
340 Prelin16Data* Duped = (Prelin16Data*) _cmsDupMem(ContextID, p16, sizeof(Prelin16Data));
342 if (Duped == NULL) return NULL;
344 Duped->EvalCurveOut16 = (_cmsInterpFn16*) _cmsDupMem(ContextID, p16->EvalCurveOut16, p16->nOutputs * sizeof(_cmsInterpFn16));
345 Duped->ParamsCurveOut16 = (cmsInterpParams**)_cmsDupMem(ContextID, p16->ParamsCurveOut16, p16->nOutputs * sizeof(cmsInterpParams*));
352 Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,
353 const cmsInterpParams* ColorMap,
354 cmsUInt32Number nInputs, cmsToneCurve** In,
355 cmsUInt32Number nOutputs, cmsToneCurve** Out )
358 Prelin16Data* p16 = (Prelin16Data*)_cmsMallocZero(ContextID, sizeof(Prelin16Data));
359 if (p16 == NULL) return NULL;
361 p16 ->nInputs = nInputs;
362 p16 ->nOutputs = nOutputs;
365 for (i=0; i < nInputs; i++) {
368 p16 -> ParamsCurveIn16[i] = NULL;
369 p16 -> EvalCurveIn16[i] = Eval16nop1D;
373 p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams;
374 p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16;
378 p16 ->CLUTparams = ColorMap;
379 p16 ->EvalCLUT = ColorMap ->Interpolation.Lerp16;
382 p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));
383 if (p16->EvalCurveOut16 == NULL)
385 _cmsFree(ContextID, p16);
389 p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));
390 if (p16->ParamsCurveOut16 == NULL)
393 _cmsFree(ContextID, p16->EvalCurveOut16);
394 _cmsFree(ContextID, p16);
398 for (i=0; i < nOutputs; i++) {
401 p16 ->ParamsCurveOut16[i] = NULL;
402 p16 -> EvalCurveOut16[i] = Eval16nop1D;
406 p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;
407 p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;
416 // Resampling ---------------------------------------------------------------------------------
418 #define PRELINEARIZATION_POINTS 4096
420 // Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for
421 // almost any transform. We use floating point precision and then convert from floating point to 16 bits.
423 cmsInt32Number XFormSampler16(CMSREGISTER const cmsUInt16Number In[],
424 CMSREGISTER cmsUInt16Number Out[],
425 CMSREGISTER void* Cargo)
427 cmsPipeline* Lut = (cmsPipeline*) Cargo;
428 cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
431 _cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);
432 _cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);
434 // From 16 bit to floating point
435 for (i=0; i < Lut ->InputChannels; i++)
436 InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);
438 // Evaluate in floating point
439 cmsPipelineEvalFloat(InFloat, OutFloat, Lut);
441 // Back to 16 bits representation
442 for (i=0; i < Lut ->OutputChannels; i++)
443 Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);
449 // Try to see if the curves of a given MPE are linear
451 cmsBool AllCurvesAreLinear(cmsStage* mpe)
453 cmsToneCurve** Curves;
454 cmsUInt32Number i, n;
456 Curves = _cmsStageGetPtrToCurveSet(mpe);
457 if (Curves == NULL) return FALSE;
459 n = cmsStageOutputChannels(mpe);
461 for (i=0; i < n; i++) {
462 if (!cmsIsToneCurveLinear(Curves[i])) return FALSE;
468 // This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose
469 // is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels
471 cmsBool PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],
472 cmsUInt32Number nChannelsOut, cmsUInt32Number nChannelsIn)
474 _cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;
475 cmsInterpParams* p16 = Grid ->Params;
476 cmsFloat64Number px, py, pz, pw;
480 if (CLUT -> Type != cmsSigCLutElemType) {
481 cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage");
485 if (nChannelsIn == 4) {
487 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
488 py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
489 pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
490 pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;
492 x0 = (int) floor(px);
493 y0 = (int) floor(py);
494 z0 = (int) floor(pz);
495 w0 = (int) floor(pw);
497 if (((px - x0) != 0) ||
500 ((pw - w0) != 0)) return FALSE; // Not on exact node
502 index = (int) p16 -> opta[3] * x0 +
503 (int) p16 -> opta[2] * y0 +
504 (int) p16 -> opta[1] * z0 +
505 (int) p16 -> opta[0] * w0;
508 if (nChannelsIn == 3) {
510 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
511 py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
512 pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
514 x0 = (int) floor(px);
515 y0 = (int) floor(py);
516 z0 = (int) floor(pz);
518 if (((px - x0) != 0) ||
520 ((pz - z0) != 0)) return FALSE; // Not on exact node
522 index = (int) p16 -> opta[2] * x0 +
523 (int) p16 -> opta[1] * y0 +
524 (int) p16 -> opta[0] * z0;
527 if (nChannelsIn == 1) {
529 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
531 x0 = (int) floor(px);
533 if (((px - x0) != 0)) return FALSE; // Not on exact node
535 index = (int) p16 -> opta[0] * x0;
538 cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
542 for (i = 0; i < (int) nChannelsOut; i++)
543 Grid->Tab.T[index + i] = Value[i];
548 // Auxiliary, to see if two values are equal or very different
550 cmsBool WhitesAreEqual(cmsUInt32Number n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
554 for (i=0; i < n; i++) {
556 if (abs(White1[i] - White2[i]) > 0xf000) return TRUE; // Values are so extremely different that the fixup should be avoided
557 if (White1[i] != White2[i]) return FALSE;
563 // Locate the node for the white point and fix it to pure white in order to avoid scum dot.
565 cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)
567 cmsUInt16Number *WhitePointIn, *WhitePointOut;
568 cmsUInt16Number WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];
569 cmsUInt32Number i, nOuts, nIns;
570 cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;
572 if (!_cmsEndPointsBySpace(EntryColorSpace,
573 &WhitePointIn, NULL, &nIns)) return FALSE;
575 if (!_cmsEndPointsBySpace(ExitColorSpace,
576 &WhitePointOut, NULL, &nOuts)) return FALSE;
578 // It needs to be fixed?
579 if (Lut ->InputChannels != nIns) return FALSE;
580 if (Lut ->OutputChannels != nOuts) return FALSE;
582 cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut);
584 if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match
586 // Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations
587 if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))
588 if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))
589 if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))
590 if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT))
593 // We need to interpolate white points of both, pre and post curves
596 cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);
598 for (i=0; i < nIns; i++) {
599 WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]);
603 for (i=0; i < nIns; i++)
604 WhiteIn[i] = WhitePointIn[i];
607 // If any post-linearization, we need to find how is represented white before the curve, do
608 // a reverse interpolation in this case.
611 cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);
613 for (i=0; i < nOuts; i++) {
615 cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
616 if (InversePostLin == NULL) {
617 WhiteOut[i] = WhitePointOut[i];
621 WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
622 cmsFreeToneCurve(InversePostLin);
627 for (i=0; i < nOuts; i++)
628 WhiteOut[i] = WhitePointOut[i];
631 // Ok, proceed with patching. May fail and we don't care if it fails
632 PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns);
637 // -----------------------------------------------------------------------------------------------------------------------------------------------
638 // This function creates simple LUT from complex ones. The generated LUT has an optional set of
639 // prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.
640 // These curves have to exist in the original LUT in order to be used in the simplified output.
641 // Caller may also use the flags to allow this feature.
642 // LUTS with all curves will be simplified to a single curve. Parametric curves are lost.
643 // This function should be used on 16-bits LUTS only, as floating point losses precision when simplified
644 // -----------------------------------------------------------------------------------------------------------------------------------------------
647 cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
649 cmsPipeline* Src = NULL;
650 cmsPipeline* Dest = NULL;
652 cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;
653 cmsUInt32Number nGridPoints;
654 cmsColorSpaceSignature ColorSpace, OutputColorSpace;
655 cmsStage *NewPreLin = NULL;
656 cmsStage *NewPostLin = NULL;
657 _cmsStageCLutData* DataCLUT;
658 cmsToneCurve** DataSetIn;
659 cmsToneCurve** DataSetOut;
662 // This is a lossy optimization! does not apply in floating-point cases
663 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
665 ColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*InputFormat));
666 OutputColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*OutputFormat));
668 // Color space must be specified
669 if (ColorSpace == (cmsColorSpaceSignature)0 ||
670 OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;
672 nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
674 // For empty LUTs, 2 points are enough
675 if (cmsPipelineStageCount(*Lut) == 0)
680 // Allocate an empty LUT
681 Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
682 if (!Dest) return FALSE;
684 // Prelinearization tables are kept unless indicated by flags
685 if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {
687 // Get a pointer to the prelinearization element
688 cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);
691 if (PreLin && PreLin ->Type == cmsSigCurveSetElemType) {
693 // Maybe this is a linear tram, so we can avoid the whole stuff
694 if (!AllCurvesAreLinear(PreLin)) {
696 // All seems ok, proceed.
697 NewPreLin = cmsStageDup(PreLin);
698 if(!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin))
701 // Remove prelinearization. Since we have duplicated the curve
702 // in destination LUT, the sampling should be applied after this stage.
703 cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin);
709 CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);
710 if (CLUT == NULL) goto Error;
712 // Add the CLUT to the destination LUT
713 if (!cmsPipelineInsertStage(Dest, cmsAT_END, CLUT)) {
717 // Postlinearization tables are kept unless indicated by flags
718 if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {
720 // Get a pointer to the postlinearization if present
721 cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);
724 if (PostLin && cmsStageType(PostLin) == cmsSigCurveSetElemType) {
726 // Maybe this is a linear tram, so we can avoid the whole stuff
727 if (!AllCurvesAreLinear(PostLin)) {
729 // All seems ok, proceed.
730 NewPostLin = cmsStageDup(PostLin);
731 if (!cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin))
734 // In destination LUT, the sampling should be applied after this stage.
735 cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);
740 // Now its time to do the sampling. We have to ignore pre/post linearization
741 // The source LUT without pre/post curves is passed as parameter.
742 if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {
744 // Ops, something went wrong, Restore stages
745 if (KeepPreLin != NULL) {
746 if (!cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin)) {
747 _cmsAssert(0); // This never happens
750 if (KeepPostLin != NULL) {
751 if (!cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin)) {
752 _cmsAssert(0); // This never happens
755 cmsPipelineFree(Dest);
761 if (KeepPreLin != NULL) cmsStageFree(KeepPreLin);
762 if (KeepPostLin != NULL) cmsStageFree(KeepPostLin);
763 cmsPipelineFree(Src);
765 DataCLUT = (_cmsStageCLutData*) CLUT ->Data;
767 if (NewPreLin == NULL) DataSetIn = NULL;
768 else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;
770 if (NewPostLin == NULL) DataSetOut = NULL;
771 else DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;
774 if (DataSetIn == NULL && DataSetOut == NULL) {
776 _cmsPipelineSetOptimizationParameters(Dest, (_cmsPipelineEval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);
780 p16 = PrelinOpt16alloc(Dest ->ContextID,
782 Dest ->InputChannels,
784 Dest ->OutputChannels,
787 _cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
791 // Don't fix white on absolute colorimetric
792 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
793 *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
795 if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
797 FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace);
803 cmsUNUSED_PARAMETER(Intent);
807 // -----------------------------------------------------------------------------------------------------------------------------------------------
808 // Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on
809 // Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works
810 // for RGB transforms. See the paper for more details
811 // -----------------------------------------------------------------------------------------------------------------------------------------------
814 // Normalize endpoints by slope limiting max and min. This assures endpoints as well.
815 // Descending curves are handled as well.
817 void SlopeLimiting(cmsToneCurve* g)
819 int BeginVal, EndVal;
820 int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5); // Cutoff at 2%
821 int AtEnd = (int) g ->nEntries - AtBegin - 1; // And 98%
822 cmsFloat64Number Val, Slope, beta;
825 if (cmsIsToneCurveDescending(g)) {
826 BeginVal = 0xffff; EndVal = 0;
829 BeginVal = 0; EndVal = 0xffff;
832 // Compute slope and offset for begin of curve
833 Val = g ->Table16[AtBegin];
834 Slope = (Val - BeginVal) / AtBegin;
835 beta = Val - Slope * AtBegin;
837 for (i=0; i < AtBegin; i++)
838 g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
840 // Compute slope and offset for the end
841 Val = g ->Table16[AtEnd];
842 Slope = (EndVal - Val) / AtBegin; // AtBegin holds the X interval, which is same in both cases
843 beta = Val - Slope * AtEnd;
845 for (i = AtEnd; i < (int) g ->nEntries; i++)
846 g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
850 // Precomputes tables for 8-bit on input devicelink.
852 Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])
855 cmsUInt16Number Input[3];
856 cmsS15Fixed16Number v1, v2, v3;
859 p8 = (Prelin8Data*)_cmsMallocZero(ContextID, sizeof(Prelin8Data));
860 if (p8 == NULL) return NULL;
862 // Since this only works for 8 bit input, values comes always as x * 257,
863 // we can safely take msb byte (x << 8 + x)
865 for (i=0; i < 256; i++) {
869 // Get 16-bit representation
870 Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i));
871 Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i));
872 Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i));
875 Input[0] = FROM_8_TO_16(i);
876 Input[1] = FROM_8_TO_16(i);
877 Input[2] = FROM_8_TO_16(i);
881 // Move to 0..1.0 in fixed domain
882 v1 = _cmsToFixedDomain((int) (Input[0] * p -> Domain[0]));
883 v2 = _cmsToFixedDomain((int) (Input[1] * p -> Domain[1]));
884 v3 = _cmsToFixedDomain((int) (Input[2] * p -> Domain[2]));
886 // Store the precalculated table of nodes
887 p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));
888 p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));
889 p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));
891 // Store the precalculated table of offsets
892 p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);
893 p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);
894 p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);
897 p8 ->ContextID = ContextID;
904 void Prelin8free(cmsContext ContextID, void* ptr)
906 _cmsFree(ContextID, ptr);
910 void* Prelin8dup(cmsContext ContextID, const void* ptr)
912 return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));
917 // A optimized interpolation for 8-bit input.
918 #define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
919 static CMS_NO_SANITIZE
920 void PrelinEval8(CMSREGISTER const cmsUInt16Number Input[],
921 CMSREGISTER cmsUInt16Number Output[],
922 CMSREGISTER const void* D)
925 cmsUInt8Number r, g, b;
926 cmsS15Fixed16Number rx, ry, rz;
927 cmsS15Fixed16Number c0, c1, c2, c3, Rest;
929 CMSREGISTER cmsS15Fixed16Number X0, X1, Y0, Y1, Z0, Z1;
930 Prelin8Data* p8 = (Prelin8Data*) D;
931 CMSREGISTER const cmsInterpParams* p = p8 ->p;
932 int TotalOut = (int) p -> nOutputs;
933 const cmsUInt16Number* LutTable = (const cmsUInt16Number*) p->Table;
935 r = (cmsUInt8Number) (Input[0] >> 8);
936 g = (cmsUInt8Number) (Input[1] >> 8);
937 b = (cmsUInt8Number) (Input[2] >> 8);
939 X0 = (cmsS15Fixed16Number) p8->X0[r];
940 Y0 = (cmsS15Fixed16Number) p8->Y0[g];
941 Z0 = (cmsS15Fixed16Number) p8->Z0[b];
947 X1 = X0 + (cmsS15Fixed16Number)((rx == 0) ? 0 : p ->opta[2]);
948 Y1 = Y0 + (cmsS15Fixed16Number)((ry == 0) ? 0 : p ->opta[1]);
949 Z1 = Z0 + (cmsS15Fixed16Number)((rz == 0) ? 0 : p ->opta[0]);
952 // These are the 6 Tetrahedral
953 for (OutChan=0; OutChan < TotalOut; OutChan++) {
955 c0 = DENS(X0, Y0, Z0);
957 if (rx >= ry && ry >= rz)
959 c1 = DENS(X1, Y0, Z0) - c0;
960 c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
961 c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
964 if (rx >= rz && rz >= ry)
966 c1 = DENS(X1, Y0, Z0) - c0;
967 c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
968 c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
971 if (rz >= rx && rx >= ry)
973 c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
974 c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
975 c3 = DENS(X0, Y0, Z1) - c0;
978 if (ry >= rx && rx >= rz)
980 c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
981 c2 = DENS(X0, Y1, Z0) - c0;
982 c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
985 if (ry >= rz && rz >= rx)
987 c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
988 c2 = DENS(X0, Y1, Z0) - c0;
989 c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
992 if (rz >= ry && ry >= rx)
994 c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
995 c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
996 c3 = DENS(X0, Y0, Z1) - c0;
1002 Rest = c1 * rx + c2 * ry + c3 * rz + 0x8001;
1003 Output[OutChan] = (cmsUInt16Number) (c0 + ((Rest + (Rest >> 16)) >> 16));
1011 // Curves that contain wide empty areas are not optimizeable
1013 cmsBool IsDegenerated(const cmsToneCurve* g)
1015 cmsUInt32Number i, Zeros = 0, Poles = 0;
1016 cmsUInt32Number nEntries = g ->nEntries;
1018 for (i=0; i < nEntries; i++) {
1020 if (g ->Table16[i] == 0x0000) Zeros++;
1021 if (g ->Table16[i] == 0xffff) Poles++;
1024 if (Zeros == 1 && Poles == 1) return FALSE; // For linear tables
1025 if (Zeros > (nEntries / 20)) return TRUE; // Degenerated, many zeros
1026 if (Poles > (nEntries / 20)) return TRUE; // Degenerated, many poles
1031 // --------------------------------------------------------------------------------------------------------------
1032 // We need xput over here
1035 cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1037 cmsPipeline* OriginalLut;
1038 cmsUInt32Number nGridPoints;
1039 cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];
1040 cmsUInt32Number t, i;
1041 cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];
1042 cmsBool lIsSuitable, lIsLinear;
1043 cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;
1044 cmsStage* OptimizedCLUTmpe;
1045 cmsColorSpaceSignature ColorSpace, OutputColorSpace;
1046 cmsStage* OptimizedPrelinMpe;
1047 cmsToneCurve** OptimizedPrelinCurves;
1048 _cmsStageCLutData* OptimizedPrelinCLUT;
1051 // This is a lossy optimization! does not apply in floating-point cases
1052 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
1054 // Only on chunky RGB
1055 if (T_COLORSPACE(*InputFormat) != PT_RGB) return FALSE;
1056 if (T_PLANAR(*InputFormat)) return FALSE;
1058 if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
1059 if (T_PLANAR(*OutputFormat)) return FALSE;
1061 // On 16 bits, user has to specify the feature
1062 if (!_cmsFormatterIs8bit(*InputFormat)) {
1063 if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;
1068 ColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*InputFormat));
1069 OutputColorSpace = _cmsICCcolorSpace((int) T_COLORSPACE(*OutputFormat));
1071 // Color space must be specified
1072 if (ColorSpace == (cmsColorSpaceSignature)0 ||
1073 OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;
1075 nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
1077 // Empty gamma containers
1078 memset(Trans, 0, sizeof(Trans));
1079 memset(TransReverse, 0, sizeof(TransReverse));
1081 // If the last stage of the original lut are curves, and those curves are
1082 // degenerated, it is likely the transform is squeezing and clipping
1083 // the output from previous CLUT. We cannot optimize this case
1085 cmsStage* last = cmsPipelineGetPtrToLastStage(OriginalLut);
1087 if (last == NULL) goto Error;
1088 if (cmsStageType(last) == cmsSigCurveSetElemType) {
1090 _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*)cmsStageData(last);
1091 for (i = 0; i < Data->nCurves; i++) {
1092 if (IsDegenerated(Data->TheCurves[i]))
1098 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1099 Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);
1100 if (Trans[t] == NULL) goto Error;
1103 // Populate the curves
1104 for (i=0; i < PRELINEARIZATION_POINTS; i++) {
1106 v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
1108 // Feed input with a gray ramp
1109 for (t=0; t < OriginalLut ->InputChannels; t++)
1112 // Evaluate the gray value
1113 cmsPipelineEvalFloat(In, Out, OriginalLut);
1115 // Store result in curve
1116 for (t=0; t < OriginalLut ->InputChannels; t++)
1118 if (Trans[t]->Table16 != NULL)
1119 Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);
1123 // Slope-limit the obtained curves
1124 for (t = 0; t < OriginalLut ->InputChannels; t++)
1125 SlopeLimiting(Trans[t]);
1127 // Check for validity. lIsLinear is here for debug purposes
1130 for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {
1132 // Exclude if already linear
1133 if (!cmsIsToneCurveLinear(Trans[t]))
1136 // Exclude if non-monotonic
1137 if (!cmsIsToneCurveMonotonic(Trans[t]))
1138 lIsSuitable = FALSE;
1140 if (IsDegenerated(Trans[t]))
1141 lIsSuitable = FALSE;
1144 // If it is not suitable, just quit
1145 if (!lIsSuitable) goto Error;
1147 // Invert curves if possible
1148 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1149 TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]);
1150 if (TransReverse[t] == NULL) goto Error;
1153 // Now inset the reversed curves at the begin of transform
1154 LutPlusCurves = cmsPipelineDup(OriginalLut);
1155 if (LutPlusCurves == NULL) goto Error;
1157 if (!cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse)))
1160 // Create the result LUT
1161 OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);
1162 if (OptimizedLUT == NULL) goto Error;
1164 OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);
1166 // Create and insert the curves at the beginning
1167 if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe))
1170 // Allocate the CLUT for result
1171 OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);
1173 // Add the CLUT to the destination LUT
1174 if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe))
1178 if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;
1181 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1183 if (Trans[t]) cmsFreeToneCurve(Trans[t]);
1184 if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
1187 cmsPipelineFree(LutPlusCurves);
1190 OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);
1191 OptimizedPrelinCLUT = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;
1193 // Set the evaluator if 8-bit
1194 if (_cmsFormatterIs8bit(*InputFormat)) {
1196 Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID,
1197 OptimizedPrelinCLUT ->Params,
1198 OptimizedPrelinCurves);
1199 if (p8 == NULL) return FALSE;
1201 _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);
1206 Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID,
1207 OptimizedPrelinCLUT ->Params,
1208 3, OptimizedPrelinCurves, 3, NULL);
1209 if (p16 == NULL) return FALSE;
1211 _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
1215 // Don't fix white on absolute colorimetric
1216 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
1217 *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
1219 if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
1221 if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) {
1227 // And return the obtained LUT
1229 cmsPipelineFree(OriginalLut);
1230 *Lut = OptimizedLUT;
1235 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1237 if (Trans[t]) cmsFreeToneCurve(Trans[t]);
1238 if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
1241 if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves);
1242 if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT);
1246 cmsUNUSED_PARAMETER(Intent);
1247 cmsUNUSED_PARAMETER(lIsLinear);
1251 // Curves optimizer ------------------------------------------------------------------------------------------------------------------
1254 void CurvesFree(cmsContext ContextID, void* ptr)
1256 Curves16Data* Data = (Curves16Data*) ptr;
1259 for (i=0; i < Data -> nCurves; i++) {
1261 _cmsFree(ContextID, Data ->Curves[i]);
1264 _cmsFree(ContextID, Data ->Curves);
1265 _cmsFree(ContextID, ptr);
1269 void* CurvesDup(cmsContext ContextID, const void* ptr)
1271 Curves16Data* Data = (Curves16Data*)_cmsDupMem(ContextID, ptr, sizeof(Curves16Data));
1274 if (Data == NULL) return NULL;
1276 Data->Curves = (cmsUInt16Number**) _cmsDupMem(ContextID, Data->Curves, Data->nCurves * sizeof(cmsUInt16Number*));
1278 for (i=0; i < Data -> nCurves; i++) {
1279 Data->Curves[i] = (cmsUInt16Number*) _cmsDupMem(ContextID, Data->Curves[i], Data->nElements * sizeof(cmsUInt16Number));
1282 return (void*) Data;
1285 // Precomputes tables for 8-bit on input devicelink.
1287 Curves16Data* CurvesAlloc(cmsContext ContextID, cmsUInt32Number nCurves, cmsUInt32Number nElements, cmsToneCurve** G)
1289 cmsUInt32Number i, j;
1292 c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));
1293 if (c16 == NULL) return NULL;
1295 c16 ->nCurves = nCurves;
1296 c16 ->nElements = nElements;
1298 c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
1299 if (c16->Curves == NULL) {
1300 _cmsFree(ContextID, c16);
1304 for (i=0; i < nCurves; i++) {
1306 c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
1308 if (c16->Curves[i] == NULL) {
1310 for (j=0; j < i; j++) {
1311 _cmsFree(ContextID, c16->Curves[j]);
1313 _cmsFree(ContextID, c16->Curves);
1314 _cmsFree(ContextID, c16);
1318 if (nElements == 256U) {
1320 for (j=0; j < nElements; j++) {
1322 c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
1327 for (j=0; j < nElements; j++) {
1328 c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
1337 void FastEvaluateCurves8(CMSREGISTER const cmsUInt16Number In[],
1338 CMSREGISTER cmsUInt16Number Out[],
1339 CMSREGISTER const void* D)
1341 Curves16Data* Data = (Curves16Data*) D;
1345 for (i=0; i < Data ->nCurves; i++) {
1348 Out[i] = Data -> Curves[i][x];
1354 void FastEvaluateCurves16(CMSREGISTER const cmsUInt16Number In[],
1355 CMSREGISTER cmsUInt16Number Out[],
1356 CMSREGISTER const void* D)
1358 Curves16Data* Data = (Curves16Data*) D;
1361 for (i=0; i < Data ->nCurves; i++) {
1362 Out[i] = Data -> Curves[i][In[i]];
1368 void FastIdentity16(CMSREGISTER const cmsUInt16Number In[],
1369 CMSREGISTER cmsUInt16Number Out[],
1370 CMSREGISTER const void* D)
1372 cmsPipeline* Lut = (cmsPipeline*) D;
1375 for (i=0; i < Lut ->InputChannels; i++) {
1381 // If the target LUT holds only curves, the optimization procedure is to join all those
1382 // curves together. That only works on curves and does not work on matrices.
1384 cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1386 cmsToneCurve** GammaTables = NULL;
1387 cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
1388 cmsUInt32Number i, j;
1389 cmsPipeline* Src = *Lut;
1390 cmsPipeline* Dest = NULL;
1392 cmsStage* ObtainedCurves = NULL;
1395 // This is a lossy optimization! does not apply in floating-point cases
1396 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
1398 // Only curves in this LUT?
1399 for (mpe = cmsPipelineGetPtrToFirstStage(Src);
1401 mpe = cmsStageNext(mpe)) {
1402 if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE;
1405 // Allocate an empty LUT
1406 Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
1407 if (Dest == NULL) return FALSE;
1409 // Create target curves
1410 GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));
1411 if (GammaTables == NULL) goto Error;
1413 for (i=0; i < Src ->InputChannels; i++) {
1414 GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL);
1415 if (GammaTables[i] == NULL) goto Error;
1418 // Compute 16 bit result by using floating point
1419 for (i=0; i < PRELINEARIZATION_POINTS; i++) {
1421 for (j=0; j < Src ->InputChannels; j++)
1422 InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
1424 cmsPipelineEvalFloat(InFloat, OutFloat, Src);
1426 for (j=0; j < Src ->InputChannels; j++)
1427 GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);
1430 ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables);
1431 if (ObtainedCurves == NULL) goto Error;
1433 for (i=0; i < Src ->InputChannels; i++) {
1434 cmsFreeToneCurve(GammaTables[i]);
1435 GammaTables[i] = NULL;
1438 if (GammaTables != NULL) {
1439 _cmsFree(Src->ContextID, GammaTables);
1443 // Maybe the curves are linear at the end
1444 if (!AllCurvesAreLinear(ObtainedCurves)) {
1445 _cmsStageToneCurvesData* Data;
1447 if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves))
1449 Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);
1450 ObtainedCurves = NULL;
1452 // If the curves are to be applied in 8 bits, we can save memory
1453 if (_cmsFormatterIs8bit(*InputFormat)) {
1454 Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);
1456 if (c16 == NULL) goto Error;
1457 *dwFlags |= cmsFLAGS_NOCACHE;
1458 _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);
1462 Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);
1464 if (c16 == NULL) goto Error;
1465 *dwFlags |= cmsFLAGS_NOCACHE;
1466 _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);
1471 // LUT optimizes to nothing. Set the identity LUT
1472 cmsStageFree(ObtainedCurves);
1473 ObtainedCurves = NULL;
1475 if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels)))
1478 *dwFlags |= cmsFLAGS_NOCACHE;
1479 _cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);
1483 cmsPipelineFree(Src);
1489 if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves);
1490 if (GammaTables != NULL) {
1491 for (i=0; i < Src ->InputChannels; i++) {
1492 if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]);
1495 _cmsFree(Src ->ContextID, GammaTables);
1498 if (Dest != NULL) cmsPipelineFree(Dest);
1501 cmsUNUSED_PARAMETER(Intent);
1502 cmsUNUSED_PARAMETER(InputFormat);
1503 cmsUNUSED_PARAMETER(OutputFormat);
1504 cmsUNUSED_PARAMETER(dwFlags);
1507 // -------------------------------------------------------------------------------------------------------------------------------------
1508 // LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles
1512 void FreeMatShaper(cmsContext ContextID, void* Data)
1514 if (Data != NULL) _cmsFree(ContextID, Data);
1518 void* DupMatShaper(cmsContext ContextID, const void* Data)
1520 return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));
1524 // A fast matrix-shaper evaluator for 8 bits. This is a bit tricky since I'm using 1.14 signed fixed point
1525 // to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,
1526 // in total about 50K, and the performance boost is huge!
1527 static CMS_NO_SANITIZE
1528 void MatShaperEval16(CMSREGISTER const cmsUInt16Number In[],
1529 CMSREGISTER cmsUInt16Number Out[],
1530 CMSREGISTER const void* D)
1532 MatShaper8Data* p = (MatShaper8Data*) D;
1533 cmsS1Fixed14Number l1, l2, l3, r, g, b;
1534 cmsUInt32Number ri, gi, bi;
1536 // In this case (and only in this case!) we can use this simplification since
1537 // In[] is assured to come from a 8 bit number. (a << 8 | a)
1542 // Across first shaper, which also converts to 1.14 fixed point
1543 r = p->Shaper1R[ri];
1544 g = p->Shaper1G[gi];
1545 b = p->Shaper1B[bi];
1547 // Evaluate the matrix in 1.14 fixed point
1548 l1 = (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;
1549 l2 = (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;
1550 l3 = (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;
1552 // Now we have to clip to 0..1.0 range
1553 ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384U : (cmsUInt32Number) l1);
1554 gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384U : (cmsUInt32Number) l2);
1555 bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384U : (cmsUInt32Number) l3);
1557 // And across second shaper,
1558 Out[0] = p->Shaper2R[ri];
1559 Out[1] = p->Shaper2G[gi];
1560 Out[2] = p->Shaper2B[bi];
1564 // This table converts from 8 bits to 1.14 after applying the curve
1566 void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve)
1569 cmsFloat32Number R, y;
1571 for (i=0; i < 256; i++) {
1573 R = (cmsFloat32Number) (i / 255.0);
1574 y = cmsEvalToneCurveFloat(Curve, R);
1577 Table[i] = DOUBLE_TO_1FIXED14(y);
1579 Table[i] = 0x7fffffff;
1583 // This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve
1585 void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)
1588 cmsFloat32Number R, Val;
1590 for (i=0; i < 16385; i++) {
1592 R = (cmsFloat32Number) (i / 16384.0);
1593 Val = cmsEvalToneCurveFloat(Curve, R); // Val comes 0..1.0
1601 if (Is8BitsOutput) {
1603 // If 8 bits output, we can optimize further by computing the / 257 part.
1604 // first we compute the resulting byte and then we store the byte times
1605 // 257. This quantization allows to round very quick by doing a >> 8, but
1606 // since the low byte is always equal to msb, we can do a & 0xff and this works!
1607 cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0);
1608 cmsUInt8Number b = FROM_16_TO_8(w);
1610 Table[i] = FROM_8_TO_16(b);
1612 else Table[i] = _cmsQuickSaturateWord(Val * 65535.0);
1616 // Compute the matrix-shaper structure
1618 cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)
1622 cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);
1624 // Allocate a big chuck of memory to store precomputed tables
1625 p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));
1626 if (p == NULL) return FALSE;
1628 p -> ContextID = Dest -> ContextID;
1630 // Precompute tables
1631 FillFirstShaper(p ->Shaper1R, Curve1[0]);
1632 FillFirstShaper(p ->Shaper1G, Curve1[1]);
1633 FillFirstShaper(p ->Shaper1B, Curve1[2]);
1635 FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits);
1636 FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits);
1637 FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits);
1639 // Convert matrix to nFixed14. Note that those values may take more than 16 bits
1640 for (i=0; i < 3; i++) {
1641 for (j=0; j < 3; j++) {
1642 p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);
1646 for (i=0; i < 3; i++) {
1652 p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);
1656 // Mark as optimized for faster formatter
1658 *OutputFormat |= OPTIMIZED_SH(1);
1660 // Fill function pointers
1661 _cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);
1665 // 8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!
1667 cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1669 cmsStage* Curve1, *Curve2;
1670 cmsStage* Matrix1, *Matrix2;
1672 cmsBool IdentityMat;
1673 cmsPipeline* Dest, *Src;
1674 cmsFloat64Number* Offset;
1676 // Only works on RGB to RGB
1677 if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;
1679 // Only works on 8 bit input
1680 if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;
1682 // Seems suitable, proceed
1687 // shaper-matrix-matrix-shaper
1688 // shaper-matrix-shaper
1690 // Both of those constructs are possible (first because abs. colorimetric).
1691 // additionally, In the first case, the input matrix offset should be zero.
1693 IdentityMat = FALSE;
1694 if (cmsPipelineCheckAndRetreiveStages(Src, 4,
1695 cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
1696 &Curve1, &Matrix1, &Matrix2, &Curve2)) {
1698 // Get both matrices
1699 _cmsStageMatrixData* Data1 = (_cmsStageMatrixData*)cmsStageData(Matrix1);
1700 _cmsStageMatrixData* Data2 = (_cmsStageMatrixData*)cmsStageData(Matrix2);
1703 if (Matrix1->InputChannels != 3 || Matrix1->OutputChannels != 3 ||
1704 Matrix2->InputChannels != 3 || Matrix2->OutputChannels != 3) return FALSE;
1706 // Input offset should be zero
1707 if (Data1->Offset != NULL) return FALSE;
1709 // Multiply both matrices to get the result
1710 _cmsMAT3per(&res, (cmsMAT3*)Data2->Double, (cmsMAT3*)Data1->Double);
1712 // Only 2nd matrix has offset, or it is zero
1713 Offset = Data2->Offset;
1715 // Now the result is in res + Data2 -> Offset. Maybe is a plain identity?
1716 if (_cmsMAT3isIdentity(&res) && Offset == NULL) {
1718 // We can get rid of full matrix
1725 if (cmsPipelineCheckAndRetreiveStages(Src, 3,
1726 cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
1727 &Curve1, &Matrix1, &Curve2)) {
1729 _cmsStageMatrixData* Data = (_cmsStageMatrixData*)cmsStageData(Matrix1);
1731 if (Matrix1->InputChannels != 3 || Matrix1->OutputChannels != 3) return FALSE;
1733 // Copy the matrix to our result
1734 memcpy(&res, Data->Double, sizeof(res));
1736 // Preserve the Odffset (may be NULL as a zero offset)
1737 Offset = Data->Offset;
1739 if (_cmsMAT3isIdentity(&res) && Offset == NULL) {
1741 // We can get rid of full matrix
1746 return FALSE; // Not optimizeable this time
1750 // Allocate an empty LUT
1751 Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
1752 if (!Dest) return FALSE;
1754 // Assamble the new LUT
1755 if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1)))
1760 if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest->ContextID, 3, 3, (const cmsFloat64Number*)&res, Offset)))
1764 if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2)))
1767 // If identity on matrix, we can further optimize the curves, so call the join curves routine
1770 OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags);
1773 _cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1);
1774 _cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2);
1776 // In this particular optimization, cache does not help as it takes more time to deal with
1777 // the cache than with the pixel handling
1778 *dwFlags |= cmsFLAGS_NOCACHE;
1780 // Setup the optimizarion routines
1781 SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Offset, mpeC2->TheCurves, OutputFormat);
1784 cmsPipelineFree(Src);
1788 // Leave Src unchanged
1789 cmsPipelineFree(Dest);
1794 // -------------------------------------------------------------------------------------------------------------------------------------
1795 // Optimization plug-ins
1797 // List of optimizations
1798 typedef struct _cmsOptimizationCollection_st {
1800 _cmsOPToptimizeFn OptimizePtr;
1802 struct _cmsOptimizationCollection_st *Next;
1804 } _cmsOptimizationCollection;
1807 // The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling
1808 static _cmsOptimizationCollection DefaultOptimization[] = {
1810 { OptimizeByJoiningCurves, &DefaultOptimization[1] },
1811 { OptimizeMatrixShaper, &DefaultOptimization[2] },
1812 { OptimizeByComputingLinearization, &DefaultOptimization[3] },
1813 { OptimizeByResampling, NULL }
1816 // The linked list head
1817 _cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL };
1820 // Duplicates the zone of memory used by the plug-in in the new context
1822 void DupPluginOptimizationList(struct _cmsContext_struct* ctx,
1823 const struct _cmsContext_struct* src)
1825 _cmsOptimizationPluginChunkType newHead = { NULL };
1826 _cmsOptimizationCollection* entry;
1827 _cmsOptimizationCollection* Anterior = NULL;
1828 _cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin];
1830 _cmsAssert(ctx != NULL);
1831 _cmsAssert(head != NULL);
1833 // Walk the list copying all nodes
1834 for (entry = head->OptimizationCollection;
1836 entry = entry ->Next) {
1838 _cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection));
1840 if (newEntry == NULL)
1843 // We want to keep the linked list order, so this is a little bit tricky
1844 newEntry -> Next = NULL;
1846 Anterior -> Next = newEntry;
1848 Anterior = newEntry;
1850 if (newHead.OptimizationCollection == NULL)
1851 newHead.OptimizationCollection = newEntry;
1854 ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType));
1857 void _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx,
1858 const struct _cmsContext_struct* src)
1862 // Copy all linked list
1863 DupPluginOptimizationList(ctx, src);
1866 static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL };
1867 ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType));
1872 // Register new ways to optimize
1873 cmsBool _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data)
1875 cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
1876 _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
1877 _cmsOptimizationCollection* fl;
1881 ctx->OptimizationCollection = NULL;
1885 // Optimizer callback is required
1886 if (Plugin ->OptimizePtr == NULL) return FALSE;
1888 fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection));
1889 if (fl == NULL) return FALSE;
1891 // Copy the parameters
1892 fl ->OptimizePtr = Plugin ->OptimizePtr;
1895 fl ->Next = ctx->OptimizationCollection;
1898 ctx ->OptimizationCollection = fl;
1904 // The entry point for LUT optimization
1905 cmsBool CMSEXPORT _cmsOptimizePipeline(cmsContext ContextID,
1906 cmsPipeline** PtrLut,
1907 cmsUInt32Number Intent,
1908 cmsUInt32Number* InputFormat,
1909 cmsUInt32Number* OutputFormat,
1910 cmsUInt32Number* dwFlags)
1912 _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
1913 _cmsOptimizationCollection* Opts;
1914 cmsBool AnySuccess = FALSE;
1917 // A CLUT is being asked, so force this specific optimization
1918 if (*dwFlags & cmsFLAGS_FORCE_CLUT) {
1920 PreOptimize(*PtrLut);
1921 return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags);
1924 // Anything to optimize?
1925 if ((*PtrLut) ->Elements == NULL) {
1926 _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1930 // Named color pipelines cannot be optimized
1931 for (mpe = cmsPipelineGetPtrToFirstStage(*PtrLut);
1933 mpe = cmsStageNext(mpe)) {
1934 if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;
1937 // Try to get rid of identities and trivial conversions.
1938 AnySuccess = PreOptimize(*PtrLut);
1940 // After removal do we end with an identity?
1941 if ((*PtrLut) ->Elements == NULL) {
1942 _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1946 // Do not optimize, keep all precision
1947 if (*dwFlags & cmsFLAGS_NOOPTIMIZE)
1950 // Try plug-in optimizations
1951 for (Opts = ctx->OptimizationCollection;
1953 Opts = Opts ->Next) {
1955 // If one schema succeeded, we are done
1956 if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1958 return TRUE; // Optimized!
1962 // Try built-in optimizations
1963 for (Opts = DefaultOptimization;
1965 Opts = Opts ->Next) {
1967 if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1973 // Only simple optimizations succeeded