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