cmslut.c 52.5 KB
Newer Older
D
duke 已提交
1 2 3 4 5
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
6
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
7
 * particular file as subject to the "Classpath" exception as provided
8
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
9 10 11 12 13 14 15 16 17 18 19
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
20 21 22
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
23 24 25 26 27 28 29
 */

// This file is available under and governed by the GNU General Public
// License version 2 only, as published by the Free Software Foundation.
// However, the following notice accompanied the original version of this
// file:
//
30
//---------------------------------------------------------------------------------
D
duke 已提交
31
//
32
//  Little Color Management System
P
prr 已提交
33
//  Copyright (c) 1998-2017 Marti Maria Saguer
D
duke 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
53
//---------------------------------------------------------------------------------
D
duke 已提交
54 55
//

56
#include "lcms2_internal.h"
D
duke 已提交
57 58


59 60 61 62 63 64 65 66 67 68 69 70 71
// Allocates an empty multi profile element
cmsStage* CMSEXPORT _cmsStageAllocPlaceholder(cmsContext ContextID,
                                cmsStageSignature Type,
                                cmsUInt32Number InputChannels,
                                cmsUInt32Number OutputChannels,
                                _cmsStageEvalFn     EvalPtr,
                                _cmsStageDupElemFn  DupElemPtr,
                                _cmsStageFreeElemFn FreePtr,
                                void*             Data)
{
    cmsStage* ph = (cmsStage*) _cmsMallocZero(ContextID, sizeof(cmsStage));

    if (ph == NULL) return NULL;
D
duke 已提交
72 73


74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
    ph ->ContextID = ContextID;

    ph ->Type       = Type;
    ph ->Implements = Type;   // By default, no clue on what is implementing

    ph ->InputChannels  = InputChannels;
    ph ->OutputChannels = OutputChannels;
    ph ->EvalPtr        = EvalPtr;
    ph ->DupElemPtr     = DupElemPtr;
    ph ->FreePtr        = FreePtr;
    ph ->Data           = Data;

    return ph;
}


static
void EvaluateIdentity(const cmsFloat32Number In[],
                            cmsFloat32Number Out[],
                      const cmsStage *mpe)
D
duke 已提交
94
{
95 96
    memmove(Out, In, mpe ->InputChannels * sizeof(cmsFloat32Number));
}
D
duke 已提交
97 98


99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
cmsStage* CMSEXPORT cmsStageAllocIdentity(cmsContext ContextID, cmsUInt32Number nChannels)
{
    return _cmsStageAllocPlaceholder(ContextID,
                                   cmsSigIdentityElemType,
                                   nChannels, nChannels,
                                   EvaluateIdentity,
                                   NULL,
                                   NULL,
                                   NULL);
 }

// Conversion functions. From floating point to 16 bits
static
void FromFloatTo16(const cmsFloat32Number In[], cmsUInt16Number Out[], cmsUInt32Number n)
{
    cmsUInt32Number i;

    for (i=0; i < n; i++) {
        Out[i] = _cmsQuickSaturateWord(In[i] * 65535.0);
    }
D
duke 已提交
119 120
}

121 122 123
// From 16 bits to floating point
static
void From16ToFloat(const cmsUInt16Number In[], cmsFloat32Number Out[], cmsUInt32Number n)
D
duke 已提交
124
{
125
    cmsUInt32Number i;
D
duke 已提交
126

127 128 129 130
    for (i=0; i < n; i++) {
        Out[i] = (cmsFloat32Number) In[i] / 65535.0F;
    }
}
D
duke 已提交
131 132


133 134 135 136 137 138 139 140 141 142 143 144 145
// This function is quite useful to analyze the structure of a LUT and retrieve the MPE elements
// that conform the LUT. It should be called with the LUT, the number of expected elements and
// then a list of expected types followed with a list of cmsFloat64Number pointers to MPE elements. If
// the function founds a match with current pipeline, it fills the pointers and returns TRUE
// if not, returns FALSE without touching anything. Setting pointers to NULL does bypass
// the storage process.
cmsBool  CMSEXPORT cmsPipelineCheckAndRetreiveStages(const cmsPipeline* Lut, cmsUInt32Number n, ...)
{
    va_list args;
    cmsUInt32Number i;
    cmsStage* mpe;
    cmsStageSignature Type;
    void** ElemPtr;
D
duke 已提交
146

147 148
    // Make sure same number of elements
    if (cmsPipelineStageCount(Lut) != n) return FALSE;
D
duke 已提交
149

150
    va_start(args, n);
D
duke 已提交
151

152 153 154
    // Iterate across asked types
    mpe = Lut ->Elements;
    for (i=0; i < n; i++) {
D
duke 已提交
155

P
prr 已提交
156 157
        // Get asked type. cmsStageSignature is promoted to int by compiler
        Type  = (cmsStageSignature)va_arg(args, int);
158
        if (mpe ->Type != Type) {
D
duke 已提交
159

160 161 162 163 164
            va_end(args);       // Mismatch. We are done.
            return FALSE;
        }
        mpe = mpe ->Next;
    }
D
duke 已提交
165

166 167 168
    // Found a combination, fill pointers if not NULL
    mpe = Lut ->Elements;
    for (i=0; i < n; i++) {
D
duke 已提交
169

170 171 172
        ElemPtr = va_arg(args, void**);
        if (ElemPtr != NULL)
            *ElemPtr = mpe;
D
duke 已提交
173

174 175
        mpe = mpe ->Next;
    }
D
duke 已提交
176

177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    va_end(args);
    return TRUE;
}

// Below there are implementations for several types of elements. Each type may be implemented by a
// evaluation function, a duplication function, a function to free resources and a constructor.

// *************************************************************************************************
// Type cmsSigCurveSetElemType (curves)
// *************************************************************************************************

cmsToneCurve** _cmsStageGetPtrToCurveSet(const cmsStage* mpe)
{
    _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;

    return Data ->TheCurves;
}

static
void EvaluateCurves(const cmsFloat32Number In[],
                    cmsFloat32Number Out[],
                    const cmsStage *mpe)
{
B
bae 已提交
200
    _cmsStageToneCurvesData* Data;
201 202
    cmsUInt32Number i;

B
bae 已提交
203 204 205 206 207
    _cmsAssert(mpe != NULL);

    Data = (_cmsStageToneCurvesData*) mpe ->Data;
    if (Data == NULL) return;

208 209 210 211 212 213
    if (Data ->TheCurves == NULL) return;

    for (i=0; i < Data ->nCurves; i++) {
        Out[i] = cmsEvalToneCurveFloat(Data ->TheCurves[i], In[i]);
    }
}
D
duke 已提交
214

215 216 217
static
void CurveSetElemTypeFree(cmsStage* mpe)
{
B
bae 已提交
218
    _cmsStageToneCurvesData* Data;
219
    cmsUInt32Number i;
D
duke 已提交
220

B
bae 已提交
221 222 223 224 225
    _cmsAssert(mpe != NULL);

    Data = (_cmsStageToneCurvesData*) mpe ->Data;
    if (Data == NULL) return;

226 227 228 229 230 231 232 233
    if (Data ->TheCurves != NULL) {
        for (i=0; i < Data ->nCurves; i++) {
            if (Data ->TheCurves[i] != NULL)
                cmsFreeToneCurve(Data ->TheCurves[i]);
        }
    }
    _cmsFree(mpe ->ContextID, Data ->TheCurves);
    _cmsFree(mpe ->ContextID, Data);
D
duke 已提交
234 235 236 237
}


static
238
void* CurveSetDup(cmsStage* mpe)
D
duke 已提交
239
{
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
    _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) mpe ->Data;
    _cmsStageToneCurvesData* NewElem;
    cmsUInt32Number i;

    NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageToneCurvesData));
    if (NewElem == NULL) return NULL;

    NewElem ->nCurves   = Data ->nCurves;
    NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(mpe ->ContextID, NewElem ->nCurves, sizeof(cmsToneCurve*));

    if (NewElem ->TheCurves == NULL) goto Error;

    for (i=0; i < NewElem ->nCurves; i++) {

        // Duplicate each curve. It may fail.
        NewElem ->TheCurves[i] = cmsDupToneCurve(Data ->TheCurves[i]);
        if (NewElem ->TheCurves[i] == NULL) goto Error;


    }
    return (void*) NewElem;

Error:
D
duke 已提交
263

264 265 266
    if (NewElem ->TheCurves != NULL) {
        for (i=0; i < NewElem ->nCurves; i++) {
            if (NewElem ->TheCurves[i])
P
prr 已提交
267
                cmsFreeToneCurve(NewElem ->TheCurves[i]);
268 269
        }
    }
