1 //---------------------------------------------------------------------------------
3 // Little Color Management System
4 // Copyright (c) 1998-2013 Marti Maria Saguer
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:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
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.
24 //---------------------------------------------------------------------------------
26 #include "lcms2_internal.h"
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
38 // ----------------------------------------------------------------- Implementation
39 // Maxim number of nodes
40 #define MAX_NODES_IN_CURVE 4097
41 #define MINUS_INF (-1E22F)
42 #define PLUS_INF (+1E22F)
44 // The list of supported parametric curves
45 typedef struct _cmsParametricCurvesCollection_st {
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
52 struct _cmsParametricCurvesCollection_st* Next; // Next in list
54 } _cmsParametricCurvesCollection;
56 // This is the default (built-in) evaluator
57 static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
60 static _cmsParametricCurvesCollection DefaultCurves = {
61 9, // # of curve types
62 { 1, 2, 3, 4, 5, 6, 7, 8, 108 }, // Parametric curve ID
63 { 1, 3, 4, 5, 7, 4, 5, 5, 1 }, // Parameters by type
64 DefaultEvalParametricFn, // Evaluator
68 // Duplicates the zone of memory used by the plug-in in the new context
70 void DupPluginCurvesList(struct _cmsContext_struct* ctx,
71 const struct _cmsContext_struct* src)
73 _cmsCurvesPluginChunkType newHead = { NULL };
74 _cmsParametricCurvesCollection* entry;
75 _cmsParametricCurvesCollection* Anterior = NULL;
76 _cmsCurvesPluginChunkType* head = (_cmsCurvesPluginChunkType*) src->chunks[CurvesPlugin];
78 _cmsAssert(head != NULL);
80 // Walk the list copying all nodes
81 for (entry = head->ParametricCurves;
83 entry = entry ->Next) {
85 _cmsParametricCurvesCollection *newEntry = ( _cmsParametricCurvesCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsParametricCurvesCollection));
90 // We want to keep the linked list order, so this is a little bit tricky
91 newEntry -> Next = NULL;
93 Anterior -> Next = newEntry;
97 if (newHead.ParametricCurves == NULL)
98 newHead.ParametricCurves = newEntry;
101 ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsCurvesPluginChunkType));
104 // The allocator have to follow the chain
105 void _cmsAllocCurvesPluginChunk(struct _cmsContext_struct* ctx,
106 const struct _cmsContext_struct* src)
108 _cmsAssert(ctx != NULL);
112 // Copy all linked list
113 DupPluginCurvesList(ctx, src);
116 static _cmsCurvesPluginChunkType CurvesPluginChunk = { NULL };
117 ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx ->MemPool, &CurvesPluginChunk, sizeof(_cmsCurvesPluginChunkType));
122 // The linked list head
123 _cmsCurvesPluginChunkType _cmsCurvesPluginChunk = { NULL };
125 // As a way to install new parametric curves
126 cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext ContextID, cmsPluginBase* Data)
128 _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);
129 cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;
130 _cmsParametricCurvesCollection* fl;
134 ctx -> ParametricCurves = NULL;
138 fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsParametricCurvesCollection));
139 if (fl == NULL) return FALSE;
141 // Copy the parameters
142 fl ->Evaluator = Plugin ->Evaluator;
143 fl ->nFunctions = Plugin ->nFunctions;
145 // Make sure no mem overwrites
146 if (fl ->nFunctions > MAX_TYPES_IN_LCMS_PLUGIN)
147 fl ->nFunctions = MAX_TYPES_IN_LCMS_PLUGIN;
150 memmove(fl->FunctionTypes, Plugin ->FunctionTypes, fl->nFunctions * sizeof(cmsUInt32Number));
151 memmove(fl->ParameterCount, Plugin ->ParameterCount, fl->nFunctions * sizeof(cmsUInt32Number));
154 fl ->Next = ctx->ParametricCurves;
155 ctx->ParametricCurves = fl;
162 // Search in type list, return position or -1 if not found
164 int IsInSet(int Type, _cmsParametricCurvesCollection* c)
168 for (i=0; i < c ->nFunctions; i++)
169 if (abs(Type) == c ->FunctionTypes[i]) return i;
175 // Search for the collection which contains a specific type
177 _cmsParametricCurvesCollection *GetParametricCurveByType(cmsContext ContextID, int Type, int* index)
179 _cmsParametricCurvesCollection* c;
181 _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);
183 for (c = ctx->ParametricCurves; c != NULL; c = c ->Next) {
185 Position = IsInSet(Type, c);
187 if (Position != -1) {
193 // If none found, revert for defaults
194 for (c = &DefaultCurves; c != NULL; c = c ->Next) {
196 Position = IsInSet(Type, c);
198 if (Position != -1) {
208 // Low level allocate, which takes care of memory details. nEntries may be zero, and in this case
209 // no optimation curve is computed. nSegments may also be zero in the inverse case, where only the
210 // optimization curve is given. Both features simultaneously is an error
212 cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsInt32Number nEntries,
213 cmsInt32Number nSegments, const cmsCurveSegment* Segments,
214 const cmsUInt16Number* Values)
219 // We allow huge tables, which are then restricted for smoothing operations
220 if (nEntries > 65530 || nEntries < 0) {
221 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve of more than 65530 entries");
225 if (nEntries <= 0 && nSegments <= 0) {
226 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table");
230 // Allocate all required pointers, etc.
231 p = (cmsToneCurve*) _cmsMallocZero(ContextID, sizeof(cmsToneCurve));
234 // In this case, there are no segments
235 if (nSegments <= 0) {
240 p ->Segments = (cmsCurveSegment*) _cmsCalloc(ContextID, nSegments, sizeof(cmsCurveSegment));
241 if (p ->Segments == NULL) goto Error;
243 p ->Evals = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator));
244 if (p ->Evals == NULL) goto Error;
247 p -> nSegments = nSegments;
249 // This 16-bit table contains a limited precision representation of the whole curve and is kept for
250 // increasing xput on certain operations.
255 p ->Table16 = (cmsUInt16Number*) _cmsCalloc(ContextID, nEntries, sizeof(cmsUInt16Number));
256 if (p ->Table16 == NULL) goto Error;
259 p -> nEntries = nEntries;
261 // Initialize members if requested
262 if (Values != NULL && (nEntries > 0)) {
264 for (i=0; i < nEntries; i++)
265 p ->Table16[i] = Values[i];
268 // Initialize the segments stuff. The evaluator for each segment is located and a pointer to it
269 // is placed in advance to maximize performance.
270 if (Segments != NULL && (nSegments > 0)) {
272 _cmsParametricCurvesCollection *c;
274 p ->SegInterp = (cmsInterpParams**) _cmsCalloc(ContextID, nSegments, sizeof(cmsInterpParams*));
275 if (p ->SegInterp == NULL) goto Error;
277 for (i=0; i< nSegments; i++) {
279 // Type 0 is a special marker for table-based curves
280 if (Segments[i].Type == 0)
281 p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT);
283 memmove(&p ->Segments[i], &Segments[i], sizeof(cmsCurveSegment));
285 if (Segments[i].Type == 0 && Segments[i].SampledPoints != NULL)
286 p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints);
288 p ->Segments[i].SampledPoints = NULL;
291 c = GetParametricCurveByType(ContextID, Segments[i].Type, NULL);
293 p ->Evals[i] = c ->Evaluator;
297 p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);
298 if (p->InterpParams != NULL)
302 if (p -> Segments) _cmsFree(ContextID, p ->Segments);
303 if (p -> Evals) _cmsFree(ContextID, p -> Evals);
304 if (p ->Table16) _cmsFree(ContextID, p ->Table16);
305 _cmsFree(ContextID, p);
310 // Parametric Fn using floating point
312 cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)
314 cmsFloat64Number e, Val, disc;
322 if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
328 Val = pow(R, Params[0]);
331 // Type 1 Reversed: X = Y ^1/gamma
335 if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
341 Val = pow(R, 1/Params[0]);
345 // Y = (aX + b)^Gamma | X >= -b/a
348 disc = -Params[2] / Params[1];
352 e = Params[1]*R + Params[2];
355 Val = pow(e, Params[0]);
364 // X = (Y ^1/g - b) / a
369 Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
377 // Y = (aX + b)^Gamma | X <= -b/a
380 disc = -Params[2] / Params[1];
386 e = Params[1]*R + Params[2];
389 Val = pow(e, Params[0]) + Params[3];
399 // X=((Y-c)^1/g - b)/a | (Y>=c)
402 if (R >= Params[3]) {
407 Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
412 Val = -Params[2] / Params[1];
417 // IEC 61966-2.1 (sRGB)
418 // Y = (aX + b)^Gamma | X >= d
421 if (R >= Params[4]) {
423 e = Params[1]*R + Params[2];
426 Val = pow(e, Params[0]);
435 // X=((Y^1/g-b)/a) | Y >= (ad+b)^g
436 // X=Y/c | Y< (ad+b)^g
438 e = Params[1] * Params[4] + Params[2];
442 disc = pow(e, Params[0]);
446 Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
454 // Y = (aX + b)^Gamma + e | X >= d
455 // Y = cX + f | X < d
457 if (R >= Params[4]) {
459 e = Params[1]*R + Params[2];
462 Val = pow(e, Params[0]) + Params[5];
467 Val = R*Params[3] + Params[6];
472 // X=((Y-e)1/g-b)/a | Y >=(ad+b)^g+e), cd+f
476 disc = Params[3] * Params[4] + Params[6];
483 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
486 Val = (R - Params[6]) / Params[3];
491 // Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf
492 // Type 6 is basically identical to type 5 without d
494 // Y = (a * X + b) ^ Gamma + c
496 e = Params[1]*R + Params[2];
501 Val = pow(e, Params[0]) + Params[3];
504 // ((Y - c) ^1/Gamma - b) / a
510 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
514 // Y = a * log (b * X^Gamma + c) + d
517 e = Params[2] * pow(R, Params[0]) + Params[3];
521 Val = Params[1]*log10(e) + Params[4];
524 // (Y - d) / a = log(b * X ^Gamma + c)
525 // pow(10, (Y-d) / a) = b * X ^Gamma + c
526 // pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X
528 Val = pow((pow(10.0, (R-Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]);
532 //Y = a * b^(c*X+d) + e
534 Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]);
538 // Y = (log((y-e) / a) / log(b) - d ) / c
539 // a=0, b=1, c=2, d=3, e=4,
542 disc = R - Params[4];
543 if (disc < 0) Val = 0;
545 Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2];
548 // S-Shaped: (1 - (1-x)^1/g)^1/g
550 Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]);
553 // y = (1 - (1-x)^1/g)^1/g
554 // y^g = (1 - (1-x)^1/g)
555 // 1 - y^g = (1-x)^1/g
556 // (1 - y^g)^g = 1 - x
559 Val = 1 - pow(1 - pow(R, Params[0]), Params[0]);
563 // Unsupported parametric curve. Should never reach here
570 // Evaluate a segmented function for a single value. Return -1 if no valid segment found .
571 // If fn type is 0, perform an interpolation on the table
573 cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
577 for (i = g ->nSegments-1; i >= 0 ; --i) {
580 if ((R > g ->Segments[i].x0) && (R <= g ->Segments[i].x1)) {
582 // Type == 0 means segment is sampled
583 if (g ->Segments[i].Type == 0) {
585 cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0) / (g ->Segments[i].x1 - g ->Segments[i].x0);
586 cmsFloat32Number Out;
588 // Setup the table (TODO: clean that)
589 g ->SegInterp[i]-> Table = g ->Segments[i].SampledPoints;
591 g ->SegInterp[i] -> Interpolation.LerpFloat(&R1, &Out, g ->SegInterp[i]);
596 return g ->Evals[i](g->Segments[i].Type, g ->Segments[i].Params, R);
603 // Access to estimated low-res table
604 cmsUInt32Number CMSEXPORT cmsGetToneCurveEstimatedTableEntries(const cmsToneCurve* t)
606 _cmsAssert(t != NULL);
610 const cmsUInt16Number* CMSEXPORT cmsGetToneCurveEstimatedTable(const cmsToneCurve* t)
612 _cmsAssert(t != NULL);
617 // Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the
618 // floating point description empty.
619 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number Values[])
621 return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values);
625 int EntriesByGamma(cmsFloat64Number Gamma)
627 if (fabs(Gamma - 1.0) < 0.001) return 2;
632 // Create a segmented gamma, fill the table
633 cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,
634 cmsInt32Number nSegments, const cmsCurveSegment Segments[])
637 cmsFloat64Number R, Val;
639 int nGridPoints = 4096;
641 _cmsAssert(Segments != NULL);
643 // Optimizatin for identity curves.
644 if (nSegments == 1 && Segments[0].Type == 1) {
646 nGridPoints = EntriesByGamma(Segments[0].Params[0]);
649 g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL);
650 if (g == NULL) return NULL;
652 // Once we have the floating point version, we can approximate a 16 bit table of 4096 entries
653 // for performance reasons. This table would normally not be used except on 8/16 bits transforms.
654 for (i=0; i < nGridPoints; i++) {
656 R = (cmsFloat64Number) i / (nGridPoints-1);
658 Val = EvalSegmentedFn(g, R);
660 // Round and saturate
661 g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0);
667 // Use a segmented curve to store the floating point table
668 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
670 cmsCurveSegment Seg[3];
672 // A segmented tone curve should have function segments in the first and last positions
673 // Initialize segmented curve part up to 0 to constant value = samples[0]
674 Seg[0].x0 = MINUS_INF;
678 Seg[0].Params[0] = 1;
679 Seg[0].Params[1] = 0;
680 Seg[0].Params[2] = 0;
681 Seg[0].Params[3] = values[0];
682 Seg[0].Params[4] = 0;
689 Seg[1].nGridPoints = nEntries;
690 Seg[1].SampledPoints = (cmsFloat32Number*) values;
692 // Final segment is constant = lastsample
694 Seg[2].x1 = PLUS_INF;
697 Seg[2].Params[0] = 1;
698 Seg[2].Params[1] = 0;
699 Seg[2].Params[2] = 0;
700 Seg[2].Params[3] = values[nEntries-1];
701 Seg[2].Params[4] = 0;
704 return cmsBuildSegmentedToneCurve(ContextID, 3, Seg);
709 // Parameters goes as: Curve, a, b, c, d, e, f
710 // Type is the ICC type +1
711 // if type is negative, then the curve is analyticaly inverted
712 cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])
714 cmsCurveSegment Seg0;
716 cmsUInt32Number size;
717 _cmsParametricCurvesCollection* c = GetParametricCurveByType(ContextID, Type, &Pos);
719 _cmsAssert(Params != NULL);
722 cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
726 memset(&Seg0, 0, sizeof(Seg0));
732 size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number);
733 memmove(Seg0.Params, Params, size);
735 return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0);
740 // Build a gamma table based on gamma constant
741 cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma)
743 return cmsBuildParametricToneCurve(ContextID, 1, &Gamma);
747 // Free all memory taken by the gamma curve
748 void CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve)
750 cmsContext ContextID;
752 if (Curve == NULL) return;
754 ContextID = Curve ->InterpParams->ContextID;
756 _cmsFreeInterpParams(Curve ->InterpParams);
758 if (Curve -> Table16)
759 _cmsFree(ContextID, Curve ->Table16);
761 if (Curve ->Segments) {
765 for (i=0; i < Curve ->nSegments; i++) {
767 if (Curve ->Segments[i].SampledPoints) {
768 _cmsFree(ContextID, Curve ->Segments[i].SampledPoints);
771 if (Curve ->SegInterp[i] != 0)
772 _cmsFreeInterpParams(Curve->SegInterp[i]);
775 _cmsFree(ContextID, Curve ->Segments);
776 _cmsFree(ContextID, Curve ->SegInterp);
780 _cmsFree(ContextID, Curve -> Evals);
782 if (Curve) _cmsFree(ContextID, Curve);
785 // Utility function, free 3 gamma tables
786 void CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3])
789 _cmsAssert(Curve != NULL);
791 if (Curve[0] != NULL) cmsFreeToneCurve(Curve[0]);
792 if (Curve[1] != NULL) cmsFreeToneCurve(Curve[1]);
793 if (Curve[2] != NULL) cmsFreeToneCurve(Curve[2]);
795 Curve[0] = Curve[1] = Curve[2] = NULL;
799 // Duplicate a gamma table
800 cmsToneCurve* CMSEXPORT cmsDupToneCurve(const cmsToneCurve* In)
802 if (In == NULL) return NULL;
804 return AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);
807 // Joins two curves for X and Y. Curves should be monotonic.
812 cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID,
813 const cmsToneCurve* X,
814 const cmsToneCurve* Y, cmsUInt32Number nResultingPoints)
816 cmsToneCurve* out = NULL;
817 cmsToneCurve* Yreversed = NULL;
818 cmsFloat32Number t, x;
819 cmsFloat32Number* Res = NULL;
823 _cmsAssert(X != NULL);
824 _cmsAssert(Y != NULL);
826 Yreversed = cmsReverseToneCurveEx(nResultingPoints, Y);
827 if (Yreversed == NULL) goto Error;
829 Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number));
830 if (Res == NULL) goto Error;
833 for (i=0; i < nResultingPoints; i++) {
835 t = (cmsFloat32Number) i / (nResultingPoints-1);
836 x = cmsEvalToneCurveFloat(X, t);
837 Res[i] = cmsEvalToneCurveFloat(Yreversed, x);
840 // Allocate space for output
841 out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res);
845 if (Res != NULL) _cmsFree(ContextID, Res);
846 if (Yreversed != NULL) cmsFreeToneCurve(Yreversed);
853 // Get the surrounding nodes. This is tricky on non-monotonic tables
855 int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)
860 // A 1 point table is not allowed
861 if (p -> Domain[0] < 1) return -1;
863 // Let's see if ascending or descending.
864 if (LutTable[0] < LutTable[p ->Domain[0]]) {
866 // Table is overall ascending
867 for (i=p->Domain[0]-1; i >=0; --i) {
872 if (y0 <= y1) { // Increasing
873 if (In >= y0 && In <= y1) return i;
876 if (y1 < y0) { // Decreasing
877 if (In >= y1 && In <= y0) return i;
882 // Table is overall descending
883 for (i=0; i < (int) p -> Domain[0]; i++) {
888 if (y0 <= y1) { // Increasing
889 if (In >= y0 && In <= y1) return i;
892 if (y1 < y0) { // Decreasing
893 if (In >= y1 && In <= y0) return i;
901 // Reverse a gamma table
902 cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InCurve)
905 cmsFloat64Number a = 0, b = 0, y, x1, y1, x2, y2;
909 _cmsAssert(InCurve != NULL);
911 // Try to reverse it analytically whatever possible
913 if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 &&
914 /* InCurve -> Segments[0].Type <= 5 */
915 GetParametricCurveByType(InCurve ->InterpParams->ContextID, InCurve ->Segments[0].Type, NULL) != NULL) {
917 return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID,
918 -(InCurve -> Segments[0].Type),
919 InCurve -> Segments[0].Params);
922 // Nope, reverse the table.
923 out = cmsBuildTabulatedToneCurve16(InCurve ->InterpParams->ContextID, nResultSamples, NULL);
927 // We want to know if this is an ascending or descending table
928 Ascending = !cmsIsToneCurveDescending(InCurve);
930 // Iterate across Y axis
931 for (i=0; i < nResultSamples; i++) {
933 y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1);
935 // Find interval in which y is within.
936 j = GetInterval(y, InCurve->Table16, InCurve->InterpParams);
940 // Get limits of interval
941 x1 = InCurve ->Table16[j];
942 x2 = InCurve ->Table16[j+1];
944 y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1);
945 y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1);
947 // If collapsed, then use any
950 out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1);
956 a = (y2 - y1) / (x2 - x1);
961 out ->Table16[i] = _cmsQuickSaturateWord(a* y + b);
968 // Reverse a gamma table
969 cmsToneCurve* CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma)
971 _cmsAssert(InGamma != NULL);
973 return cmsReverseToneCurveEx(4096, InGamma);
976 // From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
977 // differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
979 // Smoothing and interpolation with second differences.
981 // Input: weights (w), data (y): vector from 1 to m.
982 // Input: smoothing parameter (lambda), length (m).
983 // Output: smoothed vector (z): vector from 1 to m.
986 cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[], cmsFloat32Number z[], cmsFloat32Number lambda, int m)
989 cmsFloat32Number *c, *d, *e;
993 c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
994 d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
995 e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
997 if (c != NULL && d != NULL && e != NULL) {
1000 d[1] = w[1] + lambda;
1001 c[1] = -2 * lambda / d[1];
1002 e[1] = lambda /d[1];
1004 d[2] = w[2] + 5 * lambda - d[1] * c[1] * c[1];
1005 c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
1006 e[2] = lambda / d[2];
1007 z[2] = w[2] * y[2] - c[1] * z[1];
1009 for (i = 3; i < m - 1; i++) {
1010 i1 = i - 1; i2 = i - 2;
1011 d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1012 c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
1013 e[i] = lambda / d[i];
1014 z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
1017 i1 = m - 2; i2 = m - 3;
1019 d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1020 c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
1021 z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
1022 i1 = m - 1; i2 = m - 2;
1024 d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
1025 z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
1026 z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
1028 for (i = m - 2; 1<= i; i--)
1029 z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
1035 if (c != NULL) _cmsFree(ContextID, c);
1036 if (d != NULL) _cmsFree(ContextID, d);
1037 if (e != NULL) _cmsFree(ContextID, e);
1042 // Smooths a curve sampled at regular intervals.
1043 cmsBool CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda)
1045 cmsFloat32Number w[MAX_NODES_IN_CURVE], y[MAX_NODES_IN_CURVE], z[MAX_NODES_IN_CURVE];
1046 int i, nItems, Zeros, Poles;
1048 if (Tab == NULL) return FALSE;
1050 if (cmsIsToneCurveLinear(Tab)) return TRUE; // Nothing to do
1052 nItems = Tab -> nEntries;
1054 if (nItems >= MAX_NODES_IN_CURVE) {
1055 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: too many points.");
1059 memset(w, 0, nItems * sizeof(cmsFloat32Number));
1060 memset(y, 0, nItems * sizeof(cmsFloat32Number));
1061 memset(z, 0, nItems * sizeof(cmsFloat32Number));
1063 for (i=0; i < nItems; i++)
1065 y[i+1] = (cmsFloat32Number) Tab -> Table16[i];
1069 if (!smooth2(Tab ->InterpParams->ContextID, w, y, z, (cmsFloat32Number) lambda, nItems)) return FALSE;
1071 // Do some reality - checking...
1073 for (i=nItems; i > 1; --i) {
1075 if (z[i] == 0.) Zeros++;
1076 if (z[i] >= 65535.) Poles++;
1077 if (z[i] < z[i-1]) {
1078 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic.");
1083 if (Zeros > (nItems / 3)) {
1084 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros.");
1087 if (Poles > (nItems / 3)) {
1088 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles.");
1093 for (i=0; i < nItems; i++) {
1095 // Clamp to cmsUInt16Number
1096 Tab -> Table16[i] = _cmsQuickSaturateWord(z[i+1]);
1102 // Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting
1103 // in a linear table. This way assures it is linear in 12 bits, which should be enought in most cases.
1104 cmsBool CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve)
1109 _cmsAssert(Curve != NULL);
1111 for (i=0; i < Curve ->nEntries; i++) {
1113 diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries));
1121 // Same, but for monotonicity
1122 cmsBool CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t)
1126 cmsBool lDescending;
1128 _cmsAssert(t != NULL);
1130 // Degenerated curves are monotonic? Ok, let's pass them
1132 if (n < 2) return TRUE;
1135 lDescending = cmsIsToneCurveDescending(t);
1139 last = t ->Table16[0];
1141 for (i = 1; i < n; i++) {
1143 if (t ->Table16[i] - last > 2) // We allow some ripple
1146 last = t ->Table16[i];
1152 last = t ->Table16[n-1];
1154 for (i = n-2; i >= 0; --i) {
1156 if (t ->Table16[i] - last > 2)
1159 last = t ->Table16[i];
1167 // Same, but for descending tables
1168 cmsBool CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t)
1170 _cmsAssert(t != NULL);
1172 return t ->Table16[0] > t ->Table16[t ->nEntries-1];
1176 // Another info fn: is out gamma table multisegment?
1177 cmsBool CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* t)
1179 _cmsAssert(t != NULL);
1181 return t -> nSegments > 1;
1184 cmsInt32Number CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t)
1186 _cmsAssert(t != NULL);
1188 if (t -> nSegments != 1) return 0;
1189 return t ->Segments[0].Type;
1192 // We need accuracy this time
1193 cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v)
1195 _cmsAssert(Curve != NULL);
1197 // Check for 16 bits table. If so, this is a limited-precision tone curve
1198 if (Curve ->nSegments == 0) {
1200 cmsUInt16Number In, Out;
1202 In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0);
1203 Out = cmsEvalToneCurve16(Curve, In);
1205 return (cmsFloat32Number) (Out / 65535.0);
1208 return (cmsFloat32Number) EvalSegmentedFn(Curve, v);
1211 // We need xput over here
1212 cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v)
1214 cmsUInt16Number out;
1216 _cmsAssert(Curve != NULL);
1218 Curve ->InterpParams ->Interpolation.Lerp16(&v, &out, Curve ->InterpParams);
1223 // Least squares fitting.
1224 // A mathematical procedure for finding the best-fitting curve to a given set of points by
1225 // minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.
1226 // The sum of the squares of the offsets is used instead of the offset absolute values because
1227 // this allows the residuals to be treated as a continuous differentiable quantity.
1231 // R = (yi - (xi^g))
1232 // R2 = (yi - (xi^g))2
1233 // SUM R2 = SUM (yi - (xi^g))2
1235 // dR2/dg = -2 SUM x^g log(x)(y - x^g)
1236 // solving for dR2/dg = 0
1238 // g = 1/n * SUM(log(y) / log(x))
1240 cmsFloat64Number CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision)
1242 cmsFloat64Number gamma, sum, sum2;
1243 cmsFloat64Number n, x, y, Std;
1246 _cmsAssert(t != NULL);
1250 // Excluding endpoints
1251 for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) {
1253 x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1);
1254 y = (cmsFloat64Number) cmsEvalToneCurveFloat(t, (cmsFloat32Number) x);
1256 // Avoid 7% on lower part to prevent
1257 // artifacts due to linear ramps
1259 if (y > 0. && y < 1. && x > 0.07) {
1261 gamma = log(y) / log(x);
1263 sum2 += gamma * gamma;
1268 // Take a look on SD to see if gamma isn't exponential at all
1269 Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));
1271 if (Std > Precision)
1274 return (sum / n); // The mean