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