P
prr 已提交
270
    _cmsFree(mpe ->ContextID, NewElem ->TheCurves);
271 272
    _cmsFree(mpe ->ContextID, NewElem);
    return NULL;
D
duke 已提交
273 274 275
}


276 277
// Curves == NULL forces identity curves
cmsStage* CMSEXPORT cmsStageAllocToneCurves(cmsContext ContextID, cmsUInt32Number nChannels, cmsToneCurve* const Curves[])
D
duke 已提交
278
{
279 280 281
    cmsUInt32Number i;
    _cmsStageToneCurvesData* NewElem;
    cmsStage* NewMPE;
D
duke 已提交
282 283


284 285 286 287
    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCurveSetElemType, nChannels, nChannels,
                                     EvaluateCurves, CurveSetDup, CurveSetElemTypeFree, NULL );
    if (NewMPE == NULL) return NULL;

B
bae 已提交
288
    NewElem = (_cmsStageToneCurvesData*) _cmsMallocZero(ContextID, sizeof(_cmsStageToneCurvesData));
289 290 291 292
    if (NewElem == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }
D
duke 已提交
293

B
bae 已提交
294 295
    NewMPE ->Data  = (void*) NewElem;

296 297 298 299 300 301
    NewElem ->nCurves   = nChannels;
    NewElem ->TheCurves = (cmsToneCurve**) _cmsCalloc(ContextID, nChannels, sizeof(cmsToneCurve*));
    if (NewElem ->TheCurves == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }
D
duke 已提交
302

303
    for (i=0; i < nChannels; i++) {
D
duke 已提交
304

305 306 307 308 309 310 311 312 313 314 315 316
        if (Curves == NULL) {
            NewElem ->TheCurves[i] = cmsBuildGamma(ContextID, 1.0);
        }
        else {
            NewElem ->TheCurves[i] = cmsDupToneCurve(Curves[i]);
        }

        if (NewElem ->TheCurves[i] == NULL) {
            cmsStageFree(NewMPE);
            return NULL;
        }

B
bae 已提交
317
    }
318

B
bae 已提交
319
   return NewMPE;
D
duke 已提交
320 321 322
}


323
// Create a bunch of identity curves
P
prr 已提交
324
cmsStage* CMSEXPORT _cmsStageAllocIdentityCurves(cmsContext ContextID, cmsUInt32Number nChannels)
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
{
    cmsStage* mpe = cmsStageAllocToneCurves(ContextID, nChannels, NULL);

    if (mpe == NULL) return NULL;
    mpe ->Implements = cmsSigIdentityElemType;
    return mpe;
}


// *************************************************************************************************
// Type cmsSigMatrixElemType (Matrices)
// *************************************************************************************************


// Special care should be taken here because precision loss. A temporary cmsFloat64Number buffer is being used
D
duke 已提交
340
static
341 342 343
void EvaluateMatrix(const cmsFloat32Number In[],
                    cmsFloat32Number Out[],
                    const cmsStage *mpe)
D
duke 已提交
344
{
345 346 347 348 349 350 351 352 353 354 355
    cmsUInt32Number i, j;
    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
    cmsFloat64Number Tmp;

    // Input is already in 0..1.0 notation
    for (i=0; i < mpe ->OutputChannels; i++) {

        Tmp = 0;
        for (j=0; j < mpe->InputChannels; j++) {
            Tmp += In[j] * Data->Double[i*mpe->InputChannels + j];
        }
D
duke 已提交
356

357 358
        if (Data ->Offset != NULL)
            Tmp += Data->Offset[i];
D
duke 已提交
359

360 361 362 363 364
        Out[i] = (cmsFloat32Number) Tmp;
    }


    // Output in 0..1.0 domain
D
duke 已提交
365 366 367
}


368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
// Duplicate a yet-existing matrix element
static
void* MatrixElemDup(cmsStage* mpe)
{
    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
    _cmsStageMatrixData* NewElem;
    cmsUInt32Number sz;

    NewElem = (_cmsStageMatrixData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageMatrixData));
    if (NewElem == NULL) return NULL;

    sz = mpe ->InputChannels * mpe ->OutputChannels;

    NewElem ->Double = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID, Data ->Double, sz * sizeof(cmsFloat64Number)) ;

    if (Data ->Offset)
        NewElem ->Offset = (cmsFloat64Number*) _cmsDupMem(mpe ->ContextID,
                                                Data ->Offset, mpe -> OutputChannels * sizeof(cmsFloat64Number)) ;

    return (void*) NewElem;
}


static
void MatrixElemTypeFree(cmsStage* mpe)
{
    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
P
prr 已提交
395 396
    if (Data == NULL)
        return;
397 398 399 400 401 402 403 404 405 406 407 408 409
    if (Data ->Double)
        _cmsFree(mpe ->ContextID, Data ->Double);

    if (Data ->Offset)
        _cmsFree(mpe ->ContextID, Data ->Offset);

    _cmsFree(mpe ->ContextID, mpe ->Data);
}



cmsStage*  CMSEXPORT cmsStageAllocMatrix(cmsContext ContextID, cmsUInt32Number Rows, cmsUInt32Number Cols,
                                     const cmsFloat64Number* Matrix, const cmsFloat64Number* Offset)
410
{
411 412 413
    cmsUInt32Number i, n;
    _cmsStageMatrixData* NewElem;
    cmsStage* NewMPE;
414

415
    n = Rows * Cols;
416

417
    // Check for overflow
B
bae 已提交
418 419 420
    if (n == 0) return NULL;
    if (n >= UINT_MAX / Cols) return NULL;
    if (n >= UINT_MAX / Rows) return NULL;
421
    if (n < Rows || n < Cols) return NULL;
422

423 424 425
    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigMatrixElemType, Cols, Rows,
                                     EvaluateMatrix, MatrixElemDup, MatrixElemTypeFree, NULL );
    if (NewMPE == NULL) return NULL;
426 427


428 429 430 431 432 433 434 435 436
    NewElem = (_cmsStageMatrixData*) _cmsMallocZero(ContextID, sizeof(_cmsStageMatrixData));
    if (NewElem == NULL) return NULL;


    NewElem ->Double = (cmsFloat64Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat64Number));

    if (NewElem->Double == NULL) {
        MatrixElemTypeFree(NewMPE);
        return NULL;
437 438
    }

439 440
    for (i=0; i < n; i++) {
        NewElem ->Double[i] = Matrix[i];
441 442
    }

443 444 445

    if (Offset != NULL) {

P
prr 已提交
446
        NewElem ->Offset = (cmsFloat64Number*) _cmsCalloc(ContextID, Rows, sizeof(cmsFloat64Number));
447 448 449 450 451
        if (NewElem->Offset == NULL) {
           MatrixElemTypeFree(NewMPE);
           return NULL;
        }

P
prr 已提交
452
        for (i=0; i < Rows; i++) {
453 454 455 456 457 458 459
                NewElem ->Offset[i] = Offset[i];
        }

    }

    NewMPE ->Data  = (void*) NewElem;
    return NewMPE;
460 461
}

D
duke 已提交
462

463 464 465
// *************************************************************************************************
// Type cmsSigCLutElemType
// *************************************************************************************************
D
duke 已提交
466

467

468 469 470 471 472
// Evaluate in true floating point
static
void EvaluateCLUTfloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
{
    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
D
duke 已提交
473

474 475
    Data -> Params ->Interpolation.LerpFloat(In, Out, Data->Params);
}
D
duke 已提交
476 477


