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