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