478 479 480 481 482 483
// Convert to 16 bits, evaluate, and back to floating point
static
void EvaluateCLUTfloatIn16(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
{
    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
    cmsUInt16Number In16[MAX_STAGE_CHANNELS], Out16[MAX_STAGE_CHANNELS];
D
duke 已提交
484

485 486
    _cmsAssert(mpe ->InputChannels  <= MAX_STAGE_CHANNELS);
    _cmsAssert(mpe ->OutputChannels <= MAX_STAGE_CHANNELS);
D
duke 已提交
487

488 489 490
    FromFloatTo16(In, In16, mpe ->InputChannels);
    Data -> Params ->Interpolation.Lerp16(In16, Out16, Data->Params);
    From16ToFloat(Out16, Out,  mpe ->OutputChannels);
D
duke 已提交
491 492 493
}


494 495 496 497
// Given an hypercube of b dimensions, with Dims[] number of nodes by dimension, calculate the total amount of nodes
static
cmsUInt32Number CubeSize(const cmsUInt32Number Dims[], cmsUInt32Number b)
{
B
bae 已提交
498 499 500 501 502
    cmsUInt32Number rv, dim;

    _cmsAssert(Dims != NULL);

    for (rv = 1; b > 0; b--) {
D
duke 已提交
503

B
bae 已提交
504 505 506 507 508 509 510 511
        dim = Dims[b-1];
        if (dim == 0) return 0;  // Error

        rv *= dim;

        // Check for overflow
        if (rv > UINT_MAX / dim) return 0;
    }
512 513 514

    return rv;
}
D
duke 已提交
515

516 517
static
void* CLUTElemDup(cmsStage* mpe)
D
duke 已提交
518
{
519 520
    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
    _cmsStageCLutData* NewElem;
D
duke 已提交
521 522


523 524
    NewElem = (_cmsStageCLutData*) _cmsMallocZero(mpe ->ContextID, sizeof(_cmsStageCLutData));
    if (NewElem == NULL) return NULL;
D
duke 已提交
525

526 527
    NewElem ->nEntries       = Data ->nEntries;
    NewElem ->HasFloatValues = Data ->HasFloatValues;
D
duke 已提交
528

529
    if (Data ->Tab.T) {
D
duke 已提交
530

P
prr 已提交
531
        if (Data ->HasFloatValues) {
532
            NewElem ->Tab.TFloat = (cmsFloat32Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.TFloat, Data ->nEntries * sizeof (cmsFloat32Number));
P
prr 已提交
533 534 535
            if (NewElem ->Tab.TFloat == NULL)
                goto Error;
        } else {
536
            NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
537
            if (NewElem ->Tab.T == NULL)
P
prr 已提交
538 539
                goto Error;
        }
540
    }
541

542 543 544 545 546 547
    NewElem ->Params   = _cmsComputeInterpParamsEx(mpe ->ContextID,
                                                   Data ->Params ->nSamples,
                                                   Data ->Params ->nInputs,
                                                   Data ->Params ->nOutputs,
                                                   NewElem ->Tab.T,
                                                   Data ->Params ->dwFlags);
P
prr 已提交
548 549 550 551 552 553 554 555
    if (NewElem->Params != NULL)
        return (void*) NewElem;
 Error:
    if (NewElem->Tab.T)
        // This works for both types
        _cmsFree(mpe ->ContextID, NewElem -> Tab.T);
    _cmsFree(mpe ->ContextID, NewElem);
    return NULL;
556
}
D
duke 已提交
557 558


559 560 561
static
void CLutElemTypeFree(cmsStage* mpe)
{
D
duke 已提交
562

563
    _cmsStageCLutData* Data = (_cmsStageCLutData*) mpe ->Data;
564

565 566
    // Already empty
    if (Data == NULL) return;
D
duke 已提交
567

568 569 570
    // This works for both types
    if (Data -> Tab.T)
        _cmsFree(mpe ->ContextID, Data -> Tab.T);
D
duke 已提交
571

572 573 574
    _cmsFreeInterpParams(Data ->Params);
    _cmsFree(mpe ->ContextID, mpe ->Data);
}
D
duke 已提交
575 576


577 578 579 580 581 582 583 584 585 586 587
// Allocates a 16-bit multidimensional CLUT. This is evaluated at 16-bit precision. Table may have different
// granularity on each dimension.
cmsStage* CMSEXPORT cmsStageAllocCLut16bitGranular(cmsContext ContextID,
                                         const cmsUInt32Number clutPoints[],
                                         cmsUInt32Number inputChan,
                                         cmsUInt32Number outputChan,
                                         const cmsUInt16Number* Table)
{
    cmsUInt32Number i, n;
    _cmsStageCLutData* NewElem;
    cmsStage* NewMPE;
D
duke 已提交
588

B
bae 已提交
589 590 591 592 593 594 595
    _cmsAssert(clutPoints != NULL);

    if (inputChan > MAX_INPUT_DIMENSIONS) {
        cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", inputChan, MAX_INPUT_DIMENSIONS);
        return NULL;
    }

596 597
    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
                                     EvaluateCLUTfloatIn16, CLUTElemDup, CLutElemTypeFree, NULL );
598

599
    if (NewMPE == NULL) return NULL;
D
duke 已提交
600

B
bae 已提交
601 602 603 604 605 606 607
    NewElem = (_cmsStageCLutData*) _cmsMallocZero(ContextID, sizeof(_cmsStageCLutData));
    if (NewElem == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }

    NewMPE ->Data  = (void*) NewElem;
D
duke 已提交
608

609 610
    NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
    NewElem -> HasFloatValues = FALSE;
611

B
bae 已提交
612 613 614 615 616 617
    if (n == 0) {
        cmsStageFree(NewMPE);
        return NULL;
    }


618 619 620 621 622 623 624 625 626 627 628
    NewElem ->Tab.T  = (cmsUInt16Number*) _cmsCalloc(ContextID, n, sizeof(cmsUInt16Number));
    if (NewElem ->Tab.T == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }

    if (Table != NULL) {
        for (i=0; i < n; i++) {
            NewElem ->Tab.T[i] = Table[i];
        }
    }
D
duke 已提交
629

630 631 632 633 634
    NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints, inputChan, outputChan, NewElem ->Tab.T, CMS_LERP_FLAGS_16BITS);
    if (NewElem ->Params == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }
D
duke 已提交
635

636
    return NewMPE;
D
duke 已提交
637 638
}

639 640 641 642 643 644 645 646 647 648 649 650
cmsStage* CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID,
                                    cmsUInt32Number nGridPoints,
                                    cmsUInt32Number inputChan,
                                    cmsUInt32Number outputChan,
                                    const cmsUInt16Number* Table)
{
    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
    int i;

   // Our resulting LUT would be same gridpoints on all dimensions
    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
        Dimensions[i] = nGridPoints;
D
duke 已提交
651

652 653 654 655 656 657 658 659 660
    return cmsStageAllocCLut16bitGranular(ContextID, Dimensions, inputChan, outputChan, Table);
}


cmsStage* CMSEXPORT cmsStageAllocCLutFloat(cmsContext ContextID,
                                       cmsUInt32Number nGridPoints,
                                       cmsUInt32Number inputChan,
                                       cmsUInt32Number outputChan,
                                       const cmsFloat32Number* Table)
D
duke 已提交
661
{
662 663
   cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
   int i;
D
duke 已提交
664

665 666 667
    // Our resulting LUT would be same gridpoints on all dimensions
    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
        Dimensions[i] = nGridPoints;
D
duke 已提交
668

669
    return cmsStageAllocCLutFloatGranular(ContextID, Dimensions, inputChan, outputChan, Table);
D
duke 已提交
670 671 672 673
}



674
cmsStage* CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const cmsUInt32Number clutPoints[], cmsUInt32Number inputChan, cmsUInt32Number outputChan, const cmsFloat32Number* Table)
D
duke 已提交
675
{
676 677
    cmsUInt32Number i, n;
    _cmsStageCLutData* NewElem;
B
bae 已提交
678 679 680 681 682 683 684 685
    cmsStage* NewMPE;

    _cmsAssert(clutPoints != NULL);

    if (inputChan > MAX_INPUT_DIMENSIONS) {
        cmsSignalError(ContextID, cmsERROR_RANGE, "Too many input channels (%d channels, max=%d)", inputChan, MAX_INPUT_DIMENSIONS);
        return NULL;
    }
D
duke 已提交
686

B
bae 已提交
687 688
    NewMPE = _cmsStageAllocPlaceholder(ContextID, cmsSigCLutElemType, inputChan, outputChan,
                                             EvaluateCLUTfloat, CLUTElemDup, CLutElemTypeFree, NULL);
689
    if (NewMPE == NULL) return NULL;
D
duke 已提交
690 691


B
bae 已提交
692 693 694 695 696 697 698
    NewElem = (_cmsStageCLutData*) _cmsMallocZero(ContextID, sizeof(_cmsStageCLutData));
    if (NewElem == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }

    NewMPE ->Data  = (void*) NewElem;
D
duke 已提交
699

B
bae 已提交
700 701
    // There is a potential integer overflow on conputing n and nEntries.
    NewElem -> nEntries = n = outputChan * CubeSize(clutPoints, inputChan);
702
    NewElem -> HasFloatValues = TRUE;
D
duke 已提交
703

B
bae 已提交
704 705 706 707 708
    if (n == 0) {
        cmsStageFree(NewMPE);
        return NULL;
    }

709 710 711 712 713
    NewElem ->Tab.TFloat  = (cmsFloat32Number*) _cmsCalloc(ContextID, n, sizeof(cmsFloat32Number));
    if (NewElem ->Tab.TFloat == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }
D
duke 已提交
714

715 716 717 718 719
    if (Table != NULL) {
        for (i=0; i < n; i++) {
            NewElem ->Tab.TFloat[i] = Table[i];
        }
    }
D
duke 已提交
720

721 722 723 724 725
    NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints,  inputChan, outputChan, NewElem ->Tab.TFloat, CMS_LERP_FLAGS_FLOAT);
    if (NewElem ->Params == NULL) {
        cmsStageFree(NewMPE);
        return NULL;
    }
