1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 // This file is available under and governed by the GNU General Public
  26 // License version 2 only, as published by the Free Software Foundation.
  27 // However, the following notice accompanied the original version of this
  28 // file:
  29 //
  30 //---------------------------------------------------------------------------------
  31 //
  32 //  Little Color Management System
  33 //  Copyright (c) 1998-2012 Marti Maria Saguer
  34 //
  35 // Permission is hereby granted, free of charge, to any person obtaining
  36 // a copy of this software and associated documentation files (the "Software"),
  37 // to deal in the Software without restriction, including without limitation
  38 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  39 // and/or sell copies of the Software, and to permit persons to whom the Software
  40 // is furnished to do so, subject to the following conditions:
  41 //
  42 // The above copyright notice and this permission notice shall be included in
  43 // all copies or substantial portions of the Software.
  44 //
  45 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  46 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  47 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  48 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  49 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  50 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  51 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  52 //
  53 //---------------------------------------------------------------------------------
  54 //
  55 
  56 #include "lcms2_internal.h"
  57 
  58 
  59 // Allocates an empty multi profile element
  60 cmsStage* CMSEXPORT _cmsStageAllocPlaceholder(cmsContext ContextID,
  61                                 cmsStageSignature Type,
  62                                 cmsUInt32Number InputChannels,
  63                                 cmsUInt32Number OutputChannels,
  64                                 _cmsStageEvalFn     EvalPtr,
  65                                 _cmsStageDupElemFn  DupElemPtr,
  66                                 _cmsStageFreeElemFn FreePtr,
  67                                 void*             Data)
  68 {
  69     cmsStage* ph = (cmsStage*) _cmsMallocZero(ContextID, sizeof(cmsStage));
  70 
  71     if (ph == NULL) return NULL;
  72 
  73 
  74     ph ->ContextID = ContextID;
  75 
  76     ph ->Type       = Type;
  77     ph ->Implements = Type;   // By default, no clue on what is implementing
  78 
  79     ph ->InputChannels  = InputChannels;
  80     ph ->OutputChannels = OutputChannels;
  81     ph ->EvalPtr        = EvalPtr;
  82     ph ->DupElemPtr     = DupElemPtr;
  83     ph ->FreePtr        = FreePtr;
  84     ph ->Data           = Data;
  85 
  86     return ph;
  87 }
  88 
  89 
  90 static
  91 void EvaluateIdentity(const cmsFloat32Number In[],
  92                             cmsFloat32Number Out[],
  93                       const cmsStage *mpe)
  94 {
  95     memmove(Out, In, mpe ->InputChannels * sizeof(cmsFloat32Number));
  96 }
  97 
  98 
  99 cmsStage* CMSEXPORT cmsStageAllocIdentity(cmsContext ContextID, cmsUInt32Number nChannels)
 100 {
 101     return _cmsStageAllocPlaceholder(ContextID,
 102                                    cmsSigIdentityElemType,
 103                                    nChannels, nChannels,
 104                                    EvaluateIdentity,
 105                                    NULL,
 106                                    NULL,
 107                                    NULL);
 108  }
 109 
 110 // Conversion functions. From floating point to 16 bits
 111 static
 112 void FromFloatTo16(const cmsFloat32Number In[], cmsUInt16Number Out[], cmsUInt32Number n)
 113 {
 114     cmsUInt32Number i;
 115 
 116     for (i=0; i < n; i++) {
 117         Out[i] = _cmsQuickSaturateWord(In[i] * 65535.0);
 118     }
 119 }
 120 
 121 // From 16 bits to floating point
 122 static
 123 void From16ToFloat(const cmsUInt16Number In[], cmsFloat32Number Out[], cmsUInt32Number n)
 124 {
 125     cmsUInt32Number i;
 126 
 127     for (i=0; i < n; i++) {
 128         Out[i] = (cmsFloat32Number) In[i] / 65535.0F;
 129     }
 130 }
 131 
 132 
 133 // This function is quite useful to analyze the structure of a LUT and retrieve the MPE elements
 134 // that conform the LUT. It should be called with the LUT, the number of expected elements and
 135 // then a list of expected types followed with a list of cmsFloat64Number pointers to MPE elements. If
 136 // the function founds a match with current pipeline, it fills the pointers and returns TRUE
 137 // if not, returns FALSE without touching anything. Setting pointers to NULL does bypass
 138 // the storage process.
 139 cmsBool  CMSEXPORT cmsPipelineCheckAndRetreiveStages(const cmsPipeline* Lut, cmsUInt32Number n, ...)
 140 {
 141     va_list args;
 142     cmsUInt32Number i;
 143     cmsStage* mpe;
 144     cmsStageSignature Type;
 145     void** ElemPtr;
 146 
 147     // Make sure same number of elements
 148     if (cmsPipelineStageCount(Lut) != n) return FALSE;
 149 
 150     va_start(args, n);
 151 
 152     // Iterate across asked types
 153     mpe = Lut ->Elements;
 154     for (i=0; i < n; i++) {
 155 
 156         // Get asked type
 157         Type  = (cmsStageSignature)va_arg(args, cmsStageSignature);
 158         if (mpe ->Type != Type) {
 159 
 160             va_end(args);       // Mismatch. We are done.
 161             return FALSE;
 162         }
 163         mpe = mpe ->Next;
 164     }
 165 
 166     // Found a combination, fill pointers if not NULL
 167     mpe = Lut ->Elements;
 168     for (i=0; i < n; i++) {
 169 
 170         ElemPtr = va_arg(args, void**);
 171         if (ElemPtr != NULL)
 172             *ElemPtr = mpe;
 173 
 174         mpe = mpe ->Next;
 175     }
 176 
 177     va_end(args);
 178     return TRUE;
 179 }
 180 
 181 // Below there are implementations for several types of elements. Each type may be implemented by a
 182 // evaluation function, a duplication function, a function to free resources and a constructor.
 183 
 184 // *************************************************************************************************
 185 // Type cmsSigCurveSetElemType (curves)
 186 // *************************************************************************************************
 187 
 188 cmsToneCurve** _cmsStageGetPtrToCurveSet(const cmsStage* mpe)
 189 {
 190     _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
 191 
 192     return Data ->TheCurves;
 193 }
 194 
 195 static
 196 void EvaluateCurves(const cmsFloat32Number In[],
 197                     cmsFloat32Number Out[],
 198                     const cmsStage *mpe)
 199 {
 200     _cmsStageToneCurvesData* Data;
 201     cmsUInt32Number i;
 202 
 203     _cmsAssert(mpe != NULL);
 204 
 205     Data = (_cmsStageToneCurvesData*) mpe ->Data;
 206     if (Data == NULL) return;
 207 
 208     if (Data ->TheCurves == NULL) return;
 209 
 210     for (i=0; i < Data ->nCurves; i++) {
 211         Out[i] = cmsEvalToneCurveFloat(Data ->TheCurves[i], In[i]);
 212     }
 213 }
 214 
 215 static
 216 void CurveSetElemTypeFree(cmsStage* mpe)
 217 {
 218     _cmsStageToneCurvesData* Data;
 219     cmsUInt32Number i;
 220 
 221     _cmsAssert(mpe != NULL);
 222 
 223     Data = (_cmsStageToneCurvesData*) mpe ->Data;
 224     if (Data == NULL) return;
 225 
 226     if (Data ->TheCurves != NULL) {
 227         for (i=0; i < Data ->nCurves; i++) {
 228             if (Data ->TheCurves[i] != NULL)
 229                 cmsFreeToneCurve(Data ->TheCurves[i]);
 230         }
 231     }
 232     _cmsFree(mpe ->ContextID, Data ->TheCurves);
 233     _cmsFree(mpe ->ContextID, Data);
 234 }
 235 
 236 
 237 static
 238 void* CurveSetDup(cmsStage* mpe)
 239 {
 240     _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
 241     _cmsStageToneCurvesData* NewElem;
 242     cmsUInt32Number i;
 243 
 244     NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageToneCurvesData));
 245     if (NewElem == NULL) return NULL;
 246 
 247     NewElem ->nCurves   = Data ->nCurves;
 248     NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(mpe ->ContextID, NewElem ->nCurves, sizeof(cmsToneCurve*));
 249 
 250     if (NewElem ->TheCurves == NULL) goto Error;
 251 
 252     for (i=0; i < NewElem ->nCurves; i++) {
 253 
 254         // Duplicate each curve. It may fail.
 255         NewElem ->TheCurves[i] = cmsDupToneCurve(Data ->TheCurves[i]);
 256         if (NewElem ->TheCurves[i] == NULL) goto Error;
 257 
 258 
 259     }
 260     return (void*) NewElem;
 261 
 262 Error:
 263 
 264     if (NewElem ->TheCurves != NULL) {
 265         for (i=0; i < NewElem ->nCurves; i++) {
 266             if (NewElem ->TheCurves[i])
 267                 cmsFreeToneCurve(NewElem ->TheCurves[i]);
 268         }
 269     }
 270     _cmsFree(mpe ->ContextID, NewElem ->TheCurves);
 271     _cmsFree(mpe ->ContextID, NewElem);
 272     return NULL;
 273 }
 274 
 275 
 276 // Curves == NULL forces identity curves
 277 cmsStage* CMSEXPORT cmsStageAllocToneCurves(cmsContext ContextID, cmsUInt32Number nChannels, cmsToneCurve* const Curves[])
 278 {
 279     cmsUInt32Number i;
 280     _cmsStageToneCurvesData* NewElem;
 281     cmsStage* NewMPE;
 282 
 283 
 284     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCurveSetElemType, nChannels, nChannels,
 285                                      EvaluateCurves, CurveSetDup, CurveSetElemTypeFree, NULL );
 286     if (NewMPE == NULL) return NULL;
 287 
 288     NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(ContextID, sizeof(_cmsStageToneCurvesData));
 289     if (NewElem == NULL) {
 290         cmsStageFree(NewMPE);
 291         return NULL;
 292     }
 293 
 294     NewMPE ->Data  = (void*) NewElem;
 295 
 296     NewElem ->nCurves   = nChannels;
 297     NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(ContextID, nChannels, sizeof(cmsToneCurve*));
 298     if (NewElem ->TheCurves == NULL) {
 299         cmsStageFree(NewMPE);
 300         return NULL;
 301     }
 302 
 303     for (i=0; i < nChannels; i++) {
 304 
 305         if (Curves == NULL) {
 306             NewElem ->TheCurves[i] = cmsBuildGamma(ContextID, 1.0);
 307         }
 308         else {
 309             NewElem ->TheCurves[i] = cmsDupToneCurve(Curves[i]);
 310         }
 311 
 312         if (NewElem ->TheCurves[i] == NULL) {
 313             cmsStageFree(NewMPE);
 314             return NULL;
 315         }
 316 
 317     }
 318 
 319    return NewMPE;
 320 }
 321 
 322 
 323 // Create a bunch of identity curves
 324 cmsStage* _cmsStageAllocIdentityCurves(cmsContext ContextID, int nChannels)
 325 {
 326     cmsStage* mpe = cmsStageAllocToneCurves(ContextID, nChannels, NULL);
 327 
 328     if (mpe == NULL) return NULL;
 329     mpe ->Implements = cmsSigIdentityElemType;
 330     return mpe;
 331 }
 332 
 333 
 334 // *************************************************************************************************
 335 // Type cmsSigMatrixElemType (Matrices)
 336 // *************************************************************************************************
 337 
 338 
 339 // Special care should be taken here because precision loss. A temporary cmsFloat64Number buffer is being used
 340 static
 341 void EvaluateMatrix(const cmsFloat32Number In[],
 342                     cmsFloat32Number Out[],
 343                     const cmsStage *mpe)
 344 {
 345     cmsUInt32Number i, j;
 346     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
 347     cmsFloat64Number Tmp;
 348 
 349     // Input is already in 0..1.0 notation
 350     for (i=0; i < mpe ->OutputChannels; i++) {
 351 
 352         Tmp = 0;
 353         for (j=0; j < mpe->InputChannels; j++) {
 354             Tmp += In[j] * Data->Double[i*mpe->InputChannels + j];
 355         }
 356 
 357         if (Data ->Offset != NULL)
 358             Tmp += Data->Offset[i];
 359 
 360         Out[i] = (cmsFloat32Number) Tmp;
 361     }
 362 
 363 
 364     // Output in 0..1.0 domain
 365 }
 366 
 367 
 368 // Duplicate a yet-existing matrix element
 369 static
 370 void* MatrixElemDup(cmsStage* mpe)
 371 {
 372     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
 373     _cmsStageMatrixData* NewElem;
 374     cmsUInt32Number sz;
 375 
 376     NewElem = (_cmsStageMatrixData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageMatrixData));
 377     if (NewElem == NULL) return NULL;
 378 
 379     sz = mpe ->InputChannels * mpe ->OutputChannels;
 380 
 381     NewElem ->Double = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID, Data ->Double, sz * sizeof(cmsFloat64Number)) ;
 382 
 383     if (Data ->Offset)
 384         NewElem ->Offset = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID,
 385                                                 Data ->Offset, mpe -> OutputChannels * sizeof(cmsFloat64Number)) ;
 386 
 387     return (void*) NewElem;
 388 }
 389 
 390 
 391 static
 392 void MatrixElemTypeFree(cmsStage* mpe)
 393 {
 394     _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
 395     if (Data == NULL)
 396         return;
 397     if (Data ->Double)
 398         _cmsFree(mpe ->ContextID, Data ->Double);
 399 
 400     if (Data ->Offset)
 401         _cmsFree(mpe ->ContextID, Data ->Offset);
 402 
 403     _cmsFree(mpe ->ContextID, mpe ->Data);
 404 }
 405 
 406 
 407 
 408 cmsStage*  CMSEXPORT cmsStageAllocMatrix(cmsContext ContextID, cmsUInt32Number Rows, cmsUInt32Number Cols,
 409                                      const cmsFloat64Number* Matrix, const cmsFloat64Number* Offset)
 410 {
 411     cmsUInt32Number i, n;
 412     _cmsStageMatrixData* NewElem;
 413     cmsStage* NewMPE;
 414 
 415     n = Rows * Cols;
 416 
 417     // Check for overflow
 418     if (n == 0) return NULL;
 419     if (n >= UINT_MAX / Cols) return NULL;
 420     if (n >= UINT_MAX / Rows) return NULL;
 421     if (n < Rows || n < Cols) return NULL;
 422 
 423     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigMatrixElemType, Cols, Rows,
 424                                      EvaluateMatrix, MatrixElemDup, MatrixElemTypeFree, NULL );
 425     if (NewMPE == NULL) return NULL;
 426 
 427 
 428     NewElem = (_cmsStageMatrixData*) _cmsMallocZero(ContextID, sizeof(_cmsStageMatrixData));
 429     if (NewElem == NULL) return NULL;
 430 
 431 
 432     NewElem ->Double = (cmsFloat64Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat64Number));
 433 
 434     if (NewElem->Double == NULL) {
 435         MatrixElemTypeFree(NewMPE);
 436         return NULL;
 437     }
 438 
 439     for (i=0; i < n; i++) {
 440         NewElem ->Double[i] = Matrix[i];
 441     }
 442 
 443 
 444     if (Offset != NULL) {
 445 
 446         NewElem ->Offset = (cmsFloat64Number*) _cmsCalloc(ContextID, Cols, sizeof(cmsFloat64Number));
 447         if (NewElem->Offset == NULL) {
 448            MatrixElemTypeFree(NewMPE);
 449            return NULL;
 450         }
 451 
 452         for (i=0; i < Cols; i++) {
 453                 NewElem ->Offset[i] = Offset[i];
 454         }
 455 
 456     }
 457 
 458     NewMPE ->Data  = (void*) NewElem;
 459     return NewMPE;
 460 }
 461 
 462 
 463 // *************************************************************************************************
 464 // Type cmsSigCLutElemType
 465 // *************************************************************************************************
 466 
 467 
 468 // Evaluate in true floating point
 469 static
 470 void EvaluateCLUTfloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
 471 {
 472     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
 473 
 474     Data -> Params ->Interpolation.LerpFloat(In, Out, Data->Params);
 475 }
 476 
 477 
 478 // Convert to 16 bits, evaluate, and back to floating point
 479 static
 480 void EvaluateCLUTfloatIn16(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
 481 {
 482     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
 483     cmsUInt16Number In16[MAX_STAGE_CHANNELS], Out16[MAX_STAGE_CHANNELS];
 484 
 485     _cmsAssert(mpe ->InputChannels  <= MAX_STAGE_CHANNELS);
 486     _cmsAssert(mpe ->OutputChannels <= MAX_STAGE_CHANNELS);
 487 
 488     FromFloatTo16(In, In16, mpe ->InputChannels);
 489     Data -> Params ->Interpolation.Lerp16(In16, Out16, Data->Params);
 490     From16ToFloat(Out16, Out,  mpe ->OutputChannels);
 491 }
 492 
 493 
 494 // Given an hypercube of b dimensions, with Dims[] number of nodes by dimension, calculate the total amount of nodes
 495 static
 496 cmsUInt32Number CubeSize(const cmsUInt32Number Dims[], cmsUInt32Number b)
 497 {
 498     cmsUInt32Number rv, dim;
 499 
 500     _cmsAssert(Dims != NULL);
 501 
 502     for (rv = 1; b > 0; b--) {
 503 
 504         dim = Dims[b-1];
 505         if (dim == 0) return 0;  // Error
 506 
 507         rv *= dim;
 508 
 509         // Check for overflow
 510         if (rv > UINT_MAX / dim) return 0;
 511     }
 512 
 513     return rv;
 514 }
 515 
 516 static
 517 void* CLUTElemDup(cmsStage* mpe)
 518 {
 519     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
 520     _cmsStageCLutData* NewElem;
 521 
 522 
 523     NewElem = (_cmsStageCLutData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageCLutData));
 524     if (NewElem == NULL) return NULL;
 525 
 526     NewElem ->nEntries       = Data ->nEntries;
 527     NewElem ->HasFloatValues = Data ->HasFloatValues;
 528 
 529     if (Data ->Tab.T) {
 530 
 531         if (Data ->HasFloatValues) {
 532             NewElem ->Tab.TFloat = (cmsFloat32Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.TFloat, Data ->nEntries * sizeof (cmsFloat32Number));
 533             if (NewElem ->Tab.TFloat == NULL)
 534                 goto Error;
 535         } else {
 536             NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
 537             if (NewElem ->Tab.TFloat == NULL)
 538                 goto Error;
 539         }
 540     }
 541 
 542     NewElem ->Params   = _cmsComputeInterpParamsEx(mpe ->ContextID,
 543                                                    Data ->Params ->nSamples,
 544                                                    Data ->Params ->nInputs,
 545                                                    Data ->Params ->nOutputs,
 546                                                    NewElem ->Tab.T,
 547                                                    Data ->Params ->dwFlags);
 548     if (NewElem->Params != NULL)
 549         return (void*) NewElem;
 550  Error:
 551     if (NewElem->Tab.T)
 552         // This works for both types
 553         _cmsFree(mpe ->ContextID, NewElem -> Tab.T);
 554     _cmsFree(mpe ->ContextID, NewElem);
 555     return NULL;
 556 }
 557 
 558 
 559 static
 560 void CLutElemTypeFree(cmsStage* mpe)
 561 {
 562 
 563     _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
 564 
 565     // Already empty
 566     if (Data == NULL) return;
 567 
 568     // This works for both types
 569     if (Data -> Tab.T)
 570         _cmsFree(mpe ->ContextID, Data -> Tab.T);
 571 
 572     _cmsFreeInterpParams(Data ->Params);
 573     _cmsFree(mpe ->ContextID, mpe ->Data);
 574 }
 575 
 576 
 577 // Allocates a 16-bit multidimensional CLUT. This is evaluated at 16-bit precision. Table may have different
 578 // granularity on each dimension.
 579 cmsStage* CMSEXPORT cmsStageAllocCLut16bitGranular(cmsContext ContextID,
 580                                          const cmsUInt32Number clutPoints[],
 581                                          cmsUInt32Number inputChan,
 582                                          cmsUInt32Number outputChan,
 583                                          const cmsUInt16Number* Table)
 584 {
 585     cmsUInt32Number i, n;
 586     _cmsStageCLutData* NewElem;
 587     cmsStage* NewMPE;
 588 
 589     _cmsAssert(clutPoints != NULL);
 590 
 591     if (inputChan > MAX_INPUT_DIMENSIONS) {
 592         cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", inputChan, MAX_INPUT_DIMENSIONS);
 593         return NULL;
 594     }
 595 
 596     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
 597                                      EvaluateCLUTfloatIn16, CLUTElemDup, CLutElemTypeFree, NULL );
 598 
 599     if (NewMPE == NULL) return NULL;
 600 
 601     NewElem = (_cmsStageCLutData*) _cmsMallocZero(ContextID, sizeof(_cmsStageCLutData));
 602     if (NewElem == NULL) {
 603         cmsStageFree(NewMPE);
 604         return NULL;
 605     }
 606 
 607     NewMPE ->Data  = (void*) NewElem;
 608 
 609     NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
 610     NewElem -> HasFloatValues = FALSE;
 611 
 612     if (n == 0) {
 613         cmsStageFree(NewMPE);
 614         return NULL;
 615     }
 616 
 617 
 618     NewElem ->Tab.T  = (cmsUInt16Number*) _cmsCalloc(ContextID, n, sizeof(cmsUInt16Number));
 619     if (NewElem ->Tab.T == NULL) {
 620         cmsStageFree(NewMPE);
 621         return NULL;
 622     }
 623 
 624     if (Table != NULL) {
 625         for (i=0; i < n; i++) {
 626             NewElem ->Tab.T[i] = Table[i];
 627         }
 628     }
 629 
 630     NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints, inputChan, outputChan, NewElem ->Tab.T, CMS_LERP_FLAGS_16BITS);
 631     if (NewElem ->Params == NULL) {
 632         cmsStageFree(NewMPE);
 633         return NULL;
 634     }
 635 
 636     return NewMPE;
 637 }
 638 
 639 cmsStage* CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID,
 640                                     cmsUInt32Number nGridPoints,
 641                                     cmsUInt32Number inputChan,
 642                                     cmsUInt32Number outputChan,
 643                                     const cmsUInt16Number* Table)
 644 {
 645     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
 646     int i;
 647 
 648    // Our resulting LUT would be same gridpoints on all dimensions
 649     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
 650         Dimensions[i] = nGridPoints;
 651 
 652     return cmsStageAllocCLut16bitGranular(ContextID, Dimensions, inputChan, outputChan, Table);
 653 }
 654 
 655 
 656 cmsStage* CMSEXPORT cmsStageAllocCLutFloat(cmsContext ContextID,
 657                                        cmsUInt32Number nGridPoints,
 658                                        cmsUInt32Number inputChan,
 659                                        cmsUInt32Number outputChan,
 660                                        const cmsFloat32Number* Table)
 661 {
 662    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
 663    int i;
 664 
 665     // Our resulting LUT would be same gridpoints on all dimensions
 666     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
 667         Dimensions[i] = nGridPoints;
 668 
 669     return cmsStageAllocCLutFloatGranular(ContextID, Dimensions, inputChan, outputChan, Table);
 670 }
 671 
 672 
 673 
 674 cmsStage* CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table)
 675 {
 676     cmsUInt32Number i, n;
 677     _cmsStageCLutData* NewElem;
 678     cmsStage* NewMPE;
 679 
 680     _cmsAssert(clutPoints != NULL);
 681 
 682     if (inputChan > MAX_INPUT_DIMENSIONS) {
 683         cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", inputChan, MAX_INPUT_DIMENSIONS);
 684         return NULL;
 685     }
 686 
 687     NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
 688                                              EvaluateCLUTfloat, CLUTElemDup, CLutElemTypeFree, NULL);
 689     if (NewMPE == NULL) return NULL;
 690 
 691 
 692     NewElem = (_cmsStageCLutData*) _cmsMallocZero(ContextID, sizeof(_cmsStageCLutData));
 693     if (NewElem == NULL) {
 694         cmsStageFree(NewMPE);
 695         return NULL;
 696     }
 697 
 698     NewMPE ->Data  = (void*) NewElem;
 699 
 700     // There is a potential integer overflow on conputing n and nEntries.
 701     NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
 702     NewElem -> HasFloatValues = TRUE;
 703 
 704     if (n == 0) {
 705         cmsStageFree(NewMPE);
 706         return NULL;
 707     }
 708 
 709     NewElem ->Tab.TFloat  = (cmsFloat32Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat32Number));
 710     if (NewElem ->Tab.TFloat == NULL) {
 711         cmsStageFree(NewMPE);
 712         return NULL;
 713     }
 714 
 715     if (Table != NULL) {
 716         for (i=0; i < n; i++) {
 717             NewElem ->Tab.TFloat[i] = Table[i];
 718         }
 719     }
 720 
 721     NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints,  inputChan, outputChan, NewElem ->Tab.TFloat, CMS_LERP_FLAGS_FLOAT);
 722     if (NewElem ->Params == NULL) {
 723         cmsStageFree(NewMPE);
 724         return NULL;
 725     }
 726 
 727     return NewMPE;
 728 }
 729 
 730 
 731 static
 732 int IdentitySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void * Cargo)
 733 {
 734     int nChan = *(int*) Cargo;
 735     int i;
 736 
 737     for (i=0; i < nChan; i++)
 738         Out[i] = In[i];
 739 
 740     return 1;
 741 }
 742 
 743 // Creates an MPE that just copies input to output
 744 cmsStage* _cmsStageAllocIdentityCLut(cmsContext ContextID, int nChan)
 745 {
 746     cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
 747     cmsStage* mpe ;
 748     int i;
 749 
 750     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
 751         Dimensions[i] = 2;
 752 
 753     mpe = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, nChan, nChan, NULL);
 754     if (mpe == NULL) return NULL;
 755 
 756     if (!cmsStageSampleCLut16bit(mpe, IdentitySampler, &nChan, 0)) {
 757         cmsStageFree(mpe);
 758         return NULL;
 759     }
 760 
 761     mpe ->Implements = cmsSigIdentityElemType;
 762     return mpe;
 763 }
 764 
 765 
 766 
 767 // Quantize a value 0 <= i < MaxSamples to 0..0xffff
 768 cmsUInt16Number _cmsQuantizeVal(cmsFloat64Number i, int MaxSamples)
 769 {
 770     cmsFloat64Number x;
 771 
 772     x = ((cmsFloat64Number) i * 65535.) / (cmsFloat64Number) (MaxSamples - 1);
 773     return _cmsQuickSaturateWord(x);
 774 }
 775 
 776 
 777 // This routine does a sweep on whole input space, and calls its callback
 778 // function on knots. returns TRUE if all ok, FALSE otherwise.
 779 cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, void * Cargo, cmsUInt32Number dwFlags)
 780 {
 781     int i, t, nTotalPoints, index, rest;
 782     int nInputs, nOutputs;
 783     cmsUInt32Number* nSamples;
 784     cmsUInt16Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
 785     _cmsStageCLutData* clut;
 786 
 787     if (mpe == NULL) return FALSE;
 788 
 789     clut = (_cmsStageCLutData*) mpe->Data;
 790 
 791     if (clut == NULL) return FALSE;
 792 
 793     nSamples = clut->Params ->nSamples;
 794     nInputs  = clut->Params ->nInputs;
 795     nOutputs = clut->Params ->nOutputs;
 796 
 797     if (nInputs <= 0) return FALSE;
 798     if (nOutputs <= 0) return FALSE;
 799     if (nInputs > MAX_INPUT_DIMENSIONS) return FALSE;
 800     if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
 801 
 802     nTotalPoints = CubeSize(nSamples, nInputs);
 803     if (nTotalPoints == 0) return FALSE;
 804 
 805     index = 0;
 806     for (i = 0; i < nTotalPoints; i++) {
 807 
 808         rest = i;
 809         for (t = nInputs-1; t >=0; --t) {
 810 
 811             cmsUInt32Number  Colorant = rest % nSamples[t];
 812 
 813             rest /= nSamples[t];
 814 
 815             In[t] = _cmsQuantizeVal(Colorant, nSamples[t]);
 816         }
 817 
 818         if (clut ->Tab.T != NULL) {
 819             for (t=0; t < nOutputs; t++)
 820                 Out[t] = clut->Tab.T[index + t];
 821         }
 822 
 823         if (!Sampler(In, Out, Cargo))
 824             return FALSE;
 825 
 826         if (!(dwFlags & SAMPLER_INSPECT)) {
 827 
 828             if (clut ->Tab.T != NULL) {
 829                 for (t=0; t < nOutputs; t++)
 830                     clut->Tab.T[index + t] = Out[t];
 831             }
 832         }
 833 
 834         index += nOutputs;
 835     }
 836 
 837     return TRUE;
 838 }
 839 
 840 // Same as anterior, but for floting point
 841 cmsBool CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler, void * Cargo, cmsUInt32Number dwFlags)
 842 {
 843     int i, t, nTotalPoints, index, rest;
 844     int nInputs, nOutputs;
 845     cmsUInt32Number* nSamples;
 846     cmsFloat32Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
 847     _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
 848 
 849     nSamples = clut->Params ->nSamples;
 850     nInputs  = clut->Params ->nInputs;
 851     nOutputs = clut->Params ->nOutputs;
 852 
 853     if (nInputs <= 0) return FALSE;
 854     if (nOutputs <= 0) return FALSE;
 855     if (nInputs  > MAX_INPUT_DIMENSIONS) return FALSE;
 856     if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
 857 
 858     nTotalPoints = CubeSize(nSamples, nInputs);
 859     if (nTotalPoints == 0) return FALSE;
 860 
 861     index = 0;
 862     for (i = 0; i < nTotalPoints; i++) {
 863 
 864         rest = i;
 865         for (t = nInputs-1; t >=0; --t) {
 866 
 867             cmsUInt32Number  Colorant = rest % nSamples[t];
 868 
 869             rest /= nSamples[t];
 870 
 871             In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, nSamples[t]) / 65535.0);
 872         }
 873 
 874         if (clut ->Tab.TFloat != NULL) {
 875             for (t=0; t < nOutputs; t++)
 876                 Out[t] = clut->Tab.TFloat[index + t];
 877         }
 878 
 879         if (!Sampler(In, Out, Cargo))
 880             return FALSE;
 881 
 882         if (!(dwFlags & SAMPLER_INSPECT)) {
 883 
 884             if (clut ->Tab.TFloat != NULL) {
 885                 for (t=0; t < nOutputs; t++)
 886                     clut->Tab.TFloat[index + t] = Out[t];
 887             }
 888         }
 889 
 890         index += nOutputs;
 891     }
 892 
 893     return TRUE;
 894 }
 895 
 896 
 897 
 898 // This routine does a sweep on whole input space, and calls its callback
 899 // function on knots. returns TRUE if all ok, FALSE otherwise.
 900 cmsBool CMSEXPORT cmsSliceSpace16(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
 901                                          cmsSAMPLER16 Sampler, void * Cargo)
 902 {
 903     int i, t, nTotalPoints, rest;
 904     cmsUInt16Number In[cmsMAXCHANNELS];
 905 
 906     if (nInputs >= cmsMAXCHANNELS) return FALSE;
 907 
 908     nTotalPoints = CubeSize(clutPoints, nInputs);
 909     if (nTotalPoints == 0) return FALSE;
 910 
 911     for (i = 0; i < nTotalPoints; i++) {
 912 
 913         rest = i;
 914         for (t = nInputs-1; t >=0; --t) {
 915 
 916             cmsUInt32Number  Colorant = rest % clutPoints[t];
 917 
 918             rest /= clutPoints[t];
 919             In[t] = _cmsQuantizeVal(Colorant, clutPoints[t]);
 920 
 921         }
 922 
 923         if (!Sampler(In, NULL, Cargo))
 924             return FALSE;
 925     }
 926 
 927     return TRUE;
 928 }
 929 
 930 cmsInt32Number CMSEXPORT cmsSliceSpaceFloat(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
 931                                             cmsSAMPLERFLOAT Sampler, void * Cargo)
 932 {
 933     int i, t, nTotalPoints, rest;
 934     cmsFloat32Number In[cmsMAXCHANNELS];
 935 
 936     if (nInputs >= cmsMAXCHANNELS) return FALSE;
 937 
 938     nTotalPoints = CubeSize(clutPoints, nInputs);
 939     if (nTotalPoints == 0) return FALSE;
 940 
 941     for (i = 0; i < nTotalPoints; i++) {
 942 
 943         rest = i;
 944         for (t = nInputs-1; t >=0; --t) {
 945 
 946             cmsUInt32Number  Colorant = rest % clutPoints[t];
 947 
 948             rest /= clutPoints[t];
 949             In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, clutPoints[t]) / 65535.0);
 950 
 951         }
 952 
 953         if (!Sampler(In, NULL, Cargo))
 954             return FALSE;
 955     }
 956 
 957     return TRUE;
 958 }
 959 
 960 // ********************************************************************************
 961 // Type cmsSigLab2XYZElemType
 962 // ********************************************************************************
 963 
 964 
 965 static
 966 void EvaluateLab2XYZ(const cmsFloat32Number In[],
 967                      cmsFloat32Number Out[],
 968                      const cmsStage *mpe)
 969 {
 970     cmsCIELab Lab;
 971     cmsCIEXYZ XYZ;
 972     const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
 973 
 974     // V4 rules
 975     Lab.L = In[0] * 100.0;
 976     Lab.a = In[1] * 255.0 - 128.0;
 977     Lab.b = In[2] * 255.0 - 128.0;
 978 
 979     cmsLab2XYZ(NULL, &XYZ, &Lab);
 980 
 981     // From XYZ, range 0..19997 to 0..1.0, note that 1.99997 comes from 0xffff
 982     // encoded as 1.15 fixed point, so 1 + (32767.0 / 32768.0)
 983 
 984     Out[0] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.X / XYZadj);
 985     Out[1] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Y / XYZadj);
 986     Out[2] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Z / XYZadj);
 987 
 988     cmsUNUSED_PARAMETER(mpe);
 989 
 990     return;
 991 
 992 }
 993 
 994 
 995 // No dup or free routines needed, as the structure has no pointers in it.
 996 cmsStage* _cmsStageAllocLab2XYZ(cmsContext ContextID)
 997 {
 998     return _cmsStageAllocPlaceholder(ContextID, cmsSigLab2XYZElemType, 3, 3, EvaluateLab2XYZ, NULL, NULL, NULL);
 999 }
