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