D
duke 已提交
726

727
    return NewMPE;
D
duke 已提交
728 729 730
}


731 732 733 734 735
static
int IdentitySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void * Cargo)
{
    int nChan = *(int*) Cargo;
    int i;
D
duke 已提交
736

737 738
    for (i=0; i < nChan; i++)
        Out[i] = In[i];
D
duke 已提交
739

740 741 742 743
    return 1;
}

// Creates an MPE that just copies input to output
P
prr 已提交
744
cmsStage* CMSEXPORT _cmsStageAllocIdentityCLut(cmsContext ContextID, cmsUInt32Number nChan)
D
duke 已提交
745
{
746 747 748 749 750 751
    cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
    cmsStage* mpe ;
    int i;

    for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
        Dimensions[i] = 2;
D
duke 已提交
752

753 754
    mpe = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, nChan, nChan, NULL);
    if (mpe == NULL) return NULL;
D
duke 已提交
755

756 757 758 759
    if (!cmsStageSampleCLut16bit(mpe, IdentitySampler, &nChan, 0)) {
        cmsStageFree(mpe);
        return NULL;
    }
D
duke 已提交
760

761 762 763
    mpe ->Implements = cmsSigIdentityElemType;
    return mpe;
}
D
duke 已提交
764 765 766



767
// Quantize a value 0 <= i < MaxSamples to 0..0xffff
P
prr 已提交
768
cmsUInt16Number CMSEXPORT _cmsQuantizeVal(cmsFloat64Number i, cmsUInt32Number MaxSamples)
769 770
{
    cmsFloat64Number x;
D
duke 已提交
771

772 773 774
    x = ((cmsFloat64Number) i * 65535.) / (cmsFloat64Number) (MaxSamples - 1);
    return _cmsQuickSaturateWord(x);
}
D
duke 已提交
775 776


777 778 779 780
// This routine does a sweep on whole input space, and calls its callback
// function on knots. returns TRUE if all ok, FALSE otherwise.
cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, void * Cargo, cmsUInt32Number dwFlags)
{
P
prr 已提交
781 782 783
    int i, t, index, rest;
    cmsUInt32Number nTotalPoints;
    cmsUInt32Number nInputs, nOutputs;
784
    cmsUInt32Number* nSamples;
P
prr 已提交
785
    cmsUInt16Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
B
bae 已提交
786
    _cmsStageCLutData* clut;
787

B
bae 已提交
788 789 790 791 792
    if (mpe == NULL) return FALSE;

    clut = (_cmsStageCLutData*) mpe->Data;

    if (clut == NULL) return FALSE;
D
duke 已提交
793

794 795 796
    nSamples = clut->Params ->nSamples;
    nInputs  = clut->Params ->nInputs;
    nOutputs = clut->Params ->nOutputs;
D
duke 已提交
797

P
prr 已提交
798 799 800
    if (nInputs <= 0) return FALSE;
    if (nOutputs <= 0) return FALSE;
    if (nInputs > MAX_INPUT_DIMENSIONS) return FALSE;
801
    if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
D
duke 已提交
802

P
prr 已提交
803 804 805
    memset(In, 0, sizeof(In));
    memset(Out, 0, sizeof(Out));

806
    nTotalPoints = CubeSize(nSamples, nInputs);
B
bae 已提交
807
    if (nTotalPoints == 0) return FALSE;
D
duke 已提交
808

809
    index = 0;
P
prr 已提交
810
    for (i = 0; i < (int) nTotalPoints; i++) {
D
duke 已提交
811

812
        rest = i;
P
prr 已提交
813
        for (t = (int)nInputs - 1; t >= 0; --t) {
D
duke 已提交
814

815
            cmsUInt32Number  Colorant = rest % nSamples[t];
D
duke 已提交
816

817
            rest /= nSamples[t];
D
duke 已提交
818

819 820
            In[t] = _cmsQuantizeVal(Colorant, nSamples[t]);
        }
D
duke 已提交
821

822
        if (clut ->Tab.T != NULL) {
P
prr 已提交
823
            for (t = 0; t < (int)nOutputs; t++)
824 825
                Out[t] = clut->Tab.T[index + t];
        }
D
duke 已提交
826

827 828
        if (!Sampler(In, Out, Cargo))
            return FALSE;
D
duke 已提交
829

830
        if (!(dwFlags & SAMPLER_INSPECT)) {
D
duke 已提交
831

832
            if (clut ->Tab.T != NULL) {
P
prr 已提交
833
                for (t=0; t < (int) nOutputs; t++)
834 835 836
                    clut->Tab.T[index + t] = Out[t];
            }
        }
D
duke 已提交
837

838 839
        index += nOutputs;
    }
D
duke 已提交
840

841 842
    return TRUE;
}
D
duke 已提交
843

P
prr 已提交
844
// Same as anterior, but for floating point
845 846
cmsBool CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler, void * Cargo, cmsUInt32Number dwFlags)
{
P
prr 已提交
847 848 849
    int i, t, index, rest;
    cmsUInt32Number nTotalPoints;
    cmsUInt32Number nInputs, nOutputs;
850
    cmsUInt32Number* nSamples;
P
prr 已提交
851
    cmsFloat32Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
852
    _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
D
duke 已提交
853

854 855 856
    nSamples = clut->Params ->nSamples;
    nInputs  = clut->Params ->nInputs;
    nOutputs = clut->Params ->nOutputs;
D
duke 已提交
857

P
prr 已提交
858 859 860
    if (nInputs <= 0) return FALSE;
    if (nOutputs <= 0) return FALSE;
    if (nInputs  > MAX_INPUT_DIMENSIONS) return FALSE;
861
    if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
D
duke 已提交
862

863
    nTotalPoints = CubeSize(nSamples, nInputs);
B
bae 已提交
864
    if (nTotalPoints == 0) return FALSE;
D
duke 已提交
865

866
    index = 0;
P
prr 已提交
867
    for (i = 0; i < (int)nTotalPoints; i++) {
D
duke 已提交
868

869
        rest = i;
P
prr 已提交
870
        for (t = (int) nInputs-1; t >=0; --t) {
D
duke 已提交
871

872
            cmsUInt32Number  Colorant = rest % nSamples[t];
D
duke 已提交
873

874
            rest /= nSamples[t];
D
duke 已提交
875

876 877
            In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, nSamples[t]) / 65535.0);
        }
D
duke 已提交
878

879
        if (clut ->Tab.TFloat != NULL) {
P
prr 已提交
880
            for (t=0; t < (int) nOutputs; t++)
881 882
                Out[t] = clut->Tab.TFloat[index + t];
        }
D
duke 已提交
883

884 885
        if (!Sampler(In, Out, Cargo))
            return FALSE;
D
duke 已提交
886

887
        if (!(dwFlags & SAMPLER_INSPECT)) {
D
duke 已提交
888

889
            if (clut ->Tab.TFloat != NULL) {
P
prr 已提交
890
                for (t=0; t < (int) nOutputs; t++)
891 892 893
                    clut->Tab.TFloat[index + t] = Out[t];
            }
        }
D
duke 已提交
894

895 896
        index += nOutputs;
    }
D
duke 已提交
897

898 899
    return TRUE;
}
D
duke 已提交
900 901 902



903 904 905 906 907
// This routine does a sweep on whole input space, and calls its callback
// function on knots. returns TRUE if all ok, FALSE otherwise.
cmsBool CMSEXPORT cmsSliceSpace16(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
                                         cmsSAMPLER16 Sampler, void * Cargo)
{
P
prr 已提交
908 909
    int i, t, rest;
    cmsUInt32Number nTotalPoints;
910
    cmsUInt16Number In[cmsMAXCHANNELS];
D
duke 已提交
911

912
    if (nInputs >= cmsMAXCHANNELS) return FALSE;
D
duke 已提交
913

914
    nTotalPoints = CubeSize(clutPoints, nInputs);
B
bae 已提交
915
    if (nTotalPoints == 0) return FALSE;
D
duke 已提交
916

P
prr 已提交
917
    for (i = 0; i < (int) nTotalPoints; i++) {
D
duke 已提交
918

919
        rest = i;
P
prr 已提交
920
        for (t = (int) nInputs-1; t >=0; --t) {
D
duke 已提交
921

922
            cmsUInt32Number  Colorant = rest % clutPoints[t];
D
duke 已提交
923

924 925
            rest /= clutPoints[t];
            In[t] = _cmsQuantizeVal(Colorant, clutPoints[t]);
D
duke 已提交
926

927
        }
D
duke 已提交
928

929 930 931
        if (!Sampler(In, NULL, Cargo))
            return FALSE;
    }
D
duke 已提交
932

933 934
    return TRUE;
}
D
duke 已提交
935

