1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2010 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
128         Type  = va_arg(args, cmsStageSignature);
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(Data ->TheCurves[i]);
239         }
240     }
241     _cmsFree(mpe ->ContextID, Data ->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*) _cmsMalloc(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     return NewMPE;
290 }
291 
292 
293 // Create a bunch of identity curves
_cmsStageAllocIdentityCurves(cmsContext ContextID,int nChannels)294 cmsStage* _cmsStageAllocIdentityCurves(cmsContext ContextID, int nChannels)
295 {
296     cmsStage* mpe = cmsStageAllocToneCurves(ContextID, nChannels, NULL);
297 
298     if (mpe == NULL) return NULL;
299     mpe ->Implements = cmsSigIdentityElemType;
300     return mpe;
301 }
302 
303 
304 // *************************************************************************************************
305 // Type cmsSigMatrixElemType (Matrices)
306 // *************************************************************************************************
307 
308 
309 // Special care should be taken here because precision loss. A temporary cmsFloat64Number buffer is being used
310 static
EvaluateMatrix(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)311 void EvaluateMatrix(const cmsFloat32Number In[],
312                     cmsFloat32Number Out[],
313                     const cmsStage *mpe)
314 {
315     cmsUInt32Number i, j;
316     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
317     cmsFloat64Number Tmp;
318 
319     // Input is already in 0..1.0 notation
320     for (i=0; i < mpe ->OutputChannels; i++) {
321 
322         Tmp = 0;
323         for (j=0; j < mpe->InputChannels; j++) {
324             Tmp += In[j] * Data->Double[i*mpe->InputChannels + j];
325         }
326 
327         if (Data ->Offset != NULL)
328             Tmp += Data->Offset[i];
329 
330         Out[i] = (cmsFloat32Number) Tmp;
331     }
332 
333 
334     // Output in 0..1.0 domain
335 }
336 
337 
338 // Duplicate a yet-existing matrix element
339 static
MatrixElemDup(cmsStage * mpe)340 void* MatrixElemDup(cmsStage* mpe)
341 {
342     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
343     _cmsStageMatrixData* NewElem;
344     cmsUInt32Number sz;
345 
346     NewElem = (_cmsStageMatrixData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageMatrixData));
347     if (NewElem == NULL) return NULL;
348 
349     sz = mpe ->InputChannels * mpe ->OutputChannels;
350 
351     NewElem ->Double = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID, Data ->Double, sz * sizeof(cmsFloat64Number)) ;
352 
353     if (Data ->Offset)
354         NewElem ->Offset = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID,
355                                                 Data ->Offset, mpe -> OutputChannels * sizeof(cmsFloat64Number)) ;
356 
357     return (void*) NewElem;
358 }
359 
360 
361 static
MatrixElemTypeFree(cmsStage * mpe)362 void MatrixElemTypeFree(cmsStage* mpe)
363 {
364     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
365     if (Data ->Double)
366         _cmsFree(mpe ->ContextID, Data ->Double);
367 
368     if (Data ->Offset)
369         _cmsFree(mpe ->ContextID, Data ->Offset);
370 
371     _cmsFree(mpe ->ContextID, mpe ->Data);
372 }
373 
374 
375 
cmsStageAllocMatrix(cmsContext ContextID,cmsUInt32Number Rows,cmsUInt32Number Cols,const cmsFloat64Number * Matrix,const cmsFloat64Number * Offset)376 cmsStage*  CMSEXPORT cmsStageAllocMatrix(cmsContext ContextID, cmsUInt32Number Rows, cmsUInt32Number Cols,
377                                      const cmsFloat64Number* Matrix, const cmsFloat64Number* Offset)
378 {
379     cmsUInt32Number i, n;
380     _cmsStageMatrixData* NewElem;
381     cmsStage* NewMPE;
382 
383     n = Rows * Cols;
384 
385     // Check for overflow
386     if (n == 0) return NULL;
387     if (n >= UINT_MAX / Cols) return NULL;
388     if (n >= UINT_MAX / Rows) return NULL;
389     if (n < Rows || n < Cols) return NULL;
390 
391     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigMatrixElemType, Cols, Rows,
392                                      EvaluateMatrix, MatrixElemDup, MatrixElemTypeFree, NULL );
393     if (NewMPE == NULL) return NULL;
394 
395 
396     NewElem = (_cmsStageMatrixData*) _cmsMallocZero(ContextID, sizeof(_cmsStageMatrixData));
397     if (NewElem == NULL) return NULL;
398 
399 
400     NewElem ->Double = (cmsFloat64Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat64Number));
401 
402     if (NewElem->Double == NULL) {
403         MatrixElemTypeFree(NewMPE);
404         return NULL;
405     }
406 
407     for (i=0; i < n; i++) {
408         NewElem ->Double[i] = Matrix[i];
409     }
410 
411 
412     if (Offset != NULL) {
413 
414         NewElem ->Offset = (cmsFloat64Number*) _cmsCalloc(ContextID, Cols, sizeof(cmsFloat64Number));
415         if (NewElem->Offset == NULL) {
416            MatrixElemTypeFree(NewMPE);
417            return NULL;
418         }
419 
420         for (i=0; i < Cols; i++) {
421                 NewElem ->Offset[i] = Offset[i];
422         }
423 
424     }
425 
426     NewMPE ->Data  = (void*) NewElem;
427     return NewMPE;
428 }
429 
430 
431 // *************************************************************************************************
432 // Type cmsSigCLutElemType
433 // *************************************************************************************************
434 
435 
436 // Evaluate in true floating point
437 static
EvaluateCLUTfloat(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)438 void EvaluateCLUTfloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
439 {
440     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
441 
442     Data -> Params ->Interpolation.LerpFloat(In, Out, Data->Params);
443 }
444 
445 
446 // Convert to 16 bits, evaluate, and back to floating point
447 static
EvaluateCLUTfloatIn16(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)448 void EvaluateCLUTfloatIn16(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
449 {
450     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
451     cmsUInt16Number In16[MAX_STAGE_CHANNELS], Out16[MAX_STAGE_CHANNELS];
452 
453     _cmsAssert(mpe ->InputChannels  <= MAX_STAGE_CHANNELS);
454     _cmsAssert(mpe ->OutputChannels <= MAX_STAGE_CHANNELS);
455 
456     FromFloatTo16(In, In16, mpe ->InputChannels);
457     Data -> Params ->Interpolation.Lerp16(In16, Out16, Data->Params);
458     From16ToFloat(Out16, Out,  mpe ->OutputChannels);
459 }
460 
461 
462 // Given an hypercube of b dimensions, with Dims[] number of nodes by dimension, calculate the total amount of nodes
463 static
CubeSize(const cmsUInt32Number Dims[],cmsUInt32Number b)464 cmsUInt32Number CubeSize(const cmsUInt32Number Dims[], cmsUInt32Number b)
465 {
466     cmsUInt32Number rv, dim;
467 
468     _cmsAssert(Dims != NULL);
469 
470     for (rv = 1; b > 0; b--) {
471 
472         dim = Dims[b-1];
473         if (dim == 0) return 0;  // Error
474 
475         rv *= dim;
476 
477         // Check for overflow
478         if (rv > UINT_MAX / dim) return 0;
479     }
480 
481     return rv;
482 }
483 
484 static
CLUTElemDup(cmsStage * mpe)485 void* CLUTElemDup(cmsStage* mpe)
486 {
487     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
488     _cmsStageCLutData* NewElem;
489 
490 
491     NewElem = (_cmsStageCLutData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageCLutData));
492     if (NewElem == NULL) return NULL;
493 
494     NewElem ->nEntries       = Data ->nEntries;
495     NewElem ->HasFloatValues = Data ->HasFloatValues;
496 
497     if (Data ->Tab.T) {
498 
499         if (Data ->HasFloatValues)
500             NewElem ->Tab.TFloat = (cmsFloat32Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.TFloat, Data ->nEntries * sizeof (cmsFloat32Number));
501         else
502             NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
503     }
504 
505     NewElem ->Params   = _cmsComputeInterpParamsEx(mpe ->ContextID,
506                                                    Data ->Params ->nSamples,
507                                                    Data ->Params ->nInputs,
508                                                    Data ->Params ->nOutputs,
509                                                    NewElem ->Tab.T,
510                                                    Data ->Params ->dwFlags);
511 
512     return (void*) NewElem;
513 }
514 
515 
516 static
CLutElemTypeFree(cmsStage * mpe)517 void CLutElemTypeFree(cmsStage* mpe)
518 {
519 
520     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
521 
522     // Already empty
523     if (Data == NULL) return;
524 
525     // This works for both types
526     if (Data -> Tab.T)
527         _cmsFree(mpe ->ContextID, Data -> Tab.T);
528 
529     _cmsFreeInterpParams(Data ->Params);
530     _cmsFree(mpe ->ContextID, mpe ->Data);
531 }
532 
533 
534 // Allocates a 16-bit multidimensional CLUT. This is evaluated at 16-bit precision. Table may have different
535 // granularity on each dimension.
cmsStageAllocCLut16bitGranular(cmsContext ContextID,const cmsUInt32Number clutPoints[],cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsUInt16Number * Table)536 cmsStage* CMSEXPORT cmsStageAllocCLut16bitGranular(cmsContext ContextID,
537                                          const cmsUInt32Number clutPoints[],
538                                          cmsUInt32Number inputChan,
539                                          cmsUInt32Number outputChan,
540                                          const cmsUInt16Number* Table)
541 {
542     cmsUInt32Number i, n;
543     _cmsStageCLutData* NewElem;
544     cmsStage* NewMPE;
545 
546     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
547                                      EvaluateCLUTfloatIn16, CLUTElemDup, CLutElemTypeFree, NULL );
548 
549     if (NewMPE == NULL) return NULL;
550 
551     NewElem = (_cmsStageCLutData*) _cmsMalloc(ContextID, sizeof(_cmsStageCLutData));
552     if (NewElem == NULL) {
553         cmsStageFree(NewMPE);
554         return NULL;
555     }
556 
557     NewMPE ->Data  = (void*) NewElem;
558 
559     NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
560     NewElem -> HasFloatValues = FALSE;
561 
562     if (n == 0) {
563         cmsStageFree(NewMPE);
564         return NULL;
565     }
566 
567 
568     NewElem ->Tab.T  = (cmsUInt16Number*) _cmsCalloc(ContextID, n, sizeof(cmsUInt16Number));
569     if (NewElem ->Tab.T == NULL) {
570         cmsStageFree(NewMPE);
571         return NULL;
572     }
573 
574     if (Table != NULL) {
575         for (i=0; i < n; i++) {
576             NewElem ->Tab.T[i] = Table[i];
577         }
578     }
579 
580     NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints, inputChan, outputChan, NewElem ->Tab.T, CMS_LERP_FLAGS_16BITS);
581     if (NewElem ->Params == NULL) {
582         cmsStageFree(NewMPE);
583         return NULL;
584     }
585 
586     return NewMPE;
587 }
588 
cmsStageAllocCLut16bit(cmsContext ContextID,cmsUInt32Number nGridPoints,cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsUInt16Number * Table)589 cmsStage* CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID,
590                                     cmsUInt32Number nGridPoints,
591                                     cmsUInt32Number inputChan,
592                                     cmsUInt32Number outputChan,
593                                     const cmsUInt16Number* Table)
594 {
595     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
596     int i;
597 
598    // Our resulting LUT would be same gridpoints on all dimensions
599     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
600         Dimensions[i] = nGridPoints;
601 
602 
603     return cmsStageAllocCLut16bitGranular(ContextID, Dimensions, inputChan, outputChan, Table);
604 }
605 
606 
cmsStageAllocCLutFloat(cmsContext ContextID,cmsUInt32Number nGridPoints,cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsFloat32Number * Table)607 cmsStage* CMSEXPORT cmsStageAllocCLutFloat(cmsContext ContextID,
608                                        cmsUInt32Number nGridPoints,
609                                        cmsUInt32Number inputChan,
610                                        cmsUInt32Number outputChan,
611                                        const cmsFloat32Number* Table)
612 {
613    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
614    int i;
615 
616     // Our resulting LUT would be same gridpoints on all dimensions
617     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
618         Dimensions[i] = nGridPoints;
619 
620     return cmsStageAllocCLutFloatGranular(ContextID, Dimensions, inputChan, outputChan, Table);
621 }
622 
623 
624 
cmsStageAllocCLutFloatGranular(cmsContext ContextID,const cmsUInt32Number clutPoints[],cmsUInt32Number inputChan,cmsUInt32Number outputChan,const cmsFloat32Number * Table)625 cmsStage* CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table)
626 {
627     cmsUInt32Number i, n;
628     _cmsStageCLutData* NewElem;
629     cmsStage* NewMPE;
630 
631     _cmsAssert(clutPoints != NULL);
632 
633     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
634                                              EvaluateCLUTfloat, CLUTElemDup, CLutElemTypeFree, NULL);
635     if (NewMPE == NULL) return NULL;
636 
637 
638     NewElem = (_cmsStageCLutData*) _cmsMalloc(ContextID, sizeof(_cmsStageCLutData));
639     if (NewElem == NULL) {
640         cmsStageFree(NewMPE);
641         return NULL;
642     }
643 
644     NewMPE ->Data  = (void*) NewElem;
645 
646     // There is a potential integer overflow on conputing n and nEntries.
647     NewElem -> nEntries = n = outputChan * CubeSize( clutPoints, inputChan);
648     NewElem -> HasFloatValues = TRUE;
649 
650     if (n == 0) {
651         cmsStageFree(NewMPE);
652         return NULL;
653     }
654 
655     NewElem ->Tab.TFloat  = (cmsFloat32Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat32Number));
656     if (NewElem ->Tab.TFloat == NULL) {
657         cmsStageFree(NewMPE);
658         return NULL;
659     }
660 
661     if (Table != NULL) {
662         for (i=0; i < n; i++) {
663             NewElem ->Tab.TFloat[i] = Table[i];
664         }
665     }
666 
667 
668 
669     NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints,  inputChan, outputChan, NewElem ->Tab.TFloat, CMS_LERP_FLAGS_FLOAT);
670     if (NewElem ->Params == NULL) {
671         cmsStageFree(NewMPE);
672         return NULL;
673     }
674 
675 
676 
677     return NewMPE;
678 }
679 
680 
681 static
IdentitySampler(register const cmsUInt16Number In[],register cmsUInt16Number Out[],register void * Cargo)682 int IdentitySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void * Cargo)
683 {
684     int nChan = *(int*) Cargo;
685     int i;
686 
687     for (i=0; i < nChan; i++)
688         Out[i] = In[i];
689 
690     return 1;
691 }
692 
693 // Creates an MPE that just copies input to output
_cmsStageAllocIdentityCLut(cmsContext ContextID,int nChan)694 cmsStage* _cmsStageAllocIdentityCLut(cmsContext ContextID, int nChan)
695 {
696     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
697     cmsStage* mpe ;
698     int i;
699 
700     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
701         Dimensions[i] = 2;
702 
703     mpe = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, nChan, nChan, NULL);
704     if (mpe == NULL) return NULL;
705 
706     if (!cmsStageSampleCLut16bit(mpe, IdentitySampler, &nChan, 0)) {
707         cmsStageFree(mpe);
708         return NULL;
709     }
710 
711     mpe ->Implements = cmsSigIdentityElemType;
712     return mpe;
713 }
714 
715 
716 
717 // Quantize a value 0 <= i < MaxSamples to 0..0xffff
_cmsQuantizeVal(cmsFloat64Number i,int MaxSamples)718 cmsUInt16Number _cmsQuantizeVal(cmsFloat64Number i, int MaxSamples)
719 {
720     cmsFloat64Number x;
721 
722     x = ((cmsFloat64Number) i * 65535.) / (cmsFloat64Number) (MaxSamples - 1);
723     return _cmsQuickSaturateWord(x);
724 }
725 
726 
727 // This routine does a sweep on whole input space, and calls its callback
728 // function on knots. returns TRUE if all ok, FALSE otherwise.
cmsStageSampleCLut16bit(cmsStage * mpe,cmsSAMPLER16 Sampler,void * Cargo,cmsUInt32Number dwFlags)729 cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, void * Cargo, cmsUInt32Number dwFlags)
730 {
731     int i, t, nTotalPoints, index, rest;
732     int nInputs, nOutputs;
733     cmsUInt32Number* nSamples;
734     cmsUInt16Number In[cmsMAXCHANNELS], Out[MAX_STAGE_CHANNELS];
735     _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
736 
737 
738     nSamples = clut->Params ->nSamples;
739     nInputs  = clut->Params ->nInputs;
740     nOutputs = clut->Params ->nOutputs;
741 
742     if (nInputs >= cmsMAXCHANNELS) return FALSE;
743     if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
744 
745     nTotalPoints = CubeSize(nSamples, nInputs);
746     if (nTotalPoints == 0) return FALSE;
747 
748     index = 0;
749     for (i = 0; i < nTotalPoints; i++) {
750 
751         rest = i;
752         for (t = nInputs-1; t >=0; --t) {
753 
754             cmsUInt32Number  Colorant = rest % nSamples[t];
755 
756             rest /= nSamples[t];
757 
758             In[t] = _cmsQuantizeVal(Colorant, nSamples[t]);
759         }
760 
761         if (clut ->Tab.T != NULL) {
762             for (t=0; t < nOutputs; t++)
763                 Out[t] = clut->Tab.T[index + t];
764         }
765 
766         if (!Sampler(In, Out, Cargo))
767             return FALSE;
768 
769         if (!(dwFlags & SAMPLER_INSPECT)) {
770 
771             if (clut ->Tab.T != NULL) {
772                 for (t=0; t < nOutputs; t++)
773                     clut->Tab.T[index + t] = Out[t];
774             }
775         }
776 
777         index += nOutputs;
778     }
779 
780     return TRUE;
781 }
782 
783 // Same as anterior, but for floting point
cmsStageSampleCLutFloat(cmsStage * mpe,cmsSAMPLERFLOAT Sampler,void * Cargo,cmsUInt32Number dwFlags)784 cmsBool CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler, void * Cargo, cmsUInt32Number dwFlags)
785 {
786     int i, t, nTotalPoints, index, rest;
787     int nInputs, nOutputs;
788     cmsUInt32Number* nSamples;
789     cmsFloat32Number In[cmsMAXCHANNELS], Out[MAX_STAGE_CHANNELS];
790     _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
791 
792     nSamples = clut->Params ->nSamples;
793     nInputs  = clut->Params ->nInputs;
794     nOutputs = clut->Params ->nOutputs;
795 
796     if (nInputs >= cmsMAXCHANNELS) return FALSE;
797     if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
798 
799     nTotalPoints = CubeSize(nSamples, nInputs);
800     if (nTotalPoints == 0) return FALSE;
801 
802     index = 0;
803     for (i = 0; i < nTotalPoints; i++) {
804 
805         rest = i;
806         for (t = nInputs-1; t >=0; --t) {
807 
808             cmsUInt32Number  Colorant = rest % nSamples[t];
809 
810             rest /= nSamples[t];
811 
812             In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, nSamples[t]) / 65535.0);
813         }
814 
815         if (clut ->Tab.TFloat != NULL) {
816             for (t=0; t < nOutputs; t++)
817                 Out[t] = clut->Tab.TFloat[index + t];
818         }
819 
820         if (!Sampler(In, Out, Cargo))
821             return FALSE;
822 
823         if (!(dwFlags & SAMPLER_INSPECT)) {
824 
825             if (clut ->Tab.TFloat != NULL) {
826                 for (t=0; t < nOutputs; t++)
827                     clut->Tab.TFloat[index + t] = Out[t];
828             }
829         }
830 
831         index += nOutputs;
832     }
833 
834     return TRUE;
835 }
836 
837 
838 
839 // This routine does a sweep on whole input space, and calls its callback
840 // function on knots. returns TRUE if all ok, FALSE otherwise.
cmsSliceSpace16(cmsUInt32Number nInputs,const cmsUInt32Number clutPoints[],cmsSAMPLER16 Sampler,void * Cargo)841 cmsBool CMSEXPORT cmsSliceSpace16(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
842                                          cmsSAMPLER16 Sampler, void * Cargo)
843 {
844     int i, t, nTotalPoints, rest;
845     cmsUInt16Number In[cmsMAXCHANNELS];
846 
847     if (nInputs >= cmsMAXCHANNELS) return FALSE;
848 
849     nTotalPoints = CubeSize(clutPoints, nInputs);
850     if (nTotalPoints == 0) return FALSE;
851 
852     for (i = 0; i < nTotalPoints; i++) {
853 
854         rest = i;
855         for (t = nInputs-1; t >=0; --t) {
856 
857             cmsUInt32Number  Colorant = rest % clutPoints[t];
858 
859             rest /= clutPoints[t];
860             In[t] = _cmsQuantizeVal(Colorant, clutPoints[t]);
861 
862         }
863 
864         if (!Sampler(In, NULL, Cargo))
865             return FALSE;
866     }
867 
868     return TRUE;
869 }
870 
cmsSliceSpaceFloat(cmsUInt32Number nInputs,const cmsUInt32Number clutPoints[],cmsSAMPLERFLOAT Sampler,void * Cargo)871 cmsInt32Number CMSEXPORT cmsSliceSpaceFloat(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
872                                             cmsSAMPLERFLOAT Sampler, void * Cargo)
873 {
874     int i, t, nTotalPoints, rest;
875     cmsFloat32Number 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 < nTotalPoints; i++) {
883 
884         rest = i;
885         for (t = nInputs-1; t >=0; --t) {
886 
887             cmsUInt32Number  Colorant = rest % clutPoints[t];
888 
889             rest /= clutPoints[t];
890             In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, clutPoints[t]) / 65535.0);
891 
892         }
893 
894         if (!Sampler(In, NULL, Cargo))
895             return FALSE;
896     }
897 
898     return TRUE;
899 }
900 
901 // ********************************************************************************
902 // Type cmsSigLab2XYZElemType
903 // ********************************************************************************
904 
905 
906 static
EvaluateLab2XYZ(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)907 void EvaluateLab2XYZ(const cmsFloat32Number In[],
908                      cmsFloat32Number Out[],
909                      const cmsStage *mpe)
910 {
911     cmsCIELab Lab;
912     cmsCIEXYZ XYZ;
913     const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
914 
915     // V4 rules
916     Lab.L = In[0] * 100.0;
917     Lab.a = In[1] * 255.0 - 128.0;
918     Lab.b = In[2] * 255.0 - 128.0;
919 
920     cmsLab2XYZ(NULL, &XYZ, &Lab);
921 
922     // From XYZ, range 0..19997 to 0..1.0, note that 1.99997 comes from 0xffff
923     // encoded as 1.15 fixed point, so 1 + (32767.0 / 32768.0)
924 
925     Out[0] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.X / XYZadj);
926     Out[1] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Y / XYZadj);
927     Out[2] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Z / XYZadj);
928     return;
929 
930     cmsUNUSED_PARAMETER(mpe);
931 }
932 
933 
934 // No dup or free routines needed, as the structure has no pointers in it.
_cmsStageAllocLab2XYZ(cmsContext ContextID)935 cmsStage* _cmsStageAllocLab2XYZ(cmsContext ContextID)
936 {
937     return _cmsStageAllocPlaceholder(ContextID, cmsSigLab2XYZElemType, 3, 3, EvaluateLab2XYZ, NULL, NULL, NULL);
938 }
939 
940 // ********************************************************************************
941 
942 // v2 L=100 is supposed to be placed on 0xFF00. There is no reasonable
943 // number of gridpoints that would make exact match. However, a prelinearization
944 // of 258 entries, would map 0xFF00 exactly on entry 257, and this is good to avoid scum dot.
945 // Almost all what we need but unfortunately, the rest of entries should be scaled by
946 // (255*257/256) and this is not exact.
947 
_cmsStageAllocLabV2ToV4curves(cmsContext ContextID)948 cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID)
949 {
950     cmsStage* mpe;
951     cmsToneCurve* LabTable[3];
952     int i, j;
953 
954     LabTable[0] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
955     LabTable[1] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
956     LabTable[2] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
957 
958     for (j=0; j < 3; j++) {
959 
960         if (LabTable[j] == NULL) {
961             cmsFreeToneCurveTriple(LabTable);
962             return NULL;
963         }
964 
965         // We need to map * (0xffff / 0xff00), thats same as (257 / 256)
966         // So we can use 258-entry tables to do the trick (i / 257) * (255 * 257) * (257 / 256);
967         for (i=0; i < 257; i++)  {
968 
969             LabTable[j]->Table16[i] = (cmsUInt16Number) ((i * 0xffff + 0x80) >> 8);
970         }
971 
972         LabTable[j] ->Table16[257] = 0xffff;
973     }
974 
975     mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
976     cmsFreeToneCurveTriple(LabTable);
977 
978     mpe ->Implements = cmsSigLabV2toV4;
979     return mpe;
980 }
981 
982 // ********************************************************************************
983 
984 // Matrix-based conversion, which is more accurate, but slower and cannot properly be saved in devicelink profiles
_cmsStageAllocLabV2ToV4(cmsContext ContextID)985 cmsStage* _cmsStageAllocLabV2ToV4(cmsContext ContextID)
986 {
987     static const cmsFloat64Number V2ToV4[] = { 65535.0/65280.0, 0, 0,
988                                      0, 65535.0/65280.0, 0,
989                                      0, 0, 65535.0/65280.0
990                                      };
991 
992     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V2ToV4, NULL);
993 
994     if (mpe == NULL) return mpe;
995     mpe ->Implements = cmsSigLabV2toV4;
996     return mpe;
997 }
998 
999 
1000 // Reverse direction
_cmsStageAllocLabV4ToV2(cmsContext ContextID)1001 cmsStage* _cmsStageAllocLabV4ToV2(cmsContext ContextID)
1002 {
1003     static const cmsFloat64Number V4ToV2[] = { 65280.0/65535.0, 0, 0,
1004                                      0, 65280.0/65535.0, 0,
1005                                      0, 0, 65280.0/65535.0
1006                                      };
1007 
1008      cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V4ToV2, NULL);
1009 
1010     if (mpe == NULL) return mpe;
1011     mpe ->Implements = cmsSigLabV4toV2;
1012     return mpe;
1013 }
1014 
1015 
1016 // ********************************************************************************
1017 // Type cmsSigXYZ2LabElemType
1018 // ********************************************************************************
1019 
1020 static
EvaluateXYZ2Lab(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsStage * mpe)1021 void EvaluateXYZ2Lab(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
1022 {
1023     cmsCIELab Lab;
1024     cmsCIEXYZ XYZ;
1025     const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
1026 
1027     // From 0..1.0 to XYZ
1028 
1029     XYZ.X = In[0] * XYZadj;
1030     XYZ.Y = In[1] * XYZadj;
1031     XYZ.Z = In[2] * XYZadj;
1032 
1033     cmsXYZ2Lab(NULL, &Lab, &XYZ);
1034 
1035     // From V4 Lab to 0..1.0
1036 
1037     Out[0] = (cmsFloat32Number) (Lab.L / 100.0);
1038     Out[1] = (cmsFloat32Number) ((Lab.a + 128.0) / 255.0);
1039     Out[2] = (cmsFloat32Number) ((Lab.b + 128.0) / 255.0);
1040     return;
1041 
1042     cmsUNUSED_PARAMETER(mpe);
1043 }
1044 
_cmsStageAllocXYZ2Lab(cmsContext ContextID)1045 cmsStage* _cmsStageAllocXYZ2Lab(cmsContext ContextID)
1046 {
1047     return _cmsStageAllocPlaceholder(ContextID, cmsSigXYZ2LabElemType, 3, 3, EvaluateXYZ2Lab, NULL, NULL, NULL);
1048 
1049 }
1050 
1051 // ********************************************************************************
1052 
1053 // For v4, S-Shaped curves are placed in a/b axis to increase resolution near gray
1054 
_cmsStageAllocLabPrelin(cmsContext ContextID)1055 cmsStage* _cmsStageAllocLabPrelin(cmsContext ContextID)
1056 {
1057     cmsToneCurve* LabTable[3];
1058     cmsFloat64Number Params[1] =  {2.4} ;
1059 
1060     LabTable[0] = cmsBuildGamma(ContextID, 1.0);
1061     LabTable[1] = cmsBuildParametricToneCurve(ContextID, 108, Params);
1062     LabTable[2] = cmsBuildParametricToneCurve(ContextID, 108, Params);
1063 
1064     return cmsStageAllocToneCurves(ContextID, 3, LabTable);
1065 }
1066 
1067 
1068 // Free a single MPE
cmsStageFree(cmsStage * mpe)1069 void CMSEXPORT cmsStageFree(cmsStage* mpe)
1070 {
1071     if (mpe ->FreePtr)
1072         mpe ->FreePtr(mpe);
1073 
1074     _cmsFree(mpe ->ContextID, mpe);
1075 }
1076 
1077 
cmsStageInputChannels(const cmsStage * mpe)1078 cmsUInt32Number  CMSEXPORT cmsStageInputChannels(const cmsStage* mpe)
1079 {
1080     return mpe ->InputChannels;
1081 }
1082 
cmsStageOutputChannels(const cmsStage * mpe)1083 cmsUInt32Number  CMSEXPORT cmsStageOutputChannels(const cmsStage* mpe)
1084 {
1085     return mpe ->OutputChannels;
1086 }
1087 
cmsStageType(const cmsStage * mpe)1088 cmsStageSignature CMSEXPORT cmsStageType(const cmsStage* mpe)
1089 {
1090     return mpe -> Type;
1091 }
1092 
cmsStageData(const cmsStage * mpe)1093 void* CMSEXPORT cmsStageData(const cmsStage* mpe)
1094 {
1095     return mpe -> Data;
1096 }
1097 
cmsStageNext(const cmsStage * mpe)1098 cmsStage*  CMSEXPORT cmsStageNext(const cmsStage* mpe)
1099 {
1100     return mpe -> Next;
1101 }
1102 
1103 
1104 // Duplicates an MPE
cmsStageDup(cmsStage * mpe)1105 cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
1106 {
1107     cmsStage* NewMPE;
1108 
1109     if (mpe == NULL) return NULL;
1110     NewMPE = _cmsStageAllocPlaceholder(mpe ->ContextID,
1111                                      mpe ->Type,
1112                                      mpe ->InputChannels,
1113                                      mpe ->OutputChannels,
1114                                      mpe ->EvalPtr,
1115                                      mpe ->DupElemPtr,
1116                                      mpe ->FreePtr,
1117                                      NULL);
1118     if (NewMPE == NULL) return NULL;
1119 
1120     NewMPE ->Implements     = mpe ->Implements;
1121 
1122     if (mpe ->DupElemPtr)
1123         NewMPE ->Data       = mpe ->DupElemPtr(mpe);
1124     else
1125         NewMPE ->Data       = NULL;
1126 
1127     return NewMPE;
1128 }
1129 
1130 
1131 // ***********************************************************************************************************
1132 
1133 // This function sets up the channel count
1134 
1135 static
BlessLUT(cmsPipeline * lut)1136 void BlessLUT(cmsPipeline* lut)
1137 {
1138     // We can set the input/ouput channels only if we have elements.
1139     if (lut ->Elements != NULL) {
1140 
1141         cmsStage *First, *Last;
1142 
1143         First  = cmsPipelineGetPtrToFirstStage(lut);
1144         Last   = cmsPipelineGetPtrToLastStage(lut);
1145 
1146         if (First != NULL)lut ->InputChannels = First ->InputChannels;
1147         if (Last != NULL) lut ->OutputChannels = Last ->OutputChannels;
1148     }
1149 }
1150 
1151 
1152 // Default to evaluate the LUT on 16 bit-basis. Precision is retained.
1153 static
_LUTeval16(register const cmsUInt16Number In[],register cmsUInt16Number Out[],register const void * D)1154 void _LUTeval16(register const cmsUInt16Number In[], register cmsUInt16Number Out[],  register const void* D)
1155 {
1156     cmsPipeline* lut = (cmsPipeline*) D;
1157     cmsStage *mpe;
1158     cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
1159     int Phase = 0, NextPhase;
1160 
1161     From16ToFloat(In, &Storage[Phase][0], lut ->InputChannels);
1162 
1163     for (mpe = lut ->Elements;
1164          mpe != NULL;
1165          mpe = mpe ->Next) {
1166 
1167              NextPhase = Phase ^ 1;
1168              mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
1169              Phase = NextPhase;
1170     }
1171 
1172 
1173     FromFloatTo16(&Storage[Phase][0], Out, lut ->OutputChannels);
1174 }
1175 
1176 
1177 
1178 // Does evaluate the LUT on cmsFloat32Number-basis.
1179 static
_LUTevalFloat(register const cmsFloat32Number In[],register cmsFloat32Number Out[],const void * D)1180 void _LUTevalFloat(register const cmsFloat32Number In[], register cmsFloat32Number Out[], const void* D)
1181 {
1182     cmsPipeline* lut = (cmsPipeline*) D;
1183     cmsStage *mpe;
1184     cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
1185     int Phase = 0, NextPhase;
1186 
1187     memmove(&Storage[Phase][0], In, lut ->InputChannels  * sizeof(cmsFloat32Number));
1188 
1189     for (mpe = lut ->Elements;
1190          mpe != NULL;
1191          mpe = mpe ->Next) {
1192 
1193               NextPhase = Phase ^ 1;
1194               mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
1195               Phase = NextPhase;
1196     }
1197 
1198     memmove(Out, &Storage[Phase][0], lut ->OutputChannels * sizeof(cmsFloat32Number));
1199 }
1200 
1201 
1202 
1203 
1204 // LUT Creation & Destruction
1205 
cmsPipelineAlloc(cmsContext ContextID,cmsUInt32Number InputChannels,cmsUInt32Number OutputChannels)1206 cmsPipeline* CMSEXPORT cmsPipelineAlloc(cmsContext ContextID, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels)
1207 {
1208        cmsPipeline* NewLUT;
1209 
1210        if (InputChannels >= cmsMAXCHANNELS ||
1211            OutputChannels >= cmsMAXCHANNELS) return NULL;
1212 
1213        NewLUT = (cmsPipeline*) _cmsMallocZero(ContextID, sizeof(cmsPipeline));
1214        if (NewLUT == NULL) return NULL;
1215 
1216 
1217        NewLUT -> InputChannels  = InputChannels;
1218        NewLUT -> OutputChannels = OutputChannels;
1219 
1220        NewLUT ->Eval16Fn    = _LUTeval16;
1221        NewLUT ->EvalFloatFn = _LUTevalFloat;
1222        NewLUT ->DupDataFn   = NULL;
1223        NewLUT ->FreeDataFn  = NULL;
1224        NewLUT ->Data        = NewLUT;
1225        NewLUT ->ContextID   = ContextID;
1226 
1227        BlessLUT(NewLUT);
1228 
1229        return NewLUT;
1230 }
1231 
1232 
cmsPipelineInputChannels(const cmsPipeline * lut)1233 cmsUInt32Number CMSEXPORT cmsPipelineInputChannels(const cmsPipeline* lut)
1234 {
1235     return lut ->InputChannels;
1236 }
1237 
cmsPipelineOutputChannels(const cmsPipeline * lut)1238 cmsUInt32Number CMSEXPORT cmsPipelineOutputChannels(const cmsPipeline* lut)
1239 {
1240     return lut ->OutputChannels;
1241 }
1242 
1243 // Free a profile elements LUT
cmsPipelineFree(cmsPipeline * lut)1244 void CMSEXPORT cmsPipelineFree(cmsPipeline* lut)
1245 {
1246     cmsStage *mpe, *Next;
1247 
1248     if (lut == NULL) return;
1249 
1250     for (mpe = lut ->Elements;
1251         mpe != NULL;
1252         mpe = Next) {
1253 
1254             Next = mpe ->Next;
1255             cmsStageFree(mpe);
1256     }
1257 
1258     if (lut ->FreeDataFn) lut ->FreeDataFn(lut ->ContextID, lut ->Data);
1259 
1260     _cmsFree(lut ->ContextID, lut);
1261 }
1262 
1263 
1264 // Default to evaluate the LUT on 16 bit-basis.
cmsPipelineEval16(const cmsUInt16Number In[],cmsUInt16Number Out[],const cmsPipeline * lut)1265 void CMSEXPORT cmsPipelineEval16(const cmsUInt16Number In[], cmsUInt16Number Out[],  const cmsPipeline* lut)
1266 {
1267     lut ->Eval16Fn(In, Out, lut->Data);
1268 }
1269 
1270 
1271 // Does evaluate the LUT on cmsFloat32Number-basis.
cmsPipelineEvalFloat(const cmsFloat32Number In[],cmsFloat32Number Out[],const cmsPipeline * lut)1272 void CMSEXPORT cmsPipelineEvalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsPipeline* lut)
1273 {
1274     lut ->EvalFloatFn(In, Out, lut);
1275 }
1276 
1277 
1278 
1279 // Duplicates a LUT
cmsPipelineDup(const cmsPipeline * lut)1280 cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
1281 {
1282     cmsPipeline* NewLUT;
1283     cmsStage *NewMPE, *Anterior = NULL, *mpe;
1284     cmsBool  First = TRUE;
1285 
1286     if (lut == NULL) return NULL;
1287 
1288     NewLUT = cmsPipelineAlloc(lut ->ContextID, lut ->InputChannels, lut ->OutputChannels);
1289     for (mpe = lut ->Elements;
1290          mpe != NULL;
1291          mpe = mpe ->Next) {
1292 
1293              NewMPE = cmsStageDup(mpe);
1294 
1295              if (NewMPE == NULL) {
1296                  cmsPipelineFree(NewLUT);
1297                  return NULL;
1298              }
1299 
1300              if (First) {
1301                  NewLUT ->Elements = NewMPE;
1302                  First = FALSE;
1303              }
1304              else {
1305                 Anterior ->Next = NewMPE;
1306              }
1307 
1308             Anterior = NewMPE;
1309     }
1310 
1311     NewLUT ->DupDataFn  = lut ->DupDataFn;
1312     NewLUT ->FreeDataFn = lut ->FreeDataFn;
1313 
1314     if (NewLUT ->DupDataFn != NULL)
1315         NewLUT ->Data = NewLUT ->DupDataFn(lut ->ContextID, lut->Data);
1316 
1317 
1318     NewLUT ->SaveAs8Bits    = lut ->SaveAs8Bits;
1319 
1320     BlessLUT(NewLUT);
1321     return NewLUT;
1322 }
1323 
1324 
cmsPipelineInsertStage(cmsPipeline * lut,cmsStageLoc loc,cmsStage * mpe)1325 void CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
1326 {
1327     cmsStage* Anterior = NULL, *pt;
1328 
1329     _cmsAssert(lut != NULL);
1330     _cmsAssert(mpe != NULL);
1331 
1332     switch (loc) {
1333 
1334         case cmsAT_BEGIN:
1335             mpe ->Next = lut ->Elements;
1336             lut ->Elements = mpe;
1337             break;
1338 
1339         case cmsAT_END:
1340 
1341             if (lut ->Elements == NULL)
1342                 lut ->Elements = mpe;
1343             else {
1344 
1345                 for (pt = lut ->Elements;
1346                      pt != NULL;
1347                      pt = pt -> Next) Anterior = pt;
1348 
1349                 Anterior ->Next = mpe;
1350                 mpe ->Next = NULL;
1351             }
1352             break;
1353         default:;
1354     }
1355 
1356     BlessLUT(lut);
1357 }
1358 
1359 // Unlink an element and return the pointer to it
cmsPipelineUnlinkStage(cmsPipeline * lut,cmsStageLoc loc,cmsStage ** mpe)1360 void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe)
1361 {
1362     cmsStage *Anterior, *pt, *Last;
1363     cmsStage *Unlinked = NULL;
1364 
1365 
1366     // If empty LUT, there is nothing to remove
1367     if (lut ->Elements == NULL) {
1368         if (mpe) *mpe = NULL;
1369         return;
1370     }
1371 
1372     // On depending on the strategy...
1373     switch (loc) {
1374 
1375         case cmsAT_BEGIN:
1376             {
1377                 cmsStage* elem = lut ->Elements;
1378 
1379                 lut ->Elements = elem -> Next;
1380                 elem ->Next = NULL;
1381                 Unlinked = elem;
1382 
1383             }
1384             break;
1385 
1386         case cmsAT_END:
1387             Anterior = Last = NULL;
1388             for (pt = lut ->Elements;
1389                 pt != NULL;
1390                 pt = pt -> Next) {
1391                     Anterior = Last;
1392                     Last = pt;
1393             }
1394 
1395             Unlinked = Last;  // Next already points to NULL
1396 
1397             // Truncate the chain
1398             if (Anterior)
1399                 Anterior ->Next = NULL;
1400             else
1401                 lut ->Elements = NULL;
1402             break;
1403         default:;
1404     }
1405 
1406     if (mpe)
1407         *mpe = Unlinked;
1408     else
1409         cmsStageFree(Unlinked);
1410 
1411     BlessLUT(lut);
1412 }
1413 
1414 
1415 // Concatenate two LUT into a new single one
cmsPipelineCat(cmsPipeline * l1,const cmsPipeline * l2)1416 cmsBool  CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
1417 {
1418     cmsStage* mpe, *NewMPE;
1419 
1420     // If both LUTS does not have elements, we need to inherit
1421     // the number of channels
1422     if (l1 ->Elements == NULL && l2 ->Elements == NULL) {
1423         l1 ->InputChannels  = l2 ->InputChannels;
1424         l1 ->OutputChannels = l2 ->OutputChannels;
1425     }
1426 
1427     // Cat second
1428     for (mpe = l2 ->Elements;
1429          mpe != NULL;
1430          mpe = mpe ->Next) {
1431 
1432             // We have to dup each element
1433              NewMPE = cmsStageDup(mpe);
1434 
1435              if (NewMPE == NULL) {
1436                  return FALSE;
1437              }
1438 
1439              cmsPipelineInsertStage(l1, cmsAT_END, NewMPE);
1440     }
1441 
1442   BlessLUT(l1);
1443   return TRUE;
1444 }
1445 
1446 
cmsPipelineSetSaveAs8bitsFlag(cmsPipeline * lut,cmsBool On)1447 cmsBool CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lut, cmsBool On)
1448 {
1449     cmsBool Anterior = lut ->SaveAs8Bits;
1450 
1451     lut ->SaveAs8Bits = On;
1452     return Anterior;
1453 }
1454 
1455 
cmsPipelineGetPtrToFirstStage(const cmsPipeline * lut)1456 cmsStage* CMSEXPORT cmsPipelineGetPtrToFirstStage(const cmsPipeline* lut)
1457 {
1458     return lut ->Elements;
1459 }
1460 
cmsPipelineGetPtrToLastStage(const cmsPipeline * lut)1461 cmsStage* CMSEXPORT cmsPipelineGetPtrToLastStage(const cmsPipeline* lut)
1462 {
1463     cmsStage *mpe, *Anterior = NULL;
1464 
1465     for (mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
1466         Anterior = mpe;
1467 
1468     return Anterior;
1469 }
1470 
cmsPipelineStageCount(const cmsPipeline * lut)1471 cmsUInt32Number CMSEXPORT cmsPipelineStageCount(const cmsPipeline* lut)
1472 {
1473     cmsStage *mpe;
1474     cmsUInt32Number n;
1475 
1476     for (n=0, mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
1477             n++;
1478 
1479     return n;
1480 }
1481 
1482 // This function may be used to set the optional evalueator and a block of private data. If private data is being used, an optional
1483 // duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality.
_cmsPipelineSetOptimizationParameters(cmsPipeline * Lut,_cmsOPTeval16Fn Eval16,void * PrivateData,_cmsOPTfreeDataFn FreePrivateDataFn,_cmsOPTdupDataFn DupPrivateDataFn)1484 void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut,
1485                                         _cmsOPTeval16Fn Eval16,
1486                                         void* PrivateData,
1487                                         _cmsOPTfreeDataFn FreePrivateDataFn,
1488                                         _cmsOPTdupDataFn DupPrivateDataFn)
1489 {
1490 
1491     Lut ->Eval16Fn = Eval16;
1492     Lut ->DupDataFn = DupPrivateDataFn;
1493     Lut ->FreeDataFn = FreePrivateDataFn;
1494     Lut ->Data = PrivateData;
1495 }
1496 
1497 
1498 // ----------------------------------------------------------- Reverse interpolation
1499 // Here's how it goes. The derivative Df(x) of the function f is the linear
1500 // transformation that best approximates f near the point x. It can be represented
1501 // by a matrix A whose entries are the partial derivatives of the components of f
1502 // with respect to all the coordinates. This is know as the Jacobian
1503 //
1504 // The best linear approximation to f is given by the matrix equation:
1505 //
1506 // y-y0 = A (x-x0)
1507 //
1508 // So, if x0 is a good "guess" for the zero of f, then solving for the zero of this
1509 // linear approximation will give a "better guess" for the zero of f. Thus let y=0,
1510 // and since y0=f(x0) one can solve the above equation for x. This leads to the
1511 // Newton's method formula:
1512 //
1513 // xn+1 = xn - A-1 f(xn)
1514 //
1515 // where xn+1 denotes the (n+1)-st guess, obtained from the n-th guess xn in the
1516 // fashion described above. Iterating this will give better and better approximations
1517 // if you have a "good enough" initial guess.
1518 
1519 
1520 #define JACOBIAN_EPSILON            0.001f
1521 #define INVERSION_MAX_ITERATIONS    30
1522 
1523 // Increment with reflexion on boundary
1524 static
IncDelta(cmsFloat32Number * Val)1525 void IncDelta(cmsFloat32Number *Val)
1526 {
1527     if (*Val < (1.0 - JACOBIAN_EPSILON))
1528 
1529         *Val += JACOBIAN_EPSILON;
1530 
1531     else
1532         *Val -= JACOBIAN_EPSILON;
1533 
1534 }
1535 
1536 
1537 
1538 // Euclidean distance between two vectors of n elements each one
1539 static
EuclideanDistance(cmsFloat32Number a[],cmsFloat32Number b[],int n)1540 cmsFloat32Number EuclideanDistance(cmsFloat32Number a[], cmsFloat32Number b[], int n)
1541 {
1542     cmsFloat32Number sum = 0;
1543     int i;
1544 
1545     for (i=0; i < n; i++) {
1546         cmsFloat32Number dif = b[i] - a[i];
1547         sum +=  dif * dif;
1548     }
1549 
1550     return sqrtf(sum);
1551 }
1552 
1553 
1554 // Evaluate a LUT in reverse direction. It only searches on 3->3 LUT. Uses Newton method
1555 //
1556 // x1 <- x - [J(x)]^-1 * f(x)
1557 //
1558 // lut: The LUT on where to do the search
1559 // Target: LabK, 3 values of Lab plus destination K which is fixed
1560 // Result: The obtained CMYK
1561 // Hint:   Location where begin the search
1562 
cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],cmsFloat32Number Result[],cmsFloat32Number Hint[],const cmsPipeline * lut)1563 cmsBool CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],
1564                                               cmsFloat32Number Result[],
1565                                               cmsFloat32Number Hint[],
1566                                               const cmsPipeline* lut)
1567 {
1568     cmsUInt32Number  i, j;
1569     cmsFloat64Number  error, LastError = 1E20;
1570     cmsFloat32Number  fx[4], x[4], xd[4], fxd[4];
1571     cmsVEC3 tmp, tmp2;
1572     cmsMAT3 Jacobian;
1573     cmsFloat64Number LastResult[4];
1574 
1575 
1576     // Only 3->3 and 4->3 are supported
1577     if (lut ->InputChannels != 3 && lut ->InputChannels != 4) return FALSE;
1578     if (lut ->OutputChannels != 3) return FALSE;
1579 
1580     // Mark result of -1
1581     LastResult[0] = LastResult[1] = LastResult[2] = -1.0f;
1582 
1583     // Take the hint as starting point if specified
1584     if (Hint == NULL) {
1585 
1586         // Begin at any point, we choose 1/3 of CMY axis
1587         x[0] = x[1] = x[2] = 0.3f;
1588     }
1589     else {
1590 
1591         // Only copy 3 channels from hint...
1592         for (j=0; j < 3; j++)
1593             x[j] = Hint[j];
1594     }
1595 
1596     // If Lut is 4-dimensions, then grab target[3], which is fixed
1597     if (lut ->InputChannels == 4) {
1598         x[3] = Target[3];
1599     }
1600     else x[3] = 0; // To keep lint happy
1601 
1602 
1603     // Iterate
1604     for (i = 0; i < INVERSION_MAX_ITERATIONS; i++) {
1605 
1606         // Get beginning fx
1607         cmsPipelineEvalFloat(x, fx, lut);
1608 
1609         // Compute error
1610         error = EuclideanDistance(fx, Target, 3);
1611 
1612         // If not convergent, return last safe value
1613         if (error >= LastError)
1614             break;
1615 
1616         // Keep latest values
1617         LastError     = error;
1618         for (j=0; j < lut ->InputChannels; j++)
1619                 Result[j] = x[j];
1620 
1621         // Found an exact match?
1622         if (error <= 0)
1623             break;
1624 
1625         // Obtain slope (the Jacobian)
1626         for (j = 0; j < 3; j++) {
1627 
1628             xd[0] = x[0];
1629             xd[1] = x[1];
1630             xd[2] = x[2];
1631             xd[3] = x[3];  // Keep fixed channel
1632 
1633             IncDelta(&xd[j]);
1634 
1635             cmsPipelineEvalFloat(xd, fxd, lut);
1636 
1637             Jacobian.v[0].n[j] = ((fxd[0] - fx[0]) / JACOBIAN_EPSILON);
1638             Jacobian.v[1].n[j] = ((fxd[1] - fx[1]) / JACOBIAN_EPSILON);
1639             Jacobian.v[2].n[j] = ((fxd[2] - fx[2]) / JACOBIAN_EPSILON);
1640         }
1641 
1642         // Solve system
1643         tmp2.n[0] = fx[0] - Target[0];
1644         tmp2.n[1] = fx[1] - Target[1];
1645         tmp2.n[2] = fx[2] - Target[2];
1646 
1647         if (!_cmsMAT3solve(&tmp, &Jacobian, &tmp2))
1648             return FALSE;
1649 
1650         // Move our guess
1651         x[0] -= (cmsFloat32Number) tmp.n[0];
1652         x[1] -= (cmsFloat32Number) tmp.n[1];
1653         x[2] -= (cmsFloat32Number) tmp.n[2];
1654 
1655         // Some clipping....
1656         for (j=0; j < 3; j++) {
1657             if (x[j] < 0) x[j] = 0;
1658             else
1659                 if (x[j] > 1.0) x[j] = 1.0;
1660         }
1661     }
1662 
1663     return TRUE;
1664 }
1665 
1666