1//---------------------------------------------------------------------------------
2//
3//  Little Color Management System
4//  Copyright (c) 1998-2011 Marti Maria Saguer
5//
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:
12//
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15//
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.
23//
24//---------------------------------------------------------------------------------
25//
26
27#include "lcms2_internal.h"
28
29
30//----------------------------------------------------------------------------------
31
32// Optimization for 8 bits, Shaper-CLUT (3 inputs only)
33typedef struct {
34
35    cmsContext ContextID;
36
37    const cmsInterpParams* p;   // Tetrahedrical interpolation parameters. This is a not-owned pointer.
38
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
41
42
43} Prelin8Data;
44
45
46// Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs)
47typedef struct {
48
49    cmsContext ContextID;
50
51    // Number of channels
52    int nInputs;
53    int nOutputs;
54
55    _cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS];       // The maximum number of input channels is known in advance
56    cmsInterpParams*  ParamsCurveIn16[MAX_INPUT_DIMENSIONS];
57
58    _cmsInterpFn16 EvalCLUT;            // The evaluator for 3D grid
59    const cmsInterpParams* CLUTparams;  // (not-owned pointer)
60
61
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)
64
65
66} Prelin16Data;
67
68
69// Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed
70
71typedef cmsInt32Number cmsS1Fixed14Number;   // Note that this may hold more than 16 bits!
72
73#define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5))
74
75typedef struct {
76
77    cmsContext ContextID;
78
79    cmsS1Fixed14Number Shaper1R[256];  // from 0..255 to 1.14  (0.0...1.0)
80    cmsS1Fixed14Number Shaper1G[256];
81    cmsS1Fixed14Number Shaper1B[256];
82
83    cmsS1Fixed14Number Mat[3][3];     // n.14 to n.14 (needs a saturation after that)
84    cmsS1Fixed14Number Off[3];
85
86    cmsUInt16Number Shaper2R[16385];    // 1.14 to 0..255
87    cmsUInt16Number Shaper2G[16385];
88    cmsUInt16Number Shaper2B[16385];
89
90} MatShaper8Data;
91
92// Curves, optimization is shared between 8 and 16 bits
93typedef struct {
94
95    cmsContext ContextID;
96
97    int nCurves;                  // Number of curves
98    int nElements;                // Elements in curves
99    cmsUInt16Number** Curves;     // Points to a dynamically  allocated array
100
101} Curves16Data;
102
103
104// Simple optimizations ----------------------------------------------------------------------------------------------------------
105
106
107// Remove an element in linked chain
108static
109void _RemoveElement(cmsStage** head)
110{
111    cmsStage* mpe = *head;
112    cmsStage* next = mpe ->Next;
113    *head = next;
114    cmsStageFree(mpe);
115}
116
117// Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer.
118static
119cmsBool _Remove1Op(cmsPipeline* Lut, cmsStageSignature UnaryOp)
120{
121    cmsStage** pt = &Lut ->Elements;
122    cmsBool AnyOpt = FALSE;
123
124    while (*pt != NULL) {
125
126        if ((*pt) ->Implements == UnaryOp) {
127            _RemoveElement(pt);
128            AnyOpt = TRUE;
129        }
130        else
131            pt = &((*pt) -> Next);
132    }
133
134    return AnyOpt;
135}
136
137// Same, but only if two adjacent elements are found
138static
139cmsBool _Remove2Op(cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2)
140{
141    cmsStage** pt1;
142    cmsStage** pt2;
143    cmsBool AnyOpt = FALSE;
144
145    pt1 = &Lut ->Elements;
146    if (*pt1 == NULL) return AnyOpt;
147
148    while (*pt1 != NULL) {
149
150        pt2 = &((*pt1) -> Next);
151        if (*pt2 == NULL) return AnyOpt;
152
153        if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) {
154            _RemoveElement(pt2);
155            _RemoveElement(pt1);
156            AnyOpt = TRUE;
157        }
158        else
159            pt1 = &((*pt1) -> Next);
160    }
161
162    return AnyOpt;
163}
164
165// Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed
166// by a v4 to v2 and vice-versa. The elements are then discarded.
167static
168cmsBool PreOptimize(cmsPipeline* Lut)
169{
170    cmsBool AnyOpt = FALSE, Opt;
171
172    do {
173
174        Opt = FALSE;
175
176        // Remove all identities
177        Opt |= _Remove1Op(Lut, cmsSigIdentityElemType);
178
179        // Remove XYZ2Lab followed by Lab2XYZ
180        Opt |= _Remove2Op(Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType);
181
182        // Remove Lab2XYZ followed by XYZ2Lab
183        Opt |= _Remove2Op(Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType);
184
185        // Remove V4 to V2 followed by V2 to V4
186        Opt |= _Remove2Op(Lut, cmsSigLabV4toV2, cmsSigLabV2toV4);
187
188        // Remove V2 to V4 followed by V4 to V2
189        Opt |= _Remove2Op(Lut, cmsSigLabV2toV4, cmsSigLabV4toV2);
190
191        // Remove float pcs Lab conversions
192        Opt |= _Remove2Op(Lut, cmsSigLab2FloatPCS, cmsSigFloatPCS2Lab);
193
194        // Remove float pcs Lab conversions
195        Opt |= _Remove2Op(Lut, cmsSigXYZ2FloatPCS, cmsSigFloatPCS2XYZ);
196
197        if (Opt) AnyOpt = TRUE;
198
199    } while (Opt);
200
201    return AnyOpt;
202}
203
204static
205void Eval16nop1D(register const cmsUInt16Number Input[],
206                 register cmsUInt16Number Output[],
207                 register const struct _cms_interp_struc* p)
208{
209    Output[0] = Input[0];
210
211    cmsUNUSED_PARAMETER(p);
212}
213
214static
215void PrelinEval16(register const cmsUInt16Number Input[],
216                  register cmsUInt16Number Output[],
217                  register const void* D)
218{
219    Prelin16Data* p16 = (Prelin16Data*) D;
220    cmsUInt16Number  StageABC[MAX_INPUT_DIMENSIONS];
221    cmsUInt16Number  StageDEF[cmsMAXCHANNELS];
222    int i;
223
224    for (i=0; i < p16 ->nInputs; i++) {
225
226        p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);
227    }
228
229    p16 ->EvalCLUT(StageABC, StageDEF, p16 ->CLUTparams);
230
231    for (i=0; i < p16 ->nOutputs; i++) {
232
233        p16 ->EvalCurveOut16[i](&StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
234    }
235}
236
237
238static
239void PrelinOpt16free(cmsContext ContextID, void* ptr)
240{
241    Prelin16Data* p16 = (Prelin16Data*) ptr;
242
243    _cmsFree(ContextID, p16 ->EvalCurveOut16);
244    _cmsFree(ContextID, p16 ->ParamsCurveOut16);
245
246    _cmsFree(ContextID, p16);
247}
248
249static
250void* Prelin16dup(cmsContext ContextID, const void* ptr)
251{
252    Prelin16Data* p16 = (Prelin16Data*) ptr;
253    Prelin16Data* Duped = _cmsDupMem(ContextID, p16, sizeof(Prelin16Data));
254
255    if (Duped == NULL) return NULL;
256
257    Duped ->EvalCurveOut16   = (_cmsInterpFn16*)_cmsDupMem(ContextID, p16 ->EvalCurveOut16, p16 ->nOutputs * sizeof(_cmsInterpFn16));
258    Duped ->ParamsCurveOut16 = (cmsInterpParams**)_cmsDupMem(ContextID, p16 ->ParamsCurveOut16, p16 ->nOutputs * sizeof(cmsInterpParams* ));
259
260    return Duped;
261}
262
263
264static
265Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,
266                               const cmsInterpParams* ColorMap,
267                               int nInputs, cmsToneCurve** In,
268                               int nOutputs, cmsToneCurve** Out )
269{
270    int i;
271    Prelin16Data* p16 = _cmsMallocZero(ContextID, sizeof(Prelin16Data));
272    if (p16 == NULL) return NULL;
273
274    p16 ->nInputs = nInputs;
275    p16 -> nOutputs = nOutputs;
276
277
278    for (i=0; i < nInputs; i++) {
279
280        if (In == NULL) {
281            p16 -> ParamsCurveIn16[i] = NULL;
282            p16 -> EvalCurveIn16[i] = Eval16nop1D;
283
284        }
285        else {
286            p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams;
287            p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16;
288        }
289    }
290
291    p16 ->CLUTparams = ColorMap;
292    p16 ->EvalCLUT   = ColorMap ->Interpolation.Lerp16;
293
294
295    p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));
296    p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));
297
298    for (i=0; i < nOutputs; i++) {
299
300        if (Out == NULL) {
301            p16 ->ParamsCurveOut16[i] = NULL;
302            p16 -> EvalCurveOut16[i] = Eval16nop1D;
303        }
304        else {
305
306            p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;
307            p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;
308        }
309    }
310
311    return p16;
312}
313
314
315
316// Resampling ---------------------------------------------------------------------------------
317
318#define PRELINEARIZATION_POINTS 4096
319
320// Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for
321// almost any transform. We use floating point precision and then convert from floating point to 16 bits.
322static
323int XFormSampler16(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
324{
325    cmsPipeline* Lut = (cmsPipeline*) Cargo;
326    cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
327    cmsUInt32Number i;
328
329    _cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);
330    _cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);
331
332    // From 16 bit to floating point
333    for (i=0; i < Lut ->InputChannels; i++)
334        InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);
335
336    // Evaluate in floating point
337    cmsPipelineEvalFloat(InFloat, OutFloat, Lut);
338
339    // Back to 16 bits representation
340    for (i=0; i < Lut ->OutputChannels; i++)
341        Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);
342
343    // Always succeed
344    return TRUE;
345}
346
347// Try to see if the curves of a given MPE are linear
348static
349cmsBool AllCurvesAreLinear(cmsStage* mpe)
350{
351    cmsToneCurve** Curves;
352    cmsUInt32Number i, n;
353
354    Curves = _cmsStageGetPtrToCurveSet(mpe);
355    if (Curves == NULL) return FALSE;
356
357    n = cmsStageOutputChannels(mpe);
358
359    for (i=0; i < n; i++) {
360        if (!cmsIsToneCurveLinear(Curves[i])) return FALSE;
361    }
362
363    return TRUE;
364}
365
366// This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose
367// is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels
368static
369cmsBool  PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],
370                  int nChannelsOut, int nChannelsIn)
371{
372    _cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;
373    cmsInterpParams* p16  = Grid ->Params;
374    cmsFloat64Number px, py, pz, pw;
375    int        x0, y0, z0, w0;
376    int        i, index;
377
378    if (CLUT -> Type != cmsSigCLutElemType) {
379        cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage");
380        return FALSE;
381    }
382
383	if (nChannelsIn != 1 && nChannelsIn != 3 && nChannelsIn != 4) {
384		cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
385        return FALSE;
386	}
387    if (nChannelsIn == 4) {
388
389        px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
390        py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
391        pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
392        pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;
393
394        x0 = (int) floor(px);
395        y0 = (int) floor(py);
396        z0 = (int) floor(pz);
397        w0 = (int) floor(pw);
398
399        if (((px - x0) != 0) ||
400            ((py - y0) != 0) ||
401            ((pz - z0) != 0) ||
402            ((pw - w0) != 0)) return FALSE; // Not on exact node
403
404        index = p16 -> opta[3] * x0 +
405                p16 -> opta[2] * y0 +
406                p16 -> opta[1] * z0 +
407                p16 -> opta[0] * w0;
408    }
409    else
410        if (nChannelsIn == 3) {
411
412            px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
413            py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
414            pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
415
416            x0 = (int) floor(px);
417            y0 = (int) floor(py);
418            z0 = (int) floor(pz);
419
420            if (((px - x0) != 0) ||
421                ((py - y0) != 0) ||
422                ((pz - z0) != 0)) return FALSE;  // Not on exact node
423
424            index = p16 -> opta[2] * x0 +
425                    p16 -> opta[1] * y0 +
426                    p16 -> opta[0] * z0;
427        }
428        else
429            if (nChannelsIn == 1) {
430
431                px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
432
433                x0 = (int) floor(px);
434
435                if (((px - x0) != 0)) return FALSE; // Not on exact node
436
437                index = p16 -> opta[0] * x0;
438            }
439            else {
440                cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
441                return FALSE;
442            }
443
444            for (i=0; i < nChannelsOut; i++)
445                Grid -> Tab.T[index + i] = Value[i];
446
447            return TRUE;
448}
449
450// Auxiliar, to see if two values are equal or very different
451static
452cmsBool WhitesAreEqual(int n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
453{
454    int i;
455
456    for (i=0; i < n; i++) {
457
458        if (abs(White1[i] - White2[i]) > 0xf000) return TRUE;  // Values are so extremly different that the fixup should be avoided
459        if (White1[i] != White2[i]) return FALSE;
460    }
461    return TRUE;
462}
463
464
465// Locate the node for the white point and fix it to pure white in order to avoid scum dot.
466static
467cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)
468{
469    cmsUInt16Number *WhitePointIn, *WhitePointOut;
470    cmsUInt16Number  WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];
471    cmsUInt32Number i, nOuts, nIns;
472    cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;
473
474    if (!_cmsEndPointsBySpace(EntryColorSpace,
475        &WhitePointIn, NULL, &nIns)) return FALSE;
476
477    if (!_cmsEndPointsBySpace(ExitColorSpace,
478        &WhitePointOut, NULL, &nOuts)) return FALSE;
479
480    // It needs to be fixed?
481    if (Lut ->InputChannels != nIns) return FALSE;
482    if (Lut ->OutputChannels != nOuts) return FALSE;
483
484    cmsPipelineEval16(WhitePointIn, ObtainedOut, Lut);
485
486    if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match
487
488    // Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations
489    if (!cmsPipelineCheckAndRetreiveStages(Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))
490        if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))
491            if (!cmsPipelineCheckAndRetreiveStages(Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))
492                if (!cmsPipelineCheckAndRetreiveStages(Lut, 1, cmsSigCLutElemType, &CLUT))
493                    return FALSE;
494
495    // We need to interpolate white points of both, pre and post curves
496    if (PreLin) {
497
498        cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);
499
500        for (i=0; i < nIns; i++) {
501            WhiteIn[i] = cmsEvalToneCurve16(Curves[i], WhitePointIn[i]);
502        }
503    }
504    else {
505        for (i=0; i < nIns; i++)
506            WhiteIn[i] = WhitePointIn[i];
507    }
508
509    // If any post-linearization, we need to find how is represented white before the curve, do
510    // a reverse interpolation in this case.
511    if (PostLin) {
512
513        cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);
514
515        for (i=0; i < nOuts; i++) {
516
517            cmsToneCurve* InversePostLin = cmsReverseToneCurve(Curves[i]);
518            if (InversePostLin == NULL) {
519                WhiteOut[i] = WhitePointOut[i];
520
521            } else {
522
523                WhiteOut[i] = cmsEvalToneCurve16(InversePostLin, WhitePointOut[i]);
524                cmsFreeToneCurve(InversePostLin);
525            }
526        }
527    }
528    else {
529        for (i=0; i < nOuts; i++)
530            WhiteOut[i] = WhitePointOut[i];
531    }
532
533    // Ok, proceed with patching. May fail and we don't care if it fails
534    PatchLUT(CLUT, WhiteIn, WhiteOut, nOuts, nIns);
535
536    return TRUE;
537}
538
539// -----------------------------------------------------------------------------------------------------------------------------------------------
540// This function creates simple LUT from complex ones. The generated LUT has an optional set of
541// prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.
542// These curves have to exist in the original LUT in order to be used in the simplified output.
543// Caller may also use the flags to allow this feature.
544// LUTS with all curves will be simplified to a single curve. Parametric curves are lost.
545// This function should be used on 16-bits LUTS only, as floating point losses precision when simplified
546// -----------------------------------------------------------------------------------------------------------------------------------------------
547
548static
549cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
550{
551    cmsPipeline* Src = NULL;
552    cmsPipeline* Dest = NULL;
553    cmsStage* mpe;
554    cmsStage* CLUT;
555    cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;
556    int nGridPoints;
557    cmsColorSpaceSignature ColorSpace, OutputColorSpace;
558    cmsStage *NewPreLin = NULL;
559    cmsStage *NewPostLin = NULL;
560    _cmsStageCLutData* DataCLUT;
561    cmsToneCurve** DataSetIn;
562    cmsToneCurve** DataSetOut;
563    Prelin16Data* p16;
564
565    // This is a loosy optimization! does not apply in floating-point cases
566    if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
567
568    ColorSpace       = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat));
569    OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat));
570    nGridPoints      = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
571
572    // For empty LUTs, 2 points are enough
573    if (cmsPipelineStageCount(*Lut) == 0)
574        nGridPoints = 2;
575
576    Src = *Lut;
577
578    // Named color pipelines cannot be optimized either
579    for (mpe = cmsPipelineGetPtrToFirstStage(Src);
580        mpe != NULL;
581        mpe = cmsStageNext(mpe)) {
582            if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;
583    }
584
585    // Allocate an empty LUT
586    Dest =  cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
587    if (!Dest) return FALSE;
588
589    // Prelinearization tables are kept unless indicated by flags
590    if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {
591
592        // Get a pointer to the prelinearization element
593        cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);
594
595        // Check if suitable
596        if (PreLin ->Type == cmsSigCurveSetElemType) {
597
598            // Maybe this is a linear tram, so we can avoid the whole stuff
599            if (!AllCurvesAreLinear(PreLin)) {
600
601                // All seems ok, proceed.
602                NewPreLin = cmsStageDup(PreLin);
603                if(!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin))
604                    goto Error;
605
606                // Remove prelinearization. Since we have duplicated the curve
607                // in destination LUT, the sampling shoud be applied after this stage.
608                cmsPipelineUnlinkStage(Src, cmsAT_BEGIN, &KeepPreLin);
609            }
610        }
611    }
612
613    // Allocate the CLUT
614    CLUT = cmsStageAllocCLut16bit(Src ->ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);
615    if (CLUT == NULL) return FALSE;
616
617    // Add the CLUT to the destination LUT
618    if (!cmsPipelineInsertStage(Dest, cmsAT_END, CLUT)) {
619        goto Error;
620    }
621
622    // Postlinearization tables are kept unless indicated by flags
623    if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {
624
625        // Get a pointer to the postlinearization if present
626        cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);
627
628        // Check if suitable
629        if (cmsStageType(PostLin) == cmsSigCurveSetElemType) {
630
631            // Maybe this is a linear tram, so we can avoid the whole stuff
632            if (!AllCurvesAreLinear(PostLin)) {
633
634                // All seems ok, proceed.
635                NewPostLin = cmsStageDup(PostLin);
636                if (!cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin))
637                    goto Error;
638
639                // In destination LUT, the sampling shoud be applied after this stage.
640                cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);
641            }
642        }
643    }
644
645    // Now its time to do the sampling. We have to ignore pre/post linearization
646    // The source LUT whithout pre/post curves is passed as parameter.
647    if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {
648Error:
649        // Ops, something went wrong, Restore stages
650        if (KeepPreLin != NULL) {
651            if (!cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin)) {
652                _cmsAssert(0); // This never happens
653            }
654        }
655        if (KeepPostLin != NULL) {
656            if (!cmsPipelineInsertStage(Src, cmsAT_END,   KeepPostLin)) {
657                _cmsAssert(0); // This never happens
658            }
659        }
660        cmsPipelineFree(Dest);
661        return FALSE;
662    }
663
664    // Done.
665
666    if (KeepPreLin != NULL) cmsStageFree(KeepPreLin);
667    if (KeepPostLin != NULL) cmsStageFree(KeepPostLin);
668    cmsPipelineFree(Src);
669
670    DataCLUT = (_cmsStageCLutData*) CLUT ->Data;
671
672    if (NewPreLin == NULL) DataSetIn = NULL;
673    else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;
674
675    if (NewPostLin == NULL) DataSetOut = NULL;
676    else  DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;
677
678
679    if (DataSetIn == NULL && DataSetOut == NULL) {
680
681        _cmsPipelineSetOptimizationParameters(Dest, (_cmsOPTeval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);
682    }
683    else {
684
685        p16 = PrelinOpt16alloc(Dest ->ContextID,
686            DataCLUT ->Params,
687            Dest ->InputChannels,
688            DataSetIn,
689            Dest ->OutputChannels,
690            DataSetOut);
691
692        _cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
693    }
694
695
696    // Don't fix white on absolute colorimetric
697    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
698        *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
699
700    if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
701
702        FixWhiteMisalignment(Dest, ColorSpace, OutputColorSpace);
703    }
704
705    *Lut = Dest;
706    return TRUE;
707
708    cmsUNUSED_PARAMETER(Intent);
709}
710
711
712// -----------------------------------------------------------------------------------------------------------------------------------------------
713// Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on
714// Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works
715// for RGB transforms. See the paper for more details
716// -----------------------------------------------------------------------------------------------------------------------------------------------
717
718
719// Normalize endpoints by slope limiting max and min. This assures endpoints as well.
720// Descending curves are handled as well.
721static
722void SlopeLimiting(cmsToneCurve* g)
723{
724    int BeginVal, EndVal;
725    int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5);   // Cutoff at 2%
726    int AtEnd   = g ->nEntries - AtBegin - 1;                                  // And 98%
727    cmsFloat64Number Val, Slope, beta;
728    int i;
729
730    if (cmsIsToneCurveDescending(g)) {
731        BeginVal = 0xffff; EndVal = 0;
732    }
733    else {
734        BeginVal = 0; EndVal = 0xffff;
735    }
736
737    // Compute slope and offset for begin of curve
738    Val   = g ->Table16[AtBegin];
739    Slope = (Val - BeginVal) / AtBegin;
740    beta  = Val - Slope * AtBegin;
741
742    for (i=0; i < AtBegin; i++)
743        g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
744
745    // Compute slope and offset for the end
746    Val   = g ->Table16[AtEnd];
747    Slope = (EndVal - Val) / AtBegin;   // AtBegin holds the X interval, which is same in both cases
748    beta  = Val - Slope * AtEnd;
749
750    for (i = AtEnd; i < (int) g ->nEntries; i++)
751        g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
752}
753
754
755// Precomputes tables for 8-bit on input devicelink.
756static
757Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])
758{
759    int i;
760    cmsUInt16Number Input[3];
761    cmsS15Fixed16Number v1, v2, v3;
762    Prelin8Data* p8;
763
764    p8 = (Prelin8Data*)_cmsMallocZero(ContextID, sizeof(Prelin8Data));
765    if (p8 == NULL) return NULL;
766
767    // Since this only works for 8 bit input, values comes always as x * 257,
768    // we can safely take msb byte (x << 8 + x)
769
770    for (i=0; i < 256; i++) {
771
772        if (G != NULL) {
773
774            // Get 16-bit representation
775            Input[0] = cmsEvalToneCurve16(G[0], FROM_8_TO_16(i));
776            Input[1] = cmsEvalToneCurve16(G[1], FROM_8_TO_16(i));
777            Input[2] = cmsEvalToneCurve16(G[2], FROM_8_TO_16(i));
778        }
779        else {
780            Input[0] = FROM_8_TO_16(i);
781            Input[1] = FROM_8_TO_16(i);
782            Input[2] = FROM_8_TO_16(i);
783        }
784
785
786        // Move to 0..1.0 in fixed domain
787        v1 = _cmsToFixedDomain(Input[0] * p -> Domain[0]);
788        v2 = _cmsToFixedDomain(Input[1] * p -> Domain[1]);
789        v3 = _cmsToFixedDomain(Input[2] * p -> Domain[2]);
790
791        // Store the precalculated table of nodes
792        p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));
793        p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));
794        p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));
795
796        // Store the precalculated table of offsets
797        p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);
798        p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);
799        p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);
800    }
801
802    p8 ->ContextID = ContextID;
803    p8 ->p = p;
804
805    return p8;
806}
807
808static
809void Prelin8free(cmsContext ContextID, void* ptr)
810{
811    _cmsFree(ContextID, ptr);
812}
813
814static
815void* Prelin8dup(cmsContext ContextID, const void* ptr)
816{
817    return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));
818}
819
820
821
822// A optimized interpolation for 8-bit input.
823#define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
824static
825void PrelinEval8(register const cmsUInt16Number Input[],
826                  register cmsUInt16Number Output[],
827                  register const void* D)
828{
829
830    cmsUInt8Number         r, g, b;
831    cmsS15Fixed16Number    rx, ry, rz;
832    cmsS15Fixed16Number    c0, c1, c2, c3, Rest;
833    int                    OutChan;
834    register cmsS15Fixed16Number    X0, X1, Y0, Y1, Z0, Z1;
835    Prelin8Data* p8 = (Prelin8Data*) D;
836    register const cmsInterpParams* p = p8 ->p;
837    int                    TotalOut = p -> nOutputs;
838    const cmsUInt16Number* LutTable = (const cmsUInt16Number*)p -> Table;
839
840    r = Input[0] >> 8;
841    g = Input[1] >> 8;
842    b = Input[2] >> 8;
843
844    X0 = X1 = p8->X0[r];
845    Y0 = Y1 = p8->Y0[g];
846    Z0 = Z1 = p8->Z0[b];
847
848    rx = p8 ->rx[r];
849    ry = p8 ->ry[g];
850    rz = p8 ->rz[b];
851
852    X1 = X0 + ((rx == 0) ? 0 : p ->opta[2]);
853    Y1 = Y0 + ((ry == 0) ? 0 : p ->opta[1]);
854    Z1 = Z0 + ((rz == 0) ? 0 : p ->opta[0]);
855
856
857    // These are the 6 Tetrahedral
858    for (OutChan=0; OutChan < TotalOut; OutChan++) {
859
860        c0 = DENS(X0, Y0, Z0);
861
862        if (rx >= ry && ry >= rz)
863        {
864            c1 = DENS(X1, Y0, Z0) - c0;
865            c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
866            c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
867        }
868        else
869            if (rx >= rz && rz >= ry)
870            {
871                c1 = DENS(X1, Y0, Z0) - c0;
872                c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
873                c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
874            }
875            else
876                if (rz >= rx && rx >= ry)
877                {
878                    c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
879                    c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
880                    c3 = DENS(X0, Y0, Z1) - c0;
881                }
882                else
883                    if (ry >= rx && rx >= rz)
884                    {
885                        c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
886                        c2 = DENS(X0, Y1, Z0) - c0;
887                        c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
888                    }
889                    else
890                        if (ry >= rz && rz >= rx)
891                        {
892                            c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
893                            c2 = DENS(X0, Y1, Z0) - c0;
894                            c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
895                        }
896                        else
897                            if (rz >= ry && ry >= rx)
898                            {
899                                c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
900                                c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
901                                c3 = DENS(X0, Y0, Z1) - c0;
902                            }
903                            else  {
904                                c1 = c2 = c3 = 0;
905                            }
906
907
908                            Rest = c1 * rx + c2 * ry + c3 * rz + 0x8001;
909                            Output[OutChan] = (cmsUInt16Number)c0 + ((Rest + (Rest>>16))>>16);
910
911    }
912}
913
914#undef DENS
915
916
917// Curves that contain wide empty areas are not optimizeable
918static
919cmsBool IsDegenerated(const cmsToneCurve* g)
920{
921    int i, Zeros = 0, Poles = 0;
922    int nEntries = g ->nEntries;
923
924    for (i=0; i < nEntries; i++) {
925
926        if (g ->Table16[i] == 0x0000) Zeros++;
927        if (g ->Table16[i] == 0xffff) Poles++;
928    }
929
930    if (Zeros == 1 && Poles == 1) return FALSE;  // For linear tables
931    if (Zeros > (nEntries / 4)) return TRUE;  // Degenerated, mostly zeros
932    if (Poles > (nEntries / 4)) return TRUE;  // Degenerated, mostly poles
933
934    return FALSE;
935}
936
937// --------------------------------------------------------------------------------------------------------------
938// We need xput over here
939
940static
941cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
942{
943    cmsPipeline* OriginalLut;
944    int nGridPoints;
945    cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];
946    cmsUInt32Number t, i;
947    cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];
948    cmsBool lIsSuitable, lIsLinear;
949    cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;
950    cmsStage* OptimizedCLUTmpe;
951    cmsColorSpaceSignature ColorSpace, OutputColorSpace;
952    cmsStage* OptimizedPrelinMpe;
953    cmsStage* mpe;
954    cmsToneCurve**   OptimizedPrelinCurves;
955    _cmsStageCLutData*     OptimizedPrelinCLUT;
956
957
958    // This is a loosy optimization! does not apply in floating-point cases
959    if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
960
961    // Only on RGB
962    if (T_COLORSPACE(*InputFormat)  != PT_RGB) return FALSE;
963    if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
964
965
966    // On 16 bits, user has to specify the feature
967    if (!_cmsFormatterIs8bit(*InputFormat)) {
968        if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;
969    }
970
971    OriginalLut = *Lut;
972
973   // Named color pipelines cannot be optimized either
974   for (mpe = cmsPipelineGetPtrToFirstStage(OriginalLut);
975         mpe != NULL;
976         mpe = cmsStageNext(mpe)) {
977            if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;
978    }
979
980    ColorSpace       = _cmsICCcolorSpace(T_COLORSPACE(*InputFormat));
981    OutputColorSpace = _cmsICCcolorSpace(T_COLORSPACE(*OutputFormat));
982    nGridPoints      = _cmsReasonableGridpointsByColorspace(ColorSpace, *dwFlags);
983
984    // Empty gamma containers
985    memset(Trans, 0, sizeof(Trans));
986    memset(TransReverse, 0, sizeof(TransReverse));
987
988    for (t = 0; t < OriginalLut ->InputChannels; t++) {
989        Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);
990        if (Trans[t] == NULL) goto Error;
991    }
992
993    // Populate the curves
994    for (i=0; i < PRELINEARIZATION_POINTS; i++) {
995
996        v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
997
998        // Feed input with a gray ramp
999        for (t=0; t < OriginalLut ->InputChannels; t++)
1000            In[t] = v;
1001
1002        // Evaluate the gray value
1003        cmsPipelineEvalFloat(In, Out, OriginalLut);
1004
1005        // Store result in curve
1006        for (t=0; t < OriginalLut ->InputChannels; t++)
1007            Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);
1008    }
1009
1010    // Slope-limit the obtained curves
1011    for (t = 0; t < OriginalLut ->InputChannels; t++)
1012        SlopeLimiting(Trans[t]);
1013
1014    // Check for validity
1015    lIsSuitable = TRUE;
1016    lIsLinear   = TRUE;
1017    for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {
1018
1019        // Exclude if already linear
1020        if (!cmsIsToneCurveLinear(Trans[t]))
1021            lIsLinear = FALSE;
1022
1023        // Exclude if non-monotonic
1024        if (!cmsIsToneCurveMonotonic(Trans[t]))
1025            lIsSuitable = FALSE;
1026
1027        if (IsDegenerated(Trans[t]))
1028            lIsSuitable = FALSE;
1029    }
1030
1031    // If it is not suitable, just quit
1032    if (!lIsSuitable) goto Error;
1033
1034    // Invert curves if possible
1035    for (t = 0; t < OriginalLut ->InputChannels; t++) {
1036        TransReverse[t] = cmsReverseToneCurveEx(PRELINEARIZATION_POINTS, Trans[t]);
1037        if (TransReverse[t] == NULL) goto Error;
1038    }
1039
1040    // Now inset the reversed curves at the begin of transform
1041    LutPlusCurves = cmsPipelineDup(OriginalLut);
1042    if (LutPlusCurves == NULL) goto Error;
1043
1044    if (!cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse)))
1045        goto Error;
1046
1047    // Create the result LUT
1048    OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);
1049    if (OptimizedLUT == NULL) goto Error;
1050
1051    OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);
1052
1053    // Create and insert the curves at the beginning
1054    if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe))
1055        goto Error;
1056
1057    // Allocate the CLUT for result
1058    OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);
1059
1060    // Add the CLUT to the destination LUT
1061    if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe))
1062        goto Error;
1063
1064    // Resample the LUT
1065    if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;
1066
1067    // Free resources
1068    for (t = 0; t < OriginalLut ->InputChannels; t++) {
1069
1070        if (Trans[t]) cmsFreeToneCurve(Trans[t]);
1071        if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
1072    }
1073
1074    cmsPipelineFree(LutPlusCurves);
1075
1076
1077    OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);
1078    OptimizedPrelinCLUT   = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;
1079
1080    // Set the evaluator if 8-bit
1081    if (_cmsFormatterIs8bit(*InputFormat)) {
1082
1083        Prelin8Data* p8 = PrelinOpt8alloc(OptimizedLUT ->ContextID,
1084                                                OptimizedPrelinCLUT ->Params,
1085                                                OptimizedPrelinCurves);
1086        if (p8 == NULL) return FALSE;
1087
1088        _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);
1089
1090    }
1091    else
1092    {
1093        Prelin16Data* p16 = PrelinOpt16alloc(OptimizedLUT ->ContextID,
1094            OptimizedPrelinCLUT ->Params,
1095            3, OptimizedPrelinCurves, 3, NULL);
1096        if (p16 == NULL) return FALSE;
1097
1098        _cmsPipelineSetOptimizationParameters(OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
1099
1100    }
1101
1102    // Don't fix white on absolute colorimetric
1103    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
1104        *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
1105
1106    if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
1107
1108        if (!FixWhiteMisalignment(OptimizedLUT, ColorSpace, OutputColorSpace)) {
1109
1110            return FALSE;
1111        }
1112    }
1113
1114    // And return the obtained LUT
1115
1116    cmsPipelineFree(OriginalLut);
1117    *Lut = OptimizedLUT;
1118    return TRUE;
1119
1120Error:
1121
1122    for (t = 0; t < OriginalLut ->InputChannels; t++) {
1123
1124        if (Trans[t]) cmsFreeToneCurve(Trans[t]);
1125        if (TransReverse[t]) cmsFreeToneCurve(TransReverse[t]);
1126    }
1127
1128    if (LutPlusCurves != NULL) cmsPipelineFree(LutPlusCurves);
1129    if (OptimizedLUT != NULL) cmsPipelineFree(OptimizedLUT);
1130
1131    return FALSE;
1132
1133    cmsUNUSED_PARAMETER(Intent);
1134}
1135
1136
1137// Curves optimizer ------------------------------------------------------------------------------------------------------------------
1138
1139static
1140void CurvesFree(cmsContext ContextID, void* ptr)
1141{
1142     Curves16Data* Data = (Curves16Data*) ptr;
1143     int i;
1144
1145     for (i=0; i < Data -> nCurves; i++) {
1146
1147         _cmsFree(ContextID, Data ->Curves[i]);
1148     }
1149
1150     _cmsFree(ContextID, Data ->Curves);
1151     _cmsFree(ContextID, ptr);
1152}
1153
1154static
1155void* CurvesDup(cmsContext ContextID, const void* ptr)
1156{
1157    Curves16Data* Data = (Curves16Data*)_cmsDupMem(ContextID, ptr, sizeof(Curves16Data));
1158    int i;
1159
1160    if (Data == NULL) return NULL;
1161
1162    Data ->Curves = (cmsUInt16Number**)_cmsDupMem(ContextID, Data ->Curves, Data ->nCurves * sizeof(cmsUInt16Number*));
1163
1164    for (i=0; i < Data -> nCurves; i++) {
1165        Data ->Curves[i] = (cmsUInt16Number*)_cmsDupMem(ContextID, Data ->Curves[i], Data -> nElements * sizeof(cmsUInt16Number));
1166    }
1167
1168    return (void*) Data;
1169}
1170
1171// Precomputes tables for 8-bit on input devicelink.
1172static
1173Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsToneCurve** G)
1174{
1175    int i, j;
1176    Curves16Data* c16;
1177
1178    c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));
1179    if (c16 == NULL) return NULL;
1180
1181    c16 ->nCurves = nCurves;
1182    c16 ->nElements = nElements;
1183
1184    c16 ->Curves = (cmsUInt16Number**)_cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
1185    if (c16 ->Curves == NULL) return NULL;
1186
1187    for (i=0; i < nCurves; i++) {
1188
1189        c16->Curves[i] = (cmsUInt16Number*)_cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
1190
1191        if (c16->Curves[i] == NULL) {
1192
1193            for (j=0; j < i; j++) {
1194                _cmsFree(ContextID, c16->Curves[j]);
1195            }
1196            _cmsFree(ContextID, c16->Curves);
1197            _cmsFree(ContextID, c16);
1198            return NULL;
1199        }
1200
1201        if (nElements == 256) {
1202
1203            for (j=0; j < nElements; j++) {
1204
1205                c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], FROM_8_TO_16(j));
1206            }
1207        }
1208        else {
1209
1210            for (j=0; j < nElements; j++) {
1211                c16 ->Curves[i][j] = cmsEvalToneCurve16(G[i], (cmsUInt16Number) j);
1212            }
1213        }
1214    }
1215
1216    return c16;
1217}
1218
1219static
1220void FastEvaluateCurves8(register const cmsUInt16Number In[],
1221                          register cmsUInt16Number Out[],
1222                          register const void* D)
1223{
1224    Curves16Data* Data = (Curves16Data*) D;
1225    cmsUInt8Number x;
1226    int i;
1227
1228    for (i=0; i < Data ->nCurves; i++) {
1229
1230         x = (In[i] >> 8);
1231         Out[i] = Data -> Curves[i][x];
1232    }
1233}
1234
1235
1236static
1237void FastEvaluateCurves16(register const cmsUInt16Number In[],
1238                          register cmsUInt16Number Out[],
1239                          register const void* D)
1240{
1241    Curves16Data* Data = (Curves16Data*) D;
1242    int i;
1243
1244    for (i=0; i < Data ->nCurves; i++) {
1245         Out[i] = Data -> Curves[i][In[i]];
1246    }
1247}
1248
1249
1250static
1251void FastIdentity16(register const cmsUInt16Number In[],
1252                    register cmsUInt16Number Out[],
1253                    register const void* D)
1254{
1255    cmsPipeline* Lut = (cmsPipeline*) D;
1256    cmsUInt32Number i;
1257
1258    for (i=0; i < Lut ->InputChannels; i++) {
1259         Out[i] = In[i];
1260    }
1261}
1262
1263
1264// If the target LUT holds only curves, the optimization procedure is to join all those
1265// curves together. That only works on curves and does not work on matrices.
1266static
1267cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1268{
1269    cmsToneCurve** GammaTables = NULL;
1270    cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
1271    cmsUInt32Number i, j;
1272    cmsPipeline* Src = *Lut;
1273    cmsPipeline* Dest = NULL;
1274    cmsStage* mpe;
1275    cmsStage* ObtainedCurves = NULL;
1276
1277
1278    // This is a loosy optimization! does not apply in floating-point cases
1279    if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
1280
1281    //  Only curves in this LUT?
1282    for (mpe = cmsPipelineGetPtrToFirstStage(Src);
1283         mpe != NULL;
1284         mpe = cmsStageNext(mpe)) {
1285            if (cmsStageType(mpe) != cmsSigCurveSetElemType) return FALSE;
1286    }
1287
1288    // Allocate an empty LUT
1289    Dest =  cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
1290    if (Dest == NULL) return FALSE;
1291
1292    // Create target curves
1293    GammaTables = (cmsToneCurve**) _cmsCalloc(Src ->ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));
1294    if (GammaTables == NULL) goto Error;
1295
1296    for (i=0; i < Src ->InputChannels; i++) {
1297        GammaTables[i] = cmsBuildTabulatedToneCurve16(Src ->ContextID, PRELINEARIZATION_POINTS, NULL);
1298        if (GammaTables[i] == NULL) goto Error;
1299    }
1300
1301    // Compute 16 bit result by using floating point
1302    for (i=0; i < PRELINEARIZATION_POINTS; i++) {
1303
1304        for (j=0; j < Src ->InputChannels; j++)
1305            InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
1306
1307        cmsPipelineEvalFloat(InFloat, OutFloat, Src);
1308
1309        for (j=0; j < Src ->InputChannels; j++)
1310            GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);
1311    }
1312
1313    ObtainedCurves = cmsStageAllocToneCurves(Src ->ContextID, Src ->InputChannels, GammaTables);
1314    if (ObtainedCurves == NULL) goto Error;
1315
1316    for (i=0; i < Src ->InputChannels; i++) {
1317        cmsFreeToneCurve(GammaTables[i]);
1318        GammaTables[i] = NULL;
1319    }
1320
1321    if (GammaTables != NULL) _cmsFree(Src ->ContextID, GammaTables);
1322
1323    // Maybe the curves are linear at the end
1324    if (!AllCurvesAreLinear(ObtainedCurves)) {
1325
1326        if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves))
1327            goto Error;
1328
1329        // If the curves are to be applied in 8 bits, we can save memory
1330        if (_cmsFormatterIs8bit(*InputFormat)) {
1331
1332            _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) ObtainedCurves ->Data;
1333             Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);
1334
1335             if (c16 == NULL) goto Error;
1336             *dwFlags |= cmsFLAGS_NOCACHE;
1337            _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);
1338
1339        }
1340        else {
1341
1342            _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);
1343             Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);
1344
1345             if (c16 == NULL) goto Error;
1346             *dwFlags |= cmsFLAGS_NOCACHE;
1347            _cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);
1348        }
1349    }
1350    else {
1351
1352        // LUT optimizes to nothing. Set the identity LUT
1353        cmsStageFree(ObtainedCurves);
1354
1355        if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels)))
1356            goto Error;
1357
1358        *dwFlags |= cmsFLAGS_NOCACHE;
1359        _cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);
1360    }
1361
1362    // We are done.
1363    cmsPipelineFree(Src);
1364    *Lut = Dest;
1365    return TRUE;
1366
1367Error:
1368
1369    if (ObtainedCurves != NULL) cmsStageFree(ObtainedCurves);
1370    if (GammaTables != NULL) {
1371        for (i=0; i < Src ->InputChannels; i++) {
1372            if (GammaTables[i] != NULL) cmsFreeToneCurve(GammaTables[i]);
1373        }
1374
1375        _cmsFree(Src ->ContextID, GammaTables);
1376    }
1377
1378    if (Dest != NULL) cmsPipelineFree(Dest);
1379    return FALSE;
1380
1381    cmsUNUSED_PARAMETER(Intent);
1382    cmsUNUSED_PARAMETER(InputFormat);
1383    cmsUNUSED_PARAMETER(OutputFormat);
1384    cmsUNUSED_PARAMETER(dwFlags);
1385}
1386
1387// -------------------------------------------------------------------------------------------------------------------------------------
1388// LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles
1389
1390
1391static
1392void  FreeMatShaper(cmsContext ContextID, void* Data)
1393{
1394    if (Data != NULL) _cmsFree(ContextID, Data);
1395}
1396
1397static
1398void* DupMatShaper(cmsContext ContextID, const void* Data)
1399{
1400    return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));
1401}
1402
1403
1404// A fast matrix-shaper evaluator for 8 bits. This is a bit ticky since I'm using 1.14 signed fixed point
1405// to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,
1406// in total about 50K, and the performance boost is huge!
1407static
1408void MatShaperEval16(register const cmsUInt16Number In[],
1409                     register cmsUInt16Number Out[],
1410                     register const void* D)
1411{
1412    MatShaper8Data* p = (MatShaper8Data*) D;
1413    cmsS1Fixed14Number l1, l2, l3, r, g, b;
1414    cmsUInt32Number ri, gi, bi;
1415
1416    // In this case (and only in this case!) we can use this simplification since
1417    // In[] is assured to come from a 8 bit number. (a << 8 | a)
1418    ri = In[0] & 0xFF;
1419    gi = In[1] & 0xFF;
1420    bi = In[2] & 0xFF;
1421
1422    // Across first shaper, which also converts to 1.14 fixed point
1423    r = p->Shaper1R[ri];
1424    g = p->Shaper1G[gi];
1425    b = p->Shaper1B[bi];
1426
1427    // Evaluate the matrix in 1.14 fixed point
1428    l1 =  (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;
1429    l2 =  (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;
1430    l3 =  (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;
1431
1432    // Now we have to clip to 0..1.0 range
1433    ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384 : l1);
1434    gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384 : l2);
1435    bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384 : l3);
1436
1437    // And across second shaper,
1438    Out[0] = p->Shaper2R[ri];
1439    Out[1] = p->Shaper2G[gi];
1440    Out[2] = p->Shaper2B[bi];
1441
1442}
1443
1444// This table converts from 8 bits to 1.14 after applying the curve
1445static
1446void FillFirstShaper(cmsS1Fixed14Number* Table, cmsToneCurve* Curve)
1447{
1448    int i;
1449    cmsFloat32Number R, y;
1450
1451    for (i=0; i < 256; i++) {
1452
1453        R   = (cmsFloat32Number) (i / 255.0);
1454        y   = cmsEvalToneCurveFloat(Curve, R);
1455
1456        Table[i] = DOUBLE_TO_1FIXED14(y);
1457    }
1458}
1459
1460// This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve
1461static
1462void FillSecondShaper(cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)
1463{
1464    int i;
1465    cmsFloat32Number R, Val;
1466
1467    for (i=0; i < 16385; i++) {
1468
1469        R   = (cmsFloat32Number) (i / 16384.0);
1470        Val = cmsEvalToneCurveFloat(Curve, R);    // Val comes 0..1.0
1471
1472        if (Is8BitsOutput) {
1473
1474            // If 8 bits output, we can optimize further by computing the / 257 part.
1475            // first we compute the resulting byte and then we store the byte times
1476            // 257. This quantization allows to round very quick by doing a >> 8, but
1477            // since the low byte is always equal to msb, we can do a & 0xff and this works!
1478            cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0);
1479            cmsUInt8Number  b = FROM_16_TO_8(w);
1480
1481            Table[i] = FROM_8_TO_16(b);
1482        }
1483        else Table[i]  = _cmsQuickSaturateWord(Val * 65535.0);
1484    }
1485}
1486
1487// Compute the matrix-shaper structure
1488static
1489cmsBool SetMatShaper(cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)
1490{
1491    MatShaper8Data* p;
1492    int i, j;
1493    cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);
1494
1495    // Allocate a big chuck of memory to store precomputed tables
1496    p = (MatShaper8Data*) _cmsMalloc(Dest ->ContextID, sizeof(MatShaper8Data));
1497    if (p == NULL) return FALSE;
1498
1499    p -> ContextID = Dest -> ContextID;
1500
1501    // Precompute tables
1502    FillFirstShaper(p ->Shaper1R, Curve1[0]);
1503    FillFirstShaper(p ->Shaper1G, Curve1[1]);
1504    FillFirstShaper(p ->Shaper1B, Curve1[2]);
1505
1506    FillSecondShaper(p ->Shaper2R, Curve2[0], Is8Bits);
1507    FillSecondShaper(p ->Shaper2G, Curve2[1], Is8Bits);
1508    FillSecondShaper(p ->Shaper2B, Curve2[2], Is8Bits);
1509
1510    // Convert matrix to nFixed14. Note that those values may take more than 16 bits as
1511    for (i=0; i < 3; i++) {
1512        for (j=0; j < 3; j++) {
1513            p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);
1514        }
1515    }
1516
1517    for (i=0; i < 3; i++) {
1518
1519        if (Off == NULL) {
1520            p ->Off[i] = 0;
1521        }
1522        else {
1523            p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);
1524        }
1525    }
1526
1527    // Mark as optimized for faster formatter
1528    if (Is8Bits)
1529        *OutputFormat |= OPTIMIZED_SH(1);
1530
1531    // Fill function pointers
1532    _cmsPipelineSetOptimizationParameters(Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);
1533    return TRUE;
1534}
1535
1536//  8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!
1537// TODO: Allow a third matrix for abs. colorimetric
1538static
1539cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1540{
1541    cmsStage* Curve1, *Curve2;
1542    cmsStage* Matrix1, *Matrix2;
1543    _cmsStageMatrixData* Data1;
1544    _cmsStageMatrixData* Data2;
1545    cmsMAT3 res;
1546    cmsBool IdentityMat;
1547    cmsPipeline* Dest, *Src;
1548
1549    // Only works on RGB to RGB
1550    if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;
1551
1552    // Only works on 8 bit input
1553    if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;
1554
1555    // Seems suitable, proceed
1556    Src = *Lut;
1557
1558    // Check for shaper-matrix-matrix-shaper structure, that is what this optimizer stands for
1559    if (!cmsPipelineCheckAndRetreiveStages(Src, 4,
1560        cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
1561        &Curve1, &Matrix1, &Matrix2, &Curve2)) return FALSE;
1562
1563    // Get both matrices
1564    Data1 = (_cmsStageMatrixData*) cmsStageData(Matrix1);
1565    Data2 = (_cmsStageMatrixData*) cmsStageData(Matrix2);
1566
1567    // Input offset should be zero
1568    if (Data1 ->Offset != NULL) return FALSE;
1569
1570    // Multiply both matrices to get the result
1571    _cmsMAT3per(&res, (cmsMAT3*) Data2 ->Double, (cmsMAT3*) Data1 ->Double);
1572
1573    // Now the result is in res + Data2 -> Offset. Maybe is a plain identity?
1574    IdentityMat = FALSE;
1575    if (_cmsMAT3isIdentity(&res) && Data2 ->Offset == NULL) {
1576
1577        // We can get rid of full matrix
1578        IdentityMat = TRUE;
1579    }
1580
1581      // Allocate an empty LUT
1582    Dest =  cmsPipelineAlloc(Src ->ContextID, Src ->InputChannels, Src ->OutputChannels);
1583    if (!Dest) return FALSE;
1584
1585    // Assamble the new LUT
1586    if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1)))
1587        goto Error;
1588
1589    if (!IdentityMat)
1590        if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest ->ContextID, 3, 3, (const cmsFloat64Number*) &res, Data2 ->Offset)))
1591            goto Error;
1592    if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2)))
1593        goto Error;
1594
1595    // If identity on matrix, we can further optimize the curves, so call the join curves routine
1596    if (IdentityMat) {
1597
1598        OptimizeByJoiningCurves(&Dest, Intent, InputFormat, OutputFormat, dwFlags);
1599    }
1600    else {
1601        _cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(Curve1);
1602        _cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(Curve2);
1603
1604        // In this particular optimization, cach?does not help as it takes more time to deal with
1605        // the cach?that with the pixel handling
1606        *dwFlags |= cmsFLAGS_NOCACHE;
1607
1608        // Setup the optimizarion routines
1609        SetMatShaper(Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Data2 ->Offset, mpeC2->TheCurves, OutputFormat);
1610    }
1611
1612    cmsPipelineFree(Src);
1613    *Lut = Dest;
1614    return TRUE;
1615Error:
1616    // Leave Src unchanged
1617    cmsPipelineFree(Dest);
1618    return FALSE;
1619}
1620
1621
1622// -------------------------------------------------------------------------------------------------------------------------------------
1623// Optimization plug-ins
1624
1625// List of optimizations
1626typedef struct _cmsOptimizationCollection_st {
1627
1628    _cmsOPToptimizeFn  OptimizePtr;
1629
1630    struct _cmsOptimizationCollection_st *Next;
1631
1632} _cmsOptimizationCollection;
1633
1634
1635// The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling
1636static _cmsOptimizationCollection DefaultOptimization[] = {
1637
1638    { OptimizeByJoiningCurves,            &DefaultOptimization[1] },
1639    { OptimizeMatrixShaper,               &DefaultOptimization[2] },
1640    { OptimizeByComputingLinearization,   &DefaultOptimization[3] },
1641    { OptimizeByResampling,               NULL }
1642};
1643
1644// The linked list head
1645_cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL };
1646
1647
1648// Duplicates the zone of memory used by the plug-in in the new context
1649static
1650void DupPluginOptimizationList(struct _cmsContext_struct* ctx,
1651                               const struct _cmsContext_struct* src)
1652{
1653   _cmsOptimizationPluginChunkType newHead = { NULL };
1654   _cmsOptimizationCollection*  entry;
1655   _cmsOptimizationCollection*  Anterior = NULL;
1656   _cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin];
1657
1658    _cmsAssert(ctx != NULL);
1659    _cmsAssert(head != NULL);
1660
1661    // Walk the list copying all nodes
1662   for (entry = head->OptimizationCollection;
1663        entry != NULL;
1664        entry = entry ->Next) {
1665
1666            _cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection));
1667
1668            if (newEntry == NULL)
1669                return;
1670
1671            // We want to keep the linked list order, so this is a little bit tricky
1672            newEntry -> Next = NULL;
1673            if (Anterior)
1674                Anterior -> Next = newEntry;
1675
1676            Anterior = newEntry;
1677
1678            if (newHead.OptimizationCollection == NULL)
1679                newHead.OptimizationCollection = newEntry;
1680    }
1681
1682  ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType));
1683}
1684
1685void  _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx,
1686                                         const struct _cmsContext_struct* src)
1687{
1688  if (src != NULL) {
1689
1690        // Copy all linked list
1691       DupPluginOptimizationList(ctx, src);
1692    }
1693    else {
1694        static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL };
1695        ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType));
1696    }
1697}
1698
1699
1700// Register new ways to optimize
1701cmsBool  _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data)
1702{
1703    cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
1704    _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
1705    _cmsOptimizationCollection* fl;
1706
1707    if (Data == NULL) {
1708
1709        ctx->OptimizationCollection = NULL;
1710        return TRUE;
1711    }
1712
1713    // Optimizer callback is required
1714    if (Plugin ->OptimizePtr == NULL) return FALSE;
1715
1716    fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection));
1717    if (fl == NULL) return FALSE;
1718
1719    // Copy the parameters
1720    fl ->OptimizePtr = Plugin ->OptimizePtr;
1721
1722    // Keep linked list
1723    fl ->Next = ctx->OptimizationCollection;
1724
1725    // Set the head
1726    ctx ->OptimizationCollection = fl;
1727
1728    // All is ok
1729    return TRUE;
1730}
1731
1732// The entry point for LUT optimization
1733cmsBool _cmsOptimizePipeline(cmsContext ContextID,
1734                             cmsPipeline**    PtrLut,
1735                             int              Intent,
1736                             cmsUInt32Number* InputFormat,
1737                             cmsUInt32Number* OutputFormat,
1738                             cmsUInt32Number* dwFlags)
1739{
1740    _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
1741    _cmsOptimizationCollection* Opts;
1742    cmsBool AnySuccess = FALSE;
1743
1744    // A CLUT is being asked, so force this specific optimization
1745    if (*dwFlags & cmsFLAGS_FORCE_CLUT) {
1746
1747        PreOptimize(*PtrLut);
1748        return OptimizeByResampling(PtrLut, Intent, InputFormat, OutputFormat, dwFlags);
1749    }
1750
1751    // Anything to optimize?
1752    if ((*PtrLut) ->Elements == NULL) {
1753        _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1754        return TRUE;
1755    }
1756
1757    // Try to get rid of identities and trivial conversions.
1758    AnySuccess = PreOptimize(*PtrLut);
1759
1760    // After removal do we end with an identity?
1761    if ((*PtrLut) ->Elements == NULL) {
1762        _cmsPipelineSetOptimizationParameters(*PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1763        return TRUE;
1764    }
1765
1766    // Do not optimize, keep all precision
1767    if (*dwFlags & cmsFLAGS_NOOPTIMIZE)
1768        return FALSE;
1769
1770    // Try plug-in optimizations
1771    for (Opts = ctx->OptimizationCollection;
1772         Opts != NULL;
1773         Opts = Opts ->Next) {
1774
1775            // If one schema succeeded, we are done
1776            if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1777
1778                return TRUE;    // Optimized!
1779            }
1780    }
1781
1782   // Try built-in optimizations
1783    for (Opts = DefaultOptimization;
1784         Opts != NULL;
1785         Opts = Opts ->Next) {
1786
1787            if (Opts ->OptimizePtr(PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1788
1789                return TRUE;
1790            }
1791    }
1792
1793    // Only simple optimizations succeeded
1794    return AnySuccess;
1795}
1796