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