• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2023 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 // Allocates an empty multi profile element
_cmsStageAllocPlaceholder(cmsContext ContextID,cmsStageSignature Type,cmsUInt32Number InputChannels,cmsUInt32Number OutputChannels,_cmsStageEvalFn EvalPtr,_cmsStageDupElemFn DupElemPtr,_cmsStageFreeElemFn FreePtr,void * Data)31 cmsStage* CMSEXPORT _cmsStageAllocPlaceholder(cmsContext ContextID,
32                                 cmsStageSignature Type,
33                                 cmsUInt32Number InputChannels,
34                                 cmsUInt32Number OutputChannels,
35                                 _cmsStageEvalFn     EvalPtr,
36                                 _cmsStageDupElemFn  DupElemPtr,
37                                 _cmsStageFreeElemFn FreePtr,
38                                 void*             Data)
39 {
40     cmsStage* ph = (cmsStage*) _cmsMallocZero(ContextID, sizeof(cmsStage));
41 
42     if (ph == NULL) return NULL;
43 
44 
45     ph ->ContextID = ContextID;
46 
47     ph ->Type       = Type;
48     ph ->Implements = Type;   // By default, no clue on what is implementing
49 
50     ph ->InputChannels  = InputChannels;
51     ph ->OutputChannels = OutputChannels;
52     ph ->EvalPtr        = EvalPtr;
53     ph ->DupElemPtr     = DupElemPtr;
54     ph ->FreePtr        = FreePtr;
55     ph ->Data           = Data;
56 
57     return ph;
58 }
59 
60 
61 static
EvaluateIdentity(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)62 void EvaluateIdentity(const cmsFloat32Number In[],
63                             cmsFloat32Number Out[],
64                       const cmsStage *mpe)
65 {
66     memmove(Out, In, mpe ->InputChannels * sizeof(cmsFloat32Number));
67 }
68 
69 
cmsStageAllocIdentity(cmsContext ContextID,cmsUInt32Number nChannels)70 cmsStage* CMSEXPORT cmsStageAllocIdentity(cmsContext ContextID, cmsUInt32Number nChannels)
71 {
72     return _cmsStageAllocPlaceholder(ContextID,
73                                    cmsSigIdentityElemType,
74                                    nChannels, nChannels,
75                                    EvaluateIdentity,
76                                    NULL,
77                                    NULL,
78                                    NULL);
79  }
80 
81 // Conversion functions. From floating point to 16 bits
82 static
FromFloatTo16(const cmsFloat32Number In[],cmsUInt16Number Out[],cmsUInt32Number n)83 void FromFloatTo16(const cmsFloat32Number In[], cmsUInt16Number Out[], cmsUInt32Number n)
84 {
85     cmsUInt32Number i;
86 
87     for (i=0; i < n; i++) {
88         Out[i] = _cmsQuickSaturateWord(In[i] * 65535.0);
89     }
90 }
91 
92 // From 16 bits to floating point
93 static
From16ToFloat(const cmsUInt16Number In[],cmsFloat32Number Out[],cmsUInt32Number n)94 void From16ToFloat(const cmsUInt16Number In[], cmsFloat32Number Out[], cmsUInt32Number n)
95 {
96     cmsUInt32Number i;
97 
98     for (i=0; i < n; i++) {
99         Out[i] = (cmsFloat32Number) In[i] / 65535.0F;
100     }
101 }
102 
103 
104 // This function is quite useful to analyze the structure of a LUT and retrieve the MPE elements
105 // that conform the LUT. It should be called with the LUT, the number of expected elements and
106 // then a list of expected types followed with a list of cmsFloat64Number pointers to MPE elements. If
107 // the function founds a match with current pipeline, it fills the pointers and returns TRUE
108 // if not, returns FALSE without touching anything. Setting pointers to NULL does bypass
109 // the storage process.
cmsPipelineCheckAndRetreiveStages(const cmsPipeline * Lut,cmsUInt32Number n,...)110 cmsBool  CMSEXPORT cmsPipelineCheckAndRetreiveStages(const cmsPipeline* Lut, cmsUInt32Number n, ...)
111 {
112     va_list args;
113     cmsUInt32Number i;
114     cmsStage* mpe;
115     cmsStageSignature Type;
116     void** ElemPtr;
117 
118     // Make sure same number of elements
119     if (cmsPipelineStageCount(Lut) != n) return FALSE;
120 
121     va_start(args, n);
122 
123     // Iterate across asked types
124     mpe = Lut ->Elements;
125     for (i=0; i < n; i++) {
126 
127         // Get asked type. cmsStageSignature is promoted to int by compiler
128         Type  = (cmsStageSignature)va_arg(args, int);
129         if (mpe ->Type != Type) {
130 
131             va_end(args);       // Mismatch. We are done.
132             return FALSE;
133         }
134         mpe = mpe ->Next;
135     }
136 
137     // Found a combination, fill pointers if not NULL
138     mpe = Lut ->Elements;
139     for (i=0; i < n; i++) {
140 
141         ElemPtr = va_arg(args, void**);
142         if (ElemPtr != NULL)
143             *ElemPtr = mpe;
144 
145         mpe = mpe ->Next;
146     }
147 
148     va_end(args);
149     return TRUE;
150 }
151 
152 // Below there are implementations for several types of elements. Each type may be implemented by a
153 // evaluation function, a duplication function, a function to free resources and a constructor.
154 
155 // *************************************************************************************************
156 // Type cmsSigCurveSetElemType (curves)
157 // *************************************************************************************************
158 
_cmsStageGetPtrToCurveSet(const cmsStage * mpe)159 cmsToneCurve** _cmsStageGetPtrToCurveSet(const cmsStage* mpe)
160 {
161     _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
162 
163     return Data ->TheCurves;
164 }
165 
166 static
EvaluateCurves(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)167 void EvaluateCurves(const cmsFloat32Number In[],
168                     cmsFloat32Number Out[],
169                     const cmsStage *mpe)
170 {
171     _cmsStageToneCurvesData* Data;
172     cmsUInt32Number i;
173 
174     _cmsAssert(mpe != NULL);
175 
176     Data = (_cmsStageToneCurvesData*) mpe ->Data;
177     if (Data == NULL) return;
178 
179     if (Data ->TheCurves == NULL) return;
180 
181     for (i=0; i < Data ->nCurves; i++) {
182         Out[i] = cmsEvalToneCurveFloat(Data ->TheCurves[i], In[i]);
183     }
184 }
185 
186 static
CurveSetElemTypeFree(cmsStage * mpe)187 void CurveSetElemTypeFree(cmsStage* mpe)
188 {
189     _cmsStageToneCurvesData* Data;
190     cmsUInt32Number i;
191 
192     _cmsAssert(mpe != NULL);
193 
194     Data = (_cmsStageToneCurvesData*) mpe ->Data;
195     if (Data == NULL) return;
196 
197     if (Data ->TheCurves != NULL) {
198         for (i=0; i < Data ->nCurves; i++) {
199             if (Data ->TheCurves[i] != NULL)
200                 cmsFreeToneCurve(Data ->TheCurves[i]);
201         }
202     }
203     _cmsFree(mpe ->ContextID, Data ->TheCurves);
204     _cmsFree(mpe ->ContextID, Data);
205 }
206 
207 
208 static
CurveSetDup(cmsStage * mpe)209 void* CurveSetDup(cmsStage* mpe)
210 {
211     _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
212     _cmsStageToneCurvesData* NewElem;
213     cmsUInt32Number i;
214 
215     NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageToneCurvesData));
216     if (NewElem == NULL) return NULL;
217 
218     NewElem ->nCurves   = Data ->nCurves;
219     NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(mpe ->ContextID, NewElem ->nCurves, sizeof(cmsToneCurve*));
220 
221     if (NewElem ->TheCurves == NULL) goto Error;
222 
223     for (i=0; i < NewElem ->nCurves; i++) {
224 
225         // Duplicate each curve. It may fail.
226         NewElem ->TheCurves[i] = cmsDupToneCurve(Data ->TheCurves[i]);
227         if (NewElem ->TheCurves[i] == NULL) goto Error;
228 
229 
230     }
231     return (void*) NewElem;
232 
233 Error:
234 
235     if (NewElem ->TheCurves != NULL) {
236         for (i=0; i < NewElem ->nCurves; i++) {
237             if (NewElem ->TheCurves[i])
238                 cmsFreeToneCurve(NewElem ->TheCurves[i]);
239         }
240     }
241     _cmsFree(mpe ->ContextID, NewElem ->TheCurves);
242     _cmsFree(mpe ->ContextID, NewElem);
243     return NULL;
244 }
245 
246 
247 // Curves == NULL forces identity curves
cmsStageAllocToneCurves(cmsContext ContextID,cmsUInt32Number nChannels,cmsToneCurve * const Curves[])248 cmsStage* CMSEXPORT cmsStageAllocToneCurves(cmsContext ContextID, cmsUInt32Number nChannels, cmsToneCurve* const Curves[])
249 {
250     cmsUInt32Number i;
251     _cmsStageToneCurvesData* NewElem;
252     cmsStage* NewMPE;
253 
254 
255     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCurveSetElemType, nChannels, nChannels,
256                                      EvaluateCurves, CurveSetDup, CurveSetElemTypeFree, NULL );
257     if (NewMPE == NULL) return NULL;
258 
259     NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(ContextID, sizeof(_cmsStageToneCurvesData));
260     if (NewElem == NULL) {
261         cmsStageFree(NewMPE);
262         return NULL;
263     }
264 
265     NewMPE ->Data  = (void*) NewElem;
266 
267     NewElem ->nCurves   = nChannels;
268     NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(ContextID, nChannels, sizeof(cmsToneCurve*));
269     if (NewElem ->TheCurves == NULL) {
270         cmsStageFree(NewMPE);
271         return NULL;
272     }
273 
274     for (i=0; i < nChannels; i++) {
275 
276         if (Curves == NULL) {
277             NewElem ->TheCurves[i] = cmsBuildGamma(ContextID, 1.0);
278         }
279         else {
280             NewElem ->TheCurves[i] = cmsDupToneCurve(Curves[i]);
281         }
282 
283         if (NewElem ->TheCurves[i] == NULL) {
284             cmsStageFree(NewMPE);
285             return NULL;
286         }
287 
288     }
289 
290    return NewMPE;
291 }
292 
293 
294 // Create a bunch of identity curves
_cmsStageAllocIdentityCurves(cmsContext ContextID,cmsUInt32Number nChannels)295 cmsStage* CMSEXPORT _cmsStageAllocIdentityCurves(cmsContext ContextID, cmsUInt32Number nChannels)
296 {
297     cmsStage* mpe = cmsStageAllocToneCurves(ContextID, nChannels, NULL);
298 
299     if (mpe == NULL) return NULL;
300     mpe ->Implements = cmsSigIdentityElemType;
301     return mpe;
302 }
303 
304 
305 // *************************************************************************************************
306 // Type cmsSigMatrixElemType (Matrices)
307 // *************************************************************************************************
308 
309 
310 // Special care should be taken here because precision loss. A temporary cmsFloat64Number buffer is being used
311 static
EvaluateMatrix(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)312 void EvaluateMatrix(const cmsFloat32Number In[],
313                     cmsFloat32Number Out[],
314                     const cmsStage *mpe)
315 {
316     cmsUInt32Number i, j;
317     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
318     cmsFloat64Number Tmp;
319 
320     // Input is already in 0..1.0 notation
321     for (i=0; i < mpe ->OutputChannels; i++) {
322 
323         Tmp = 0;
324         for (j=0; j < mpe->InputChannels; j++) {
325             Tmp += In[j] * Data->Double[i*mpe->InputChannels + j];
326         }
327 
328         if (Data ->Offset != NULL)
329             Tmp += Data->Offset[i];
330 
331         Out[i] = (cmsFloat32Number) Tmp;
332     }
333 
334 
335     // Output in 0..1.0 domain
336 }
337 
338 
339 // Duplicate a yet-existing matrix element
340 static
MatrixElemDup(cmsStage * mpe)341 void* MatrixElemDup(cmsStage* mpe)
342 {
343     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
344     _cmsStageMatrixData* NewElem;
345     cmsUInt32Number sz;
346 
347     NewElem = (_cmsStageMatrixData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageMatrixData));
348     if (NewElem == NULL) return NULL;
349 
350     sz = mpe ->InputChannels * mpe ->OutputChannels;
351 
352     NewElem ->Double = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID, Data ->Double, sz * sizeof(cmsFloat64Number)) ;
353 
354     if (Data ->Offset)
355         NewElem ->Offset = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID,
356                                                 Data ->Offset, mpe -> OutputChannels * sizeof(cmsFloat64Number)) ;
357 
358     return (void*) NewElem;
359 }
360 
361 
362 static
MatrixElemTypeFree(cmsStage * mpe)363 void MatrixElemTypeFree(cmsStage* mpe)
364 {
365     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
366     if (Data == NULL)
367         return;
368     if (Data ->Double)
369         _cmsFree(mpe ->ContextID, Data ->Double);
370 
371     if (Data ->Offset)
372         _cmsFree(mpe ->ContextID, Data ->Offset);
373 
374     _cmsFree(mpe ->ContextID, mpe ->Data);
375 }
376 
377 
378 
cmsStageAllocMatrix(cmsContext ContextID,cmsUInt32Number Rows,cmsUInt32Number Cols,const cmsFloat64Number * Matrix,const cmsFloat64Number * Offset)379 cmsStage*  CMSEXPORT cmsStageAllocMatrix(cmsContext ContextID, cmsUInt32Number Rows, cmsUInt32Number Cols,
380                                      const cmsFloat64Number* Matrix, const cmsFloat64Number* Offset)
381 {
382     cmsUInt32Number i, n;
383     _cmsStageMatrixData* NewElem;
384     cmsStage* NewMPE;
385 
386     n = Rows * Cols;
387 
388     // Check for overflow
389     if (n == 0) return NULL;
390     if (n >= UINT_MAX / Cols) return NULL;
391     if (n >= UINT_MAX / Rows) return NULL;
392     if (n < Rows || n < Cols) return NULL;
393 
394     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigMatrixElemType, Cols, Rows,
395                                      EvaluateMatrix, MatrixElemDup, MatrixElemTypeFree, NULL );
396     if (NewMPE == NULL) return NULL;
397 
398 
399     NewElem = (_cmsStageMatrixData*) _cmsMallocZero(ContextID, sizeof(_cmsStageMatrixData));
400     if (NewElem == NULL) goto Error;
401     NewMPE->Data = (void*)NewElem;
402 
403     NewElem ->Double = (cmsFloat64Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat64Number));
404     if (NewElem->Double == NULL) goto Error;
405 
406     for (i=0; i < n; i++) {
407         NewElem ->Double[i] = Matrix[i];
408     }
409 
410     if (Offset != NULL) {
411 
412         NewElem ->Offset = (cmsFloat64Number*) _cmsCalloc(ContextID, Rows, sizeof(cmsFloat64Number));
413         if (NewElem->Offset == NULL) goto Error;
414 
415         for (i=0; i < Rows; i++) {
416                 NewElem ->Offset[i] = Offset[i];
417         }
418     }
419 
420     return NewMPE;
421 
422 Error:
423     cmsStageFree(NewMPE);
424     return NULL;
425 }
426 
427 
428 // *************************************************************************************************
429 // Type cmsSigCLutElemType
430 // *************************************************************************************************
431 
432 
433 // Evaluate in true floating point
434 static
EvaluateCLUTfloat(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)435 void EvaluateCLUTfloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
436 {
437     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
438 
439     Data -> Params ->Interpolation.LerpFloat(In, Out, Data->Params);
440 }
441 
442 
443 // Convert to 16 bits, evaluate, and back to floating point
444 static
EvaluateCLUTfloatIn16(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)445 void EvaluateCLUTfloatIn16(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
446 {
447     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
448     cmsUInt16Number In16[MAX_STAGE_CHANNELS], Out16[MAX_STAGE_CHANNELS];
449 
450     _cmsAssert(mpe ->InputChannels  <= MAX_STAGE_CHANNELS);
451     _cmsAssert(mpe ->OutputChannels <= MAX_STAGE_CHANNELS);
452 
453     FromFloatTo16(In, In16, mpe ->InputChannels);
454     Data -> Params ->Interpolation.Lerp16(In16, Out16, Data->Params);
455     From16ToFloat(Out16, Out,  mpe ->OutputChannels);
456 }
457 
458 
459 // Given an hypercube of b dimensions, with Dims[] number of nodes by dimension, calculate the total amount of nodes
460 static
CubeSize(const cmsUInt32Number Dims[],cmsUInt32Number b)461 cmsUInt32Number CubeSize(const cmsUInt32Number Dims[], cmsUInt32Number b)
462 {
463     cmsUInt32Number rv, dim;
464 
465     _cmsAssert(Dims != NULL);
466 
467     for (rv = 1; b > 0; b--) {
468 
469         dim = Dims[b-1];
470         if (dim <= 1) return 0;  // Error
471 
472         rv *= dim;
473 
474         // Check for overflow
475         if (rv > UINT_MAX / dim) return 0;
476     }
477 
478     return rv;
479 }
480 
481 static
CLUTElemDup(cmsStage * mpe)482 void* CLUTElemDup(cmsStage* mpe)
483 {
484     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
485     _cmsStageCLutData* NewElem;
486 
487 
488     NewElem = (_cmsStageCLutData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageCLutData));
489     if (NewElem == NULL) return NULL;
490 
491     NewElem ->nEntries       = Data ->nEntries;
492     NewElem ->HasFloatValues = Data ->HasFloatValues;
493 
494     if (Data ->Tab.T) {
495 
496         if (Data ->HasFloatValues) {
497             NewElem ->Tab.TFloat = (cmsFloat32Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.TFloat, Data ->nEntries * sizeof (cmsFloat32Number));
498             if (NewElem ->Tab.TFloat == NULL)
499                 goto Error;
500         } else {
501             NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
502             if (NewElem ->Tab.T == NULL)
503                 goto Error;
504         }
505     }
506 
507     NewElem ->Params   = _cmsComputeInterpParamsEx(mpe ->ContextID,
508                                                    Data ->Params ->nSamples,
509                                                    Data ->Params ->nInputs,
510                                                    Data ->Params ->nOutputs,
511                                                    NewElem ->Tab.T,
512                                                    Data ->Params ->dwFlags);
513     if (NewElem->Params != NULL)
514         return (void*) NewElem;
515  Error:
516     if (NewElem->Tab.T)
517         // This works for both types
518         _cmsFree(mpe ->ContextID, NewElem -> Tab.T);
519     _cmsFree(mpe ->ContextID, NewElem);
520     return NULL;
521 }
522 
523 
524 static
CLutElemTypeFree(cmsStage * mpe)525 void CLutElemTypeFree(cmsStage* mpe)
526 {
527 
528     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
529 
530     // Already empty
531     if (Data == NULL) return;
532 
533     // This works for both types
534     if (Data -> Tab.T)
535         _cmsFree(mpe ->ContextID, Data -> Tab.T);
536 
537     _cmsFreeInterpParams(Data ->Params);
538     _cmsFree(mpe ->ContextID, mpe ->Data);
539 }
540 
541 
542 // Allocates a 16-bit multidimensional CLUT. This is evaluated at 16-bit precision. Table may have different
543 // granularity on each dimension.
cmsStageAllocCLut16bitGranular(cmsContext ContextID,const cmsUInt32Number clutPoints[],cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsUInt16Number * Table)544 cmsStage* CMSEXPORT cmsStageAllocCLut16bitGranular(cmsContext ContextID,
545                                          const cmsUInt32Number clutPoints[],
546                                          cmsUInt32Number inputChan,
547                                          cmsUInt32Number outputChan,
548                                          const cmsUInt16Number* Table)
549 {
550     cmsUInt32Number i, n;
551     _cmsStageCLutData* NewElem;
552     cmsStage* NewMPE;
553 
554     _cmsAssert(clutPoints != NULL);
555 
556     if (inputChan > MAX_INPUT_DIMENSIONS) {
557         cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", inputChan, MAX_INPUT_DIMENSIONS);
558         return NULL;
559     }
560 
561     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
562                                      EvaluateCLUTfloatIn16, CLUTElemDup, CLutElemTypeFree, NULL );
563 
564     if (NewMPE == NULL) return NULL;
565 
566     NewElem = (_cmsStageCLutData*) _cmsMallocZero(ContextID, sizeof(_cmsStageCLutData));
567     if (NewElem == NULL) {
568         cmsStageFree(NewMPE);
569         return NULL;
570     }
571 
572     NewMPE ->Data  = (void*) NewElem;
573 
574     NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
575     NewElem -> HasFloatValues = FALSE;
576 
577     if (n == 0) {
578         cmsStageFree(NewMPE);
579         return NULL;
580     }
581 
582 
583     NewElem ->Tab.T  = (cmsUInt16Number*) _cmsCalloc(ContextID, n, sizeof(cmsUInt16Number));
584     if (NewElem ->Tab.T == NULL) {
585         cmsStageFree(NewMPE);
586         return NULL;
587     }
588 
589     if (Table != NULL) {
590         for (i=0; i < n; i++) {
591             NewElem ->Tab.T[i] = Table[i];
592         }
593     }
594 
595     NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints, inputChan, outputChan, NewElem ->Tab.T, CMS_LERP_FLAGS_16BITS);
596     if (NewElem ->Params == NULL) {
597         cmsStageFree(NewMPE);
598         return NULL;
599     }
600 
601     return NewMPE;
602 }
603 
cmsStageAllocCLut16bit(cmsContext ContextID,cmsUInt32Number nGridPoints,cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsUInt16Number * Table)604 cmsStage* CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID,
605                                     cmsUInt32Number nGridPoints,
606                                     cmsUInt32Number inputChan,
607                                     cmsUInt32Number outputChan,
608                                     const cmsUInt16Number* Table)
609 {
610     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
611     int i;
612 
613    // Our resulting LUT would be same gridpoints on all dimensions
614     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
615         Dimensions[i] = nGridPoints;
616 
617     return cmsStageAllocCLut16bitGranular(ContextID, Dimensions, inputChan, outputChan, Table);
618 }
619 
620 
cmsStageAllocCLutFloat(cmsContext ContextID,cmsUInt32Number nGridPoints,cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsFloat32Number * Table)621 cmsStage* CMSEXPORT cmsStageAllocCLutFloat(cmsContext ContextID,
622                                        cmsUInt32Number nGridPoints,
623                                        cmsUInt32Number inputChan,
624                                        cmsUInt32Number outputChan,
625                                        const cmsFloat32Number* Table)
626 {
627    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
628    int i;
629 
630     // Our resulting LUT would be same gridpoints on all dimensions
631     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
632         Dimensions[i] = nGridPoints;
633 
634     return cmsStageAllocCLutFloatGranular(ContextID, Dimensions, inputChan, outputChan, Table);
635 }
636 
637 
638 
cmsStageAllocCLutFloatGranular(cmsContext ContextID,const cmsUInt32Number clutPoints[],cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsFloat32Number * Table)639 cmsStage* CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table)
640 {
641     cmsUInt32Number i, n;
642     _cmsStageCLutData* NewElem;
643     cmsStage* NewMPE;
644 
645     _cmsAssert(clutPoints != NULL);
646 
647     if (inputChan > MAX_INPUT_DIMENSIONS) {
648         cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", inputChan, MAX_INPUT_DIMENSIONS);
649         return NULL;
650     }
651 
652     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
653                                              EvaluateCLUTfloat, CLUTElemDup, CLutElemTypeFree, NULL);
654     if (NewMPE == NULL) return NULL;
655 
656 
657     NewElem = (_cmsStageCLutData*) _cmsMallocZero(ContextID, sizeof(_cmsStageCLutData));
658     if (NewElem == NULL) {
659         cmsStageFree(NewMPE);
660         return NULL;
661     }
662 
663     NewMPE ->Data  = (void*) NewElem;
664 
665     // There is a potential integer overflow on conputing n and nEntries.
666     NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
667     NewElem -> HasFloatValues = TRUE;
668 
669     if (n == 0) {
670         cmsStageFree(NewMPE);
671         return NULL;
672     }
673 
674     NewElem ->Tab.TFloat  = (cmsFloat32Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat32Number));
675     if (NewElem ->Tab.TFloat == NULL) {
676         cmsStageFree(NewMPE);
677         return NULL;
678     }
679 
680     if (Table != NULL) {
681         for (i=0; i < n; i++) {
682             NewElem ->Tab.TFloat[i] = Table[i];
683         }
684     }
685 
686     NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints,  inputChan, outputChan, NewElem ->Tab.TFloat, CMS_LERP_FLAGS_FLOAT);
687     if (NewElem ->Params == NULL) {
688         cmsStageFree(NewMPE);
689         return NULL;
690     }
691 
692     return NewMPE;
693 }
694 
695 
696 static
IdentitySampler(CMSREGISTER const cmsUInt16Number In[],CMSREGISTER cmsUInt16Number Out[],CMSREGISTER void * Cargo)697 int IdentitySampler(CMSREGISTER const cmsUInt16Number In[], CMSREGISTER cmsUInt16Number Out[], CMSREGISTER void * Cargo)
698 {
699     int nChan = *(int*) Cargo;
700     int i;
701 
702     for (i=0; i < nChan; i++)
703         Out[i] = In[i];
704 
705     return 1;
706 }
707 
708 // Creates an MPE that just copies input to output
_cmsStageAllocIdentityCLut(cmsContext ContextID,cmsUInt32Number nChan)709 cmsStage* CMSEXPORT _cmsStageAllocIdentityCLut(cmsContext ContextID, cmsUInt32Number nChan)
710 {
711     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
712     cmsStage* mpe ;
713     int i;
714 
715     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
716         Dimensions[i] = 2;
717 
718     mpe = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, nChan, nChan, NULL);
719     if (mpe == NULL) return NULL;
720 
721     if (!cmsStageSampleCLut16bit(mpe, IdentitySampler, &nChan, 0)) {
722         cmsStageFree(mpe);
723         return NULL;
724     }
725 
726     mpe ->Implements = cmsSigIdentityElemType;
727     return mpe;
728 }
729 
730 
731 
732 // Quantize a value 0 <= i < MaxSamples to 0..0xffff
_cmsQuantizeVal(cmsFloat64Number i,cmsUInt32Number MaxSamples)733 cmsUInt16Number CMSEXPORT _cmsQuantizeVal(cmsFloat64Number i, cmsUInt32Number MaxSamples)
734 {
735     cmsFloat64Number x;
736 
737     x = ((cmsFloat64Number) i * 65535.) / (cmsFloat64Number) (MaxSamples - 1);
738     return _cmsQuickSaturateWord(x);
739 }
740 
741 
742 // This routine does a sweep on whole input space, and calls its callback
743 // function on knots. returns TRUE if all ok, FALSE otherwise.
cmsStageSampleCLut16bit(cmsStage * mpe,cmsSAMPLER16 Sampler,void * Cargo,cmsUInt32Number dwFlags)744 cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, void * Cargo, cmsUInt32Number dwFlags)
745 {
746     int i, t, index, rest;
747     cmsUInt32Number nTotalPoints;
748     cmsUInt32Number nInputs, nOutputs;
749     cmsUInt32Number* nSamples;
750     cmsUInt16Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
751     _cmsStageCLutData* clut;
752 
753     if (mpe == NULL) return FALSE;
754 
755     clut = (_cmsStageCLutData*) mpe->Data;
756 
757     if (clut == NULL) return FALSE;
758 
759     nSamples = clut->Params ->nSamples;
760     nInputs  = clut->Params ->nInputs;
761     nOutputs = clut->Params ->nOutputs;
762 
763     if (nInputs <= 0) return FALSE;
764     if (nOutputs <= 0) return FALSE;
765     if (nInputs > MAX_INPUT_DIMENSIONS) return FALSE;
766     if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
767 
768     memset(In, 0, sizeof(In));
769     memset(Out, 0, sizeof(Out));
770 
771     nTotalPoints = CubeSize(nSamples, nInputs);
772     if (nTotalPoints == 0) return FALSE;
773 
774     index = 0;
775     for (i = 0; i < (int) nTotalPoints; i++) {
776 
777         rest = i;
778         for (t = (int)nInputs - 1; t >= 0; --t) {
779 
780             cmsUInt32Number  Colorant = rest % nSamples[t];
781 
782             rest /= nSamples[t];
783 
784             In[t] = _cmsQuantizeVal(Colorant, nSamples[t]);
785         }
786 
787         if (clut ->Tab.T != NULL) {
788             for (t = 0; t < (int)nOutputs; t++)
789                 Out[t] = clut->Tab.T[index + t];
790         }
791 
792         if (!Sampler(In, Out, Cargo))
793             return FALSE;
794 
795         if (!(dwFlags & SAMPLER_INSPECT)) {
796 
797             if (clut ->Tab.T != NULL) {
798                 for (t=0; t < (int) nOutputs; t++)
799                     clut->Tab.T[index + t] = Out[t];
800             }
801         }
802 
803         index += nOutputs;
804     }
805 
806     return TRUE;
807 }
808 
809 // Same as anterior, but for floating point
cmsStageSampleCLutFloat(cmsStage * mpe,cmsSAMPLERFLOAT Sampler,void * Cargo,cmsUInt32Number dwFlags)810 cmsBool CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler, void * Cargo, cmsUInt32Number dwFlags)
811 {
812     int i, t, index, rest;
813     cmsUInt32Number nTotalPoints;
814     cmsUInt32Number nInputs, nOutputs;
815     cmsUInt32Number* nSamples;
816     cmsFloat32Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
817     _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
818 
819     nSamples = clut->Params ->nSamples;
820     nInputs  = clut->Params ->nInputs;
821     nOutputs = clut->Params ->nOutputs;
822 
823     if (nInputs <= 0) return FALSE;
824     if (nOutputs <= 0) return FALSE;
825     if (nInputs  > MAX_INPUT_DIMENSIONS) return FALSE;
826     if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
827 
828     nTotalPoints = CubeSize(nSamples, nInputs);
829     if (nTotalPoints == 0) return FALSE;
830 
831     index = 0;
832     for (i = 0; i < (int)nTotalPoints; i++) {
833 
834         rest = i;
835         for (t = (int) nInputs-1; t >=0; --t) {
836 
837             cmsUInt32Number  Colorant = rest % nSamples[t];
838 
839             rest /= nSamples[t];
840 
841             In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, nSamples[t]) / 65535.0);
842         }
843 
844         if (clut ->Tab.TFloat != NULL) {
845             for (t=0; t < (int) nOutputs; t++)
846                 Out[t] = clut->Tab.TFloat[index + t];
847         }
848 
849         if (!Sampler(In, Out, Cargo))
850             return FALSE;
851 
852         if (!(dwFlags & SAMPLER_INSPECT)) {
853 
854             if (clut ->Tab.TFloat != NULL) {
855                 for (t=0; t < (int) nOutputs; t++)
856                     clut->Tab.TFloat[index + t] = Out[t];
857             }
858         }
859 
860         index += nOutputs;
861     }
862 
863     return TRUE;
864 }
865 
866 
867 
868 // This routine does a sweep on whole input space, and calls its callback
869 // function on knots. returns TRUE if all ok, FALSE otherwise.
cmsSliceSpace16(cmsUInt32Number nInputs,const cmsUInt32Number clutPoints[],cmsSAMPLER16 Sampler,void * Cargo)870 cmsBool CMSEXPORT cmsSliceSpace16(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
871                                          cmsSAMPLER16 Sampler, void * Cargo)
872 {
873     int i, t, rest;
874     cmsUInt32Number nTotalPoints;
875     cmsUInt16Number In[cmsMAXCHANNELS];
876 
877     if (nInputs >= cmsMAXCHANNELS) return FALSE;
878 
879     nTotalPoints = CubeSize(clutPoints, nInputs);
880     if (nTotalPoints == 0) return FALSE;
881 
882     for (i = 0; i < (int) nTotalPoints; i++) {
883 
884         rest = i;
885         for (t = (int) nInputs-1; t >=0; --t) {
886 
887             cmsUInt32Number  Colorant = rest % clutPoints[t];
888 
889             rest /= clutPoints[t];
890             In[t] = _cmsQuantizeVal(Colorant, clutPoints[t]);
891 
892         }
893 
894         if (!Sampler(In, NULL, Cargo))
895             return FALSE;
896     }
897 
898     return TRUE;
899 }
900 
cmsSliceSpaceFloat(cmsUInt32Number nInputs,const cmsUInt32Number clutPoints[],cmsSAMPLERFLOAT Sampler,void * Cargo)901 cmsInt32Number CMSEXPORT cmsSliceSpaceFloat(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
902                                             cmsSAMPLERFLOAT Sampler, void * Cargo)
903 {
904     int i, t, rest;
905     cmsUInt32Number nTotalPoints;
906     cmsFloat32Number In[cmsMAXCHANNELS];
907 
908     if (nInputs >= cmsMAXCHANNELS) return FALSE;
909 
910     nTotalPoints = CubeSize(clutPoints, nInputs);
911     if (nTotalPoints == 0) return FALSE;
912 
913     for (i = 0; i < (int) nTotalPoints; i++) {
914 
915         rest = i;
916         for (t = (int) nInputs-1; t >=0; --t) {
917 
918             cmsUInt32Number  Colorant = rest % clutPoints[t];
919 
920             rest /= clutPoints[t];
921             In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, clutPoints[t]) / 65535.0);
922 
923         }
924 
925         if (!Sampler(In, NULL, Cargo))
926             return FALSE;
927     }
928 
929     return TRUE;
930 }
931 
932 // ********************************************************************************
933 // Type cmsSigLab2XYZElemType
934 // ********************************************************************************
935 
936 
937 static
EvaluateLab2XYZ(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)938 void EvaluateLab2XYZ(const cmsFloat32Number In[],
939                      cmsFloat32Number Out[],
940                      const cmsStage *mpe)
941 {
942     cmsCIELab Lab;
943     cmsCIEXYZ XYZ;
944     const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
945 
946     // V4 rules
947     Lab.L = In[0] * 100.0;
948     Lab.a = In[1] * 255.0 - 128.0;
949     Lab.b = In[2] * 255.0 - 128.0;
950 
951     cmsLab2XYZ(NULL, &XYZ, &Lab);
952 
953     // From XYZ, range 0..19997 to 0..1.0, note that 1.99997 comes from 0xffff
954     // encoded as 1.15 fixed point, so 1 + (32767.0 / 32768.0)
955 
956     Out[0] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.X / XYZadj);
957     Out[1] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Y / XYZadj);
958     Out[2] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Z / XYZadj);
959     return;
960 
961     cmsUNUSED_PARAMETER(mpe);
962 }
963 
964 
965 // No dup or free routines needed, as the structure has no pointers in it.
_cmsStageAllocLab2XYZ(cmsContext ContextID)966 cmsStage* CMSEXPORT _cmsStageAllocLab2XYZ(cmsContext ContextID)
967 {
968     return _cmsStageAllocPlaceholder(ContextID, cmsSigLab2XYZElemType, 3, 3, EvaluateLab2XYZ, NULL, NULL, NULL);
969 }
970 
971 // ********************************************************************************
972 
973 // v2 L=100 is supposed to be placed on 0xFF00. There is no reasonable
974 // number of gridpoints that would make exact match. However, a prelinearization
975 // of 258 entries, would map 0xFF00 exactly on entry 257, and this is good to avoid scum dot.
976 // Almost all what we need but unfortunately, the rest of entries should be scaled by
977 // (255*257/256) and this is not exact.
978 
_cmsStageAllocLabV2ToV4curves(cmsContext ContextID)979 cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID)
980 {
981     cmsStage* mpe;
982     cmsToneCurve* LabTable[3];
983     int i, j;
984 
985     LabTable[0] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
986     LabTable[1] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
987     LabTable[2] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
988 
989     for (j=0; j < 3; j++) {
990 
991         if (LabTable[j] == NULL) {
992             cmsFreeToneCurveTriple(LabTable);
993             return NULL;
994         }
995 
996         // We need to map * (0xffff / 0xff00), that's same as (257 / 256)
997         // So we can use 258-entry tables to do the trick (i / 257) * (255 * 257) * (257 / 256);
998         for (i=0; i < 257; i++)  {
999 
1000             LabTable[j]->Table16[i] = (cmsUInt16Number) ((i * 0xffff + 0x80) >> 8);
1001         }
1002 
1003         LabTable[j] ->Table16[257] = 0xffff;
1004     }
1005 
1006     mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
1007     cmsFreeToneCurveTriple(LabTable);
1008 
1009     if (mpe == NULL) return NULL;
1010     mpe ->Implements = cmsSigLabV2toV4;
1011     return mpe;
1012 }
1013 
1014 // ********************************************************************************
1015 
1016 // Matrix-based conversion, which is more accurate, but slower and cannot properly be saved in devicelink profiles
_cmsStageAllocLabV2ToV4(cmsContext ContextID)1017 cmsStage* CMSEXPORT _cmsStageAllocLabV2ToV4(cmsContext ContextID)
1018 {
1019     static const cmsFloat64Number V2ToV4[] = { 65535.0/65280.0, 0, 0,
1020                                      0, 65535.0/65280.0, 0,
1021                                      0, 0, 65535.0/65280.0
1022                                      };
1023 
1024     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V2ToV4, NULL);
1025 
1026     if (mpe == NULL) return mpe;
1027     mpe ->Implements = cmsSigLabV2toV4;
1028     return mpe;
1029 }
1030 
1031 
1032 // Reverse direction
_cmsStageAllocLabV4ToV2(cmsContext ContextID)1033 cmsStage* CMSEXPORT _cmsStageAllocLabV4ToV2(cmsContext ContextID)
1034 {
1035     static const cmsFloat64Number V4ToV2[] = { 65280.0/65535.0, 0, 0,
1036                                      0, 65280.0/65535.0, 0,
1037                                      0, 0, 65280.0/65535.0
1038                                      };
1039 
1040      cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V4ToV2, NULL);
1041 
1042     if (mpe == NULL) return mpe;
1043     mpe ->Implements = cmsSigLabV4toV2;
1044     return mpe;
1045 }
1046 
1047 
1048 // To Lab to float. Note that the MPE gives numbers in normal Lab range
1049 // and we need 0..1.0 range for the formatters
1050 // L* : 0...100 => 0...1.0  (L* / 100)
1051 // ab* : -128..+127 to 0..1  ((ab* + 128) / 255)
1052 
_cmsStageNormalizeFromLabFloat(cmsContext ContextID)1053 cmsStage* _cmsStageNormalizeFromLabFloat(cmsContext ContextID)
1054 {
1055     static const cmsFloat64Number a1[] = {
1056         1.0/100.0, 0, 0,
1057         0, 1.0/255.0, 0,
1058         0, 0, 1.0/255.0
1059     };
1060 
1061     static const cmsFloat64Number o1[] = {
1062         0,
1063         128.0/255.0,
1064         128.0/255.0
1065     };
1066 
1067     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, a1, o1);
1068 
1069     if (mpe == NULL) return mpe;
1070     mpe ->Implements = cmsSigLab2FloatPCS;
1071     return mpe;
1072 }
1073 
1074 // Fom XYZ to floating point PCS
_cmsStageNormalizeFromXyzFloat(cmsContext ContextID)1075 cmsStage* _cmsStageNormalizeFromXyzFloat(cmsContext ContextID)
1076 {
1077 #define n (32768.0/65535.0)
1078     static const cmsFloat64Number a1[] = {
1079         n, 0, 0,
1080         0, n, 0,
1081         0, 0, n
1082     };
1083 #undef n
1084 
1085     cmsStage *mpe =  cmsStageAllocMatrix(ContextID, 3, 3, a1, NULL);
1086 
1087     if (mpe == NULL) return mpe;
1088     mpe ->Implements = cmsSigXYZ2FloatPCS;
1089     return mpe;
1090 }
1091 
_cmsStageNormalizeToLabFloat(cmsContext ContextID)1092 cmsStage* _cmsStageNormalizeToLabFloat(cmsContext ContextID)
1093 {
1094     static const cmsFloat64Number a1[] = {
1095         100.0, 0, 0,
1096         0, 255.0, 0,
1097         0, 0, 255.0
1098     };
1099 
1100     static const cmsFloat64Number o1[] = {
1101         0,
1102         -128.0,
1103         -128.0
1104     };
1105 
1106     cmsStage *mpe =  cmsStageAllocMatrix(ContextID, 3, 3, a1, o1);
1107     if (mpe == NULL) return mpe;
1108     mpe ->Implements = cmsSigFloatPCS2Lab;
1109     return mpe;
1110 }
1111 
_cmsStageNormalizeToXyzFloat(cmsContext ContextID)1112 cmsStage* _cmsStageNormalizeToXyzFloat(cmsContext ContextID)
1113 {
1114 #define n (65535.0/32768.0)
1115 
1116     static const cmsFloat64Number a1[] = {
1117         n, 0, 0,
1118         0, n, 0,
1119         0, 0, n
1120     };
1121 #undef n
1122 
1123     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, a1, NULL);
1124     if (mpe == NULL) return mpe;
1125     mpe ->Implements = cmsSigFloatPCS2XYZ;
1126     return mpe;
1127 }
1128 
1129 // Clips values smaller than zero
1130 static
Clipper(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)1131 void Clipper(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
1132 {
1133        cmsUInt32Number i;
1134        for (i = 0; i < mpe->InputChannels; i++) {
1135 
1136               cmsFloat32Number n = In[i];
1137               Out[i] = n < 0 ? 0 : n;
1138        }
1139 }
1140 
_cmsStageClipNegatives(cmsContext ContextID,cmsUInt32Number nChannels)1141 cmsStage*  _cmsStageClipNegatives(cmsContext ContextID, cmsUInt32Number nChannels)
1142 {
1143        return _cmsStageAllocPlaceholder(ContextID, cmsSigClipNegativesElemType,
1144               nChannels, nChannels, Clipper, NULL, NULL, NULL);
1145 }
1146 
1147 // ********************************************************************************
1148 // Type cmsSigXYZ2LabElemType
1149 // ********************************************************************************
1150 
1151 static
EvaluateXYZ2Lab(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)1152 void EvaluateXYZ2Lab(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
1153 {
1154     cmsCIELab Lab;
1155     cmsCIEXYZ XYZ;
1156     const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
1157 
1158     // From 0..1.0 to XYZ
1159 
1160     XYZ.X = In[0] * XYZadj;
1161     XYZ.Y = In[1] * XYZadj;
1162     XYZ.Z = In[2] * XYZadj;
1163 
1164     cmsXYZ2Lab(NULL, &Lab, &XYZ);
1165 
1166     // From V4 Lab to 0..1.0
1167 
1168     Out[0] = (cmsFloat32Number) (Lab.L / 100.0);
1169     Out[1] = (cmsFloat32Number) ((Lab.a + 128.0) / 255.0);
1170     Out[2] = (cmsFloat32Number) ((Lab.b + 128.0) / 255.0);
1171     return;
1172 
1173     cmsUNUSED_PARAMETER(mpe);
1174 }
1175 
_cmsStageAllocXYZ2Lab(cmsContext ContextID)1176 cmsStage* CMSEXPORT _cmsStageAllocXYZ2Lab(cmsContext ContextID)
1177 {
1178     return _cmsStageAllocPlaceholder(ContextID, cmsSigXYZ2LabElemType, 3, 3, EvaluateXYZ2Lab, NULL, NULL, NULL);
1179 
1180 }
1181 
1182 // ********************************************************************************
1183 
1184 // For v4, S-Shaped curves are placed in a/b axis to increase resolution near gray
1185 
_cmsStageAllocLabPrelin(cmsContext ContextID)1186 cmsStage* _cmsStageAllocLabPrelin(cmsContext ContextID)
1187 {
1188     cmsToneCurve* LabTable[3];
1189     cmsFloat64Number Params[1] =  {2.4} ;
1190 
1191     LabTable[0] = cmsBuildGamma(ContextID, 1.0);
1192     LabTable[1] = cmsBuildParametricToneCurve(ContextID, 108, Params);
1193     LabTable[2] = cmsBuildParametricToneCurve(ContextID, 108, Params);
1194 
1195     return cmsStageAllocToneCurves(ContextID, 3, LabTable);
1196 }
1197 
1198 
1199 // Free a single MPE
cmsStageFree(cmsStage * mpe)1200 void CMSEXPORT cmsStageFree(cmsStage* mpe)
1201 {
1202     if (mpe ->FreePtr)
1203         mpe ->FreePtr(mpe);
1204 
1205     _cmsFree(mpe ->ContextID, mpe);
1206 }
1207 
1208 
cmsStageInputChannels(const cmsStage * mpe)1209 cmsUInt32Number  CMSEXPORT cmsStageInputChannels(const cmsStage* mpe)
1210 {
1211     return mpe ->InputChannels;
1212 }
1213 
cmsStageOutputChannels(const cmsStage * mpe)1214 cmsUInt32Number  CMSEXPORT cmsStageOutputChannels(const cmsStage* mpe)
1215 {
1216     return mpe ->OutputChannels;
1217 }
1218 
cmsStageType(const cmsStage * mpe)1219 cmsStageSignature CMSEXPORT cmsStageType(const cmsStage* mpe)
1220 {
1221     return mpe -> Type;
1222 }
1223 
cmsStageData(const cmsStage * mpe)1224 void* CMSEXPORT cmsStageData(const cmsStage* mpe)
1225 {
1226     return mpe -> Data;
1227 }
1228 
cmsGetStageContextID(const cmsStage * mpe)1229 cmsContext CMSEXPORT cmsGetStageContextID(const cmsStage* mpe)
1230 {
1231     return mpe -> ContextID;
1232 }
1233 
cmsStageNext(const cmsStage * mpe)1234 cmsStage*  CMSEXPORT cmsStageNext(const cmsStage* mpe)
1235 {
1236     return mpe -> Next;
1237 }
1238 
1239 
1240 // Duplicates an MPE
cmsStageDup(cmsStage * mpe)1241 cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
1242 {
1243     cmsStage* NewMPE;
1244 
1245     if (mpe == NULL) return NULL;
1246     NewMPE = _cmsStageAllocPlaceholder(mpe ->ContextID,
1247                                      mpe ->Type,
1248                                      mpe ->InputChannels,
1249                                      mpe ->OutputChannels,
1250                                      mpe ->EvalPtr,
1251                                      mpe ->DupElemPtr,
1252                                      mpe ->FreePtr,
1253                                      NULL);
1254     if (NewMPE == NULL) return NULL;
1255 
1256     NewMPE ->Implements = mpe ->Implements;
1257 
1258     if (mpe ->DupElemPtr) {
1259 
1260         NewMPE ->Data = mpe ->DupElemPtr(mpe);
1261 
1262         if (NewMPE->Data == NULL) {
1263 
1264             cmsStageFree(NewMPE);
1265             return NULL;
1266         }
1267 
1268     } else {
1269 
1270         NewMPE ->Data       = NULL;
1271     }
1272 
1273     return NewMPE;
1274 }
1275 
1276 
1277 // ***********************************************************************************************************
1278 
1279 // This function sets up the channel count
1280 static
BlessLUT(cmsPipeline * lut)1281 cmsBool BlessLUT(cmsPipeline* lut)
1282 {
1283     // We can set the input/output channels only if we have elements.
1284     if (lut ->Elements != NULL) {
1285 
1286         cmsStage* prev;
1287         cmsStage* next;
1288         cmsStage* First;
1289         cmsStage* Last;
1290 
1291         First  = cmsPipelineGetPtrToFirstStage(lut);
1292         Last   = cmsPipelineGetPtrToLastStage(lut);
1293 
1294         if (First == NULL || Last == NULL) return FALSE;
1295 
1296         lut->InputChannels = First->InputChannels;
1297         lut->OutputChannels = Last->OutputChannels;
1298 
1299         // Check chain consistency
1300         prev = First;
1301         next = prev->Next;
1302 
1303         while (next != NULL)
1304         {
1305             if (next->InputChannels != prev->OutputChannels)
1306                 return FALSE;
1307 
1308             next = next->Next;
1309             prev = prev->Next;
1310     }
1311 }
1312 
1313     return TRUE;
1314 }
1315 
1316 
1317 // Default to evaluate the LUT on 16 bit-basis. Precision is retained.
1318 static
_LUTeval16(CMSREGISTER const cmsUInt16Number In[],CMSREGISTER cmsUInt16Number Out[],CMSREGISTER const void * D)1319 void _LUTeval16(CMSREGISTER const cmsUInt16Number In[], CMSREGISTER cmsUInt16Number Out[],  CMSREGISTER const void* D)
1320 {
1321     cmsPipeline* lut = (cmsPipeline*) D;
1322     cmsStage *mpe;
1323     cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS] = {0.0f};
1324     int Phase = 0, NextPhase;
1325 
1326     From16ToFloat(In, &Storage[Phase][0], lut ->InputChannels);
1327 
1328     for (mpe = lut ->Elements;
1329          mpe != NULL;
1330          mpe = mpe ->Next) {
1331 
1332              NextPhase = Phase ^ 1;
1333              mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
1334              Phase = NextPhase;
1335     }
1336 
1337 
1338     FromFloatTo16(&Storage[Phase][0], Out, lut ->OutputChannels);
1339 }
1340 
1341 
1342 
1343 // Does evaluate the LUT on cmsFloat32Number-basis.
1344 static
_LUTevalFloat(const cmsFloat32Number In[],cmsFloat32Number Out[],const void * D)1345 void _LUTevalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const void* D)
1346 {
1347     cmsPipeline* lut = (cmsPipeline*) D;
1348     cmsStage *mpe;
1349     cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS] = {0.0f};
1350     int Phase = 0, NextPhase;
1351 
1352     memmove(&Storage[Phase][0], In, lut ->InputChannels  * sizeof(cmsFloat32Number));
1353 
1354     for (mpe = lut ->Elements;
1355          mpe != NULL;
1356          mpe = mpe ->Next) {
1357 
1358               NextPhase = Phase ^ 1;
1359               mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
1360               Phase = NextPhase;
1361     }
1362 
1363     memmove(Out, &Storage[Phase][0], lut ->OutputChannels * sizeof(cmsFloat32Number));
1364 }
1365 
1366 
1367 // LUT Creation & Destruction
cmsPipelineAlloc(cmsContext ContextID,cmsUInt32Number InputChannels,cmsUInt32Number OutputChannels)1368 cmsPipeline* CMSEXPORT cmsPipelineAlloc(cmsContext ContextID, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels)
1369 {
1370        cmsPipeline* NewLUT;
1371 
1372        // A value of zero in channels is allowed as placeholder
1373        if (InputChannels >= cmsMAXCHANNELS ||
1374            OutputChannels >= cmsMAXCHANNELS) return NULL;
1375 
1376        NewLUT = (cmsPipeline*) _cmsMallocZero(ContextID, sizeof(cmsPipeline));
1377        if (NewLUT == NULL) return NULL;
1378 
1379        NewLUT -> InputChannels  = InputChannels;
1380        NewLUT -> OutputChannels = OutputChannels;
1381 
1382        NewLUT ->Eval16Fn    = _LUTeval16;
1383        NewLUT ->EvalFloatFn = _LUTevalFloat;
1384        NewLUT ->DupDataFn   = NULL;
1385        NewLUT ->FreeDataFn  = NULL;
1386        NewLUT ->Data        = NewLUT;
1387        NewLUT ->ContextID   = ContextID;
1388 
1389        if (!BlessLUT(NewLUT))
1390        {
1391            _cmsFree(ContextID, NewLUT);
1392            return NULL;
1393        }
1394 
1395        return NewLUT;
1396 }
1397 
cmsGetPipelineContextID(const cmsPipeline * lut)1398 cmsContext CMSEXPORT cmsGetPipelineContextID(const cmsPipeline* lut)
1399 {
1400     _cmsAssert(lut != NULL);
1401     return lut ->ContextID;
1402 }
1403 
cmsPipelineInputChannels(const cmsPipeline * lut)1404 cmsUInt32Number CMSEXPORT cmsPipelineInputChannels(const cmsPipeline* lut)
1405 {
1406     _cmsAssert(lut != NULL);
1407     return lut ->InputChannels;
1408 }
1409 
cmsPipelineOutputChannels(const cmsPipeline * lut)1410 cmsUInt32Number CMSEXPORT cmsPipelineOutputChannels(const cmsPipeline* lut)
1411 {
1412     _cmsAssert(lut != NULL);
1413     return lut ->OutputChannels;
1414 }
1415 
1416 // Free a profile elements LUT
cmsPipelineFree(cmsPipeline * lut)1417 void CMSEXPORT cmsPipelineFree(cmsPipeline* lut)
1418 {
1419     cmsStage *mpe, *Next;
1420 
1421     if (lut == NULL) return;
1422 
1423     for (mpe = lut ->Elements;
1424         mpe != NULL;
1425         mpe = Next) {
1426 
1427             Next = mpe ->Next;
1428             cmsStageFree(mpe);
1429     }
1430 
1431     if (lut ->FreeDataFn) lut ->FreeDataFn(lut ->ContextID, lut ->Data);
1432 
1433     _cmsFree(lut ->ContextID, lut);
1434 }
1435 
1436 
1437 // Default to evaluate the LUT on 16 bit-basis.
cmsPipelineEval16(const cmsUInt16Number In[],cmsUInt16Number Out[],const cmsPipeline * lut)1438 void CMSEXPORT cmsPipelineEval16(const cmsUInt16Number In[], cmsUInt16Number Out[],  const cmsPipeline* lut)
1439 {
1440     _cmsAssert(lut != NULL);
1441     lut ->Eval16Fn(In, Out, lut->Data);
1442 }
1443 
1444 
1445 // Does evaluate the LUT on cmsFloat32Number-basis.
cmsPipelineEvalFloat(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsPipeline * lut)1446 void CMSEXPORT cmsPipelineEvalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsPipeline* lut)
1447 {
1448     _cmsAssert(lut != NULL);
1449     lut ->EvalFloatFn(In, Out, lut);
1450 }
1451 
1452 
1453 
1454 // Duplicates a LUT
cmsPipelineDup(const cmsPipeline * lut)1455 cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
1456 {
1457     cmsPipeline* NewLUT;
1458     cmsStage *NewMPE, *Anterior = NULL, *mpe;
1459     cmsBool  First = TRUE;
1460 
1461     if (lut == NULL) return NULL;
1462 
1463     NewLUT = cmsPipelineAlloc(lut ->ContextID, lut ->InputChannels, lut ->OutputChannels);
1464     if (NewLUT == NULL) return NULL;
1465 
1466     for (mpe = lut ->Elements;
1467          mpe != NULL;
1468          mpe = mpe ->Next) {
1469 
1470              NewMPE = cmsStageDup(mpe);
1471 
1472              if (NewMPE == NULL) {
1473                  cmsPipelineFree(NewLUT);
1474                  return NULL;
1475              }
1476 
1477              if (First) {
1478                  NewLUT ->Elements = NewMPE;
1479                  First = FALSE;
1480              }
1481              else {
1482                 if (Anterior != NULL)
1483                     Anterior ->Next = NewMPE;
1484              }
1485 
1486             Anterior = NewMPE;
1487     }
1488 
1489     NewLUT ->Eval16Fn    = lut ->Eval16Fn;
1490     NewLUT ->EvalFloatFn = lut ->EvalFloatFn;
1491     NewLUT ->DupDataFn   = lut ->DupDataFn;
1492     NewLUT ->FreeDataFn  = lut ->FreeDataFn;
1493 
1494     if (NewLUT ->DupDataFn != NULL)
1495         NewLUT ->Data = NewLUT ->DupDataFn(lut ->ContextID, lut->Data);
1496 
1497 
1498     NewLUT ->SaveAs8Bits    = lut ->SaveAs8Bits;
1499 
1500     if (!BlessLUT(NewLUT))
1501     {
1502         _cmsFree(lut->ContextID, NewLUT);
1503         return NULL;
1504     }
1505 
1506     return NewLUT;
1507 }
1508 
1509 
cmsPipelineInsertStage(cmsPipeline * lut,cmsStageLoc loc,cmsStage * mpe)1510 int CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
1511 {
1512     cmsStage* Anterior = NULL, *pt;
1513 
1514     if (lut == NULL || mpe == NULL)
1515         return FALSE;
1516 
1517     switch (loc) {
1518 
1519         case cmsAT_BEGIN:
1520             mpe ->Next = lut ->Elements;
1521             lut ->Elements = mpe;
1522             break;
1523 
1524         case cmsAT_END:
1525 
1526             if (lut ->Elements == NULL)
1527                 lut ->Elements = mpe;
1528             else {
1529 
1530                 for (pt = lut ->Elements;
1531                      pt != NULL;
1532                      pt = pt -> Next) Anterior = pt;
1533 
1534                 Anterior ->Next = mpe;
1535                 mpe ->Next = NULL;
1536             }
1537             break;
1538         default:;
1539             return FALSE;
1540     }
1541 
1542     return BlessLUT(lut);
1543 }
1544 
1545 // Unlink an element and return the pointer to it
cmsPipelineUnlinkStage(cmsPipeline * lut,cmsStageLoc loc,cmsStage ** mpe)1546 void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe)
1547 {
1548     cmsStage *Anterior, *pt, *Last;
1549     cmsStage *Unlinked = NULL;
1550 
1551 
1552     // If empty LUT, there is nothing to remove
1553     if (lut ->Elements == NULL) {
1554         if (mpe) *mpe = NULL;
1555         return;
1556     }
1557 
1558     // On depending on the strategy...
1559     switch (loc) {
1560 
1561         case cmsAT_BEGIN:
1562             {
1563                 cmsStage* elem = lut ->Elements;
1564 
1565                 lut ->Elements = elem -> Next;
1566                 elem ->Next = NULL;
1567                 Unlinked = elem;
1568 
1569             }
1570             break;
1571 
1572         case cmsAT_END:
1573             Anterior = Last = NULL;
1574             for (pt = lut ->Elements;
1575                 pt != NULL;
1576                 pt = pt -> Next) {
1577                     Anterior = Last;
1578                     Last = pt;
1579             }
1580 
1581             Unlinked = Last;  // Next already points to NULL
1582 
1583             // Truncate the chain
1584             if (Anterior)
1585                 Anterior ->Next = NULL;
1586             else
1587                 lut ->Elements = NULL;
1588             break;
1589         default:;
1590     }
1591 
1592     if (mpe)
1593         *mpe = Unlinked;
1594     else
1595         cmsStageFree(Unlinked);
1596 
1597     // May fail, but we ignore it
1598     BlessLUT(lut);
1599 }
1600 
1601 
1602 // Concatenate two LUT into a new single one
cmsPipelineCat(cmsPipeline * l1,const cmsPipeline * l2)1603 cmsBool  CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
1604 {
1605     cmsStage* mpe;
1606 
1607     // If both LUTS does not have elements, we need to inherit
1608     // the number of channels
1609     if (l1 ->Elements == NULL && l2 ->Elements == NULL) {
1610         l1 ->InputChannels  = l2 ->InputChannels;
1611         l1 ->OutputChannels = l2 ->OutputChannels;
1612     }
1613 
1614     // Cat second
1615     for (mpe = l2 ->Elements;
1616          mpe != NULL;
1617          mpe = mpe ->Next) {
1618 
1619             // We have to dup each element
1620             if (!cmsPipelineInsertStage(l1, cmsAT_END, cmsStageDup(mpe)))
1621                 return FALSE;
1622     }
1623 
1624     return BlessLUT(l1);
1625 }
1626 
1627 
cmsPipelineSetSaveAs8bitsFlag(cmsPipeline * lut,cmsBool On)1628 cmsBool CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lut, cmsBool On)
1629 {
1630     cmsBool Anterior = lut ->SaveAs8Bits;
1631 
1632     lut ->SaveAs8Bits = On;
1633     return Anterior;
1634 }
1635 
1636 
cmsPipelineGetPtrToFirstStage(const cmsPipeline * lut)1637 cmsStage* CMSEXPORT cmsPipelineGetPtrToFirstStage(const cmsPipeline* lut)
1638 {
1639     return lut ->Elements;
1640 }
1641 
cmsPipelineGetPtrToLastStage(const cmsPipeline * lut)1642 cmsStage* CMSEXPORT cmsPipelineGetPtrToLastStage(const cmsPipeline* lut)
1643 {
1644     cmsStage *mpe, *Anterior = NULL;
1645 
1646     for (mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
1647         Anterior = mpe;
1648 
1649     return Anterior;
1650 }
1651 
cmsPipelineStageCount(const cmsPipeline * lut)1652 cmsUInt32Number CMSEXPORT cmsPipelineStageCount(const cmsPipeline* lut)
1653 {
1654     cmsStage *mpe;
1655     cmsUInt32Number n;
1656 
1657     for (n=0, mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
1658             n++;
1659 
1660     return n;
1661 }
1662 
1663 // This function may be used to set the optional evaluator and a block of private data. If private data is being used, an optional
1664 // duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality.
_cmsPipelineSetOptimizationParameters(cmsPipeline * Lut,_cmsPipelineEval16Fn Eval16,void * PrivateData,_cmsFreeUserDataFn FreePrivateDataFn,_cmsDupUserDataFn DupPrivateDataFn)1665 void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut,
1666                                         _cmsPipelineEval16Fn Eval16,
1667                                         void* PrivateData,
1668                                         _cmsFreeUserDataFn FreePrivateDataFn,
1669                                         _cmsDupUserDataFn  DupPrivateDataFn)
1670 {
1671 
1672     Lut ->Eval16Fn = Eval16;
1673     Lut ->DupDataFn = DupPrivateDataFn;
1674     Lut ->FreeDataFn = FreePrivateDataFn;
1675     Lut ->Data = PrivateData;
1676 }
1677 
1678 
1679 // ----------------------------------------------------------- Reverse interpolation
1680 // Here's how it goes. The derivative Df(x) of the function f is the linear
1681 // transformation that best approximates f near the point x. It can be represented
1682 // by a matrix A whose entries are the partial derivatives of the components of f
1683 // with respect to all the coordinates. This is know as the Jacobian
1684 //
1685 // The best linear approximation to f is given by the matrix equation:
1686 //
1687 // y-y0 = A (x-x0)
1688 //
1689 // So, if x0 is a good "guess" for the zero of f, then solving for the zero of this
1690 // linear approximation will give a "better guess" for the zero of f. Thus let y=0,
1691 // and since y0=f(x0) one can solve the above equation for x. This leads to the
1692 // Newton's method formula:
1693 //
1694 // xn+1 = xn - A-1 f(xn)
1695 //
1696 // where xn+1 denotes the (n+1)-st guess, obtained from the n-th guess xn in the
1697 // fashion described above. Iterating this will give better and better approximations
1698 // if you have a "good enough" initial guess.
1699 
1700 
1701 #define JACOBIAN_EPSILON            0.001f
1702 #define INVERSION_MAX_ITERATIONS    30
1703 
1704 // Increment with reflexion on boundary
1705 static
IncDelta(cmsFloat32Number * Val)1706 void IncDelta(cmsFloat32Number *Val)
1707 {
1708     if (*Val < (1.0 - JACOBIAN_EPSILON))
1709 
1710         *Val += JACOBIAN_EPSILON;
1711 
1712     else
1713         *Val -= JACOBIAN_EPSILON;
1714 
1715 }
1716 
1717 
1718 
1719 // Euclidean distance between two vectors of n elements each one
1720 static
EuclideanDistance(cmsFloat32Number a[],cmsFloat32Number b[],int n)1721 cmsFloat32Number EuclideanDistance(cmsFloat32Number a[], cmsFloat32Number b[], int n)
1722 {
1723     cmsFloat32Number sum = 0;
1724     int i;
1725 
1726     for (i=0; i < n; i++) {
1727         cmsFloat32Number dif = b[i] - a[i];
1728         sum +=  dif * dif;
1729     }
1730 
1731     return sqrtf(sum);
1732 }
1733 
1734 
1735 // Evaluate a LUT in reverse direction. It only searches on 3->3 LUT. Uses Newton method
1736 //
1737 // x1 <- x - [J(x)]^-1 * f(x)
1738 //
1739 // lut: The LUT on where to do the search
1740 // Target: LabK, 3 values of Lab plus destination K which is fixed
1741 // Result: The obtained CMYK
1742 // Hint:   Location where begin the search
1743 
cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],cmsFloat32Number Result[],cmsFloat32Number Hint[],const cmsPipeline * lut)1744 cmsBool CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],
1745                                               cmsFloat32Number Result[],
1746                                               cmsFloat32Number Hint[],
1747                                               const cmsPipeline* lut)
1748 {
1749     cmsUInt32Number  i, j;
1750     cmsFloat64Number  error, LastError = 1E20;
1751     cmsFloat32Number  fx[4], x[4], xd[4], fxd[4];
1752     cmsVEC3 tmp, tmp2;
1753     cmsMAT3 Jacobian;
1754 
1755     // Only 3->3 and 4->3 are supported
1756     if (lut ->InputChannels != 3 && lut ->InputChannels != 4) return FALSE;
1757     if (lut ->OutputChannels != 3) return FALSE;
1758 
1759     // Take the hint as starting point if specified
1760     if (Hint == NULL) {
1761 
1762         // Begin at any point, we choose 1/3 of CMY axis
1763         x[0] = x[1] = x[2] = 0.3f;
1764     }
1765     else {
1766 
1767         // Only copy 3 channels from hint...
1768         for (j=0; j < 3; j++)
1769             x[j] = Hint[j];
1770     }
1771 
1772     // If Lut is 4-dimensions, then grab target[3], which is fixed
1773     if (lut ->InputChannels == 4) {
1774         x[3] = Target[3];
1775     }
1776     else x[3] = 0; // To keep lint happy
1777 
1778 
1779     // Iterate
1780     for (i = 0; i < INVERSION_MAX_ITERATIONS; i++) {
1781 
1782         // Get beginning fx
1783         cmsPipelineEvalFloat(x, fx, lut);
1784 
1785         // Compute error
1786         error = EuclideanDistance(fx, Target, 3);
1787 
1788         // If not convergent, return last safe value
1789         if (error >= LastError)
1790             break;
1791 
1792         // Keep latest values
1793         LastError     = error;
1794         for (j=0; j < lut ->InputChannels; j++)
1795                 Result[j] = x[j];
1796 
1797         // Found an exact match?
1798         if (error <= 0)
1799             break;
1800 
1801         // Obtain slope (the Jacobian)
1802         for (j = 0; j < 3; j++) {
1803 
1804             xd[0] = x[0];
1805             xd[1] = x[1];
1806             xd[2] = x[2];
1807             xd[3] = x[3];  // Keep fixed channel
1808 
1809             IncDelta(&xd[j]);
1810 
1811             cmsPipelineEvalFloat(xd, fxd, lut);
1812 
1813             Jacobian.v[0].n[j] = ((fxd[0] - fx[0]) / JACOBIAN_EPSILON);
1814             Jacobian.v[1].n[j] = ((fxd[1] - fx[1]) / JACOBIAN_EPSILON);
1815             Jacobian.v[2].n[j] = ((fxd[2] - fx[2]) / JACOBIAN_EPSILON);
1816         }
1817 
1818         // Solve system
1819         tmp2.n[0] = fx[0] - Target[0];
1820         tmp2.n[1] = fx[1] - Target[1];
1821         tmp2.n[2] = fx[2] - Target[2];
1822 
1823         if (!_cmsMAT3solve(&tmp, &Jacobian, &tmp2))
1824             return FALSE;
1825 
1826         // Move our guess
1827         x[0] -= (cmsFloat32Number) tmp.n[0];
1828         x[1] -= (cmsFloat32Number) tmp.n[1];
1829         x[2] -= (cmsFloat32Number) tmp.n[2];
1830 
1831         // Some clipping....
1832         for (j=0; j < 3; j++) {
1833             if (x[j] < 0) x[j] = 0;
1834             else
1835                 if (x[j] > 1.0) x[j] = 1.0;
1836         }
1837     }
1838 
1839     return TRUE;
1840 }
1841 
1842 
1843