1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2013 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(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
59 
60 // The built-in list
61 static _cmsParametricCurvesCollection DefaultCurves = {
62     9,                                  // # of curve types
63     { 1, 2, 3, 4, 5, 6, 7, 8, 108 },    // Parametric curve ID
64     { 1, 3, 4, 5, 7, 4, 5, 5, 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,_cmsParametricCurvesCollection * c)165 int IsInSet(int Type, _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 _cmsParametricCurvesCollection *GetParametricCurveByType(cmsContext ContextID, int Type, int* index)
179 {
180     _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 optimation 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         _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 // Parametric Fn using floating point
313 static
DefaultEvalParametricFn(cmsContext ContextID,cmsInt32Number Type,const cmsFloat64Number Params[],cmsFloat64Number R)314 cmsFloat64Number DefaultEvalParametricFn(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)
315 {
316     cmsFloat64Number e, Val, disc;
317     cmsUNUSED_PARAMETER(ContextID);
318 
319     switch (Type) {
320 
321    // X = Y ^ Gamma
322     case 1:
323         if (R < 0) {
324 
325             if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
326                 Val = R;
327             else
328                 Val = 0;
329         }
330         else
331             Val = pow(R, Params[0]);
332         break;
333 
334     // Type 1 Reversed: X = Y ^1/gamma
335     case -1:
336         if (R < 0) {
337 
338             if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
339                 Val = R;
340             else
341                 Val = 0;
342         }
343         else
344         {
345             if (fabs(Params[0]) < MATRIX_DET_TOLERANCE)
346                 Val = PLUS_INF;
347             else
348                 Val = pow(R, 1 / Params[0]);
349         }
350         break;
351 
352     // CIE 122-1966
353     // Y = (aX + b)^Gamma  | X >= -b/a
354     // Y = 0               | else
355     case 2:
356     {
357 
358         if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)
359         {
360             Val = 0;
361         }
362         else
363         {
364             disc = -Params[2] / Params[1];
365 
366             if (R >= disc) {
367 
368                 e = Params[1] * R + Params[2];
369 
370                 if (e > 0)
371                     Val = pow(e, Params[0]);
372                 else
373                     Val = 0;
374             }
375             else
376                 Val = 0;
377         }
378     }
379     break;
380 
381      // Type 2 Reversed
382      // X = (Y ^1/g  - b) / a
383      case -2:
384      {
385          if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||
386              fabs(Params[1]) < MATRIX_DET_TOLERANCE)
387          {
388              Val = 0;
389          }
390          else
391          {
392              if (R < 0)
393                  Val = 0;
394              else
395                  Val = (pow(R, 1.0 / Params[0]) - Params[2]) / Params[1];
396 
397              if (Val < 0)
398                  Val = 0;
399          }
400      }
401      break;
402 
403 
404     // IEC 61966-3
405     // Y = (aX + b)^Gamma | X <= -b/a
406     // Y = c              | else
407     case 3:
408     {
409         if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)
410         {
411             Val = 0;
412         }
413         else
414         {
415             disc = -Params[2] / Params[1];
416             if (disc < 0)
417                 disc = 0;
418 
419             if (R >= disc) {
420 
421                 e = Params[1] * R + Params[2];
422 
423                 if (e > 0)
424                     Val = pow(e, Params[0]) + Params[3];
425                 else
426                     Val = 0;
427             }
428             else
429                 Val = Params[3];
430         }
431     }
432     break;
433 
434 
435     // Type 3 reversed
436     // X=((Y-c)^1/g - b)/a      | (Y>=c)
437     // X=-b/a                   | (Y<c)
438     case -3:
439     {
440         if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)
441         {
442             Val = 0;
443         }
444         else
445         {
446             if (R >= Params[3]) {
447 
448                 e = R - Params[3];
449 
450                 if (e > 0)
451                     Val = (pow(e, 1 / Params[0]) - Params[2]) / Params[1];
452                 else
453                     Val = 0;
454             }
455             else {
456                 Val = -Params[2] / Params[1];
457             }
458         }
459     }
460     break;
461 
462 
463     // IEC 61966-2.1 (sRGB)
464     // Y = (aX + b)^Gamma | X >= d
465     // Y = cX             | X < d
466     case 4:
467         if (R >= Params[4]) {
468 
469             e = Params[1]*R + Params[2];
470 
471             if (e > 0)
472                 Val = pow(e, Params[0]);
473             else
474                 Val = 0;
475         }
476         else
477             Val = R * Params[3];
478         break;
479 
480     // Type 4 reversed
481     // X=((Y^1/g-b)/a)    | Y >= (ad+b)^g
482     // X=Y/c              | Y< (ad+b)^g
483     case -4:
484     {
485         if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||
486             fabs(Params[1]) < MATRIX_DET_TOLERANCE ||
487             fabs(Params[3]) < MATRIX_DET_TOLERANCE)
488         {
489             Val = 0;
490         }
491         else
492         {
493             e = Params[1] * Params[4] + Params[2];
494             if (e < 0)
495                 disc = 0;
496             else
497                 disc = pow(e, Params[0]);
498 
499             if (R >= disc) {
500 
501                 Val = (pow(R, 1.0 / Params[0]) - Params[2]) / Params[1];
502             }
503             else {
504                 Val = R / Params[3];
505             }
506         }
507     }
508     break;
509 
510 
511     // Y = (aX + b)^Gamma + e | X >= d
512     // Y = cX + f             | X < d
513     case 5:
514         if (R >= Params[4]) {
515 
516             e = Params[1]*R + Params[2];
517 
518             if (e > 0)
519                 Val = pow(e, Params[0]) + Params[5];
520             else
521                 Val = Params[5];
522         }
523         else
524             Val = R*Params[3] + Params[6];
525         break;
526 
527 
528     // Reversed type 5
529     // X=((Y-e)1/g-b)/a   | Y >=(ad+b)^g+e), cd+f
530     // X=(Y-f)/c          | else
531     case -5:
532     {
533         if (fabs(Params[1]) < MATRIX_DET_TOLERANCE ||
534             fabs(Params[3]) < MATRIX_DET_TOLERANCE)
535         {
536             Val = 0;
537         }
538         else
539         {
540             disc = Params[3] * Params[4] + Params[6];
541             if (R >= disc) {
542 
543                 e = R - Params[5];
544                 if (e < 0)
545                     Val = 0;
546                 else
547                     Val = (pow(e, 1.0 / Params[0]) - Params[2]) / Params[1];
548             }
549             else {
550                 Val = (R - Params[6]) / Params[3];
551             }
552         }
553     }
554     break;
555 
556 
557     // Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf
558     // Type 6 is basically identical to type 5 without d
559 
560     // Y = (a * X + b) ^ Gamma + c
561     case 6:
562         e = Params[1]*R + Params[2];
563 
564         if (e < 0)
565             Val = Params[3];
566         else
567             Val = pow(e, Params[0]) + Params[3];
568         break;
569 
570     // ((Y - c) ^1/Gamma - b) / a
571     case -6:
572     {
573         if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)
574         {
575             Val = 0;
576         }
577         else
578         {
579             e = R - Params[3];
580             if (e < 0)
581                 Val = 0;
582             else
583                 Val = (pow(e, 1.0 / Params[0]) - Params[2]) / Params[1];
584         }
585     }
586     break;
587 
588 
589     // Y = a * log (b * X^Gamma + c) + d
590     case 7:
591 
592        e = Params[2] * pow(R, Params[0]) + Params[3];
593        if (e <= 0)
594            Val = Params[4];
595        else
596            Val = Params[1]*log10(e) + Params[4];
597        break;
598 
599     // (Y - d) / a = log(b * X ^Gamma + c)
600     // pow(10, (Y-d) / a) = b * X ^Gamma + c
601     // pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X
602     case -7:
603     {
604         if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||
605             fabs(Params[1]) < MATRIX_DET_TOLERANCE ||
606             fabs(Params[2]) < MATRIX_DET_TOLERANCE)
607         {
608             Val = 0;
609         }
610         else
611         {
612             Val = pow((pow(10.0, (R - Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]);
613         }
614     }
615     break;
616 
617 
618    //Y = a * b^(c*X+d) + e
619    case 8:
620        Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]);
621        break;
622 
623 
624    // Y = (log((y-e) / a) / log(b) - d ) / c
625    // a=0, b=1, c=2, d=3, e=4,
626    case -8:
627 
628        disc = R - Params[4];
629        if (disc < 0) Val = 0;
630        else
631        {
632            if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||
633                fabs(Params[2]) < MATRIX_DET_TOLERANCE)
634            {
635                Val = 0;
636            }
637            else
638            {
639                Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2];
640            }
641        }
642        break;
643 
644    // S-Shaped: (1 - (1-x)^1/g)^1/g
645    case 108:
646        if (fabs(Params[0]) < MATRIX_DET_TOLERANCE)
647            Val = 0;
648        else
649            Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]);
650       break;
651 
652     // y = (1 - (1-x)^1/g)^1/g
653     // y^g = (1 - (1-x)^1/g)
654     // 1 - y^g = (1-x)^1/g
655     // (1 - y^g)^g = 1 - x
656     // 1 - (1 - y^g)^g
657     case -108:
658         Val = 1 - pow(1 - pow(R, Params[0]), Params[0]);
659         break;
660 
661     default:
662         // Unsupported parametric curve. Should never reach here
663         return 0;
664     }
665 
666     return Val;
667 }
668 
669 // Evaluate a segmented function for a single value. Return -Inf if no valid segment found .
670 // If fn type is 0, perform an interpolation on the table
671 static
EvalSegmentedFn(cmsContext ContextID,const cmsToneCurve * g,cmsFloat64Number R)672 cmsFloat64Number EvalSegmentedFn(cmsContext ContextID, const cmsToneCurve *g, cmsFloat64Number R)
673 {
674     int i;
675     cmsFloat32Number Out32;
676     cmsFloat64Number Out;
677 
678     for (i = (int) g->nSegments - 1; i >= 0; --i) {
679 
680         // Check for domain
681         if ((R > g->Segments[i].x0) && (R <= g->Segments[i].x1)) {
682 
683             // Type == 0 means segment is sampled
684             if (g->Segments[i].Type == 0) {
685 
686                 cmsFloat32Number R1 = (cmsFloat32Number)(R - g->Segments[i].x0) / (g->Segments[i].x1 - g->Segments[i].x0);
687 
688                 // Setup the table (TODO: clean that)
689                 g->SegInterp[i]->Table = g->Segments[i].SampledPoints;
690 
691                 g->SegInterp[i]->Interpolation.LerpFloat(ContextID, &R1, &Out32, g->SegInterp[i]);
692                 Out = (cmsFloat64Number) Out32;
693 
694             }
695             else {
696                 Out = g->Evals[i](ContextID, g->Segments[i].Type, g->Segments[i].Params, R);
697             }
698 
699             if (isinf(Out))
700                 return PLUS_INF;
701             else
702             {
703                 if (isinf(-Out))
704                     return MINUS_INF;
705             }
706 
707             return Out;
708         }
709     }
710 
711     return MINUS_INF;
712 }
713 
714 // Access to estimated low-res table
cmsGetToneCurveEstimatedTableEntries(cmsContext ContextID,const cmsToneCurve * t)715 cmsUInt32Number CMSEXPORT cmsGetToneCurveEstimatedTableEntries(cmsContext ContextID, const cmsToneCurve* t)
716 {
717     cmsUNUSED_PARAMETER(ContextID);
718     _cmsAssert(t != NULL);
719     return t ->nEntries;
720 }
721 
cmsGetToneCurveEstimatedTable(cmsContext ContextID,const cmsToneCurve * t)722 const cmsUInt16Number* CMSEXPORT cmsGetToneCurveEstimatedTable(cmsContext ContextID, const cmsToneCurve* t)
723 {
724     cmsUNUSED_PARAMETER(ContextID);
725     _cmsAssert(t != NULL);
726     return t ->Table16;
727 }
728 
729 
730 // Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the
731 // floating point description empty.
cmsBuildTabulatedToneCurve16(cmsContext ContextID,cmsUInt32Number nEntries,const cmsUInt16Number Values[])732 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsUInt32Number nEntries, const cmsUInt16Number Values[])
733 {
734     return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values);
735 }
736 
737 static
EntriesByGamma(cmsFloat64Number Gamma)738 cmsUInt32Number EntriesByGamma(cmsFloat64Number Gamma)
739 {
740     if (fabs(Gamma - 1.0) < 0.001) return 2;
741     return 4096;
742 }
743 
744 
745 // Create a segmented gamma, fill the table
cmsBuildSegmentedToneCurve(cmsContext ContextID,cmsUInt32Number nSegments,const cmsCurveSegment Segments[])746 cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,
747                                                    cmsUInt32Number nSegments, const cmsCurveSegment Segments[])
748 {
749     cmsUInt32Number i;
750     cmsFloat64Number R, Val;
751     cmsToneCurve* g;
752     cmsUInt32Number nGridPoints = 4096;
753 
754     _cmsAssert(Segments != NULL);
755 
756     // Optimizatin for identity curves.
757     if (nSegments == 1 && Segments[0].Type == 1) {
758 
759         nGridPoints = EntriesByGamma(Segments[0].Params[0]);
760     }
761 
762     g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL);
763     if (g == NULL) return NULL;
764 
765     // Once we have the floating point version, we can approximate a 16 bit table of 4096 entries
766     // for performance reasons. This table would normally not be used except on 8/16 bits transforms.
767     for (i = 0; i < nGridPoints; i++) {
768 
769         R   = (cmsFloat64Number) i / (nGridPoints-1);
770 
771         Val = EvalSegmentedFn(ContextID, g, R);
772 
773         // Round and saturate
774         g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0);
775     }
776 
777     return g;
778 }
779 
780 // Use a segmented curve to store the floating point table
cmsBuildTabulatedToneCurveFloat(cmsContext ContextID,cmsUInt32Number nEntries,const cmsFloat32Number values[])781 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
782 {
783     cmsCurveSegment Seg[3];
784 
785     // A segmented tone curve should have function segments in the first and last positions
786     // Initialize segmented curve part up to 0 to constant value = samples[0]
787     Seg[0].x0 = MINUS_INF;
788     Seg[0].x1 = 0;
789     Seg[0].Type = 6;
790 
791     Seg[0].Params[0] = 1;
792     Seg[0].Params[1] = 0;
793     Seg[0].Params[2] = 0;
794     Seg[0].Params[3] = values[0];
795     Seg[0].Params[4] = 0;
796 
797     // From zero to 1
798     Seg[1].x0 = 0;
799     Seg[1].x1 = 1.0;
800     Seg[1].Type = 0;
801 
802     Seg[1].nGridPoints = nEntries;
803     Seg[1].SampledPoints = (cmsFloat32Number*) values;
804 
805     // Final segment is constant = lastsample
806     Seg[2].x0 = 1.0;
807     Seg[2].x1 = PLUS_INF;
808     Seg[2].Type = 6;
809 
810     Seg[2].Params[0] = 1;
811     Seg[2].Params[1] = 0;
812     Seg[2].Params[2] = 0;
813     Seg[2].Params[3] = values[nEntries-1];
814     Seg[2].Params[4] = 0;
815 
816 
817     return cmsBuildSegmentedToneCurve(ContextID, 3, Seg);
818 }
819 
820 // Parametric curves
821 //
822 // Parameters goes as: Curve, a, b, c, d, e, f
823 // Type is the ICC type +1
824 // if type is negative, then the curve is analytically inverted
cmsBuildParametricToneCurve(cmsContext ContextID,cmsInt32Number Type,const cmsFloat64Number Params[])825 cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])
826 {
827     cmsCurveSegment Seg0;
828     int Pos = 0;
829     cmsUInt32Number size;
830     _cmsParametricCurvesCollection* c = GetParametricCurveByType(ContextID, Type, &Pos);
831 
832     _cmsAssert(Params != NULL);
833 
834     if (c == NULL) {
835         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
836         return NULL;
837     }
838 
839     memset(&Seg0, 0, sizeof(Seg0));
840 
841     Seg0.x0   = MINUS_INF;
842     Seg0.x1   = PLUS_INF;
843     Seg0.Type = Type;
844 
845     size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number);
846     memmove(Seg0.Params, Params, size);
847 
848     return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0);
849 }
850 
851 
852 
853 // Build a gamma table based on gamma constant
cmsBuildGamma(cmsContext ContextID,cmsFloat64Number Gamma)854 cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma)
855 {
856     return cmsBuildParametricToneCurve(ContextID, 1, &Gamma);
857 }
858 
859 
860 // Free all memory taken by the gamma curve
cmsFreeToneCurve(cmsContext ContextID,cmsToneCurve * Curve)861 void CMSEXPORT cmsFreeToneCurve(cmsContext ContextID, cmsToneCurve* Curve)
862 {
863     if (Curve == NULL) return;
864 
865     _cmsFreeInterpParams(ContextID, Curve ->InterpParams);
866 
867     if (Curve -> Table16)
868         _cmsFree(ContextID, Curve ->Table16);
869 
870     if (Curve ->Segments) {
871 
872         cmsUInt32Number i;
873 
874         for (i=0; i < Curve ->nSegments; i++) {
875 
876             if (Curve ->Segments[i].SampledPoints) {
877                 _cmsFree(ContextID, Curve ->Segments[i].SampledPoints);
878             }
879 
880             if (Curve ->SegInterp[i] != 0)
881                 _cmsFreeInterpParams(ContextID, Curve->SegInterp[i]);
882         }
883 
884         _cmsFree(ContextID, Curve ->Segments);
885         _cmsFree(ContextID, Curve ->SegInterp);
886     }
887 
888     if (Curve -> Evals)
889         _cmsFree(ContextID, Curve -> Evals);
890 
891     if (Curve) _cmsFree(ContextID, Curve);
892 }
893 
894 // Utility function, free 3 gamma tables
cmsFreeToneCurveTriple(cmsContext ContextID,cmsToneCurve * Curve[3])895 void CMSEXPORT cmsFreeToneCurveTriple(cmsContext ContextID, cmsToneCurve* Curve[3])
896 {
897 
898     _cmsAssert(Curve != NULL);
899 
900     if (Curve[0] != NULL) cmsFreeToneCurve(ContextID, Curve[0]);
901     if (Curve[1] != NULL) cmsFreeToneCurve(ContextID, Curve[1]);
902     if (Curve[2] != NULL) cmsFreeToneCurve(ContextID, Curve[2]);
903 
904     Curve[0] = Curve[1] = Curve[2] = NULL;
905 }
906 
907 
908 // Duplicate a gamma table
cmsDupToneCurve(cmsContext ContextID,const cmsToneCurve * In)909 cmsToneCurve* CMSEXPORT cmsDupToneCurve(cmsContext ContextID, const cmsToneCurve* In)
910 {
911     if (In == NULL) return NULL;
912 
913     return  AllocateToneCurveStruct(ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);
914 }
915 
916 // Joins two curves for X and Y. Curves should be monotonic.
917 // We want to get
918 //
919 //      y = Y^-1(X(t))
920 //
cmsJoinToneCurve(cmsContext ContextID,const cmsToneCurve * X,const cmsToneCurve * Y,cmsUInt32Number nResultingPoints)921 cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID,
922                                       const cmsToneCurve* X,
923                                       const cmsToneCurve* Y, cmsUInt32Number nResultingPoints)
924 {
925     cmsToneCurve* out = NULL;
926     cmsToneCurve* Yreversed = NULL;
927     cmsFloat32Number t, x;
928     cmsFloat32Number* Res = NULL;
929     cmsUInt32Number i;
930 
931 
932     _cmsAssert(X != NULL);
933     _cmsAssert(Y != NULL);
934 
935     Yreversed = cmsReverseToneCurveEx(ContextID, nResultingPoints, Y);
936     if (Yreversed == NULL) goto Error;
937 
938     Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number));
939     if (Res == NULL) goto Error;
940 
941     //Iterate
942     for (i=0; i <  nResultingPoints; i++) {
943 
944         t = (cmsFloat32Number) i / (nResultingPoints-1);
945         x = cmsEvalToneCurveFloat(ContextID, X,  t);
946         Res[i] = cmsEvalToneCurveFloat(ContextID, Yreversed, x);
947     }
948 
949     // Allocate space for output
950     out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res);
951 
952 Error:
953 
954     if (Res != NULL) _cmsFree(ContextID, Res);
955     if (Yreversed != NULL) cmsFreeToneCurve(ContextID, Yreversed);
956 
957     return out;
958 }
959 
960 
961 
962 // Get the surrounding nodes. This is tricky on non-monotonic tables
963 static
GetInterval(cmsFloat64Number In,const cmsUInt16Number LutTable[],const struct _cms_interp_struc * p)964 int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)
965 {
966     int i;
967     int y0, y1;
968 
969     // A 1 point table is not allowed
970     if (p -> Domain[0] < 1) return -1;
971 
972     // Let's see if ascending or descending.
973     if (LutTable[0] < LutTable[p ->Domain[0]]) {
974 
975         // Table is overall ascending
976         for (i = (int) p->Domain[0] - 1; i >= 0; --i) {
977 
978             y0 = LutTable[i];
979             y1 = LutTable[i+1];
980 
981             if (y0 <= y1) { // Increasing
982                 if (In >= y0 && In <= y1) return i;
983             }
984             else
985                 if (y1 < y0) { // Decreasing
986                     if (In >= y1 && In <= y0) return i;
987                 }
988         }
989     }
990     else {
991         // Table is overall descending
992         for (i=0; i < (int) p -> Domain[0]; i++) {
993 
994             y0 = LutTable[i];
995             y1 = LutTable[i+1];
996 
997             if (y0 <= y1) { // Increasing
998                 if (In >= y0 && In <= y1) return i;
999             }
1000             else
1001                 if (y1 < y0) { // Decreasing
1002                     if (In >= y1 && In <= y0) return i;
1003                 }
1004         }
1005     }
1006 
1007     return -1;
1008 }
1009 
1010 // Reverse a gamma table
cmsReverseToneCurveEx(cmsContext ContextID,cmsUInt32Number nResultSamples,const cmsToneCurve * InCurve)1011 cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsContext ContextID, cmsUInt32Number nResultSamples, const cmsToneCurve* InCurve)
1012 {
1013     cmsToneCurve *out;
1014     cmsFloat64Number a = 0, b = 0, y, x1, y1, x2, y2;
1015     int i, j;
1016     int Ascending;
1017 
1018     _cmsAssert(InCurve != NULL);
1019 
1020     // Try to reverse it analytically whatever possible
1021 
1022     if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 &&
1023         /* InCurve -> Segments[0].Type <= 5 */
1024         GetParametricCurveByType(ContextID, InCurve ->Segments[0].Type, NULL) != NULL) {
1025 
1026         return cmsBuildParametricToneCurve(ContextID,
1027                                        -(InCurve -> Segments[0].Type),
1028                                        InCurve -> Segments[0].Params);
1029     }
1030 
1031     // Nope, reverse the table.
1032     out = cmsBuildTabulatedToneCurve16(ContextID, nResultSamples, NULL);
1033     if (out == NULL)
1034         return NULL;
1035 
1036     // We want to know if this is an ascending or descending table
1037     Ascending = !cmsIsToneCurveDescending(ContextID, InCurve);
1038 
1039     // Iterate across Y axis
1040     for (i=0; i < (int) nResultSamples; i++) {
1041 
1042         y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1);
1043 
1044         // Find interval in which y is within.
1045         j = GetInterval(y, InCurve->Table16, InCurve->InterpParams);
1046         if (j >= 0) {
1047 
1048 
1049             // Get limits of interval
1050             x1 = InCurve ->Table16[j];
1051             x2 = InCurve ->Table16[j+1];
1052 
1053             y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1);
1054             y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1);
1055 
1056             // If collapsed, then use any
1057             if (x1 == x2) {
1058 
1059                 out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1);
1060                 continue;
1061 
1062             } else {
1063 
1064                 // Interpolate
1065                 a = (y2 - y1) / (x2 - x1);
1066                 b = y2 - a * x2;
1067             }
1068         }
1069 
1070         out ->Table16[i] = _cmsQuickSaturateWord(a* y + b);
1071     }
1072 
1073 
1074     return out;
1075 }
1076 
1077 // Reverse a gamma table
cmsReverseToneCurve(cmsContext ContextID,const cmsToneCurve * InGamma)1078 cmsToneCurve* CMSEXPORT cmsReverseToneCurve(cmsContext ContextID, const cmsToneCurve* InGamma)
1079 {
1080     _cmsAssert(InGamma != NULL);
1081 
1082     return cmsReverseToneCurveEx(ContextID, 4096, InGamma);
1083 }
1084 
1085 // From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
1086 // differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
1087 //
1088 // Smoothing and interpolation with second differences.
1089 //
1090 //   Input:  weights (w), data (y): vector from 1 to m.
1091 //   Input:  smoothing parameter (lambda), length (m).
1092 //   Output: smoothed vector (z): vector from 1 to m.
1093 
1094 static
smooth2(cmsContext ContextID,cmsFloat32Number w[],cmsFloat32Number y[],cmsFloat32Number z[],cmsFloat32Number lambda,int m)1095 cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[],
1096                 cmsFloat32Number z[], cmsFloat32Number lambda, int m)
1097 {
1098     int i, i1, i2;
1099     cmsFloat32Number *c, *d, *e;
1100     cmsBool st;
1101 
1102 
1103     c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
1104     d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
1105     e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
1106 
1107     if (c != NULL && d != NULL && e != NULL) {
1108 
1109 
1110     d[1] = w[1] + lambda;
1111     c[1] = -2 * lambda / d[1];
1112     e[1] = lambda /d[1];
1113     z[1] = w[1] * y[1];
1114     d[2] = w[2] + 5 * lambda - d[1] * c[1] *  c[1];
1115     c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
1116     e[2] = lambda / d[2];
1117     z[2] = w[2] * y[2] - c[1] * z[1];
1118 
1119     for (i = 3; i < m - 1; i++) {
1120         i1 = i - 1; i2 = i - 2;
1121         d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1122         c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
1123         e[i] = lambda / d[i];
1124         z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
1125     }
1126 
1127     i1 = m - 2; i2 = m - 3;
1128 
1129     d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1130     c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
1131     z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
1132     i1 = m - 1; i2 = m - 2;
1133 
1134     d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1135     z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
1136     z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
1137 
1138     for (i = m - 2; 1<= i; i--)
1139         z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
1140 
1141       st = TRUE;
1142     }
1143     else st = FALSE;
1144 
1145     if (c != NULL) _cmsFree(ContextID, c);
1146     if (d != NULL) _cmsFree(ContextID, d);
1147     if (e != NULL) _cmsFree(ContextID, e);
1148 
1149     return st;
1150 }
1151 
1152 // Smooths a curve sampled at regular intervals.
cmsSmoothToneCurve(cmsContext ContextID,cmsToneCurve * Tab,cmsFloat64Number lambda)1153 cmsBool  CMSEXPORT cmsSmoothToneCurve(cmsContext ContextID, cmsToneCurve* Tab, cmsFloat64Number lambda)
1154 {
1155     cmsBool SuccessStatus = TRUE;
1156     cmsFloat32Number *w, *y, *z;
1157     cmsUInt32Number i, nItems, Zeros, Poles;
1158 
1159     if (Tab != NULL && Tab->InterpParams != NULL)
1160     {
1161         if (!cmsIsToneCurveLinear(ContextID, Tab)) // Only non-linear curves need smoothing
1162         {
1163             nItems = Tab->nEntries;
1164             if (nItems < MAX_NODES_IN_CURVE)
1165             {
1166                 // Allocate one more item than needed
1167                 w = (cmsFloat32Number *)_cmsCalloc(ContextID, nItems + 1, sizeof(cmsFloat32Number));
1168                 y = (cmsFloat32Number *)_cmsCalloc(ContextID, nItems + 1, sizeof(cmsFloat32Number));
1169                 z = (cmsFloat32Number *)_cmsCalloc(ContextID, nItems + 1, sizeof(cmsFloat32Number));
1170 
1171                 if (w != NULL && y != NULL && z != NULL) // Ensure no memory allocation failure
1172                 {
1173                     memset(w, 0, (nItems + 1) * sizeof(cmsFloat32Number));
1174                     memset(y, 0, (nItems + 1) * sizeof(cmsFloat32Number));
1175                     memset(z, 0, (nItems + 1) * sizeof(cmsFloat32Number));
1176 
1177                     for (i = 0; i < nItems; i++)
1178                     {
1179                         y[i + 1] = (cmsFloat32Number)Tab->Table16[i];
1180                         w[i + 1] = 1.0;
1181                     }
1182 
1183                     if (smooth2(ContextID, w, y, z, (cmsFloat32Number)lambda, (int)nItems))
1184                     {
1185                         // Do some reality - checking...
1186 
1187                         Zeros = Poles = 0;
1188                         for (i = nItems; i > 1; --i)
1189                         {
1190                             if (z[i] == 0.) Zeros++;
1191                             if (z[i] >= 65535.) Poles++;
1192                             if (z[i] < z[i - 1])
1193                             {
1194                                 cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic.");
1195                                 SuccessStatus = FALSE;
1196                                 break;
1197                             }
1198                         }
1199 
1200                         if (SuccessStatus && Zeros > (nItems / 3))
1201                         {
1202                             cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros.");
1203                             SuccessStatus = FALSE;
1204                         }
1205 
1206                         if (SuccessStatus && Poles > (nItems / 3))
1207                         {
1208                             cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles.");
1209                             SuccessStatus = FALSE;
1210                         }
1211 
1212                         if (SuccessStatus) // Seems ok
1213                         {
1214                             for (i = 0; i < nItems; i++)
1215                             {
1216                                 // Clamp to cmsUInt16Number
1217                                 Tab->Table16[i] = _cmsQuickSaturateWord(z[i + 1]);
1218                             }
1219                         }
1220                     }
1221                     else // Could not smooth
1222                     {
1223                         cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Function smooth2 failed.");
1224                         SuccessStatus = FALSE;
1225                     }
1226                 }
1227                 else // One or more buffers could not be allocated
1228                 {
1229                     cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Could not allocate memory.");
1230                     SuccessStatus = FALSE;
1231                 }
1232 
1233                 if (z != NULL)
1234                     _cmsFree(ContextID, z);
1235 
1236                 if (y != NULL)
1237                     _cmsFree(ContextID, y);
1238 
1239                 if (w != NULL)
1240                     _cmsFree(ContextID, w);
1241             }
1242             else // too many items in the table
1243             {
1244                 cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Too many points.");
1245                 SuccessStatus = FALSE;
1246             }
1247         }
1248     }
1249     else // Tab parameter or Tab->InterpParams is NULL
1250     {
1251         // Can't signal an error here since the ContextID is not known at this point
1252         SuccessStatus = FALSE;
1253     }
1254 
1255     return SuccessStatus;
1256 }
1257 
1258 // Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting
1259 // in a linear table. This way assures it is linear in 12 bits, which should be enough in most cases.
cmsIsToneCurveLinear(cmsContext ContextID,const cmsToneCurve * Curve)1260 cmsBool CMSEXPORT cmsIsToneCurveLinear(cmsContext ContextID, const cmsToneCurve* Curve)
1261 {
1262     int i;
1263     int diff;
1264     cmsUNUSED_PARAMETER(ContextID);
1265 
1266     _cmsAssert(Curve != NULL);
1267 
1268     for (i=0; i < (int) Curve ->nEntries; i++) {
1269 
1270         diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries));
1271         if (diff > 0x0f)
1272             return FALSE;
1273     }
1274 
1275     return TRUE;
1276 }
1277 
1278 // Same, but for monotonicity
cmsIsToneCurveMonotonic(cmsContext ContextID,const cmsToneCurve * t)1279 cmsBool  CMSEXPORT cmsIsToneCurveMonotonic(cmsContext ContextID, const cmsToneCurve* t)
1280 {
1281     cmsUInt32Number n;
1282     int i, last;
1283     cmsBool lDescending;
1284 
1285     _cmsAssert(t != NULL);
1286 
1287     // Degenerated curves are monotonic? Ok, let's pass them
1288     n = t ->nEntries;
1289     if (n < 2) return TRUE;
1290 
1291     // Curve direction
1292     lDescending = cmsIsToneCurveDescending(ContextID, t);
1293 
1294     if (lDescending) {
1295 
1296         last = t ->Table16[0];
1297 
1298         for (i = 1; i < (int) n; i++) {
1299 
1300             if (t ->Table16[i] - last > 2) // We allow some ripple
1301                 return FALSE;
1302             else
1303                 last = t ->Table16[i];
1304 
1305         }
1306     }
1307     else {
1308 
1309         last = t ->Table16[n-1];
1310 
1311         for (i = (int) n - 2; i >= 0; --i) {
1312 
1313             if (t ->Table16[i] - last > 2)
1314                 return FALSE;
1315             else
1316                 last = t ->Table16[i];
1317 
1318         }
1319     }
1320 
1321     return TRUE;
1322 }
1323 
1324 // Same, but for descending tables
cmsIsToneCurveDescending(cmsContext ContextID,const cmsToneCurve * t)1325 cmsBool  CMSEXPORT cmsIsToneCurveDescending(cmsContext ContextID, const cmsToneCurve* t)
1326 {
1327     _cmsAssert(t != NULL);
1328     cmsUNUSED_PARAMETER(ContextID);
1329 
1330     return t ->Table16[0] > t ->Table16[t ->nEntries-1];
1331 }
1332 
1333 
1334 // Another info fn: is out gamma table multisegment?
cmsIsToneCurveMultisegment(cmsContext ContextID,const cmsToneCurve * t)1335 cmsBool  CMSEXPORT cmsIsToneCurveMultisegment(cmsContext ContextID, const cmsToneCurve* t)
1336 {
1337     _cmsAssert(t != NULL);
1338     cmsUNUSED_PARAMETER(ContextID);
1339 
1340     return t -> nSegments > 1;
1341 }
1342 
cmsGetToneCurveParametricType(cmsContext ContextID,const cmsToneCurve * t)1343 cmsInt32Number  CMSEXPORT cmsGetToneCurveParametricType(cmsContext ContextID, const cmsToneCurve* t)
1344 {
1345     _cmsAssert(t != NULL);
1346     cmsUNUSED_PARAMETER(ContextID);
1347 
1348     if (t -> nSegments != 1) return 0;
1349     return t ->Segments[0].Type;
1350 }
1351 
1352 // We need accuracy this time
cmsEvalToneCurveFloat(cmsContext ContextID,const cmsToneCurve * Curve,cmsFloat32Number v)1353 cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(cmsContext ContextID, const cmsToneCurve* Curve, cmsFloat32Number v)
1354 {
1355     _cmsAssert(Curve != NULL);
1356 
1357     // Check for 16 bits table. If so, this is a limited-precision tone curve
1358     if (Curve ->nSegments == 0) {
1359 
1360         cmsUInt16Number In, Out;
1361 
1362         In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0);
1363         Out = cmsEvalToneCurve16(ContextID, Curve, In);
1364 
1365         return (cmsFloat32Number) (Out / 65535.0);
1366     }
1367 
1368     return (cmsFloat32Number) EvalSegmentedFn(ContextID, Curve, v);
1369 }
1370 
1371 // We need xput over here
cmsEvalToneCurve16(cmsContext ContextID,const cmsToneCurve * Curve,cmsUInt16Number v)1372 cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(cmsContext ContextID, const cmsToneCurve* Curve, cmsUInt16Number v)
1373 {
1374     cmsUInt16Number out;
1375 
1376     _cmsAssert(Curve != NULL);
1377 
1378     Curve ->InterpParams ->Interpolation.Lerp16(ContextID, &v, &out, Curve ->InterpParams);
1379     return out;
1380 }
1381 
1382 
1383 // Least squares fitting.
1384 // A mathematical procedure for finding the best-fitting curve to a given set of points by
1385 // minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.
1386 // The sum of the squares of the offsets is used instead of the offset absolute values because
1387 // this allows the residuals to be treated as a continuous differentiable quantity.
1388 //
1389 // y = f(x) = x ^ g
1390 //
1391 // R  = (yi - (xi^g))
1392 // R2 = (yi - (xi^g))2
1393 // SUM R2 = SUM (yi - (xi^g))2
1394 //
1395 // dR2/dg = -2 SUM x^g log(x)(y - x^g)
1396 // solving for dR2/dg = 0
1397 //
1398 // g = 1/n * SUM(log(y) / log(x))
1399 
cmsEstimateGamma(cmsContext ContextID,const cmsToneCurve * t,cmsFloat64Number Precision)1400 cmsFloat64Number CMSEXPORT cmsEstimateGamma(cmsContext ContextID, const cmsToneCurve* t, cmsFloat64Number Precision)
1401 {
1402     cmsFloat64Number gamma, sum, sum2;
1403     cmsFloat64Number n, x, y, Std;
1404     cmsUInt32Number i;
1405 
1406     _cmsAssert(t != NULL);
1407 
1408     sum = sum2 = n = 0;
1409 
1410     // Excluding endpoints
1411     for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) {
1412 
1413         x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1);
1414         y = (cmsFloat64Number) cmsEvalToneCurveFloat(ContextID, t, (cmsFloat32Number) x);
1415 
1416         // Avoid 7% on lower part to prevent
1417         // artifacts due to linear ramps
1418 
1419         if (y > 0. && y < 1. && x > 0.07) {
1420 
1421             gamma = log(y) / log(x);
1422             sum  += gamma;
1423             sum2 += gamma * gamma;
1424             n++;
1425         }
1426     }
1427 
1428     // Take a look on SD to see if gamma isn't exponential at all
1429     Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));
1430 
1431     if (Std > Precision)
1432         return -1.0;
1433 
1434     return (sum / n);   // The mean
1435 }
1436