936 937 938
cmsInt32Number CMSEXPORT cmsSliceSpaceFloat(cmsUInt32Number nInputs, const cmsUInt32Number clutPoints[],
                                            cmsSAMPLERFLOAT Sampler, void * Cargo)
{
P
prr 已提交
939 940
    int i, t, rest;
    cmsUInt32Number nTotalPoints;
941
    cmsFloat32Number In[cmsMAXCHANNELS];
D
duke 已提交
942

943
    if (nInputs >= cmsMAXCHANNELS) return FALSE;
D
duke 已提交
944

945
    nTotalPoints = CubeSize(clutPoints, nInputs);
B
bae 已提交
946
    if (nTotalPoints == 0) return FALSE;
D
duke 已提交
947

P
prr 已提交
948
    for (i = 0; i < (int) nTotalPoints; i++) {
D
duke 已提交
949

950
        rest = i;
P
prr 已提交
951
        for (t = (int) nInputs-1; t >=0; --t) {
D
duke 已提交
952

953
            cmsUInt32Number  Colorant = rest % clutPoints[t];
D
duke 已提交
954

955 956
            rest /= clutPoints[t];
            In[t] =  (cmsFloat32Number) (_cmsQuantizeVal(Colorant, clutPoints[t]) / 65535.0);
D
duke 已提交
957

958
        }
D
duke 已提交
959

960 961 962
        if (!Sampler(In, NULL, Cargo))
            return FALSE;
    }
D
duke 已提交
963

964 965
    return TRUE;
}
D
duke 已提交
966

967 968 969
// ********************************************************************************
// Type cmsSigLab2XYZElemType
// ********************************************************************************
D
duke 已提交
970 971


972 973 974 975 976 977 978 979
static
void EvaluateLab2XYZ(const cmsFloat32Number In[],
                     cmsFloat32Number Out[],
                     const cmsStage *mpe)
{
    cmsCIELab Lab;
    cmsCIEXYZ XYZ;
    const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
D
duke 已提交
980

981 982 983 984
    // V4 rules
    Lab.L = In[0] * 100.0;
    Lab.a = In[1] * 255.0 - 128.0;
    Lab.b = In[2] * 255.0 - 128.0;
D
duke 已提交
985

986
    cmsLab2XYZ(NULL, &XYZ, &Lab);
D
duke 已提交
987

988 989
    // From XYZ, range 0..19997 to 0..1.0, note that 1.99997 comes from 0xffff
    // encoded as 1.15 fixed point, so 1 + (32767.0 / 32768.0)
D
duke 已提交
990

991 992 993 994
    Out[0] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.X / XYZadj);
    Out[1] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Y / XYZadj);
    Out[2] = (cmsFloat32Number) ((cmsFloat64Number) XYZ.Z / XYZadj);
    return;
D
duke 已提交
995

996
    cmsUNUSED_PARAMETER(mpe);
D
duke 已提交
997 998 999
}


1000
// No dup or free routines needed, as the structure has no pointers in it.
P
prr 已提交
1001
cmsStage* CMSEXPORT _cmsStageAllocLab2XYZ(cmsContext ContextID)
D
duke 已提交
1002
{
1003 1004
    return _cmsStageAllocPlaceholder(ContextID, cmsSigLab2XYZElemType, 3, 3, EvaluateLab2XYZ, NULL, NULL, NULL);
}
D
duke 已提交
1005

1006
// ********************************************************************************
D
duke 已提交
1007

1008 1009 1010 1011 1012
// v2 L=100 is supposed to be placed on 0xFF00. There is no reasonable
// number of gridpoints that would make exact match. However, a prelinearization
// of 258 entries, would map 0xFF00 exactly on entry 257, and this is good to avoid scum dot.
// Almost all what we need but unfortunately, the rest of entries should be scaled by
// (255*257/256) and this is not exact.
D
duke 已提交
1013

1014 1015 1016 1017 1018
cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID)
{
    cmsStage* mpe;
    cmsToneCurve* LabTable[3];
    int i, j;
D
duke 已提交
1019

1020 1021 1022
    LabTable[0] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
    LabTable[1] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
    LabTable[2] = cmsBuildTabulatedToneCurve16(ContextID, 258, NULL);
D
duke 已提交
1023

1024
    for (j=0; j < 3; j++) {
D
duke 已提交
1025

1026 1027 1028 1029
        if (LabTable[j] == NULL) {
            cmsFreeToneCurveTriple(LabTable);
            return NULL;
        }
D
duke 已提交
1030

P
prr 已提交
1031
        // We need to map * (0xffff / 0xff00), that's same as (257 / 256)
1032 1033
        // So we can use 258-entry tables to do the trick (i / 257) * (255 * 257) * (257 / 256);
        for (i=0; i < 257; i++)  {
D
duke 已提交
1034

1035 1036
            LabTable[j]->Table16[i] = (cmsUInt16Number) ((i * 0xffff + 0x80) >> 8);
        }
D
duke 已提交
1037

1038 1039
        LabTable[j] ->Table16[257] = 0xffff;
    }
D
duke 已提交
1040

1041 1042
    mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
    cmsFreeToneCurveTriple(LabTable);
D
duke 已提交
1043

P
prr 已提交
1044
    if (mpe == NULL) return NULL;
1045 1046 1047
    mpe ->Implements = cmsSigLabV2toV4;
    return mpe;
}
D
duke 已提交
1048

1049
// ********************************************************************************
D
duke 已提交
1050

1051
// Matrix-based conversion, which is more accurate, but slower and cannot properly be saved in devicelink profiles
P
prr 已提交
1052
cmsStage* CMSEXPORT _cmsStageAllocLabV2ToV4(cmsContext ContextID)
1053 1054 1055 1056 1057
{
    static const cmsFloat64Number V2ToV4[] = { 65535.0/65280.0, 0, 0,
                                     0, 65535.0/65280.0, 0,
                                     0, 0, 65535.0/65280.0
                                     };
D
duke 已提交
1058

1059
    cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V2ToV4, NULL);
D
duke 已提交
1060

1061 1062 1063
    if (mpe == NULL) return mpe;
    mpe ->Implements = cmsSigLabV2toV4;
    return mpe;
D
duke 已提交
1064 1065 1066
}


1067
// Reverse direction
P
prr 已提交
1068
cmsStage* CMSEXPORT _cmsStageAllocLabV4ToV2(cmsContext ContextID)
1069 1070 1071 1072 1073
{
    static const cmsFloat64Number V4ToV2[] = { 65280.0/65535.0, 0, 0,
                                     0, 65280.0/65535.0, 0,
                                     0, 0, 65280.0/65535.0
                                     };
D
duke 已提交
1074

1075
     cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, V4ToV2, NULL);
D
duke 已提交
1076

1077 1078 1079 1080
    if (mpe == NULL) return mpe;
    mpe ->Implements = cmsSigLabV4toV2;
    return mpe;
}
D
duke 已提交
1081 1082


B
bae 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
// To Lab to float. Note that the MPE gives numbers in normal Lab range
// and we need 0..1.0 range for the formatters
// L* : 0...100 => 0...1.0  (L* / 100)
// ab* : -128..+127 to 0..1  ((ab* + 128) / 255)

cmsStage* _cmsStageNormalizeFromLabFloat(cmsContext ContextID)
{
    static const cmsFloat64Number a1[] = {
        1.0/100.0, 0, 0,
        0, 1.0/255.0, 0,
        0, 0, 1.0/255.0
    };

    static const cmsFloat64Number o1[] = {
        0,
        128.0/255.0,
        128.0/255.0
    };

    cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, a1, o1);

    if (mpe == NULL) return mpe;
    mpe ->Implements = cmsSigLab2FloatPCS;
    return mpe;
}

// Fom XYZ to floating point PCS
cmsStage* _cmsStageNormalizeFromXyzFloat(cmsContext ContextID)
{
#define n (32768.0/65535.0)
    static const cmsFloat64Number a1[] = {
        n, 0, 0,
        0, n, 0,
        0, 0, n
    };
#undef n

    cmsStage *mpe =  cmsStageAllocMatrix(ContextID, 3, 3, a1, NULL);

    if (mpe == NULL) return mpe;
    mpe ->Implements = cmsSigXYZ2FloatPCS;
    return mpe;
}

