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