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