cmsStage* _cmsStageNormalizeToLabFloat(cmsContext ContextID)
{
    static const cmsFloat64Number a1[] = {
        100.0, 0, 0,
        0, 255.0, 0,
        0, 0, 255.0
    };

    static const cmsFloat64Number o1[] = {
        0,
        -128.0,
        -128.0
    };

    cmsStage *mpe =  cmsStageAllocMatrix(ContextID, 3, 3, a1, o1);
    if (mpe == NULL) return mpe;
    mpe ->Implements = cmsSigFloatPCS2Lab;
    return mpe;
}

cmsStage* _cmsStageNormalizeToXyzFloat(cmsContext ContextID)
{
#define n (65535.0/32768.0)

    static const cmsFloat64Number a1[] = {
        n, 0, 0,
        0, n, 0,
        0, 0, n
    };
#undef n

    cmsStage *mpe = cmsStageAllocMatrix(ContextID, 3, 3, a1, NULL);
    if (mpe == NULL) return mpe;
    mpe ->Implements = cmsSigFloatPCS2XYZ;
    return mpe;
}

P
prr 已提交
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
// Clips values smaller than zero
static
void Clipper(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
{
       cmsUInt32Number i;
       for (i = 0; i < mpe->InputChannels; i++) {

              cmsFloat32Number n = In[i];
              Out[i] = n < 0 ? 0 : n;
       }
}
B
bae 已提交
1175

P
prr 已提交
1176
cmsStage*  _cmsStageClipNegatives(cmsContext ContextID, cmsUInt32Number nChannels)
P
prr 已提交
1177 1178 1179 1180
{
       return _cmsStageAllocPlaceholder(ContextID, cmsSigClipNegativesElemType,
              nChannels, nChannels, Clipper, NULL, NULL, NULL);
}
B
bae 已提交
1181

1182 1183 1184
// ********************************************************************************
// Type cmsSigXYZ2LabElemType
// ********************************************************************************
D
duke 已提交
1185

1186 1187 1188 1189 1190 1191
static
void EvaluateXYZ2Lab(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsStage *mpe)
{
    cmsCIELab Lab;
    cmsCIEXYZ XYZ;
    const cmsFloat64Number XYZadj = MAX_ENCODEABLE_XYZ;
D
duke 已提交
1192

1193
    // From 0..1.0 to XYZ
D
duke 已提交
1194

1195 1196 1197
    XYZ.X = In[0] * XYZadj;
    XYZ.Y = In[1] * XYZadj;
    XYZ.Z = In[2] * XYZadj;
D
duke 已提交
1198

1199
    cmsXYZ2Lab(NULL, &Lab, &XYZ);
D
duke 已提交
1200

1201
    // From V4 Lab to 0..1.0
D
duke 已提交
1202

1203 1204 1205 1206 1207 1208 1209 1210
    Out[0] = (cmsFloat32Number) (Lab.L / 100.0);
    Out[1] = (cmsFloat32Number) ((Lab.a + 128.0) / 255.0);
    Out[2] = (cmsFloat32Number) ((Lab.b + 128.0) / 255.0);
    return;

    cmsUNUSED_PARAMETER(mpe);
}

P
prr 已提交
1211
cmsStage* CMSEXPORT _cmsStageAllocXYZ2Lab(cmsContext ContextID)
D
duke 已提交
1212
{
1213
    return _cmsStageAllocPlaceholder(ContextID, cmsSigXYZ2LabElemType, 3, 3, EvaluateXYZ2Lab, NULL, NULL, NULL);
D
duke 已提交
1214

1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
}

// ********************************************************************************

// For v4, S-Shaped curves are placed in a/b axis to increase resolution near gray

cmsStage* _cmsStageAllocLabPrelin(cmsContext ContextID)
{
    cmsToneCurve* LabTable[3];
    cmsFloat64Number Params[1] =  {2.4} ;

    LabTable[0] = cmsBuildGamma(ContextID, 1.0);
    LabTable[1] = cmsBuildParametricToneCurve(ContextID, 108, Params);
    LabTable[2] = cmsBuildParametricToneCurve(ContextID, 108, Params);

    return cmsStageAllocToneCurves(ContextID, 3, LabTable);
}


// Free a single MPE
void CMSEXPORT cmsStageFree(cmsStage* mpe)
{
    if (mpe ->FreePtr)
        mpe ->FreePtr(mpe);

    _cmsFree(mpe ->ContextID, mpe);
}


cmsUInt32Number  CMSEXPORT cmsStageInputChannels(const cmsStage* mpe)
{
    return mpe ->InputChannels;
}

cmsUInt32Number  CMSEXPORT cmsStageOutputChannels(const cmsStage* mpe)
{
    return mpe ->OutputChannels;
}

cmsStageSignature CMSEXPORT cmsStageType(const cmsStage* mpe)
{
    return mpe -> Type;
}
D
duke 已提交
1258

1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
void* CMSEXPORT cmsStageData(const cmsStage* mpe)
{
    return mpe -> Data;
}

cmsStage*  CMSEXPORT cmsStageNext(const cmsStage* mpe)
{
    return mpe -> Next;
}


// Duplicates an MPE
cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
{
    cmsStage* NewMPE;

    if (mpe == NULL) return NULL;
    NewMPE = _cmsStageAllocPlaceholder(mpe ->ContextID,
                                     mpe ->Type,
                                     mpe ->InputChannels,
                                     mpe ->OutputChannels,
                                     mpe ->EvalPtr,
                                     mpe ->DupElemPtr,
                                     mpe ->FreePtr,
                                     NULL);
    if (NewMPE == NULL) return NULL;

P
prr 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
    NewMPE ->Implements = mpe ->Implements;

    if (mpe ->DupElemPtr) {

        NewMPE ->Data = mpe ->DupElemPtr(mpe);

        if (NewMPE->Data == NULL) {

            cmsStageFree(NewMPE);
            return NULL;
        }

    } else {
1299 1300

        NewMPE ->Data       = NULL;
P
prr 已提交
1301
    }
D
duke 已提交
1302

1303
    return NewMPE;
D
duke 已提交
1304 1305 1306
}


1307 1308 1309
// ***********************************************************************************************************

// This function sets up the channel count
D
duke 已提交
1310
static
P
prr 已提交
1311
cmsBool BlessLUT(cmsPipeline* lut)
D
duke 已提交
1312
{
P
prr 已提交
1313
    // We can set the input/output channels only if we have elements.
1314 1315
    if (lut ->Elements != NULL) {

P
prr 已提交
1316 1317 1318 1319
        cmsStage* prev;
        cmsStage* next;
        cmsStage* First;
        cmsStage* Last;
1320 1321 1322 1323

        First  = cmsPipelineGetPtrToFirstStage(lut);
        Last   = cmsPipelineGetPtrToLastStage(lut);

P
prr 已提交
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
        if (First == NULL || Last == NULL) return FALSE;

        lut->InputChannels = First->InputChannels;
        lut->OutputChannels = Last->OutputChannels;

        // Check chain consistency
        prev = First;
        next = prev->Next;

        while (next != NULL)
        {
            if (next->InputChannels != prev->OutputChannels)
                return FALSE;

            next = next->Next;
            prev = prev->Next;
1340
    }
D
duke 已提交
1341 1342
}

P
prr 已提交
1343 1344 1345
    return TRUE;
}

1346 1347

// Default to evaluate the LUT on 16 bit-basis. Precision is retained.
D
duke 已提交
1348
static
1349
void _LUTeval16(register const cmsUInt16Number In[], register cmsUInt16Number Out[],  register const void* D)
D
duke 已提交
1350
{
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
    cmsPipeline* lut = (cmsPipeline*) D;
    cmsStage *mpe;
    cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
    int Phase = 0, NextPhase;

    From16ToFloat(In, &Storage[Phase][0], lut ->InputChannels);

    for (mpe = lut ->Elements;
         mpe != NULL;
         mpe = mpe ->Next) {

             NextPhase = Phase ^ 1;
             mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
             Phase = NextPhase;
    }


    FromFloatTo16(&Storage[Phase][0], Out, lut ->OutputChannels);
D
duke 已提交
1369 1370
}

1371 1372 1373


// Does evaluate the LUT on cmsFloat32Number-basis.
D
duke 已提交
1374
static
1375
void _LUTevalFloat(register const cmsFloat32Number In[], register cmsFloat32Number Out[], const void* D)
D
duke 已提交
1376
{
1377 1378 1379 1380 1381 1382
    cmsPipeline* lut = (cmsPipeline*) D;
    cmsStage *mpe;
    cmsFloat32Number Storage[2][MAX_STAGE_CHANNELS];
    int Phase = 0, NextPhase;

    memmove(&Storage[Phase][0], In, lut ->InputChannels  * sizeof(cmsFloat32Number));
D
duke 已提交
1383

1384 1385 1386 1387 1388 1389 1390 1391
    for (mpe = lut ->Elements;
         mpe != NULL;
         mpe = mpe ->Next) {

              NextPhase = Phase ^ 1;
              mpe ->EvalPtr(&Storage[Phase][0], &Storage[NextPhase][0], mpe);
              Phase = NextPhase;
    }
D
duke 已提交
1392

1393
    memmove(Out, &Storage[Phase][0], lut ->OutputChannels * sizeof(cmsFloat32Number));
D
duke 已提交
1394 1395 1396
}


1397 1398
// LUT Creation & Destruction
cmsPipeline* CMSEXPORT cmsPipelineAlloc(cmsContext ContextID, cmsUInt32Number InputChannels, cmsUInt32Number OutputChannels)
D
duke 已提交
1399
{
1400 1401
       cmsPipeline* NewLUT;

P
prr 已提交
1402
       // A value of zero in channels is allowed as placeholder
1403 1404 1405 1406 1407 1408 1409 1410
       if (InputChannels >= cmsMAXCHANNELS ||
           OutputChannels >= cmsMAXCHANNELS) return NULL;

       NewLUT = (cmsPipeline*) _cmsMallocZero(ContextID, sizeof(cmsPipeline));
       if (NewLUT == NULL) return NULL;

       NewLUT -> InputChannels  = InputChannels;
       NewLUT -> OutputChannels = OutputChannels;
D
duke 已提交
1411

1412 1413 1414 1415 1416
       NewLUT ->Eval16Fn    = _LUTeval16;
       NewLUT ->EvalFloatFn = _LUTevalFloat;
       NewLUT ->DupDataFn   = NULL;
       NewLUT ->FreeDataFn  = NULL;
       NewLUT ->Data        = NewLUT;
B
bae 已提交
1417
       NewLUT ->ContextID   = ContextID;
1418

P
prr 已提交
1419 1420 1421 1422 1423
       if (!BlessLUT(NewLUT))
       {
           _cmsFree(ContextID, NewLUT);
           return NULL;
       }
1424 1425 1426

       return NewLUT;
}
D
duke 已提交
1427

B
bae 已提交
1428 1429 1430 1431 1432
cmsContext CMSEXPORT cmsGetPipelineContextID(const cmsPipeline* lut)
{
    _cmsAssert(lut != NULL);
    return lut ->ContextID;
}
D
duke 已提交
1433

1434 1435
cmsUInt32Number CMSEXPORT cmsPipelineInputChannels(const cmsPipeline* lut)
{
B
bae 已提交
1436
    _cmsAssert(lut != NULL);
1437 1438 1439 1440 1441
    return lut ->InputChannels;
}

cmsUInt32Number CMSEXPORT cmsPipelineOutputChannels(const cmsPipeline* lut)
{
B
bae 已提交
1442
    _cmsAssert(lut != NULL);
1443 1444 1445 1446 1447 1448 1449
    return lut ->OutputChannels;
}

// Free a profile elements LUT
void CMSEXPORT cmsPipelineFree(cmsPipeline* lut)
{
    cmsStage *mpe, *Next;
D
duke 已提交
1450

1451
    if (lut == NULL) return;
D
duke 已提交
1452

1453 1454 1455
    for (mpe = lut ->Elements;
        mpe != NULL;
        mpe = Next) {
D
duke 已提交
1456

1457 1458
            Next = mpe ->Next;
            cmsStageFree(mpe);
D
duke 已提交
1459
    }
1460 1461 1462 1463

    if (lut ->FreeDataFn) lut ->FreeDataFn(lut ->ContextID, lut ->Data);

    _cmsFree(lut ->ContextID, lut);
D
duke 已提交
1464 1465 1466
}


1467 1468 1469
// Default to evaluate the LUT on 16 bit-basis.
void CMSEXPORT cmsPipelineEval16(const cmsUInt16Number In[], cmsUInt16Number Out[],  const cmsPipeline* lut)
{
B
bae 已提交
1470
    _cmsAssert(lut != NULL);
1471 1472 1473
    lut ->Eval16Fn(In, Out, lut->Data);
}

D
duke 已提交
1474

1475 1476 1477
// Does evaluate the LUT on cmsFloat32Number-basis.
void CMSEXPORT cmsPipelineEvalFloat(const cmsFloat32Number In[], cmsFloat32Number Out[], const cmsPipeline* lut)
{
B
bae 已提交
1478
    _cmsAssert(lut != NULL);
1479 1480
    lut ->EvalFloatFn(In, Out, lut);
}
D
duke 已提交
1481 1482


1483 1484 1485

// Duplicates a LUT
cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
D
duke 已提交
1486
{
1487 1488 1489 1490 1491 1492 1493
    cmsPipeline* NewLUT;
    cmsStage *NewMPE, *Anterior = NULL, *mpe;
    cmsBool  First = TRUE;

    if (lut == NULL) return NULL;

    NewLUT = cmsPipelineAlloc(lut ->ContextID, lut ->InputChannels, lut ->OutputChannels);
1494 1495
    if (NewLUT == NULL) return NULL;

1496 1497 1498 1499 1500
    for (mpe = lut ->Elements;
         mpe != NULL;
         mpe = mpe ->Next) {

             NewMPE = cmsStageDup(mpe);
D
duke 已提交
1501

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
             if (NewMPE == NULL) {
                 cmsPipelineFree(NewLUT);
                 return NULL;
             }

             if (First) {
                 NewLUT ->Elements = NewMPE;
                 First = FALSE;
             }
             else {
1512 1513
                if (Anterior != NULL)
                    Anterior ->Next = NewMPE;
1514 1515 1516 1517
             }

            Anterior = NewMPE;
    }
D
duke 已提交
1518

B
bae 已提交
1519 1520 1521 1522
    NewLUT ->Eval16Fn    = lut ->Eval16Fn;
    NewLUT ->EvalFloatFn = lut ->EvalFloatFn;
    NewLUT ->DupDataFn   = lut ->DupDataFn;
    NewLUT ->FreeDataFn  = lut ->FreeDataFn;
D
duke 已提交
1523

1524 1525
    if (NewLUT ->DupDataFn != NULL)
        NewLUT ->Data = NewLUT ->DupDataFn(lut ->ContextID, lut->Data);
D
duke 已提交
1526

1527 1528 1529

    NewLUT ->SaveAs8Bits    = lut ->SaveAs8Bits;

P
prr 已提交
1530 1531 1532 1533 1534 1535
    if (!BlessLUT(NewLUT))
    {
        _cmsFree(lut->ContextID, NewLUT);
        return NULL;
    }

1536 1537 1538 1539
    return NewLUT;
}


P
prr 已提交
1540
int CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
1541 1542 1543
{
    cmsStage* Anterior = NULL, *pt;

P
prr 已提交
1544 1545
    if (lut == NULL || mpe == NULL)
        return FALSE;
B
bae 已提交
1546

1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    switch (loc) {

        case cmsAT_BEGIN:
            mpe ->Next = lut ->Elements;
            lut ->Elements = mpe;
            break;

        case cmsAT_END:

            if (lut ->Elements == NULL)
                lut ->Elements = mpe;
            else {

                for (pt = lut ->Elements;
                     pt != NULL;
                     pt = pt -> Next) Anterior = pt;

                Anterior ->Next = mpe;
                mpe ->Next = NULL;
            }
            break;
        default:;
P
prr 已提交
1569
            return FALSE;
1570 1571
    }

P
prr 已提交
1572
    return BlessLUT(lut);
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
}

// Unlink an element and return the pointer to it
void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe)
{
    cmsStage *Anterior, *pt, *Last;
    cmsStage *Unlinked = NULL;


    // If empty LUT, there is nothing to remove
    if (lut ->Elements == NULL) {
        if (mpe) *mpe = NULL;
        return;
    }

    // On depending on the strategy...
    switch (loc) {

        case cmsAT_BEGIN:
            {
                cmsStage* elem = lut ->Elements;

                lut ->Elements = elem -> Next;
                elem ->Next = NULL;
                Unlinked = elem;

            }
            break;

        case cmsAT_END:
            Anterior = Last = NULL;
            for (pt = lut ->Elements;
                pt != NULL;
                pt = pt -> Next) {
                    Anterior = Last;
                    Last = pt;
            }

            Unlinked = Last;  // Next already points to NULL

            // Truncate the chain
            if (Anterior)
                Anterior ->Next = NULL;
            else
                lut ->Elements = NULL;
            break;
        default:;
    }

    if (mpe)
        *mpe = Unlinked;
D
duke 已提交
1624
    else
1625
        cmsStageFree(Unlinked);
D
duke 已提交
1626

P
prr 已提交
1627
    // May fail, but we ignore it
1628 1629
    BlessLUT(lut);
}
D
duke 已提交
1630 1631


