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