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-2013 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 #include "lcms2_internal.h"
  56 
  57 // Tone curves are powerful constructs that can contain curves specified in diverse ways.
  58 // The curve is stored in segments, where each segment can be sampled or specified by parameters.
  59 // a 16.bit simplification of the *whole* curve is kept for optimization purposes. For float operation,
  60 // each segment is evaluated separately. Plug-ins may be used to define new parametric schemes,
  61 // each plug-in may define up to MAX_TYPES_IN_LCMS_PLUGIN functions types. For defining a function,
  62 // the plug-in should provide the type id, how many parameters each type has, and a pointer to
  63 // a procedure that evaluates the function. In the case of reverse evaluation, the evaluator will
  64 // be called with the type id as a negative value, and a sampled version of the reversed curve
  65 // will be built.
  66 
  67 // ----------------------------------------------------------------- Implementation
  68 // Maxim number of nodes
  69 #define MAX_NODES_IN_CURVE   4097
  70 #define MINUS_INF            (-1E22F)
  71 #define PLUS_INF             (+1E22F)
  72 
  73 // The list of supported parametric curves
  74 typedef struct _cmsParametricCurvesCollection_st {
  75 
  76     int nFunctions;                                     // Number of supported functions in this chunk
  77     int FunctionTypes[MAX_TYPES_IN_LCMS_PLUGIN];        // The identification types
  78     int ParameterCount[MAX_TYPES_IN_LCMS_PLUGIN];       // Number of parameters for each function
  79     cmsParametricCurveEvaluator    Evaluator;           // The evaluator
  80 
  81     struct _cmsParametricCurvesCollection_st* Next; // Next in list
  82 
  83 } _cmsParametricCurvesCollection;
  84 
  85 // This is the default (built-in) evaluator
  86 static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
  87 
  88 // The built-in list
  89 static _cmsParametricCurvesCollection DefaultCurves = {
  90     9,                                  // # of curve types
  91     { 1, 2, 3, 4, 5, 6, 7, 8, 108 },    // Parametric curve ID
  92     { 1, 3, 4, 5, 7, 4, 5, 5, 1 },      // Parameters by type
  93     DefaultEvalParametricFn,            // Evaluator
  94     NULL                                // Next in chain
  95 };
  96 
  97 // Duplicates the zone of memory used by the plug-in in the new context
  98 static
  99 void DupPluginCurvesList(struct _cmsContext_struct* ctx,
 100                                                const struct _cmsContext_struct* src)
 101 {
 102    _cmsCurvesPluginChunkType newHead = { NULL };
 103    _cmsParametricCurvesCollection*  entry;
 104    _cmsParametricCurvesCollection*  Anterior = NULL;
 105    _cmsCurvesPluginChunkType* head = (_cmsCurvesPluginChunkType*) src->chunks[CurvesPlugin];
 106 
 107     _cmsAssert(head != NULL);
 108 
 109     // Walk the list copying all nodes
 110    for (entry = head->ParametricCurves;
 111         entry != NULL;
 112         entry = entry ->Next) {
 113 
 114             _cmsParametricCurvesCollection *newEntry = ( _cmsParametricCurvesCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsParametricCurvesCollection));
 115 
 116             if (newEntry == NULL)
 117                 return;
 118 
 119             // We want to keep the linked list order, so this is a little bit tricky
 120             newEntry -> Next = NULL;
 121             if (Anterior)
 122                 Anterior -> Next = newEntry;
 123 
 124             Anterior = newEntry;
 125 
 126             if (newHead.ParametricCurves == NULL)
 127                 newHead.ParametricCurves = newEntry;
 128     }
 129 
 130   ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsCurvesPluginChunkType));
 131 }
 132 
 133 // The allocator have to follow the chain
 134 void _cmsAllocCurvesPluginChunk(struct _cmsContext_struct* ctx,
 135                                 const struct _cmsContext_struct* src)
 136 {
 137     _cmsAssert(ctx != NULL);
 138 
 139     if (src != NULL) {
 140 
 141         // Copy all linked list
 142        DupPluginCurvesList(ctx, src);
 143     }
 144     else {
 145         static _cmsCurvesPluginChunkType CurvesPluginChunk = { NULL };
 146         ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx ->MemPool, &CurvesPluginChunk, sizeof(_cmsCurvesPluginChunkType));
 147     }
 148 }
 149 
 150 
 151 // The linked list head
 152 _cmsCurvesPluginChunkType _cmsCurvesPluginChunk = { NULL };
 153 
 154 // As a way to install new parametric curves
 155 cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext ContextID, cmsPluginBase* Data)
 156 {
 157     _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);
 158     cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;
 159     _cmsParametricCurvesCollection* fl;
 160 
 161     if (Data == NULL) {
 162 
 163           ctx -> ParametricCurves =  NULL;
 164           return TRUE;
 165     }
 166 
 167     fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsParametricCurvesCollection));
 168     if (fl == NULL) return FALSE;
 169 
 170     // Copy the parameters
 171     fl ->Evaluator  = Plugin ->Evaluator;
 172     fl ->nFunctions = Plugin ->nFunctions;
 173 
 174     // Make sure no mem overwrites
 175     if (fl ->nFunctions > MAX_TYPES_IN_LCMS_PLUGIN)
 176         fl ->nFunctions = MAX_TYPES_IN_LCMS_PLUGIN;
 177 
 178     // Copy the data
 179     memmove(fl->FunctionTypes,  Plugin ->FunctionTypes,   fl->nFunctions * sizeof(cmsUInt32Number));
 180     memmove(fl->ParameterCount, Plugin ->ParameterCount,  fl->nFunctions * sizeof(cmsUInt32Number));
 181 
 182     // Keep linked list
 183     fl ->Next = ctx->ParametricCurves;
 184     ctx->ParametricCurves = fl;
 185 
 186     // All is ok
 187     return TRUE;
 188 }
 189 
 190 
 191 // Search in type list, return position or -1 if not found
 192 static
 193 int IsInSet(int Type, _cmsParametricCurvesCollection* c)
 194 {
 195     int i;
 196 
 197     for (i=0; i < c ->nFunctions; i++)
 198         if (abs(Type) == c ->FunctionTypes[i]) return i;
 199 
 200     return -1;
 201 }
 202 
 203 
 204 // Search for the collection which contains a specific type
 205 static
 206 _cmsParametricCurvesCollection *GetParametricCurveByType(cmsContext ContextID, int Type, int* index)
 207 {
 208     _cmsParametricCurvesCollection* c;
 209     int Position;
 210     _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);
 211 
 212     for (c = ctx->ParametricCurves; c != NULL; c = c ->Next) {
 213 
 214         Position = IsInSet(Type, c);
 215 
 216         if (Position != -1) {
 217             if (index != NULL)
 218                 *index = Position;
 219             return c;
 220         }
 221     }
 222     // If none found, revert for defaults
 223     for (c = &DefaultCurves; c != NULL; c = c ->Next) {
 224 
 225         Position = IsInSet(Type, c);
 226 
 227         if (Position != -1) {
 228             if (index != NULL)
 229                 *index = Position;
 230             return c;
 231         }
 232     }
 233 
 234     return NULL;
 235 }
 236 
 237 // Low level allocate, which takes care of memory details. nEntries may be zero, and in this case
 238 // no optimation curve is computed. nSegments may also be zero in the inverse case, where only the
 239 // optimization curve is given. Both features simultaneously is an error
 240 static
 241 cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsInt32Number nEntries,
 242                                       cmsInt32Number nSegments, const cmsCurveSegment* Segments,
 243                                       const cmsUInt16Number* Values)
 244 {
 245     cmsToneCurve* p;
 246     int i;
 247 
 248     // We allow huge tables, which are then restricted for smoothing operations
 249     if (nEntries > 65530 || nEntries < 0) {
 250         cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve of more than 65530 entries");
 251         return NULL;
 252     }
 253 
 254     if (nEntries <= 0 && nSegments <= 0) {
 255         cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table");
 256         return NULL;
 257     }
 258 
 259     // Allocate all required pointers, etc.
 260     p = (cmsToneCurve*) _cmsMallocZero(ContextID, sizeof(cmsToneCurve));
 261     if (!p) return NULL;
 262 
 263     // In this case, there are no segments
 264     if (nSegments <= 0) {
 265         p ->Segments = NULL;
 266         p ->Evals = NULL;
 267     }
 268     else {
 269         p ->Segments = (cmsCurveSegment*) _cmsCalloc(ContextID, nSegments, sizeof(cmsCurveSegment));
 270         if (p ->Segments == NULL) goto Error;
 271 
 272         p ->Evals    = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator));
 273         if (p ->Evals == NULL) goto Error;
 274     }
 275 
 276     p -> nSegments = nSegments;
 277 
 278     // This 16-bit table contains a limited precision representation of the whole curve and is kept for
 279     // increasing xput on certain operations.
 280     if (nEntries <= 0) {
 281         p ->Table16 = NULL;
 282     }
 283     else {
 284        p ->Table16 = (cmsUInt16Number*)  _cmsCalloc(ContextID, nEntries, sizeof(cmsUInt16Number));
 285        if (p ->Table16 == NULL) goto Error;
 286     }
 287 
 288     p -> nEntries  = nEntries;
 289 
 290     // Initialize members if requested
 291     if (Values != NULL && (nEntries > 0)) {
 292 
 293         for (i=0; i < nEntries; i++)
 294             p ->Table16[i] = Values[i];
 295     }
 296 
 297     // Initialize the segments stuff. The evaluator for each segment is located and a pointer to it
 298     // is placed in advance to maximize performance.
 299     if (Segments != NULL && (nSegments > 0)) {
 300 
 301         _cmsParametricCurvesCollection *c;
 302 
 303         p ->SegInterp = (cmsInterpParams**) _cmsCalloc(ContextID, nSegments, sizeof(cmsInterpParams*));
 304         if (p ->SegInterp == NULL) goto Error;
 305 
 306         for (i=0; i< nSegments; i++) {
 307 
 308             // Type 0 is a special marker for table-based curves
 309             if (Segments[i].Type == 0)
 310                 p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT);
 311 
 312             memmove(&p ->Segments[i], &Segments[i], sizeof(cmsCurveSegment));
 313 
 314             if (Segments[i].Type == 0 && Segments[i].SampledPoints != NULL)
 315                 p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints);
 316             else
 317                 p ->Segments[i].SampledPoints = NULL;
 318 
 319 
 320             c = GetParametricCurveByType(ContextID, Segments[i].Type, NULL);
 321             if (c != NULL)
 322                     p ->Evals[i] = c ->Evaluator;
 323         }
 324     }
 325 
 326     p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);
 327     if (p->InterpParams != NULL)
 328         return p;
 329 
 330 Error:
 331     if (p -> Segments) _cmsFree(ContextID, p ->Segments);
 332     if (p -> Evals) _cmsFree(ContextID, p -> Evals);
 333     if (p ->Table16) _cmsFree(ContextID, p ->Table16);
 334     _cmsFree(ContextID, p);
 335     return NULL;
 336 }
 337 
 338 
 339 // Parametric Fn using floating point
 340 static
 341 cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)
 342 {
 343     cmsFloat64Number e, Val, disc;
 344 
 345     switch (Type) {
 346 
 347    // X = Y ^ Gamma
 348     case 1:
 349         if (R < 0) {
 350 
 351             if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
 352                 Val = R;
 353             else
 354                 Val = 0;
 355         }
 356         else
 357             Val = pow(R, Params[0]);
 358         break;
 359 
 360     // Type 1 Reversed: X = Y ^1/gamma
 361     case -1:
 362          if (R < 0) {
 363 
 364             if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
 365                 Val = R;
 366             else
 367                 Val = 0;
 368         }
 369         else
 370             Val = pow(R, 1/Params[0]);
 371         break;
 372 
 373     // CIE 122-1966
 374     // Y = (aX + b)^Gamma  | X >= -b/a
 375     // Y = 0               | else
 376     case 2:
 377         disc = -Params[2] / Params[1];
 378 
 379         if (R >= disc ) {
 380 
 381             e = Params[1]*R + Params[2];
 382 
 383             if (e > 0)
 384                 Val = pow(e, Params[0]);
 385             else
 386                 Val = 0;
 387         }
 388         else
 389             Val = 0;
 390         break;
 391 
 392      // Type 2 Reversed
 393      // X = (Y ^1/g  - b) / a
 394      case -2:
 395          if (R < 0)
 396              Val = 0;
 397          else
 398              Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
 399 
 400          if (Val < 0)
 401               Val = 0;
 402          break;
 403 
 404 
 405     // IEC 61966-3
 406     // Y = (aX + b)^Gamma | X <= -b/a
 407     // Y = c              | else
 408     case 3:
 409         disc = -Params[2] / Params[1];
 410         if (disc < 0)
 411             disc = 0;
 412 
 413         if (R >= disc) {
 414 
 415             e = Params[1]*R + Params[2];
 416 
 417             if (e > 0)
 418                 Val = pow(e, Params[0]) + Params[3];
 419             else
 420                 Val = 0;
 421         }
 422         else
 423             Val = Params[3];
 424         break;
 425 
 426 
 427     // Type 3 reversed
 428     // X=((Y-c)^1/g - b)/a      | (Y>=c)
 429     // X=-b/a                   | (Y<c)
 430     case -3:
 431         if (R >= Params[3])  {
 432 
 433             e = R - Params[3];
 434 
 435             if (e > 0)
 436                 Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
 437             else
 438                 Val = 0;
 439         }
 440         else {
 441             Val = -Params[2] / Params[1];
 442         }
 443         break;
 444 
 445 
 446     // IEC 61966-2.1 (sRGB)
 447     // Y = (aX + b)^Gamma | X >= d
 448     // Y = cX             | X < d
 449     case 4:
 450         if (R >= Params[4]) {
 451 
 452             e = Params[1]*R + Params[2];
 453 
 454             if (e > 0)
 455                 Val = pow(e, Params[0]);
 456             else
 457                 Val = 0;
 458         }
 459         else
 460             Val = R * Params[3];
 461         break;
 462 
 463     // Type 4 reversed
 464     // X=((Y^1/g-b)/a)    | Y >= (ad+b)^g
 465     // X=Y/c              | Y< (ad+b)^g
 466     case -4:
 467         e = Params[1] * Params[4] + Params[2];
 468         if (e < 0)
 469             disc = 0;
 470         else
 471             disc = pow(e, Params[0]);
 472 
 473         if (R >= disc) {
 474 
 475             Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
 476         }
 477         else {
 478             Val = R / Params[3];
 479         }
 480         break;
 481 
 482 
 483     // Y = (aX + b)^Gamma + e | X >= d
 484     // Y = cX + f             | X < d
 485     case 5:
 486         if (R >= Params[4]) {
 487 
 488             e = Params[1]*R + Params[2];
 489 
 490             if (e > 0)
 491                 Val = pow(e, Params[0]) + Params[5];
 492             else
 493                 Val = Params[5];
 494         }
 495         else
 496             Val = R*Params[3] + Params[6];
 497         break;
 498 
 499 
 500     // Reversed type 5
 501     // X=((Y-e)1/g-b)/a   | Y >=(ad+b)^g+e), cd+f
 502     // X=(Y-f)/c          | else
 503     case -5:
 504 
 505         disc = Params[3] * Params[4] + Params[6];
 506         if (R >= disc) {
 507 
 508             e = R - Params[5];
 509             if (e < 0)
 510                 Val = 0;
 511             else
 512                 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
 513         }
 514         else {
 515             Val = (R - Params[6]) / Params[3];
 516         }
 517         break;
 518 
 519 
 520     // Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf
 521     // Type 6 is basically identical to type 5 without d
 522 
 523     // Y = (a * X + b) ^ Gamma + c
 524     case 6:
 525         e = Params[1]*R + Params[2];
 526 
 527         if (e < 0)
 528             Val = Params[3];
 529         else
 530             Val = pow(e, Params[0]) + Params[3];
 531         break;
 532 
 533     // ((Y - c) ^1/Gamma - b) / a
 534     case -6:
 535         e = R - Params[3];
 536         if (e < 0)
 537             Val = 0;
 538         else
 539         Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
 540         break;
 541 
 542 
 543     // Y = a * log (b * X^Gamma + c) + d
 544     case 7:
 545 
 546        e = Params[2] * pow(R, Params[0]) + Params[3];
 547        if (e <= 0)
 548            Val = Params[4];
 549        else
 550            Val = Params[1]*log10(e) + Params[4];
 551        break;
 552 
 553     // (Y - d) / a = log(b * X ^Gamma + c)
 554     // pow(10, (Y-d) / a) = b * X ^Gamma + c
 555     // pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X
 556     case -7:
 557        Val = pow((pow(10.0, (R-Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]);
 558        break;
 559 
 560 
 561    //Y = a * b^(c*X+d) + e
 562    case 8:
 563        Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]);
 564        break;
 565 
 566 
 567    // Y = (log((y-e) / a) / log(b) - d ) / c
 568    // a=0, b=1, c=2, d=3, e=4,
 569    case -8:
 570 
 571        disc = R - Params[4];
 572        if (disc < 0) Val = 0;
 573        else
 574            Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2];
 575        break;
 576 
 577    // S-Shaped: (1 - (1-x)^1/g)^1/g
 578    case 108:
 579       Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]);
 580       break;
 581 
 582     // y = (1 - (1-x)^1/g)^1/g
 583     // y^g = (1 - (1-x)^1/g)
 584     // 1 - y^g = (1-x)^1/g
 585     // (1 - y^g)^g = 1 - x
 586     // 1 - (1 - y^g)^g
 587     case -108:
 588         Val = 1 - pow(1 - pow(R, Params[0]), Params[0]);
 589         break;
 590 
 591     default:
 592         // Unsupported parametric curve. Should never reach here
 593         return 0;
 594     }
 595 
 596     return Val;
 597 }
 598 
 599 // Evaluate a segmented function for a single value. Return -1 if no valid segment found .
 600 // If fn type is 0, perform an interpolation on the table
 601 static
 602 cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
 603 {
 604     int i;
 605 
 606     for (i = g ->nSegments-1; i >= 0 ; --i) {
 607 
 608         // Check for domain
 609         if ((R > g ->Segments[i].x0) && (R <= g ->Segments[i].x1)) {
 610 
 611             // Type == 0 means segment is sampled
 612             if (g ->Segments[i].Type == 0) {
 613 
 614                 cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0) / (g ->Segments[i].x1 - g ->Segments[i].x0);
 615                 cmsFloat32Number Out[cmsMAXCHANNELS];
 616                 // Setup the table (TODO: clean that)
 617                 g ->SegInterp[i]-> Table = g ->Segments[i].SampledPoints;
 618 
 619                 g ->SegInterp[i] -> Interpolation.LerpFloat(&R1, Out, g ->SegInterp[i]);
 620 
 621                 return Out[0];
 622             }
 623             else
 624                 return g ->Evals[i](g->Segments[i].Type, g ->Segments[i].Params, R);
 625         }
 626     }
 627 
 628     return MINUS_INF;
 629 }
 630 
 631 // Access to estimated low-res table
 632 cmsUInt32Number CMSEXPORT cmsGetToneCurveEstimatedTableEntries(const cmsToneCurve* t)
 633 {
 634     _cmsAssert(t != NULL);
 635     return t ->nEntries;
 636 }
 637 
 638 const cmsUInt16Number* CMSEXPORT cmsGetToneCurveEstimatedTable(const cmsToneCurve* t)
 639 {
 640     _cmsAssert(t != NULL);
 641     return t ->Table16;
 642 }
 643 
 644 
 645 // Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the
 646 // floating point description empty.
 647 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number Values[])
 648 {
 649     return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values);
 650 }
 651 
 652 static
 653 int EntriesByGamma(cmsFloat64Number Gamma)
 654 {
 655     if (fabs(Gamma - 1.0) < 0.001) return 2;
 656     return 4096;
 657 }
 658 
 659 
 660 // Create a segmented gamma, fill the table
 661 cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,
 662                                                    cmsInt32Number nSegments, const cmsCurveSegment Segments[])
 663 {
 664     int i;
 665     cmsFloat64Number R, Val;
 666     cmsToneCurve* g;
 667     int nGridPoints = 4096;
 668 
 669     _cmsAssert(Segments != NULL);
 670 
 671     // Optimizatin for identity curves.
 672     if (nSegments == 1 && Segments[0].Type == 1) {
 673 
 674         nGridPoints = EntriesByGamma(Segments[0].Params[0]);
 675     }
 676 
 677     g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL);
 678     if (g == NULL) return NULL;
 679 
 680     // Once we have the floating point version, we can approximate a 16 bit table of 4096 entries
 681     // for performance reasons. This table would normally not be used except on 8/16 bits transforms.
 682     for (i=0; i < nGridPoints; i++) {
 683 
 684         R   = (cmsFloat64Number) i / (nGridPoints-1);
 685 
 686         Val = EvalSegmentedFn(g, R);
 687 
 688         // Round and saturate
 689         g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0);
 690     }
 691 
 692     return g;
 693 }
 694 
 695 // Use a segmented curve to store the floating point table
 696 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
 697 {
 698     cmsCurveSegment Seg[3];
 699 
 700     // A segmented tone curve should have function segments in the first and last positions
 701     // Initialize segmented curve part up to 0 to constant value = samples[0]
 702     Seg[0].x0 = MINUS_INF;
 703     Seg[0].x1 = 0;
 704     Seg[0].Type = 6;
 705 
 706     Seg[0].Params[0] = 1;
 707     Seg[0].Params[1] = 0;
 708     Seg[0].Params[2] = 0;
 709     Seg[0].Params[3] = values[0];
 710     Seg[0].Params[4] = 0;
 711 
 712     // From zero to 1
 713     Seg[1].x0 = 0;
 714     Seg[1].x1 = 1.0;
 715     Seg[1].Type = 0;
 716 
 717     Seg[1].nGridPoints = nEntries;
 718     Seg[1].SampledPoints = (cmsFloat32Number*) values;
 719 
 720     // Final segment is constant = lastsample
 721     Seg[2].x0 = 1.0;
 722     Seg[2].x1 = PLUS_INF;
 723     Seg[2].Type = 6;
 724 
 725     Seg[2].Params[0] = 1;
 726     Seg[2].Params[1] = 0;
 727     Seg[2].Params[2] = 0;
 728     Seg[2].Params[3] = values[nEntries-1];
 729     Seg[2].Params[4] = 0;
 730 
 731 
 732     return cmsBuildSegmentedToneCurve(ContextID, 3, Seg);
 733 }
 734 
 735 // Parametric curves
 736 //
 737 // Parameters goes as: Curve, a, b, c, d, e, f
 738 // Type is the ICC type +1
 739 // if type is negative, then the curve is analyticaly inverted
 740 cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])
 741 {
 742     cmsCurveSegment Seg0;
 743     int Pos = 0;
 744     cmsUInt32Number size;
 745     _cmsParametricCurvesCollection* c = GetParametricCurveByType(ContextID, Type, &Pos);
 746 
 747     _cmsAssert(Params != NULL);
 748 
 749     if (c == NULL) {
 750         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
 751         return NULL;
 752     }
 753 
 754     memset(&Seg0, 0, sizeof(Seg0));
 755 
 756     Seg0.x0   = MINUS_INF;
 757     Seg0.x1   = PLUS_INF;
 758     Seg0.Type = Type;
 759 
 760     size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number);
 761     memmove(Seg0.Params, Params, size);
 762 
 763     return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0);
 764 }
 765 
 766 
 767 
 768 // Build a gamma table based on gamma constant
 769 cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma)
 770 {
 771     return cmsBuildParametricToneCurve(ContextID, 1, &Gamma);
 772 }
 773 
 774 
 775 // Free all memory taken by the gamma curve
 776 void CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve)
 777 {
 778     cmsContext ContextID;
 779 
 780     if (Curve == NULL) return;
 781 
 782     ContextID = Curve ->InterpParams->ContextID;
 783 
 784     _cmsFreeInterpParams(Curve ->InterpParams);
 785 
 786     if (Curve -> Table16)
 787         _cmsFree(ContextID, Curve ->Table16);
 788 
 789     if (Curve ->Segments) {
 790 
 791         cmsUInt32Number i;
 792 
 793         for (i=0; i < Curve ->nSegments; i++) {
 794 
 795             if (Curve ->Segments[i].SampledPoints) {
 796                 _cmsFree(ContextID, Curve ->Segments[i].SampledPoints);
 797             }
 798 
 799             if (Curve ->SegInterp[i] != 0)
 800                 _cmsFreeInterpParams(Curve->SegInterp[i]);
 801         }
 802 
 803         _cmsFree(ContextID, Curve ->Segments);
 804         _cmsFree(ContextID, Curve ->SegInterp);
 805     }
 806 
 807     if (Curve -> Evals)
 808         _cmsFree(ContextID, Curve -> Evals);
 809 
 810     if (Curve) _cmsFree(ContextID, Curve);
 811 }
 812 
 813 // Utility function, free 3 gamma tables
 814 void CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3])
 815 {
 816 
 817     _cmsAssert(Curve != NULL);
 818 
 819     if (Curve[0] != NULL) cmsFreeToneCurve(Curve[0]);
 820     if (Curve[1] != NULL) cmsFreeToneCurve(Curve[1]);
 821     if (Curve[2] != NULL) cmsFreeToneCurve(Curve[2]);
 822 
 823     Curve[0] = Curve[1] = Curve[2] = NULL;
 824 }
 825 
 826 
 827 // Duplicate a gamma table
 828 cmsToneCurve* CMSEXPORT cmsDupToneCurve(const cmsToneCurve* In)
 829 {
 830     if (In == NULL) return NULL;
 831 
 832     return  AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);
 833 }
 834 
 835 // Joins two curves for X and Y. Curves should be monotonic.
 836 // We want to get
 837 //
 838 //      y = Y^-1(X(t))
 839 //
 840 cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID,
 841                                       const cmsToneCurve* X,
 842                                       const cmsToneCurve* Y, cmsUInt32Number nResultingPoints)
 843 {
 844     cmsToneCurve* out = NULL;
 845     cmsToneCurve* Yreversed = NULL;
 846     cmsFloat32Number t, x;
 847     cmsFloat32Number* Res = NULL;
 848     cmsUInt32Number i;
 849 
 850 
 851     _cmsAssert(X != NULL);
 852     _cmsAssert(Y != NULL);
 853 
 854     Yreversed = cmsReverseToneCurveEx(nResultingPoints, Y);
 855     if (Yreversed == NULL) goto Error;
 856 
 857     Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number));
 858     if (Res == NULL) goto Error;
 859 
 860     //Iterate
 861     for (i=0; i <  nResultingPoints; i++) {
 862 
 863         t = (cmsFloat32Number) i / (nResultingPoints-1);
 864         x = cmsEvalToneCurveFloat(X,  t);
 865         Res[i] = cmsEvalToneCurveFloat(Yreversed, x);
 866     }
 867 
 868     // Allocate space for output
 869     out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res);
 870 
 871 Error:
 872 
 873     if (Res != NULL) _cmsFree(ContextID, Res);
 874     if (Yreversed != NULL) cmsFreeToneCurve(Yreversed);
 875 
 876     return out;
 877 }
 878 
 879 
 880 
 881 // Get the surrounding nodes. This is tricky on non-monotonic tables
 882 static
 883 int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)
 884 {
 885     int i;
 886     int y0, y1;
 887 
 888     // A 1 point table is not allowed
 889     if (p -> Domain[0] < 1) return -1;
 890 
 891     // Let's see if ascending or descending.
 892     if (LutTable[0] < LutTable[p ->Domain[0]]) {
 893 
 894         // Table is overall ascending
 895         for (i=p->Domain[0]-1; i >=0; --i) {
 896 
 897             y0 = LutTable[i];
 898             y1 = LutTable[i+1];
 899 
 900             if (y0 <= y1) { // Increasing
 901                 if (In >= y0 && In <= y1) return i;
 902             }
 903             else
 904                 if (y1 < y0) { // Decreasing
 905                     if (In >= y1 && In <= y0) return i;
 906                 }
 907         }
 908     }
 909     else {
 910         // Table is overall descending
 911         for (i=0; i < (int) p -> Domain[0]; i++) {
 912 
 913             y0 = LutTable[i];
 914             y1 = LutTable[i+1];
 915 
 916             if (y0 <= y1) { // Increasing
 917                 if (In >= y0 && In <= y1) return i;
 918             }
 919             else
 920                 if (y1 < y0) { // Decreasing
 921                     if (In >= y1 && In <= y0) return i;
 922                 }
 923         }
 924     }
 925 
 926     return -1;
 927 }
 928 
 929 // Reverse a gamma table
 930 cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InCurve)
 931 {
 932     cmsToneCurve *out;
 933     cmsFloat64Number a = 0, b = 0, y, x1, y1, x2, y2;
 934     int i, j;
 935     int Ascending;
 936 
 937     _cmsAssert(InCurve != NULL);
 938 
 939     // Try to reverse it analytically whatever possible
 940 
 941     if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 &&
 942         /* InCurve -> Segments[0].Type <= 5 */
 943         GetParametricCurveByType(InCurve ->InterpParams->ContextID, InCurve ->Segments[0].Type, NULL) != NULL) {
 944 
 945         return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID,
 946                                        -(InCurve -> Segments[0].Type),
 947                                        InCurve -> Segments[0].Params);
 948     }
 949 
 950     // Nope, reverse the table.
 951     out = cmsBuildTabulatedToneCurve16(InCurve ->InterpParams->ContextID, nResultSamples, NULL);
 952     if (out == NULL)
 953         return NULL;
 954 
 955     // We want to know if this is an ascending or descending table
 956     Ascending = !cmsIsToneCurveDescending(InCurve);
 957 
 958     // Iterate across Y axis
 959     for (i=0; i <  nResultSamples; i++) {
 960 
 961         y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1);
 962 
 963         // Find interval in which y is within.
 964         j = GetInterval(y, InCurve->Table16, InCurve->InterpParams);
 965         if (j >= 0) {
 966 
 967 
 968             // Get limits of interval
 969             x1 = InCurve ->Table16[j];
 970             x2 = InCurve ->Table16[j+1];
 971 
 972             y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1);
 973             y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1);
 974 
 975             // If collapsed, then use any
 976             if (x1 == x2) {
 977 
 978                 out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1);
 979                 continue;
 980 
 981             } else {
 982 
 983                 // Interpolate
 984                 a = (y2 - y1) / (x2 - x1);
 985                 b = y2 - a * x2;
 986             }
 987         }
 988 
 989         out ->Table16[i] = _cmsQuickSaturateWord(a* y + b);
 990     }
 991 
 992 
 993     return out;
 994 }
 995 
 996 // Reverse a gamma table
 997 cmsToneCurve* CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma)
 998 {
 999     _cmsAssert(InGamma != NULL);
1000 
1001     return cmsReverseToneCurveEx(4096, InGamma);
1002 }
1003 
1004 // From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
1005 // differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
1006 //
1007 // Smoothing and interpolation with second differences.
1008 //
1009 //   Input:  weights (w), data (y): vector from 1 to m.
1010 //   Input:  smoothing parameter (lambda), length (m).
1011 //   Output: smoothed vector (z): vector from 1 to m.
1012 
1013 static
1014 cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[], cmsFloat32Number z[], cmsFloat32Number lambda, int m)
1015 {
1016     int i, i1, i2;
1017     cmsFloat32Number *c, *d, *e;
1018     cmsBool st;
1019 
1020 
1021     c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
1022     d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
1023     e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
1024 
1025     if (c != NULL && d != NULL && e != NULL) {
1026 
1027 
1028     d[1] = w[1] + lambda;
1029     c[1] = -2 * lambda / d[1];
1030     e[1] = lambda /d[1];
1031     z[1] = w[1] * y[1];
1032     d[2] = w[2] + 5 * lambda - d[1] * c[1] *  c[1];
1033     c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
1034     e[2] = lambda / d[2];
1035     z[2] = w[2] * y[2] - c[1] * z[1];
1036 
1037     for (i = 3; i < m - 1; i++) {
1038         i1 = i - 1; i2 = i - 2;
1039         d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1040         c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
1041         e[i] = lambda / d[i];
1042         z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
1043     }
1044 
1045     i1 = m - 2; i2 = m - 3;
1046 
1047     d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1048     c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
1049     z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
1050     i1 = m - 1; i2 = m - 2;
1051 
1052     d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1053     z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
1054     z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
1055 
1056     for (i = m - 2; 1<= i; i--)
1057         z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
1058 
1059       st = TRUE;
1060     }
1061     else st = FALSE;
1062 
1063     if (c != NULL) _cmsFree(ContextID, c);
1064     if (d != NULL) _cmsFree(ContextID, d);
1065     if (e != NULL) _cmsFree(ContextID, e);
1066 
1067     return st;
1068 }
1069 
1070 // Smooths a curve sampled at regular intervals.
1071 cmsBool  CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda)
1072 {
1073     cmsFloat32Number w[MAX_NODES_IN_CURVE], y[MAX_NODES_IN_CURVE], z[MAX_NODES_IN_CURVE];
1074     int i, nItems, Zeros, Poles;
1075 
1076     if (Tab == NULL) return FALSE;
1077 
1078     if (cmsIsToneCurveLinear(Tab)) return TRUE; // Nothing to do
1079 
1080     nItems = Tab -> nEntries;
1081 
1082     if (nItems >= MAX_NODES_IN_CURVE) {
1083         cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: too many points.");
1084         return FALSE;
1085     }
1086 
1087     memset(w, 0, nItems * sizeof(cmsFloat32Number));
1088     memset(y, 0, nItems * sizeof(cmsFloat32Number));
1089     memset(z, 0, nItems * sizeof(cmsFloat32Number));
1090 
1091     for (i=0; i < nItems; i++)
1092     {
1093         y[i+1] = (cmsFloat32Number) Tab -> Table16[i];
1094         w[i+1] = 1.0;
1095     }
1096 
1097     if (!smooth2(Tab ->InterpParams->ContextID, w, y, z, (cmsFloat32Number) lambda, nItems)) return FALSE;
1098 
1099     // Do some reality - checking...
1100     Zeros = Poles = 0;
1101     for (i=nItems; i > 1; --i) {
1102 
1103         if (z[i] == 0.) Zeros++;
1104         if (z[i] >= 65535.) Poles++;
1105         if (z[i] < z[i-1]) {
1106             cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic.");
1107             return FALSE;
1108         }
1109     }
1110 
1111     if (Zeros > (nItems / 3)) {
1112         cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros.");
1113         return FALSE;
1114     }
1115     if (Poles > (nItems / 3)) {
1116         cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles.");
1117         return FALSE;
1118     }
1119 
1120     // Seems ok
1121     for (i=0; i < nItems; i++) {
1122 
1123         // Clamp to cmsUInt16Number
1124         Tab -> Table16[i] = _cmsQuickSaturateWord(z[i+1]);
1125     }
1126 
1127     return TRUE;
1128 }
1129 
1130 // Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting
1131 // in a linear table. This way assures it is linear in 12 bits, which should be enought in most cases.
1132 cmsBool CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve)
1133 {
1134     cmsUInt32Number i;
1135     int diff;
1136 
1137     _cmsAssert(Curve != NULL);
1138 
1139     for (i=0; i < Curve ->nEntries; i++) {
1140 
1141         diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries));
1142         if (diff > 0x0f)
1143             return FALSE;
1144     }
1145 
1146     return TRUE;
1147 }
1148 
1149 // Same, but for monotonicity
1150 cmsBool  CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t)
1151 {
1152     int n;
1153     int i, last;
1154     cmsBool lDescending;
1155 
1156     _cmsAssert(t != NULL);
1157 
1158     // Degenerated curves are monotonic? Ok, let's pass them
1159     n = t ->nEntries;
1160     if (n < 2) return TRUE;
1161 
1162     // Curve direction
1163     lDescending = cmsIsToneCurveDescending(t);
1164 
1165     if (lDescending) {
1166 
1167         last = t ->Table16[0];
1168 
1169         for (i = 1; i < n; i++) {
1170 
1171             if (t ->Table16[i] - last > 2) // We allow some ripple
1172                 return FALSE;
1173             else
1174                 last = t ->Table16[i];
1175 
1176         }
1177     }
1178     else {
1179 
1180         last = t ->Table16[n-1];
1181 
1182         for (i = n-2; i >= 0; --i) {
1183 
1184             if (t ->Table16[i] - last > 2)
1185                 return FALSE;
1186             else
1187                 last = t ->Table16[i];
1188 
1189         }
1190     }
1191 
1192     return TRUE;
1193 }
1194 
1195 // Same, but for descending tables
1196 cmsBool  CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t)
1197 {
1198     _cmsAssert(t != NULL);
1199 
1200     return t ->Table16[0] > t ->Table16[t ->nEntries-1];
1201 }
1202 
1203 
1204 // Another info fn: is out gamma table multisegment?
1205 cmsBool  CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* t)
1206 {
1207     _cmsAssert(t != NULL);
1208 
1209     return t -> nSegments > 1;
1210 }
1211 
1212 cmsInt32Number  CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t)
1213 {
1214     _cmsAssert(t != NULL);
1215 
1216     if (t -> nSegments != 1) return 0;
1217     return t ->Segments[0].Type;
1218 }
1219 
1220 // We need accuracy this time
1221 cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v)
1222 {
1223     _cmsAssert(Curve != NULL);
1224 
1225     // Check for 16 bits table. If so, this is a limited-precision tone curve
1226     if (Curve ->nSegments == 0) {
1227 
1228         cmsUInt16Number In, Out;
1229 
1230         In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0);
1231         Out = cmsEvalToneCurve16(Curve, In);
1232 
1233         return (cmsFloat32Number) (Out / 65535.0);
1234     }
1235 
1236     return (cmsFloat32Number) EvalSegmentedFn(Curve, v);
1237 }
1238 
1239 // We need xput over here
1240 cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v)
1241 {
1242     cmsUInt16Number out[cmsMAXCHANNELS];
1243     cmsUInt16Number in[2] = {v, 0};
1244 
1245     _cmsAssert(Curve != NULL);
1246     Curve ->InterpParams ->Interpolation.Lerp16(in, out, Curve ->InterpParams);
1247     return out[0];
1248 }
1249 
1250 
1251 // Least squares fitting.
1252 // A mathematical procedure for finding the best-fitting curve to a given set of points by
1253 // minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.
1254 // The sum of the squares of the offsets is used instead of the offset absolute values because
1255 // this allows the residuals to be treated as a continuous differentiable quantity.
1256 //
1257 // y = f(x) = x ^ g
1258 //
1259 // R  = (yi - (xi^g))
1260 // R2 = (yi - (xi^g))2
1261 // SUM R2 = SUM (yi - (xi^g))2
1262 //
1263 // dR2/dg = -2 SUM x^g log(x)(y - x^g)
1264 // solving for dR2/dg = 0
1265 //
1266 // g = 1/n * SUM(log(y) / log(x))
1267 
1268 cmsFloat64Number CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision)
1269 {
1270     cmsFloat64Number gamma, sum, sum2;
1271     cmsFloat64Number n, x, y, Std;
1272     cmsUInt32Number i;
1273 
1274     _cmsAssert(t != NULL);
1275 
1276     sum = sum2 = n = 0;
1277 
1278     // Excluding endpoints
1279     for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) {
1280 
1281         x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1);
1282         y = (cmsFloat64Number) cmsEvalToneCurveFloat(t, (cmsFloat32Number) x);
1283 
1284         // Avoid 7% on lower part to prevent
1285         // artifacts due to linear ramps
1286 
1287         if (y > 0. && y < 1. && x > 0.07) {
1288 
1289             gamma = log(y) / log(x);
1290             sum  += gamma;
1291             sum2 += gamma * gamma;
1292             n++;
1293         }
1294     }
1295 
1296     // Take a look on SD to see if gamma isn't exponential at all
1297     Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));
1298 
1299     if (Std > Precision)
1300         return -1.0;
1301 
1302     return (sum / n);   // The mean
1303 }