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