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