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