1632 1633 1634
// Concatenate two LUT into a new single one
cmsBool  CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
{
P
prr 已提交
1635
    cmsStage* mpe;
1636 1637 1638 1639 1640 1641 1642

    // If both LUTS does not have elements, we need to inherit
    // the number of channels
    if (l1 ->Elements == NULL && l2 ->Elements == NULL) {
        l1 ->InputChannels  = l2 ->InputChannels;
        l1 ->OutputChannels = l2 ->OutputChannels;
    }
D
duke 已提交
1643

1644 1645 1646 1647
    // Cat second
    for (mpe = l2 ->Elements;
         mpe != NULL;
         mpe = mpe ->Next) {
D
duke 已提交
1648

1649
            // We have to dup each element
P
prr 已提交
1650 1651
            if (!cmsPipelineInsertStage(l1, cmsAT_END, cmsStageDup(mpe)))
                return FALSE;
1652 1653
    }

P
prr 已提交
1654
    return BlessLUT(l1);
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692
}


cmsBool CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lut, cmsBool On)
{
    cmsBool Anterior = lut ->SaveAs8Bits;

    lut ->SaveAs8Bits = On;
    return Anterior;
}


cmsStage* CMSEXPORT cmsPipelineGetPtrToFirstStage(const cmsPipeline* lut)
{
    return lut ->Elements;
}

