2 //---------------------------------------------------------------------------------
4 // Little Color Management System
5 // Copyright (c) 1998-2010 Marti Maria Saguer
7 // Permission is hereby granted, free of charge, to any person obtaining
8 // a copy of this software and associated documentation files (the "Software"),
9 // to deal in the Software without restriction, including without limitation
10 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 // and/or sell copies of the Software, and to permit persons to whom the Software
12 // is furnished to do so, subject to the following conditions:
14 // The above copyright notice and this permission notice shall be included in
15 // all copies or substantial portions of the Software.
17 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
19 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25 //---------------------------------------------------------------------------------
28 #include "lcms2_internal.h"
31 //----------------------------------------------------------------------------------
33 // Optimization for 8 bits, Shaper-CLUT (3 inputs only)
38 const cmsInterpParams* p; // Tetrahedrical interpolation parameters. This is a not-owned pointer.
40 cmsUInt16Number rx[256], ry[256], rz[256];
41 cmsUInt32Number X0[256], Y0[256], Z0[256]; // Precomputed nodes and offsets for 8-bit input data
47 // Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs)
56 // Since there is no limitation of the output number of channels, this buffer holding the connexion CLUT-shaper
57 // has to be dynamically allocated. This is not the case of first step shaper-CLUT, which is limited to max inputs
58 cmsUInt16Number* StageDEF;
60 _cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS]; // The maximum number of input channels is known in advance
61 cmsInterpParams* ParamsCurveIn16[MAX_INPUT_DIMENSIONS];
63 _cmsInterpFn16 EvalCLUT; // The evaluator for 3D grid
64 const cmsInterpParams* CLUTparams; // (not-owned pointer)
67 _cmsInterpFn16* EvalCurveOut16; // Points to an array of curve evaluators in 16 bits (not-owned pointer)
68 cmsInterpParams** ParamsCurveOut16; // Points to an array of references to interpolation params (not-owned pointer)
74 // Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed
76 typedef cmsInt32Number cmsS1Fixed14Number; // Note that this may hold more than 16 bits!
78 #define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5))
84 cmsS1Fixed14Number Shaper1R[256]; // from 0..255 to 1.14 (0.0...1.0)
85 cmsS1Fixed14Number Shaper1G[256];
86 cmsS1Fixed14Number Shaper1B[256];
88 cmsS1Fixed14Number Mat[3][3]; // n.14 to n.14 (needs a saturation after that)
89 cmsS1Fixed14Number Off[3];
91 cmsUInt16Number Shaper2R[16385]; // 1.14 to 0..255
92 cmsUInt16Number Shaper2G[16385];
93 cmsUInt16Number Shaper2B[16385];
97 // Curves, optimization is shared between 8 and 16 bits
100 cmsContext ContextID;
102 int nCurves; // Number of curves
103 int nElements; // Elements in curves
104 cmsUInt16Number** Curves; // Points to a dynamically allocated array
109 // Simple optimizations ----------------------------------------------------------------------------------------------------------
112 // Remove an element in linked chain
114 void _RemoveElement(cmsStage** head)
116 cmsStage* mpe = *head;
117 cmsStage* next = mpe ->Next;
122 // Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer.
124 cmsBool _Remove1Op(cmsPipeline* Lut, cmsStageSignature UnaryOp)
126 cmsStage** pt = &Lut ->Elements;
127 cmsBool AnyOpt = FALSE;
129 while (*pt != NULL) {
131 if ((*pt) ->Implements == UnaryOp) {
136 pt = &((*pt) -> Next);
142 // Same, but only if two adjacent elements are found
144 cmsBool _Remove2Op(cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2)
148 cmsBool AnyOpt = FALSE;
150 pt1 = &Lut ->Elements;
151 if (*pt1 == NULL) return AnyOpt;
153 while (*pt1 != NULL) {
155 pt2 = &((*pt1) -> Next);
156 if (*pt2 == NULL) return AnyOpt;
158 if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) {
164 pt1 = &((*pt1) -> Next);
170 // Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed
171 // by a v4 to v2 and vice-versa. The elements are then discarded.
173 cmsBool PreOptimize(cmsPipeline* Lut)
175 cmsBool AnyOpt = FALSE, Opt;
183 // Remove all identities
184 Opt |= _Remove1Op(Lut, cmsSigIdentityElemType);
186 // Remove XYZ2Lab followed by Lab2XYZ
187 Opt |= _Remove2Op(Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType);
189 // Remove Lab2XYZ followed by XYZ2Lab
190 Opt |= _Remove2Op(Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType);
192 // Remove V4 to V2 followed by V2 to V4
193 Opt |= _Remove2Op(Lut, cmsSigLabV4toV2, cmsSigLabV2toV4);
195 // Remove V2 to V4 followed by V4 to V2
196 Opt |= _Remove2Op(Lut, cmsSigLabV2toV4, cmsSigLabV4toV2);
198 if (Opt) AnyOpt = TRUE;
206 void Eval16nop1D(register const cmsUInt16Number Input[],
207 register cmsUInt16Number Output[],
208 register const struct _cms_interp_struc* p)
210 Output[0] = Input[0];
212 cmsUNUSED_PARAMETER(p);
216 void PrelinEval16(register const cmsUInt16Number Input[],
217 register cmsUInt16Number Output[],
218 register const void* D)
220 Prelin16Data* p16 = (Prelin16Data*) D;
221 cmsUInt16Number StageABC[MAX_INPUT_DIMENSIONS];
224 for (i=0; i < p16 ->nInputs; i++) {
226 p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);
229 p16 ->EvalCLUT(StageABC, p16 ->StageDEF, p16 ->CLUTparams);
231 for (i=0; i < p16 ->nOutputs; i++) {
233 p16 ->EvalCurveOut16[i](&p16->StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
239 void PrelinOpt16free(cmsContext ContextID, void* ptr)
241 Prelin16Data* p16 = (Prelin16Data*) ptr;
243 _cmsFree(ContextID, p16 ->StageDEF);
244 _cmsFree(ContextID, p16 ->EvalCurveOut16);
245 _cmsFree(ContextID, p16 ->ParamsCurveOut16);
247 _cmsFree(ContextID, p16);
251 void* Prelin16dup(cmsContext ContextID, const void* ptr)
253 Prelin16Data* p16 = (Prelin16Data*) ptr;
254 Prelin16Data* Duped = _cmsDupMem(ContextID, p16, sizeof(Prelin16Data));
256 if (Duped == NULL) return NULL;
258 Duped ->StageDEF = _cmsCalloc(ContextID, p16 ->nOutputs, sizeof(cmsUInt16Number));
259 Duped ->EvalCurveOut16 = _cmsDupMem(ContextID, p16 ->EvalCurveOut16, p16 ->nOutputs * sizeof(_cmsInterpFn16));
260 Duped ->ParamsCurveOut16 = _cmsDupMem(ContextID, p16 ->ParamsCurveOut16, p16 ->nOutputs * sizeof(cmsInterpParams* ));
267 Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,
268 const cmsInterpParams* ColorMap,
269 int nInputs, cmsToneCurve** In,
270 int nOutputs, cmsToneCurve** Out )
273 Prelin16Data* p16 = (Prelin16Data*) _cmsMallocZero(ContextID, sizeof(Prelin16Data));
274 if (p16 == NULL) return NULL;
276 p16 ->nInputs = nInputs;
277 p16 -> nOutputs = nOutputs;
280 for (i=0; i < nInputs; i++) {
283 p16 -> ParamsCurveIn16[i] = NULL;
284 p16 -> EvalCurveIn16[i] = Eval16nop1D;
288 p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams;
289 p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16;
293 p16 ->CLUTparams = ColorMap;
294 p16 ->EvalCLUT = ColorMap ->Interpolation.Lerp16;
297 p16 -> StageDEF = _cmsCalloc(ContextID, p16 ->nOutputs, sizeof(cmsUInt16Number));
298 p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));
299 p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));
301 for (i=0; i < nOutputs; i++) {
304 p16 ->ParamsCurveOut16[i] = NULL;
305 p16 -> EvalCurveOut16[i] = Eval16nop1D;
309 p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;
310 p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;
319 // Resampling ---------------------------------------------------------------------------------
321 #define PRELINEARIZATION_POINTS 4096
323 // Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for
324 // almost any transform. We use floating point precision and then convert from floating point to 16 bits.
326 int XFormSampler16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
328 cmsPipeline* Lut = (cmsPipeline*) Cargo;
329 cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
332 _cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);
333 _cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);
335 // From 16 bit to floating point
336 for (i=0; i < Lut ->InputChannels; i++)
337 InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);
339 // Evaluate in floating point
340 cmsPipelineEvalFloat(InFloat, OutFloat, Lut);
342 // Back to 16 bits representation
343 for (i=0; i < Lut ->OutputChannels; i++)
344 Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);
350 // Try to see if the curves of a given MPE are linear
352 cmsBool AllCurvesAreLinear(cmsStage* mpe)
354 cmsToneCurve** Curves;
355 cmsUInt32Number i, n;
357 Curves = _cmsStageGetPtrToCurveSet(mpe);
358 if (Curves == NULL) return FALSE;
360 n = cmsStageOutputChannels(mpe);
362 for (i=0; i < n; i++) {
363 if (!cmsIsToneCurveLinear(Curves[i])) return FALSE;
369 // This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose
370 // is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels
372 cmsBool PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],
373 int nChannelsOut, int nChannelsIn)
375 _cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;
376 cmsInterpParams* p16 = Grid ->Params;
377 cmsFloat64Number px, py, pz, pw;
381 if (CLUT -> Type != cmsSigCLutElemType) {
382 cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut MPE");
386 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
387 py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
388 pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
389 pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;
391 x0 = (int) floor(px);
392 y0 = (int) floor(py);
393 z0 = (int) floor(pz);
394 w0 = (int) floor(pw);
396 if (nChannelsIn == 4) {
398 if (((px - x0) != 0) ||
401 ((pw - w0) != 0)) return FALSE; // Not on exact node
403 index = p16 -> opta[3] * x0 +
404 p16 -> opta[2] * y0 +
405 p16 -> opta[1] * z0 +
409 if (nChannelsIn == 3) {
411 if (((px - x0) != 0) ||
413 ((pz - z0) != 0)) return FALSE; // Not on exact node
415 index = p16 -> opta[2] * x0 +
416 p16 -> opta[1] * y0 +
420 if (nChannelsIn == 1) {
422 if (((px - x0) != 0)) return FALSE; // Not on exact node
424 index = p16 -> opta[0] * x0;
427 cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
431 for (i=0; i < nChannelsOut; i++)
432 Grid -> Tab.T[index + i] = Value[i];
437 // Auxiliar, to see if two values are equal.
439 cmsBool WhitesAreEqual(int n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
443 for (i=0; i < n; i++) {
444 if (White1[i] != White2[i]) return FALSE;
450 // Locate the node for the white point and fix it to pure white in order to avoid scum dot.
452 cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)
454 cmsUInt16Number *WhitePointIn, *WhitePointOut;
455 cmsUInt16Number WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];
456 cmsUInt32Number i, nOuts, nIns;
457 cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;
459 if (!_cmsEndPointsBySpace(EntryColorSpace,
460 &WhitePointIn, NULL, &nIns)) return FALSE;
462 if (!_cmsEndPointsBySpace(ExitColorSpace,
463 &WhitePointOut, NULL, &nOuts)) return FALSE;
465 // It needs to be fixed?
467 cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut);
469 if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match
471 // Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations
472 if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))
473 if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))
474 if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))
475 if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT))
478 // We need to interpolate white points of both, pre and post curves
481 cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);
483 for (i=0; i < nIns; i++) {
484 WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]);
488 for (i=0; i < nIns; i++)
489 WhiteIn[i] = WhitePointIn[i];
492 // If any post-linearization, we need to find how is represented white before the curve, do
493 // a reverse interpolation in this case.
496 cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);
498 for (i=0; i < nOuts; i++) {
500 cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
501 WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
502 cmsFreeToneCurve(InversePostLin);
506 for (i=0; i < nOuts; i++)
507 WhiteOut[i] = WhitePointOut[i];
510 // Ok, proceed with patching. May fail and we don't care if it fails
511 PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns);
516 // -----------------------------------------------------------------------------------------------------------------------------------------------
517 // This function creates simple LUT from complex ones. The generated LUT has an optional set of
518 // prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.
519 // These curves have to exist in the original LUT in order to be used in the simplified output.
520 // Caller may also use the flags to allow this feature.
521 // LUTS with all curves will be simplified to a single curve. Parametric curves are lost.
522 // This function should be used on 16-bits LUTS only, as floating point losses precision when simplified
523 // -----------------------------------------------------------------------------------------------------------------------------------------------
526 cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
531 cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;
533 cmsColorSpaceSignature ColorSpace, OutputColorSpace;
534 cmsStage *NewPreLin = NULL;
535 cmsStage *NewPostLin = NULL;
536 _cmsStageCLutData* DataCLUT;
537 cmsToneCurve** DataSetIn;
538 cmsToneCurve** DataSetOut;
542 // This is a loosy optimization! does not apply in floating-point cases
543 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
545 ColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat));
546 OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat));
547 nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
549 // For empty LUTs, 2 points are enough
550 if (cmsPipelineStageCount(*Lut) == 0)
555 // Allocate an empty LUT
556 Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
557 if (!Dest) return FALSE;
559 // Prelinearization tables are kept unless indicated by flags
560 if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {
562 // Get a pointer to the prelinearization element
563 cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);
566 if (PreLin ->Type == cmsSigCurveSetElemType) {
568 // Maybe this is a linear tram, so we can avoid the whole stuff
569 if (!AllCurvesAreLinear(PreLin)) {
571 // All seems ok, proceed.
572 NewPreLin = cmsStageDup(PreLin);
573 cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin);
575 // Remove prelinearization. Since we have duplicated the curve
576 // in destination LUT, the sampling shoud be applied after this stage.
577 cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin);
583 CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);
584 if (CLUT == NULL) return FALSE;
586 // Add the CLUT to the destination LUT
587 cmsPipelineInsertStage(Dest, cmsAT_END, CLUT);
589 // Postlinearization tables are kept unless indicated by flags
590 if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {
592 // Get a pointer to the postlinearization if present
593 cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);
596 if (cmsStageType(PostLin) == cmsSigCurveSetElemType) {
598 // Maybe this is a linear tram, so we can avoid the whole stuff
599 if (!AllCurvesAreLinear(PostLin)) {
601 // All seems ok, proceed.
602 NewPostLin = cmsStageDup(PostLin);
603 cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin);
605 // In destination LUT, the sampling shoud be applied after this stage.
606 cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);
611 // Now its time to do the sampling. We have to ignore pre/post linearization
612 // The source LUT whithout pre/post curves is passed as parameter.
613 if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {
615 // Ops, something went wrong, Restore stages
616 if (KeepPreLin != NULL) cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin);
617 if (KeepPostLin != NULL) cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin);
618 cmsPipelineFree(Dest);
624 if (KeepPreLin != NULL) cmsStageFree(KeepPreLin);
625 if (KeepPostLin != NULL) cmsStageFree(KeepPostLin);
626 cmsPipelineFree(Src);
628 DataCLUT = (_cmsStageCLutData*) CLUT ->Data;
630 if (NewPreLin == NULL) DataSetIn = NULL;
631 else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;
633 if (NewPostLin == NULL) DataSetOut = NULL;
634 else DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;
637 if (DataSetIn == NULL && DataSetOut == NULL) {
639 _cmsPipelineSetOptimizationParameters(Dest, (_cmsOPTeval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);
643 p16 = PrelinOpt16alloc(Dest ->ContextID,
645 Dest ->InputChannels,
647 Dest ->OutputChannels,
651 _cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
655 // Don't fix white on absolute colorimetric
656 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
657 *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
659 if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
661 FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace);
667 cmsUNUSED_PARAMETER(Intent);
671 // -----------------------------------------------------------------------------------------------------------------------------------------------
672 // Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on
673 // Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works
674 // for RGB transforms. See the paper for more details
675 // -----------------------------------------------------------------------------------------------------------------------------------------------
678 // Normalize endpoints by slope limiting max and min. This assures endpoints as well.
679 // Descending curves are handled as well.
681 void SlopeLimiting(cmsToneCurve* g)
683 int BeginVal, EndVal;
684 int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5); // Cutoff at 2%
685 int AtEnd = g ->nEntries - AtBegin - 1; // And 98%
686 cmsFloat64Number Val, Slope, beta;
689 if (cmsIsToneCurveDescending(g)) {
690 BeginVal = 0xffff; EndVal = 0;
693 BeginVal = 0; EndVal = 0xffff;
696 // Compute slope and offset for begin of curve
697 Val = g ->Table16[AtBegin];
698 Slope = (Val - BeginVal) / AtBegin;
699 beta = Val - Slope * AtBegin;
701 for (i=0; i < AtBegin; i++)
702 g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
704 // Compute slope and offset for the end
705 Val = g ->Table16[AtEnd];
706 Slope = (EndVal - Val) / AtBegin; // AtBegin holds the X interval, which is same in both cases
707 beta = Val - Slope * AtEnd;
709 for (i = AtEnd; i < (int) g ->nEntries; i++)
710 g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
714 // Precomputes tables for 8-bit on input devicelink.
716 Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])
719 cmsUInt16Number Input[3];
720 cmsS15Fixed16Number v1, v2, v3;
723 p8 = _cmsMallocZero(ContextID, sizeof(Prelin8Data));
724 if (p8 == NULL) return NULL;
726 // Since this only works for 8 bit input, values comes always as x * 257,
727 // we can safely take msb byte (x << 8 + x)
729 for (i=0; i < 256; i++) {
733 // Get 16-bit representation
734 Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i));
735 Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i));
736 Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i));
739 Input[0] = FROM_8_TO_16(i);
740 Input[1] = FROM_8_TO_16(i);
741 Input[2] = FROM_8_TO_16(i);
745 // Move to 0..1.0 in fixed domain
746 v1 = _cmsToFixedDomain(Input[0] * p -> Domain[0]);
747 v2 = _cmsToFixedDomain(Input[1] * p -> Domain[1]);
748 v3 = _cmsToFixedDomain(Input[2] * p -> Domain[2]);
750 // Store the precalculated table of nodes
751 p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));
752 p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));
753 p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));
755 // Store the precalculated table of offsets
756 p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);
757 p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);
758 p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);
761 p8 ->ContextID = ContextID;
768 void Prelin8free(cmsContext ContextID, void* ptr)
770 _cmsFree(ContextID, ptr);
774 void* Prelin8dup(cmsContext ContextID, const void* ptr)
776 return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));
781 // A optimized interpolation for 8-bit input.
782 #define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
784 void PrelinEval8(register const cmsUInt16Number Input[],
785 register cmsUInt16Number Output[],
786 register const void* D)
789 cmsUInt8Number r, g, b;
790 cmsS15Fixed16Number rx, ry, rz;
791 cmsS15Fixed16Number c0, c1, c2, c3, Rest;
793 register cmsS15Fixed16Number X0, X1, Y0, Y1, Z0, Z1;
794 Prelin8Data* p8 = (Prelin8Data*) D;
795 register const cmsInterpParams* p = p8 ->p;
796 int TotalOut = p -> nOutputs;
797 const cmsUInt16Number* LutTable = p -> Table;
811 X1 = X0 + ((rx == 0) ? 0 : p ->opta[2]);
812 Y1 = Y0 + ((ry == 0) ? 0 : p ->opta[1]);
813 Z1 = Z0 + ((rz == 0) ? 0 : p ->opta[0]);
816 // These are the 6 Tetrahedral
817 for (OutChan=0; OutChan < TotalOut; OutChan++) {
819 c0 = DENS(X0, Y0, Z0);
821 if (rx >= ry && ry >= rz)
823 c1 = DENS(X1, Y0, Z0) - c0;
824 c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
825 c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
828 if (rx >= rz && rz >= ry)
830 c1 = DENS(X1, Y0, Z0) - c0;
831 c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
832 c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
835 if (rz >= rx && rx >= ry)
837 c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
838 c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
839 c3 = DENS(X0, Y0, Z1) - c0;
842 if (ry >= rx && rx >= rz)
844 c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
845 c2 = DENS(X0, Y1, Z0) - c0;
846 c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
849 if (ry >= rz && rz >= rx)
851 c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
852 c2 = DENS(X0, Y1, Z0) - c0;
853 c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
856 if (rz >= ry && ry >= rx)
858 c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
859 c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
860 c3 = DENS(X0, Y0, Z1) - c0;
867 Rest = c1 * rx + c2 * ry + c3 * rz;
869 Output[OutChan] = (cmsUInt16Number)c0 + ROUND_FIXED_TO_INT(_cmsToFixedDomain(Rest));
876 // --------------------------------------------------------------------------------------------------------------
877 // We need xput over here
880 cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
882 cmsPipeline* OriginalLut;
884 cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];
885 cmsUInt32Number t, i;
886 cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];
887 cmsBool lIsSuitable, lIsLinear;
888 cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;
889 cmsStage* OptimizedCLUTmpe;
890 cmsColorSpaceSignature ColorSpace, OutputColorSpace;
891 cmsStage* OptimizedPrelinMpe;
892 cmsToneCurve** OptimizedPrelinCurves;
893 _cmsStageCLutData* OptimizedPrelinCLUT;
896 // This is a loosy optimization! does not apply in floating-point cases
897 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
900 if (T_COLORSPACE(*InputFormat) != PT_RGB) return FALSE;
901 if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
904 // On 16 bits, user has to specify the feature
905 if (!_cmsFormatterIs8bit(*InputFormat)) {
906 if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;
910 ColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat));
911 OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat));
912 nGridPoints = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
914 // Empty gamma containers
915 memset(Trans, 0, sizeof(Trans));
916 memset(TransReverse, 0, sizeof(TransReverse));
918 for (t = 0; t < OriginalLut ->InputChannels; t++) {
919 Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);
920 if (Trans[t] == NULL) goto Error;
923 // Populate the curves
924 for (i=0; i < PRELINEARIZATION_POINTS; i++) {
926 v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
928 // Feed input with a gray ramp
929 for (t=0; t < OriginalLut ->InputChannels; t++)
932 // Evaluate the gray value
933 cmsPipelineEvalFloat(In, Out, OriginalLut);
935 // Store result in curve
936 for (t=0; t < OriginalLut ->InputChannels; t++)
937 Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);
940 // Slope-limit the obtained curves
941 for (t = 0; t < OriginalLut ->InputChannels; t++)
942 SlopeLimiting(Trans[t]);
944 // Check for validity
947 for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {
949 // Exclude if already linear
950 if (!cmsIsToneCurveLinear(Trans[t]))
953 // Exclude if non-monotonic
954 if (!cmsIsToneCurveMonotonic(Trans[t]))
958 // If it is not suitable, just quit
959 if (!lIsSuitable) goto Error;
961 // Invert curves if possible
962 for (t = 0; t < OriginalLut ->InputChannels; t++) {
963 TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]);
964 if (TransReverse[t] == NULL) goto Error;
967 // Now inset the reversed curves at the begin of transform
968 LutPlusCurves = cmsPipelineDup(OriginalLut);
969 if (LutPlusCurves == NULL) goto Error;
971 cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse));
973 // Create the result LUT
974 OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);
975 if (OptimizedLUT == NULL) goto Error;
977 OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);
979 // Create and insert the curves at the beginning
980 cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe);
982 // Allocate the CLUT for result
983 OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);
985 // Add the CLUT to the destination LUT
986 cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe);
989 if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;
992 for (t = 0; t < OriginalLut ->InputChannels; t++) {
994 if (Trans[t]) cmsFreeToneCurve(Trans[t]);
995 if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
998 cmsPipelineFree(LutPlusCurves);
1001 OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);
1002 OptimizedPrelinCLUT = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;
1004 // Set the evaluator if 8-bit
1005 if (_cmsFormatterIs8bit(*InputFormat)) {
1007 Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID,
1008 OptimizedPrelinCLUT ->Params,
1009 OptimizedPrelinCurves);
1010 if (p8 == NULL) return FALSE;
1012 _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);
1017 Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID,
1018 OptimizedPrelinCLUT ->Params,
1019 3, OptimizedPrelinCurves, 3, NULL);
1020 if (p16 == NULL) return FALSE;
1022 _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
1026 // Don't fix white on absolute colorimetric
1027 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
1028 *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
1030 if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
1032 if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) {
1038 // And return the obtained LUT
1040 cmsPipelineFree(OriginalLut);
1041 *Lut = OptimizedLUT;
1046 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1048 if (Trans[t]) cmsFreeToneCurve(Trans[t]);
1049 if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
1052 if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves);
1053 if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT);
1057 cmsUNUSED_PARAMETER(Intent);
1061 // Curves optimizer ------------------------------------------------------------------------------------------------------------------
1064 void CurvesFree(cmsContext ContextID, void* ptr)
1066 Curves16Data* Data = (Curves16Data*) ptr;
1069 for (i=0; i < Data -> nCurves; i++) {
1071 _cmsFree(ContextID, Data ->Curves[i]);
1074 _cmsFree(ContextID, Data ->Curves);
1075 _cmsFree(ContextID, ptr);
1079 void* CurvesDup(cmsContext ContextID, const void* ptr)
1081 Curves16Data* Data = _cmsDupMem(ContextID, ptr, sizeof(Curves16Data));
1084 if (Data == NULL) return NULL;
1086 Data ->Curves = _cmsDupMem(ContextID, Data ->Curves, Data ->nCurves * sizeof(cmsUInt16Number*));
1088 for (i=0; i < Data -> nCurves; i++) {
1089 Data ->Curves[i] = _cmsDupMem(ContextID, Data ->Curves[i], Data -> nElements * sizeof(cmsUInt16Number));
1092 return (void*) Data;
1095 // Precomputes tables for 8-bit on input devicelink.
1097 Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)
1102 c16 = _cmsMallocZero(ContextID, sizeof(Curves16Data));
1103 if (c16 == NULL) return NULL;
1105 c16 ->nCurves = nCurves;
1106 c16 ->nElements = nElements;
1108 c16 ->Curves = _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
1109 if (c16 ->Curves == NULL) return NULL;
1111 for (i=0; i < nCurves; i++) {
1113 c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
1115 if (nElements == 256) {
1117 for (j=0; j < nElements; j++) {
1119 c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
1124 for (j=0; j < nElements; j++) {
1125 c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
1134 void FastEvaluateCurves8(register const cmsUInt16Number In[],
1135 register cmsUInt16Number Out[],
1136 register const void* D)
1138 Curves16Data* Data = (Curves16Data*) D;
1142 for (i=0; i < Data ->nCurves; i++) {
1145 Out[i] = Data -> Curves[i][x];
1151 void FastEvaluateCurves16(register const cmsUInt16Number In[],
1152 register cmsUInt16Number Out[],
1153 register const void* D)
1155 Curves16Data* Data = (Curves16Data*) D;
1158 for (i=0; i < Data ->nCurves; i++) {
1159 Out[i] = Data -> Curves[i][In[i]];
1165 void FastIdentity16(register const cmsUInt16Number In[],
1166 register cmsUInt16Number Out[],
1167 register const void* D)
1169 cmsPipeline* Lut = (cmsPipeline*) D;
1172 for (i=0; i < Lut ->InputChannels; i++) {
1178 // If the target LUT holds only curves, the optimization procedure is to join all those
1179 // curves together. That only works on curves and does not work on matrices.
1181 cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1183 cmsToneCurve** GammaTables = NULL;
1184 cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
1185 cmsUInt32Number i, j;
1186 cmsPipeline* Src = *Lut;
1187 cmsPipeline* Dest = NULL;
1189 cmsStage* ObtainedCurves = NULL;
1192 // This is a loosy optimization! does not apply in floating-point cases
1193 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
1195 // Only curves in this LUT?
1196 for (mpe = cmsPipelineGetPtrToFirstStage(Src);
1198 mpe = cmsStageNext(mpe)) {
1199 if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE;
1202 // Allocate an empty LUT
1203 Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
1204 if (Dest == NULL) return FALSE;
1206 // Create target curves
1207 GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));
1208 if (GammaTables == NULL) goto Error;
1210 for (i=0; i < Src ->InputChannels; i++) {
1211 GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL);
1212 if (GammaTables[i] == NULL) goto Error;
1215 // Compute 16 bit result by using floating point
1216 for (i=0; i < PRELINEARIZATION_POINTS; i++) {
1218 for (j=0; j < Src ->InputChannels; j++)
1219 InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
1221 cmsPipelineEvalFloat(InFloat, OutFloat, Src);
1223 for (j=0; j < Src ->InputChannels; j++)
1224 GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);
1227 ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables);
1228 if (ObtainedCurves == NULL) goto Error;
1230 for (i=0; i < Src ->InputChannels; i++) {
1231 cmsFreeToneCurve(GammaTables[i]);
1232 GammaTables[i] = NULL;
1235 if (GammaTables != NULL) _cmsFree(Src ->ContextID, GammaTables);
1237 // Maybe the curves are linear at the end
1238 if (!AllCurvesAreLinear(ObtainedCurves)) {
1240 cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves);
1242 // If the curves are to be applied in 8 bits, we can save memory
1243 if (_cmsFormatterIs8bit(*InputFormat)) {
1245 _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) ObtainedCurves ->Data;
1246 Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);
1248 *dwFlags |= cmsFLAGS_NOCACHE;
1249 _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);
1254 _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);
1255 Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);
1257 *dwFlags |= cmsFLAGS_NOCACHE;
1258 _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);
1263 // LUT optimizes to nothing. Set the identity LUT
1264 cmsStageFree(ObtainedCurves);
1266 cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels));
1268 *dwFlags |= cmsFLAGS_NOCACHE;
1269 _cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);
1273 cmsPipelineFree(Src);
1279 if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves);
1280 if (GammaTables != NULL) {
1281 for (i=0; i < Src ->InputChannels; i++) {
1282 if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]);
1285 _cmsFree(Src ->ContextID, GammaTables);
1288 if (Dest != NULL) cmsPipelineFree(Dest);
1291 cmsUNUSED_PARAMETER(Intent);
1292 cmsUNUSED_PARAMETER(InputFormat);
1293 cmsUNUSED_PARAMETER(OutputFormat);
1294 cmsUNUSED_PARAMETER(dwFlags);
1297 // -------------------------------------------------------------------------------------------------------------------------------------
1298 // LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles
1302 void FreeMatShaper(cmsContext ContextID, void* Data)
1304 if (Data != NULL) _cmsFree(ContextID, Data);
1308 void* DupMatShaper(cmsContext ContextID, const void* Data)
1310 return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));
1314 // A fast matrix-shaper evaluator for 8 bits. This is a bit ticky since I'm using 1.14 signed fixed point
1315 // to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,
1316 // in total about 50K, and the performance boost is huge!
1318 void MatShaperEval16(register const cmsUInt16Number In[],
1319 register cmsUInt16Number Out[],
1320 register const void* D)
1322 MatShaper8Data* p = (MatShaper8Data*) D;
1323 cmsS1Fixed14Number l1, l2, l3, r, g, b;
1324 cmsUInt32Number ri, gi, bi;
1326 // In this case (and only in this case!) we can use this simplification since
1327 // In[] is assured to come from a 8 bit number. (a << 8 | a)
1332 // Across first shaper, which also converts to 1.14 fixed point
1333 r = p->Shaper1R[ri];
1334 g = p->Shaper1G[gi];
1335 b = p->Shaper1B[bi];
1337 // Evaluate the matrix in 1.14 fixed point
1338 l1 = (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;
1339 l2 = (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;
1340 l3 = (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;
1342 // Now we have to clip to 0..1.0 range
1343 ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384 : l1);
1344 gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384 : l2);
1345 bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384 : l3);
1347 // And across second shaper,
1348 Out[0] = p->Shaper2R[ri];
1349 Out[1] = p->Shaper2G[gi];
1350 Out[2] = p->Shaper2B[bi];
1354 // This table converts from 8 bits to 1.14 after applying the curve
1356 void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve)
1359 cmsFloat32Number R, y;
1361 for (i=0; i < 256; i++) {
1363 R = (cmsFloat32Number) (i / 255.0);
1364 y = cmsEvalToneCurveFloat(Curve, R);
1366 Table[i] = DOUBLE_TO_1FIXED14(y);
1370 // This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve
1372 void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)
1375 cmsFloat32Number R, Val;
1377 for (i=0; i < 16385; i++) {
1379 R = (cmsFloat32Number) (i / 16384.0);
1380 Val = cmsEvalToneCurveFloat(Curve, R); // Val comes 0..1.0
1382 if (Is8BitsOutput) {
1384 // If 8 bits output, we can optimize further by computing the / 257 part.
1385 // first we compute the resulting byte and then we store the byte times
1386 // 257. This quantization allows to round very quick by doing a >> 8, but
1387 // since the low byte is always equal to msb, we can do a & 0xff and this works!
1388 cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0 + 0.5);
1389 cmsUInt8Number b = FROM_16_TO_8(w);
1391 Table[i] = FROM_8_TO_16(b);
1393 else Table[i] = _cmsQuickSaturateWord(Val * 65535.0 + 0.5);
1397 // Compute the matrix-shaper structure
1399 cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)
1403 cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);
1405 // Allocate a big chuck of memory to store precomputed tables
1406 p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));
1407 if (p == NULL) return FALSE;
1409 p -> ContextID = Dest -> ContextID;
1411 // Precompute tables
1412 FillFirstShaper(p ->Shaper1R, Curve1[0]);
1413 FillFirstShaper(p ->Shaper1G, Curve1[1]);
1414 FillFirstShaper(p ->Shaper1B, Curve1[2]);
1416 FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits);
1417 FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits);
1418 FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits);
1420 // Convert matrix to nFixed14. Note that those values may take more than 16 bits as
1421 for (i=0; i < 3; i++) {
1422 for (j=0; j < 3; j++) {
1423 p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);
1427 for (i=0; i < 3; i++) {
1433 p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);
1437 // Mark as optimized for faster formatter
1439 *OutputFormat |= OPTIMIZED_SH(1);
1441 // Fill function pointers
1442 _cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);
1446 // 8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!
1447 // TODO: Allow a third matrix for abs. colorimetric
1449 cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1451 cmsStage* Curve1, *Curve2;
1452 cmsStage* Matrix1, *Matrix2;
1453 _cmsStageMatrixData* Data1;
1454 _cmsStageMatrixData* Data2;
1456 cmsBool IdentityMat;
1457 cmsPipeline* Dest, *Src;
1459 // Only works on RGB to RGB
1460 if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;
1462 // Only works on 8 bit input
1463 if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;
1465 // Seems suitable, proceed
1468 // Check for shaper-matrix-matrix-shaper structure, that is what this optimizer stands for
1469 if (!cmsPipelineCheckAndRetreiveStages(Src, 4,
1470 cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
1471 &Curve1, &Matrix1, &Matrix2, &Curve2)) return FALSE;
1473 // Get both matrices
1474 Data1 = (_cmsStageMatrixData*) cmsStageData(Matrix1);
1475 Data2 = (_cmsStageMatrixData*) cmsStageData(Matrix2);
1477 // Input offset should be zero
1478 if (Data1 ->Offset != NULL) return FALSE;
1480 // Multiply both matrices to get the result
1481 _cmsMAT3per(&res, (cmsMAT3*) Data2 ->Double, (cmsMAT3*) Data1 ->Double);
1483 // Now the result is in res + Data2 -> Offset. Maybe is a plain identity?
1484 IdentityMat = FALSE;
1485 if (_cmsMAT3isIdentity(&res) && Data2 ->Offset == NULL) {
1487 // We can get rid of full matrix
1491 // Allocate an empty LUT
1492 Dest = cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
1493 if (!Dest) return FALSE;
1495 // Assamble the new LUT
1496 cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1));
1498 cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest ->ContextID, 3, 3, (const cmsFloat64Number*) &res, Data2 ->Offset));
1499 cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2));
1501 // If identity on matrix, we can further optimize the curves, so call the join curves routine
1504 OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags);
1507 _cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1);
1508 _cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2);
1510 // In this particular optimization, cach� does not help as it takes more time to deal with
1511 // the cach� that with the pixel handling
1512 *dwFlags |= cmsFLAGS_NOCACHE;
1514 // Setup the optimizarion routines
1515 SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Data2 ->Offset, mpeC2->TheCurves, OutputFormat);
1518 cmsPipelineFree(Src);
1524 // -------------------------------------------------------------------------------------------------------------------------------------
1525 // Optimization plug-ins
1527 // List of optimizations
1528 typedef struct _cmsOptimizationCollection_st {
1530 _cmsOPToptimizeFn OptimizePtr;
1532 struct _cmsOptimizationCollection_st *Next;
1534 } _cmsOptimizationCollection;
1537 // The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling
1538 static _cmsOptimizationCollection DefaultOptimization[] = {
1540 { OptimizeByJoiningCurves, &DefaultOptimization[1] },
1541 { OptimizeMatrixShaper, &DefaultOptimization[2] },
1542 { OptimizeByComputingLinearization, &DefaultOptimization[3] },
1543 { OptimizeByResampling, NULL }
1546 // The linked list head
1547 static _cmsOptimizationCollection* OptimizationCollection = DefaultOptimization;
1549 // Register new ways to optimize
1550 cmsBool _cmsRegisterOptimizationPlugin(cmsPluginBase* Data)
1552 cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
1553 _cmsOptimizationCollection* fl;
1557 OptimizationCollection = DefaultOptimization;
1561 // Optimizer callback is required
1562 if (Plugin ->OptimizePtr == NULL) return FALSE;
1564 fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(sizeof(_cmsOptimizationCollection));
1565 if (fl == NULL) return FALSE;
1567 // Copy the parameters
1568 fl ->OptimizePtr = Plugin ->OptimizePtr;
1571 fl ->Next = OptimizationCollection;
1572 OptimizationCollection = fl;
1578 // The entry point for LUT optimization
1579 cmsBool _cmsOptimizePipeline(cmsPipeline** PtrLut,
1581 cmsUInt32Number* InputFormat,
1582 cmsUInt32Number* OutputFormat,
1583 cmsUInt32Number* dwFlags)
1585 _cmsOptimizationCollection* Opts;
1586 cmsBool AnySuccess = FALSE;
1588 // A CLUT is being asked, so force this specific optimization
1589 if (*dwFlags & cmsFLAGS_FORCE_CLUT) {
1591 PreOptimize(*PtrLut);
1592 return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags);
1595 // Anything to optimize?
1596 if ((*PtrLut) ->Elements == NULL) {
1597 _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1601 // Try to get rid of identities and trivial conversions.
1602 AnySuccess = PreOptimize(*PtrLut);
1604 // After removal do we end with an identity?
1605 if ((*PtrLut) ->Elements == NULL) {
1606 _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1610 // Do not optimize, keep all precision
1611 if (*dwFlags & cmsFLAGS_NOOPTIMIZE)
1614 // Try built-in optimizations and plug-in
1615 for (Opts = OptimizationCollection;
1617 Opts = Opts ->Next) {
1619 // If one schema succeeded, we are done
1620 if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1622 return TRUE; // Optimized!
1626 // Only simple optimizations succeeded