1000 
1001 // ********************************************************************************
1002 
1003 // v2 L=100 is supposed to be placed on 0xFF00. There is no reasonable
1004 // number of gridpoints that would make exact match. However, a prelinearization
1005 // of 258 entries, would map 0xFF00 exactly on entry 257, and this is good to avoid scum dot.
1006 // Almost all what we need but unfortunately, the rest of entries should be scaled by
1007 // (255*257/256) and this is not exact.
1008 
1009 cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID)
1010 {
1011     cmsStage* mpe;
1012     cmsToneCurve* LabTable[3];
1013     int i, j;
1014 
1015     LabTable[0] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
1016     LabTable[1] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
1017     LabTable[2] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
1018 
1019     for (j=0; j < 3; j++) {
1020 
1021         if (LabTable[j] == NULL) {
1022             cmsFreeToneCurveTriple(LabTable);
1023             return NULL;
1024         }
1025 
1026         // We need to map * (0xffff / 0xff00), thats same as (257 / 256)
1027         // So we can use 258-entry tables to do the trick (i / 257) * (255 * 257) * (257 / 256);
1028         for (i=0; i < 257; i++)  {
1029 
1030             LabTable[j]->Table16[i] = (cmsUInt16Number) ((i * 0xffff + 0x80) >> 8);
1031         }
1032 
1033         LabTable[j] ->Table16[257] = 0xffff;
1034     }
1035 
1036     mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
1037     cmsFreeToneCurveTriple(LabTable);
1038 
1039     if (mpe == NULL) return NULL;
1040     mpe ->Implements = cmsSigLabV2toV4;
1041     return mpe;
1042 }
1043 
1044 // ********************************************************************************
1045 
1046 // Matrix-based conversion, which is more accurate, but slower and cannot properly be saved in devicelink profiles
1047 cmsStage* _cmsStageAllocLabV2ToV4(cmsContext ContextID)
1048 {
1049     static const cmsFloat64Number V2ToV4[] = { 65535.0/65280.0, 0, 0,
1050                                      0, 65535.0/65280.0, 0,
1051                                      0, 0, 65535.0/65280.0
1052                                      };
1053 
1054     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V2ToV4, NULL);
1055 
1056     if (mpe == NULL) return mpe;
1057     mpe ->Implements = cmsSigLabV2toV4;
1058     return mpe;
1059 }
1060 
1061 
1062 // Reverse direction
1063 cmsStage* _cmsStageAllocLabV4ToV2(cmsContext ContextID)
1064 {
1065     static const cmsFloat64Number V4ToV2[] = { 65280.0/65535.0, 0, 0,
1066                                      0, 65280.0/65535.0, 0,
1067                                      0, 0, 65280.0/65535.0
1068                                      };
1069 
1070      cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V4ToV2, NULL);
1071 
1072     if (mpe == NULL) return mpe;
1073     mpe ->Implements = cmsSigLabV4toV2;
1074     return mpe;
1075 }
1076 
1077 
1078 // To Lab to float. Note that the MPE gives numbers in normal Lab range
1079 // and we need 0..1.0 range for the formatters
1080 // L* : 0...100 => 0...1.0  (L* / 100)
1081 // ab* : -128..+127 to 0..1  ((ab* + 128) / 255)
1082 
1083 cmsStage* _cmsStageNormalizeFromLabFloat(cmsContext ContextID)
1084 {
1085     static const cmsFloat64Number a1[] = {
1086         1.0/100.0, 0, 0,
1087         0, 1.0/255.0, 0,
1088         0, 0, 1.0/255.0
1089     };
1090 
1091     static const cmsFloat64Number o1[] = {
1092         0,
1093         128.0/255.0,
1094         128.0/255.0
1095     };
1096 
1097     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, a1, o1);
1098 
1099     if (mpe == NULL) return mpe;
1100     mpe ->Implements = cmsSigLab2FloatPCS;
1101     return mpe;
1102 }
1103 
1104 // Fom XYZ to floating point PCS
1105 cmsStage* _cmsStageNormalizeFromXyzFloat(cmsContext ContextID)
1106 {
1107 #define n (32768.0/65535.0)
1108     static const cmsFloat64Number a1[] = {
1109         n, 0, 0,
1110         0, n, 0,
1111         0, 0, n
1112     };
1113 #undef n
1114 
1115     cmsStage *mpe =  cmsStageAllocMatrix(ContextID, 3, 3, a1, NULL);
1116 
1117     if (mpe == NULL) return mpe;
1118     mpe ->Implements = cmsSigXYZ2FloatPCS;
1119     return mpe;
1120 }
1121 
1122 cmsStage* _cmsStageNormalizeToLabFloat(cmsContext ContextID)
1123 {
1124     static const cmsFloat64Number a1[] = {
1125         100.0, 0, 0,
1126         0, 255.0, 0,
1127         0, 0, 255.0
1128     };
1129 
1130     static const cmsFloat64Number o1[] = {
1131         0,
1132         -128.0,
1133         -128.0
1134     };
1135 
1136     cmsStage *mpe =  cmsStageAllocMatrix(ContextID, 3, 3, a1, o1);
1137     if (mpe == NULL) return mpe;
1138     mpe ->Implements = cmsSigFloatPCS2Lab;
1139     return mpe;
1140 }
1141 
1142 cmsStage* _cmsStageNormalizeToXyzFloat(cmsContext ContextID)
1143 {
1144 #define n (65535.0/32768.0)
1145 
1146     static const cmsFloat64Number a1[] = {
1147         n, 0, 0,
1148         0, n, 0,
1149         0, 0, n
1150     };
1151 #undef n
1152 
1153     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, a1, NULL);
1154     if (mpe == NULL) return mpe;
1155     mpe ->Implements = cmsSigFloatPCS2XYZ;
1156     return mpe;
1157 }
1158 
1159 // Clips values smaller than zero
1160 static
1161 void Clipper(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
1162 {
1163        cmsUInt32Number i;
1164        for (i = 0; i < mpe->InputChannels; i++) {
1165 
1166               cmsFloat32Number n = In[i];
1167               Out[i] = n < 0 ? 0 : n;
1168        }
1169 }
1170 
1171 cmsStage*  _cmsStageClipNegatives(cmsContext ContextID, int nChannels)
1172 {
1173        return _cmsStageAllocPlaceholder(ContextID, cmsSigClipNegativesElemType,
1174               nChannels, nChannels, Clipper, NULL, NULL, NULL);
1175 }
1176 
1177 // ********************************************************************************
1178 // Type cmsSigXYZ2LabElemType
1179 // ********************************************************************************
1180 
1181 static
1182 void EvaluateXYZ2Lab(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
1183 {
1184     cmsCIELab Lab;
1185     cmsCIEXYZ XYZ;
1186     const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
1187 
1188     // From 0..1.0 to XYZ
1189 
1190     XYZ.X = In[0] * XYZadj;
1191     XYZ.Y = In[1] * XYZadj;
1192     XYZ.Z = In[2] * XYZadj;
1193 
1194     cmsXYZ2Lab(NULL, &Lab, &XYZ);
1195 
1196     // From V4 Lab to 0..1.0
1197 
1198     Out[0] = (cmsFloat32Number) (Lab.L / 100.0);
1199     Out[1] = (cmsFloat32Number) ((Lab.a + 128.0) / 255.0);
1200     Out[2] = (cmsFloat32Number) ((Lab.b + 128.0) / 255.0);
1201 
1202     cmsUNUSED_PARAMETER(mpe);
1203 
1204     return;
1205 
1206 }
1207 
1208 cmsStage* _cmsStageAllocXYZ2Lab(cmsContext ContextID)
1209 {
1210     return _cmsStageAllocPlaceholder(ContextID, cmsSigXYZ2LabElemType, 3, 3, EvaluateXYZ2Lab, NULL, NULL, NULL);
1211 
1212 }
1213 
1214 // ********************************************************************************
1215 
1216 // For v4, S-Shaped curves are placed in a/b axis to increase resolution near gray
1217 
1218 cmsStage* _cmsStageAllocLabPrelin(cmsContext ContextID)
1219 {
1220     cmsToneCurve* LabTable[3];
1221     cmsFloat64Number Params[1] =  {2.4} ;
1222 
1223     LabTable[0] = cmsBuildGamma(ContextID, 1.0);
1224     LabTable[1] = cmsBuildParametricToneCurve(ContextID, 108, Params);
1225     LabTable[2] = cmsBuildParametricToneCurve(ContextID, 108, Params);
1226 
1227     return cmsStageAllocToneCurves(ContextID, 3, LabTable);
1228 }
1229 
1230 
1231 // Free a single MPE
1232 void CMSEXPORT cmsStageFree(cmsStage* mpe)
1233 {
1234     if (mpe ->FreePtr)
1235         mpe ->FreePtr(mpe);
1236 
1237     _cmsFree(mpe ->ContextID, mpe);
1238 }
1239 
1240 
1241 cmsUInt32Number  CMSEXPORT cmsStageInputChannels(const cmsStage* mpe)
1242 {
1243     return mpe ->InputChannels;
1244 }
1245 
1246 cmsUInt32Number  CMSEXPORT cmsStageOutputChannels(const cmsStage* mpe)
1247 {
1248     return mpe ->OutputChannels;
1249 }
1250 
1251 cmsStageSignature CMSEXPORT cmsStageType(const cmsStage* mpe)
1252 {
1253     return mpe -> Type;
1254 }
1255 
1256 void* CMSEXPORT cmsStageData(const cmsStage* mpe)
1257 {
1258     return mpe -> Data;
1259 }
1260 
1261 cmsStage*  CMSEXPORT cmsStageNext(const cmsStage* mpe)
1262 {
1263     return mpe -> Next;
1264 }
1265 
1266 
1267 // Duplicates an MPE
1268 cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
1269 {
1270     cmsStage* NewMPE;
1271 
1272     if (mpe == NULL) return NULL;
1273     NewMPE = _cmsStageAllocPlaceholder(mpe ->ContextID,
1274                                      mpe ->Type,
1275                                      mpe ->InputChannels,
1276                                      mpe ->OutputChannels,
1277                                      mpe ->EvalPtr,
1278                                      mpe ->DupElemPtr,
1279                                      mpe ->FreePtr,
1280                                      NULL);
1281     if (NewMPE == NULL) return NULL;
1282 
1283     NewMPE ->Implements = mpe ->Implements;
1284 
1285     if (mpe ->DupElemPtr) {
1286 
1287         NewMPE ->Data = mpe ->DupElemPtr(mpe);
1288 
1289         if (NewMPE->Data == NULL) {
1290 
1291             cmsStageFree(NewMPE);
1292             return NULL;
1293         }
1294 
1295     } else {
1296 
1297         NewMPE ->Data       = NULL;
1298     }
1299 
1300     return NewMPE;
1301 }
1302 
1303 
1304 // ***********************************************************************************************************
1305 
1306 // This function sets up the channel count
1307 
1308 static
1309 void BlessLUT(cmsPipeline* lut)
1310 {
1311     // We can set the input/ouput channels only if we have elements.
1312     if (lut ->Elements != NULL) {
1313 
1314         cmsStage *First, *Last;
1315 
1316         First  = cmsPipelineGetPtrToFirstStage(lut);
1317         Last   = cmsPipelineGetPtrToLastStage(lut);
1318 
1319         if (First != NULL)lut ->InputChannels = First ->InputChannels;
1320         if (Last != NULL) lut ->OutputChannels = Last ->OutputChannels;
1321     }
1322 }
1323 
1324 
1325 // Default to evaluate the LUT on 16 bit-basis. Precision is retained.
1326 static
1327 void _LUTeval16(register const cmsUInt16Number In[], register cmsUInt16Number Out[],  register const void* D)
1328 {
1329     cmsPipeline* lut = (cmsPipeline*) D;
1330     cmsStage *mpe;
1331     cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
1332     int Phase = 0, NextPhase;
1333 
1334     From16ToFloat(In, &Storage[Phase][0], lut ->InputChannels);
1335 
1336     for (mpe = lut ->Elements;
1337          mpe != NULL;
1338          mpe = mpe ->Next) {
1339 
1340              NextPhase = Phase ^ 1;
1341              mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
1342              Phase = NextPhase;
1343     }
1344 
1345 
1346     FromFloatTo16(&Storage[Phase][0], Out, lut ->OutputChannels);
1347 }
1348 
1349 
1350 
1351 // Does evaluate the LUT on cmsFloat32Number-basis.
1352 static
1353 void _LUTevalFloat(register const cmsFloat32Number In[], register cmsFloat32Number Out[], const void* D)
1354 {
1355     cmsPipeline* lut = (cmsPipeline*) D;
1356     cmsStage *mpe;
1357     cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
1358     int Phase = 0, NextPhase;
1359 
1360     memmove(&Storage[Phase][0], In, lut ->InputChannels  * sizeof(cmsFloat32Number));
1361 
1362     for (mpe = lut ->Elements;
1363          mpe != NULL;
1364          mpe = mpe ->Next) {
1365 
1366               NextPhase = Phase ^ 1;
1367               mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
1368               Phase = NextPhase;
1369     }
1370 
1371     memmove(Out, &Storage[Phase][0], lut ->OutputChannels * sizeof(cmsFloat32Number));
1372 }
1373 
1374 
1375 
1376 
1377 // LUT Creation & Destruction
1378 
1379 cmsPipeline* CMSEXPORT cmsPipelineAlloc(cmsContext ContextID, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels)
1380 {
1381        cmsPipeline* NewLUT;
1382 
1383        if (InputChannels >= cmsMAXCHANNELS ||
1384            OutputChannels >= cmsMAXCHANNELS) return NULL;
1385 
1386        NewLUT = (cmsPipeline*) _cmsMallocZero(ContextID, sizeof(cmsPipeline));
1387        if (NewLUT == NULL) return NULL;
1388 
1389 
1390        NewLUT -> InputChannels  = InputChannels;
1391        NewLUT -> OutputChannels = OutputChannels;
1392 
1393        NewLUT ->Eval16Fn    = _LUTeval16;
1394        NewLUT ->EvalFloatFn = _LUTevalFloat;
1395        NewLUT ->DupDataFn   = NULL;
1396        NewLUT ->FreeDataFn  = NULL;
1397        NewLUT ->Data        = NewLUT;
1398        NewLUT ->ContextID   = ContextID;
1399 
1400        BlessLUT(NewLUT);
1401 
1402        return NewLUT;
1403 }
1404 
1405 cmsContext CMSEXPORT cmsGetPipelineContextID(const cmsPipeline* lut)
1406 {
1407     _cmsAssert(lut != NULL);
1408     return lut ->ContextID;
1409 }
1410 
1411 cmsUInt32Number CMSEXPORT cmsPipelineInputChannels(const cmsPipeline* lut)
1412 {
1413     _cmsAssert(lut != NULL);
1414     return lut ->InputChannels;
1415 }
1416 
1417 cmsUInt32Number CMSEXPORT cmsPipelineOutputChannels(const cmsPipeline* lut)
1418 {
1419     _cmsAssert(lut != NULL);
1420     return lut ->OutputChannels;
1421 }
1422 
1423 // Free a profile elements LUT
1424 void CMSEXPORT cmsPipelineFree(cmsPipeline* lut)
1425 {
1426     cmsStage *mpe, *Next;
1427 
1428     if (lut == NULL) return;
1429 
1430     for (mpe = lut ->Elements;
1431         mpe != NULL;
1432         mpe = Next) {
1433 
1434             Next = mpe ->Next;
1435             cmsStageFree(mpe);
1436     }
1437 
1438     if (lut ->FreeDataFn) lut ->FreeDataFn(lut ->ContextID, lut ->Data);
1439 
1440     _cmsFree(lut ->ContextID, lut);
1441 }
1442 
1443 
1444 // Default to evaluate the LUT on 16 bit-basis.
1445 void CMSEXPORT cmsPipelineEval16(const cmsUInt16Number In[], cmsUInt16Number Out[],  const cmsPipeline* lut)
1446 {
1447     _cmsAssert(lut != NULL);
1448     lut ->Eval16Fn(In, Out, lut->Data);
1449 }
1450 
1451 
1452 // Does evaluate the LUT on cmsFloat32Number-basis.
1453 void CMSEXPORT cmsPipelineEvalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsPipeline* lut)
1454 {
1455     _cmsAssert(lut != NULL);
1456     lut ->EvalFloatFn(In, Out, lut);
1457 }
1458 
1459 
1460 
1461 // Duplicates a LUT
1462 cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
1463 {
1464     cmsPipeline* NewLUT;
1465     cmsStage *NewMPE, *Anterior = NULL, *mpe;
1466     cmsBool  First = TRUE;
1467 
1468     if (lut == NULL) return NULL;
1469 
1470     NewLUT = cmsPipelineAlloc(lut ->ContextID, lut ->InputChannels, lut ->OutputChannels);
1471     if (NewLUT == NULL) return NULL;
1472 
1473     for (mpe = lut ->Elements;
1474          mpe != NULL;
1475          mpe = mpe ->Next) {
1476 
1477              NewMPE = cmsStageDup(mpe);
1478 
1479              if (NewMPE == NULL) {
1480                  cmsPipelineFree(NewLUT);
1481                  return NULL;
1482              }
1483 
1484              if (First) {
1485                  NewLUT ->Elements = NewMPE;
1486                  First = FALSE;
1487              }
1488              else {
1489                 Anterior ->Next = NewMPE;
1490              }
1491 
1492             Anterior = NewMPE;
1493     }
1494 
1495     NewLUT ->Eval16Fn    = lut ->Eval16Fn;
1496     NewLUT ->EvalFloatFn = lut ->EvalFloatFn;
1497     NewLUT ->DupDataFn   = lut ->DupDataFn;
1498     NewLUT ->FreeDataFn  = lut ->FreeDataFn;
1499 
1500     if (NewLUT ->DupDataFn != NULL)
1501         NewLUT ->Data = NewLUT ->DupDataFn(lut ->ContextID, lut->Data);
1502 
1503 
1504     NewLUT ->SaveAs8Bits    = lut ->SaveAs8Bits;
1505 
1506     BlessLUT(NewLUT);
1507     return NewLUT;
1508 }
1509 
1510 
1511 int CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
1512 {
1513     cmsStage* Anterior = NULL, *pt;
1514 
1515     if (lut == NULL || mpe == NULL)
1516         return FALSE;
1517 
1518     switch (loc) {
1519 
1520         case cmsAT_BEGIN:
1521             mpe ->Next = lut ->Elements;
1522             lut ->Elements = mpe;
1523             break;
1524 
1525         case cmsAT_END:
1526 
1527             if (lut ->Elements == NULL)
1528                 lut ->Elements = mpe;
1529             else {
1530 
1531                 for (pt = lut ->Elements;
1532                      pt != NULL;
1533                      pt = pt -> Next) Anterior = pt;
1534 
1535                 Anterior ->Next = mpe;
1536                 mpe ->Next = NULL;
1537             }
1538             break;
1539         default:;
1540             return FALSE;
1541     }
1542 
1543     BlessLUT(lut);
1544     return TRUE;
1545 }
1546 
1547 // Unlink an element and return the pointer to it
1548 void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe)
1549 {
1550     cmsStage *Anterior, *pt, *Last;
1551     cmsStage *Unlinked = NULL;
1552 
1553 
1554     // If empty LUT, there is nothing to remove
1555     if (lut ->Elements == NULL) {
1556         if (mpe) *mpe = NULL;
1557         return;
1558     }
1559 
1560     // On depending on the strategy...
1561     switch (loc) {
1562 
1563         case cmsAT_BEGIN:
1564             {
1565                 cmsStage* elem = lut ->Elements;
1566 
1567                 lut ->Elements = elem -> Next;
1568                 elem ->Next = NULL;
1569                 Unlinked = elem;
1570 
1571             }
1572             break;
1573 
1574         case cmsAT_END:
1575             Anterior = Last = NULL;
1576             for (pt = lut ->Elements;
1577                 pt != NULL;
1578                 pt = pt -> Next) {
1579                     Anterior = Last;
1580                     Last = pt;
1581             }
1582 
1583             Unlinked = Last;  // Next already points to NULL
1584 
1585             // Truncate the chain
1586             if (Anterior)
1587                 Anterior ->Next = NULL;
1588             else
1589                 lut ->Elements = NULL;
1590             break;
1591         default:;
1592     }
1593 
1594     if (mpe)
1595         *mpe = Unlinked;
1596     else
1597         cmsStageFree(Unlinked);
1598 
1599     BlessLUT(lut);
1600 }
1601 
1602 
1603 // Concatenate two LUT into a new single one
1604 cmsBool  CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
1605 {
1606     cmsStage* mpe;
1607 
1608     // If both LUTS does not have elements, we need to inherit
1609     // the number of channels
1610     if (l1 ->Elements == NULL && l2 ->Elements == NULL) {
1611         l1 ->InputChannels  = l2 ->InputChannels;
1612         l1 ->OutputChannels = l2 ->OutputChannels;
1613     }
1614 
1615     // Cat second
1616     for (mpe = l2 ->Elements;
1617          mpe != NULL;
1618          mpe = mpe ->Next) {
1619 
1620             // We have to dup each element
1621             if (!cmsPipelineInsertStage(l1, cmsAT_END, cmsStageDup(mpe)))
1622                 return FALSE;
1623     }
1624 
1625     BlessLUT(l1);
1626     return TRUE;
1627 }
1628 
1629 
1630 cmsBool CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lut, cmsBool On)
1631 {
1632     cmsBool Anterior = lut ->SaveAs8Bits;
1633 
1634     lut ->SaveAs8Bits = On;
1635     return Anterior;
1636 }
1637 
1638 
1639 cmsStage* CMSEXPORT cmsPipelineGetPtrToFirstStage(const cmsPipeline* lut)
1640 {
1641     return lut ->Elements;
1642 }
1643 
1644 cmsStage* CMSEXPORT cmsPipelineGetPtrToLastStage(const cmsPipeline* lut)
1645 {
1646     cmsStage *mpe, *Anterior = NULL;
1647 
1648     for (mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
1649         Anterior = mpe;
1650 
1651     return Anterior;
1652 }
1653 
1654 cmsUInt32Number CMSEXPORT cmsPipelineStageCount(const cmsPipeline* lut)
1655 {
1656     cmsStage *mpe;
1657     cmsUInt32Number n;
1658 
1659     for (n=0, mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
1660             n++;
1661 
1662     return n;
1663 }
1664 
1665 // This function may be used to set the optional evaluator and a block of private data. If private data is being used, an optional
1666 // duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality.
1667 void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut,
1668                                         _cmsOPTeval16Fn Eval16,
1669                                         void* PrivateData,
1670                                         _cmsFreeUserDataFn FreePrivateDataFn,
1671                                         _cmsDupUserDataFn  DupPrivateDataFn)
1672 {
1673 
1674     Lut ->Eval16Fn = Eval16;
1675     Lut ->DupDataFn = DupPrivateDataFn;
1676     Lut ->FreeDataFn = FreePrivateDataFn;
1677     Lut ->Data = PrivateData;
1678 }
1679 
1680 
1681 // ----------------------------------------------------------- Reverse interpolation
1682 // Here's how it goes. The derivative Df(x) of the function f is the linear
1683 // transformation that best approximates f near the point x. It can be represented
1684 // by a matrix A whose entries are the partial derivatives of the components of f
1685 // with respect to all the coordinates. This is know as the Jacobian
1686 //
1687 // The best linear approximation to f is given by the matrix equation:
1688 //
1689 // y-y0 = A (x-x0)
1690 //
1691 // So, if x0 is a good "guess" for the zero of f, then solving for the zero of this
1692 // linear approximation will give a "better guess" for the zero of f. Thus let y=0,
1693 // and since y0=f(x0) one can solve the above equation for x. This leads to the
1694 // Newton's method formula:
1695 //
1696 // xn+1 = xn - A-1 f(xn)
1697 //
1698 // where xn+1 denotes the (n+1)-st guess, obtained from the n-th guess xn in the
1699 // fashion described above. Iterating this will give better and better approximations
1700 // if you have a "good enough" initial guess.
1701 
1702 
1703 #define JACOBIAN_EPSILON            0.001f
1704 #define INVERSION_MAX_ITERATIONS    30
1705 
1706 // Increment with reflexion on boundary
1707 static
1708 void IncDelta(cmsFloat32Number *Val)
1709 {
1710     if (*Val < (1.0 - JACOBIAN_EPSILON))
1711 
1712         *Val += JACOBIAN_EPSILON;
1713 
1714     else
1715         *Val -= JACOBIAN_EPSILON;
1716 
1717 }
1718 
1719 
1720 
1721 // Euclidean distance between two vectors of n elements each one
1722 static
1723 cmsFloat32Number EuclideanDistance(cmsFloat32Number a[], cmsFloat32Number b[], int n)
1724 {
1725     cmsFloat32Number sum = 0;
1726     int i;
1727 
1728     for (i=0; i < n; i++) {
1729         cmsFloat32Number dif = b[i] - a[i];
1730         sum +=  dif * dif;
1731     }
1732 
1733     return sqrtf(sum);
1734 }
1735 
1736 
1737 // Evaluate a LUT in reverse direction. It only searches on 3->3 LUT. Uses Newton method
1738 //
1739 // x1 <- x - [J(x)]^-1 * f(x)
1740 //
1741 // lut: The LUT on where to do the search
1742 // Target: LabK, 3 values of Lab plus destination K which is fixed
1743 // Result: The obtained CMYK
1744 // Hint:   Location where begin the search
1745 
1746 cmsBool CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],
1747                                               cmsFloat32Number Result[],
1748                                               cmsFloat32Number Hint[],
1749                                               const cmsPipeline* lut)
1750 {
1751     cmsUInt32Number  i, j;
1752     cmsFloat64Number  error, LastError = 1E20;
1753     cmsFloat32Number  fx[4], x[4], xd[4], fxd[4];
1754     cmsVEC3 tmp, tmp2;
1755     cmsMAT3 Jacobian;
1756 
1757     // Only 3->3 and 4->3 are supported
1758     if (lut ->InputChannels != 3 && lut ->InputChannels != 4) return FALSE;
1759     if (lut ->OutputChannels != 3) return FALSE;
1760 
1761     // Take the hint as starting point if specified
1762     if (Hint == NULL) {
1763 
1764         // Begin at any point, we choose 1/3 of CMY axis
1765         x[0] = x[1] = x[2] = 0.3f;
1766     }
1767     else {
1768 
1769         // Only copy 3 channels from hint...
1770         for (j=0; j < 3; j++)
1771             x[j] = Hint[j];
1772     }
1773 
1774     // If Lut is 4-dimensions, then grab target[3], which is fixed
1775     if (lut ->InputChannels == 4) {
1776         x[3] = Target[3];
1777     }
1778     else x[3] = 0; // To keep lint happy
1779 
1780 
1781     // Iterate
1782     for (i = 0; i < INVERSION_MAX_ITERATIONS; i++) {
1783 
1784         // Get beginning fx
1785         cmsPipelineEvalFloat(x, fx, lut);
1786 
1787         // Compute error
1788         error = EuclideanDistance(fx, Target, 3);
1789 
1790         // If not convergent, return last safe value
1791         if (error >= LastError)
1792             break;
1793 
1794         // Keep latest values
1795         LastError     = error;
1796         for (j=0; j < lut ->InputChannels; j++)
1797                 Result[j] = x[j];
1798 
1799         // Found an exact match?
1800         if (error <= 0)
1801             break;
1802 
1803         // Obtain slope (the Jacobian)
1804         for (j = 0; j < 3; j++) {
1805 
1806             xd[0] = x[0];
1807             xd[1] = x[1];
1808             xd[2] = x[2];
1809             xd[3] = x[3];  // Keep fixed channel
1810 
1811             IncDelta(&xd[j]);
1812 
1813             cmsPipelineEvalFloat(xd, fxd, lut);
1814 
1815             Jacobian.v[0].n[j] = ((fxd[0] - fx[0]) / JACOBIAN_EPSILON);
1816             Jacobian.v[1].n[j] = ((fxd[1] - fx[1]) / JACOBIAN_EPSILON);
1817             Jacobian.v[2].n[j] = ((fxd[2] - fx[2]) / JACOBIAN_EPSILON);
1818         }
1819 
1820         // Solve system
1821         tmp2.n[0] = fx[0] - Target[0];
1822         tmp2.n[1] = fx[1] - Target[1];
1823         tmp2.n[2] = fx[2] - Target[2];
1824 
1825         if (!_cmsMAT3solve(&tmp, &Jacobian, &tmp2))
1826             return FALSE;
1827 
1828         // Move our guess
1829         x[0] -= (cmsFloat32Number) tmp.n[0];
1830         x[1] -= (cmsFloat32Number) tmp.n[1];
1831         x[2] -= (cmsFloat32Number) tmp.n[2];
1832 
1833         // Some clipping....
1834         for (j=0; j < 3; j++) {
1835             if (x[j] < 0) x[j] = 0;
1836             else
1837                 if (x[j] > 1.0) x[j] = 1.0;
1838         }
1839     }
1840 
1841     return TRUE;
1842 }