cmsStage* CMSEXPORT cmsPipelineGetPtrToLastStage(const cmsPipeline* lut)
{
    cmsStage *mpe, *Anterior = NULL;

    for (mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
        Anterior = mpe;

    return Anterior;
}

cmsUInt32Number CMSEXPORT cmsPipelineStageCount(const cmsPipeline* lut)
{
    cmsStage *mpe;
    cmsUInt32Number n;

    for (n=0, mpe = lut ->Elements; mpe != NULL; mpe = mpe ->Next)
            n++;

    return n;
}

B
bae 已提交
1693
// This function may be used to set the optional evaluator and a block of private data. If private data is being used, an optional
1694 1695 1696 1697
// duplicator and free functions should also be specified in order to duplicate the LUT construct. Use NULL to inhibit such functionality.
void CMSEXPORT _cmsPipelineSetOptimizationParameters(cmsPipeline* Lut,
                                        _cmsOPTeval16Fn Eval16,
                                        void* PrivateData,
B
bae 已提交
1698 1699
                                        _cmsFreeUserDataFn FreePrivateDataFn,
                                        _cmsDupUserDataFn  DupPrivateDataFn)
1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
{

    Lut ->Eval16Fn = Eval16;
    Lut ->DupDataFn = DupPrivateDataFn;
    Lut ->FreeDataFn = FreePrivateDataFn;
    Lut ->Data = PrivateData;
}


// ----------------------------------------------------------- Reverse interpolation
// Here's how it goes. The derivative Df(x) of the function f is the linear
// transformation that best approximates f near the point x. It can be represented
// by a matrix A whose entries are the partial derivatives of the components of f
// with respect to all the coordinates. This is know as the Jacobian
//
// The best linear approximation to f is given by the matrix equation:
//
// y-y0 = A (x-x0)
//
// So, if x0 is a good "guess" for the zero of f, then solving for the zero of this
// linear approximation will give a "better guess" for the zero of f. Thus let y=0,
// and since y0=f(x0) one can solve the above equation for x. This leads to the
// Newton's method formula:
//
// xn+1 = xn - A-1 f(xn)
//
// where xn+1 denotes the (n+1)-st guess, obtained from the n-th guess xn in the
// fashion described above. Iterating this will give better and better approximations
// if you have a "good enough" initial guess.


#define JACOBIAN_EPSILON            0.001f
#define INVERSION_MAX_ITERATIONS    30

// Increment with reflexion on boundary
static
void IncDelta(cmsFloat32Number *Val)
{
    if (*Val < (1.0 - JACOBIAN_EPSILON))

        *Val += JACOBIAN_EPSILON;

    else
        *Val -= JACOBIAN_EPSILON;

}



// Euclidean distance between two vectors of n elements each one
static
cmsFloat32Number EuclideanDistance(cmsFloat32Number a[], cmsFloat32Number b[], int n)
{
    cmsFloat32Number sum = 0;
    int i;

    for (i=0; i < n; i++) {
        cmsFloat32Number dif = b[i] - a[i];
        sum +=  dif * dif;
    }

    return sqrtf(sum);
}


// Evaluate a LUT in reverse direction. It only searches on 3->3 LUT. Uses Newton method
//
// x1 <- x - [J(x)]^-1 * f(x)
//
// lut: The LUT on where to do the search
// Target: LabK, 3 values of Lab plus destination K which is fixed
// Result: The obtained CMYK
// Hint:   Location where begin the search

cmsBool CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],
                                              cmsFloat32Number Result[],
                                              cmsFloat32Number Hint[],
                                              const cmsPipeline* lut)
{
    cmsUInt32Number  i, j;
    cmsFloat64Number  error, LastError = 1E20;
    cmsFloat32Number  fx[4], x[4], xd[4], fxd[4];
    cmsVEC3 tmp, tmp2;
    cmsMAT3 Jacobian;

    // Only 3->3 and 4->3 are supported
    if (lut ->InputChannels != 3 && lut ->InputChannels != 4) return FALSE;
    if (lut ->OutputChannels != 3) return FALSE;

    // Take the hint as starting point if specified
    if (Hint == NULL) {

        // Begin at any point, we choose 1/3 of CMY axis
        x[0] = x[1] = x[2] = 0.3f;
D
duke 已提交
1794 1795 1796
    }
    else {

1797 1798 1799
        // Only copy 3 channels from hint...
        for (j=0; j < 3; j++)
            x[j] = Hint[j];
D
duke 已提交
1800 1801
    }

1802 1803 1804 1805 1806
    // If Lut is 4-dimensions, then grab target[3], which is fixed
    if (lut ->InputChannels == 4) {
        x[3] = Target[3];
    }
    else x[3] = 0; // To keep lint happy
D
duke 已提交
1807 1808


1809
    // Iterate
D
duke 已提交
1810 1811 1812
    for (i = 0; i < INVERSION_MAX_ITERATIONS; i++) {

        // Get beginning fx
1813
        cmsPipelineEvalFloat(x, fx, lut);
D
duke 已提交
1814 1815

        // Compute error
1816
        error = EuclideanDistance(fx, Target, 3);
D
duke 已提交
1817 1818 1819 1820 1821 1822

        // If not convergent, return last safe value
        if (error >= LastError)
            break;

        // Keep latest values
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
        LastError     = error;
        for (j=0; j < lut ->InputChannels; j++)
                Result[j] = x[j];

        // Found an exact match?
        if (error <= 0)
            break;

        // Obtain slope (the Jacobian)
        for (j = 0; j < 3; j++) {
D
duke 已提交
1833

1834 1835 1836 1837
            xd[0] = x[0];
            xd[1] = x[1];
            xd[2] = x[2];
            xd[3] = x[3];  // Keep fixed channel
D
duke 已提交
1838

1839 1840 1841 1842 1843 1844 1845 1846
            IncDelta(&xd[j]);

            cmsPipelineEvalFloat(xd, fxd, lut);

            Jacobian.v[0].n[j] = ((fxd[0] - fx[0]) / JACOBIAN_EPSILON);
            Jacobian.v[1].n[j] = ((fxd[1] - fx[1]) / JACOBIAN_EPSILON);
            Jacobian.v[2].n[j] = ((fxd[2] - fx[2]) / JACOBIAN_EPSILON);
        }
D
duke 已提交
1847

1848
        // Solve system
1849 1850 1851
        tmp2.n[0] = fx[0] - Target[0];
        tmp2.n[1] = fx[1] - Target[1];
        tmp2.n[2] = fx[2] - Target[2];
D
duke 已提交
1852

1853 1854
        if (!_cmsMAT3solve(&tmp, &Jacobian, &tmp2))
            return FALSE;
D
duke 已提交
1855 1856

        // Move our guess
1857 1858 1859
        x[0] -= (cmsFloat32Number) tmp.n[0];
        x[1] -= (cmsFloat32Number) tmp.n[1];
        x[2] -= (cmsFloat32Number) tmp.n[2];
D
duke 已提交
1860 1861

        // Some clipping....
1862 1863 1864 1865 1866
        for (j=0; j < 3; j++) {
            if (x[j] < 0) x[j] = 0;
            else
                if (x[j] > 1.0) x[j] = 1.0;
        }
D
duke 已提交
1867 1868
    }

1869
    return TRUE;
D
duke 已提交
1870
}
1871

B
bae 已提交
1872