Merged-in libcms2 v2.5
[AROS.git] / workbench / libs / lcms2 / src / cmsgamma.c
blobe1531034d039bfa2c3779440a02f8fe8d41d0bec
1 //---------------------------------------------------------------------------------
2 //
3 // Little Color Management System
4 // Copyright (c) 1998-2013 Marti Maria Saguer
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
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
36 // will be built.
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;
57 // This is the default (built-in) evaluator
58 static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
60 // The built-in list
61 static _cmsParametricCurvesCollection DefaultCurves = {
62 9, // # of curve types
63 { 1, 2, 3, 4, 5, 6, 7, 8, 108 }, // Parametric curve ID
64 { 1, 3, 4, 5, 7, 4, 5, 5, 1 }, // Parameters by type
65 DefaultEvalParametricFn, // Evaluator
66 NULL // Next in chain
69 // The linked list head
70 static _cmsParametricCurvesCollection* ParametricCurves = &DefaultCurves;
72 // As a way to install new parametric curves
73 cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext id, cmsPluginBase* Data)
75 cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;
76 _cmsParametricCurvesCollection* fl;
78 if (Data == NULL) {
80 ParametricCurves = &DefaultCurves;
81 return TRUE;
84 fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(id, sizeof(_cmsParametricCurvesCollection));
85 if (fl == NULL) return FALSE;
87 // Copy the parameters
88 fl ->Evaluator = Plugin ->Evaluator;
89 fl ->nFunctions = Plugin ->nFunctions;
91 // Make sure no mem overwrites
92 if (fl ->nFunctions > MAX_TYPES_IN_LCMS_PLUGIN)
93 fl ->nFunctions = MAX_TYPES_IN_LCMS_PLUGIN;
95 // Copy the data
96 memmove(fl->FunctionTypes, Plugin ->FunctionTypes, fl->nFunctions * sizeof(cmsUInt32Number));
97 memmove(fl->ParameterCount, Plugin ->ParameterCount, fl->nFunctions * sizeof(cmsUInt32Number));
99 // Keep linked list
100 fl ->Next = ParametricCurves;
101 ParametricCurves = fl;
103 // All is ok
104 return TRUE;
108 // Search in type list, return position or -1 if not found
109 static
110 int IsInSet(int Type, _cmsParametricCurvesCollection* c)
112 int i;
114 for (i=0; i < c ->nFunctions; i++)
115 if (abs(Type) == c ->FunctionTypes[i]) return i;
117 return -1;
121 // Search for the collection which contains a specific type
122 static
123 _cmsParametricCurvesCollection *GetParametricCurveByType(int Type, int* index)
125 _cmsParametricCurvesCollection* c;
126 int Position;
128 for (c = ParametricCurves; c != NULL; c = c ->Next) {
130 Position = IsInSet(Type, c);
132 if (Position != -1) {
133 if (index != NULL)
134 *index = Position;
135 return c;
139 return NULL;
142 // Low level allocate, which takes care of memory details. nEntries may be zero, and in this case
143 // no optimation curve is computed. nSegments may also be zero in the inverse case, where only the
144 // optimization curve is given. Both features simultaneously is an error
145 static
146 cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsInt32Number nEntries,
147 cmsInt32Number nSegments, const cmsCurveSegment* Segments,
148 const cmsUInt16Number* Values)
150 cmsToneCurve* p;
151 int i;
153 // We allow huge tables, which are then restricted for smoothing operations
154 if (nEntries > 65530 || nEntries < 0) {
155 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve of more than 65530 entries");
156 return NULL;
159 if (nEntries <= 0 && nSegments <= 0) {
160 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table");
161 return NULL;
164 // Allocate all required pointers, etc.
165 p = (cmsToneCurve*) _cmsMallocZero(ContextID, sizeof(cmsToneCurve));
166 if (!p) return NULL;
168 // In this case, there are no segments
169 if (nSegments <= 0) {
170 p ->Segments = NULL;
171 p ->Evals = NULL;
173 else {
174 p ->Segments = (cmsCurveSegment*) _cmsCalloc(ContextID, nSegments, sizeof(cmsCurveSegment));
175 if (p ->Segments == NULL) goto Error;
177 p ->Evals = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator));
178 if (p ->Evals == NULL) goto Error;
181 p -> nSegments = nSegments;
183 // This 16-bit table contains a limited precision representation of the whole curve and is kept for
184 // increasing xput on certain operations.
185 if (nEntries <= 0) {
186 p ->Table16 = NULL;
188 else {
189 p ->Table16 = (cmsUInt16Number*) _cmsCalloc(ContextID, nEntries, sizeof(cmsUInt16Number));
190 if (p ->Table16 == NULL) goto Error;
193 p -> nEntries = nEntries;
195 // Initialize members if requested
196 if (Values != NULL && (nEntries > 0)) {
198 for (i=0; i < nEntries; i++)
199 p ->Table16[i] = Values[i];
202 // Initialize the segments stuff. The evaluator for each segment is located and a pointer to it
203 // is placed in advance to maximize performance.
204 if (Segments != NULL && (nSegments > 0)) {
206 _cmsParametricCurvesCollection *c;
208 p ->SegInterp = (cmsInterpParams**) _cmsCalloc(ContextID, nSegments, sizeof(cmsInterpParams*));
209 if (p ->SegInterp == NULL) goto Error;
211 for (i=0; i< nSegments; i++) {
213 // Type 0 is a special marker for table-based curves
214 if (Segments[i].Type == 0)
215 p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT);
217 memmove(&p ->Segments[i], &Segments[i], sizeof(cmsCurveSegment));
219 if (Segments[i].Type == 0 && Segments[i].SampledPoints != NULL)
220 p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints);
221 else
222 p ->Segments[i].SampledPoints = NULL;
225 c = GetParametricCurveByType(Segments[i].Type, NULL);
226 if (c != NULL)
227 p ->Evals[i] = c ->Evaluator;
231 p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);
232 if (p->InterpParams != NULL)
233 return p;
235 Error:
236 if (p -> Segments) _cmsFree(ContextID, p ->Segments);
237 if (p -> Evals) _cmsFree(ContextID, p -> Evals);
238 if (p ->Table16) _cmsFree(ContextID, p ->Table16);
239 _cmsFree(ContextID, p);
240 return NULL;
244 // Parametric Fn using floating point
245 static
246 cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)
248 cmsFloat64Number e, Val, disc;
250 switch (Type) {
252 // X = Y ^ Gamma
253 case 1:
254 if (R < 0) {
256 if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
257 Val = R;
258 else
259 Val = 0;
261 else
262 Val = pow(R, Params[0]);
263 break;
265 // Type 1 Reversed: X = Y ^1/gamma
266 case -1:
267 if (R < 0) {
269 if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)
270 Val = R;
271 else
272 Val = 0;
274 else
275 Val = pow(R, 1/Params[0]);
276 break;
278 // CIE 122-1966
279 // Y = (aX + b)^Gamma | X >= -b/a
280 // Y = 0 | else
281 case 2:
282 disc = -Params[2] / Params[1];
284 if (R >= disc ) {
286 e = Params[1]*R + Params[2];
288 if (e > 0)
289 Val = pow(e, Params[0]);
290 else
291 Val = 0;
293 else
294 Val = 0;
295 break;
297 // Type 2 Reversed
298 // X = (Y ^1/g - b) / a
299 case -2:
300 if (R < 0)
301 Val = 0;
302 else
303 Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
305 if (Val < 0)
306 Val = 0;
307 break;
310 // IEC 61966-3
311 // Y = (aX + b)^Gamma | X <= -b/a
312 // Y = c | else
313 case 3:
314 disc = -Params[2] / Params[1];
315 if (disc < 0)
316 disc = 0;
318 if (R >= disc) {
320 e = Params[1]*R + Params[2];
322 if (e > 0)
323 Val = pow(e, Params[0]) + Params[3];
324 else
325 Val = 0;
327 else
328 Val = Params[3];
329 break;
332 // Type 3 reversed
333 // X=((Y-c)^1/g - b)/a | (Y>=c)
334 // X=-b/a | (Y<c)
335 case -3:
336 if (R >= Params[3]) {
338 e = R - Params[3];
340 if (e > 0)
341 Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1];
342 else
343 Val = 0;
345 else {
346 Val = -Params[2] / Params[1];
348 break;
351 // IEC 61966-2.1 (sRGB)
352 // Y = (aX + b)^Gamma | X >= d
353 // Y = cX | X < d
354 case 4:
355 if (R >= Params[4]) {
357 e = Params[1]*R + Params[2];
359 if (e > 0)
360 Val = pow(e, Params[0]);
361 else
362 Val = 0;
364 else
365 Val = R * Params[3];
366 break;
368 // Type 4 reversed
369 // X=((Y^1/g-b)/a) | Y >= (ad+b)^g
370 // X=Y/c | Y< (ad+b)^g
371 case -4:
372 e = Params[1] * Params[4] + Params[2];
373 if (e < 0)
374 disc = 0;
375 else
376 disc = pow(e, Params[0]);
378 if (R >= disc) {
380 Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1];
382 else {
383 Val = R / Params[3];
385 break;
388 // Y = (aX + b)^Gamma + e | X >= d
389 // Y = cX + f | X < d
390 case 5:
391 if (R >= Params[4]) {
393 e = Params[1]*R + Params[2];
395 if (e > 0)
396 Val = pow(e, Params[0]) + Params[5];
397 else
398 Val = Params[5];
400 else
401 Val = R*Params[3] + Params[6];
402 break;
405 // Reversed type 5
406 // X=((Y-e)1/g-b)/a | Y >=(ad+b)^g+e), cd+f
407 // X=(Y-f)/c | else
408 case -5:
410 disc = Params[3] * Params[4] + Params[6];
411 if (R >= disc) {
413 e = R - Params[5];
414 if (e < 0)
415 Val = 0;
416 else
417 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
419 else {
420 Val = (R - Params[6]) / Params[3];
422 break;
425 // Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf
426 // Type 6 is basically identical to type 5 without d
428 // Y = (a * X + b) ^ Gamma + c
429 case 6:
430 e = Params[1]*R + Params[2];
432 if (e < 0)
433 Val = Params[3];
434 else
435 Val = pow(e, Params[0]) + Params[3];
436 break;
438 // ((Y - c) ^1/Gamma - b) / a
439 case -6:
440 e = R - Params[3];
441 if (e < 0)
442 Val = 0;
443 else
444 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1];
445 break;
448 // Y = a * log (b * X^Gamma + c) + d
449 case 7:
451 e = Params[2] * pow(R, Params[0]) + Params[3];
452 if (e <= 0)
453 Val = Params[4];
454 else
455 Val = Params[1]*log10(e) + Params[4];
456 break;
458 // (Y - d) / a = log(b * X ^Gamma + c)
459 // pow(10, (Y-d) / a) = b * X ^Gamma + c
460 // pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X
461 case -7:
462 Val = pow((pow(10.0, (R-Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]);
463 break;
466 //Y = a * b^(c*X+d) + e
467 case 8:
468 Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]);
469 break;
472 // Y = (log((y-e) / a) / log(b) - d ) / c
473 // a=0, b=1, c=2, d=3, e=4,
474 case -8:
476 disc = R - Params[4];
477 if (disc < 0) Val = 0;
478 else
479 Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2];
480 break;
482 // S-Shaped: (1 - (1-x)^1/g)^1/g
483 case 108:
484 Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]);
485 break;
487 // y = (1 - (1-x)^1/g)^1/g
488 // y^g = (1 - (1-x)^1/g)
489 // 1 - y^g = (1-x)^1/g
490 // (1 - y^g)^g = 1 - x
491 // 1 - (1 - y^g)^g
492 case -108:
493 Val = 1 - pow(1 - pow(R, Params[0]), Params[0]);
494 break;
496 default:
497 // Unsupported parametric curve. Should never reach here
498 return 0;
501 return Val;
504 // Evaluate a segmented funtion for a single value. Return -1 if no valid segment found .
505 // If fn type is 0, perform an interpolation on the table
506 static
507 cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
509 int i;
511 for (i = g ->nSegments-1; i >= 0 ; --i) {
513 // Check for domain
514 if ((R > g ->Segments[i].x0) && (R <= g ->Segments[i].x1)) {
516 // Type == 0 means segment is sampled
517 if (g ->Segments[i].Type == 0) {
519 cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0) / (g ->Segments[i].x1 - g ->Segments[i].x0);
520 cmsFloat32Number Out;
522 // Setup the table (TODO: clean that)
523 g ->SegInterp[i]-> Table = g ->Segments[i].SampledPoints;
525 g ->SegInterp[i] -> Interpolation.LerpFloat(&R1, &Out, g ->SegInterp[i]);
527 return Out;
529 else
530 return g ->Evals[i](g->Segments[i].Type, g ->Segments[i].Params, R);
534 return MINUS_INF;
537 // Access to estimated low-res table
538 cmsUInt32Number CMSEXPORT cmsGetToneCurveEstimatedTableEntries(const cmsToneCurve* t)
540 _cmsAssert(t != NULL);
541 return t ->nEntries;
544 const cmsUInt16Number* CMSEXPORT cmsGetToneCurveEstimatedTable(const cmsToneCurve* t)
546 _cmsAssert(t != NULL);
547 return t ->Table16;
551 // Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the
552 // floating point description empty.
553 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number Values[])
555 return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values);
558 static
559 int EntriesByGamma(cmsFloat64Number Gamma)
561 if (fabs(Gamma - 1.0) < 0.001) return 2;
562 return 4096;
566 // Create a segmented gamma, fill the table
567 cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,
568 cmsInt32Number nSegments, const cmsCurveSegment Segments[])
570 int i;
571 cmsFloat64Number R, Val;
572 cmsToneCurve* g;
573 int nGridPoints = 4096;
575 _cmsAssert(Segments != NULL);
577 // Optimizatin for identity curves.
578 if (nSegments == 1 && Segments[0].Type == 1) {
580 nGridPoints = EntriesByGamma(Segments[0].Params[0]);
583 g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL);
584 if (g == NULL) return NULL;
586 // Once we have the floating point version, we can approximate a 16 bit table of 4096 entries
587 // for performance reasons. This table would normally not be used except on 8/16 bits transforms.
588 for (i=0; i < nGridPoints; i++) {
590 R = (cmsFloat64Number) i / (nGridPoints-1);
592 Val = EvalSegmentedFn(g, R);
594 // Round and saturate
595 g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0);
598 return g;
601 // Use a segmented curve to store the floating point table
602 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
604 cmsCurveSegment Seg[3];
606 // A segmented tone curve should have function segments in the first and last positions
607 // Initialize segmented curve part up to 0 to constant value = samples[0]
608 Seg[0].x0 = MINUS_INF;
609 Seg[0].x1 = 0;
610 Seg[0].Type = 6;
612 Seg[0].Params[0] = 1;
613 Seg[0].Params[1] = 0;
614 Seg[0].Params[2] = 0;
615 Seg[0].Params[3] = values[0];
616 Seg[0].Params[4] = 0;
618 // From zero to 1
619 Seg[1].x0 = 0;
620 Seg[1].x1 = 1.0;
621 Seg[1].Type = 0;
623 Seg[1].nGridPoints = nEntries;
624 Seg[1].SampledPoints = (cmsFloat32Number*) values;
626 // Final segment is constant = lastsample
627 Seg[2].x0 = 1.0;
628 Seg[2].x1 = PLUS_INF;
629 Seg[2].Type = 6;
631 Seg[2].Params[0] = 1;
632 Seg[2].Params[1] = 0;
633 Seg[2].Params[2] = 0;
634 Seg[2].Params[3] = values[nEntries-1];
635 Seg[2].Params[4] = 0;
638 return cmsBuildSegmentedToneCurve(ContextID, 3, Seg);
641 // Parametric curves
643 // Parameters goes as: Curve, a, b, c, d, e, f
644 // Type is the ICC type +1
645 // if type is negative, then the curve is analyticaly inverted
646 cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])
648 cmsCurveSegment Seg0;
649 int Pos = 0;
650 cmsUInt32Number size;
651 _cmsParametricCurvesCollection* c = GetParametricCurveByType(Type, &Pos);
653 _cmsAssert(Params != NULL);
655 if (c == NULL) {
656 cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);
657 return NULL;
660 memset(&Seg0, 0, sizeof(Seg0));
662 Seg0.x0 = MINUS_INF;
663 Seg0.x1 = PLUS_INF;
664 Seg0.Type = Type;
666 size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number);
667 memmove(Seg0.Params, Params, size);
669 return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0);
674 // Build a gamma table based on gamma constant
675 cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma)
677 return cmsBuildParametricToneCurve(ContextID, 1, &Gamma);
681 // Free all memory taken by the gamma curve
682 void CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve)
684 cmsContext ContextID;
686 if (Curve == NULL) return;
688 ContextID = Curve ->InterpParams->ContextID;
690 _cmsFreeInterpParams(Curve ->InterpParams);
692 if (Curve -> Table16)
693 _cmsFree(ContextID, Curve ->Table16);
695 if (Curve ->Segments) {
697 cmsUInt32Number i;
699 for (i=0; i < Curve ->nSegments; i++) {
701 if (Curve ->Segments[i].SampledPoints) {
702 _cmsFree(ContextID, Curve ->Segments[i].SampledPoints);
705 if (Curve ->SegInterp[i] != 0)
706 _cmsFreeInterpParams(Curve->SegInterp[i]);
709 _cmsFree(ContextID, Curve ->Segments);
710 _cmsFree(ContextID, Curve ->SegInterp);
713 if (Curve -> Evals)
714 _cmsFree(ContextID, Curve -> Evals);
716 if (Curve) _cmsFree(ContextID, Curve);
719 // Utility function, free 3 gamma tables
720 void CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3])
723 _cmsAssert(Curve != NULL);
725 if (Curve[0] != NULL) cmsFreeToneCurve(Curve[0]);
726 if (Curve[1] != NULL) cmsFreeToneCurve(Curve[1]);
727 if (Curve[2] != NULL) cmsFreeToneCurve(Curve[2]);
729 Curve[0] = Curve[1] = Curve[2] = NULL;
733 // Duplicate a gamma table
734 cmsToneCurve* CMSEXPORT cmsDupToneCurve(const cmsToneCurve* In)
736 if (In == NULL) return NULL;
738 return AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);
741 // Joins two curves for X and Y. Curves should be monotonic.
742 // We want to get
744 // y = Y^-1(X(t))
746 cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID,
747 const cmsToneCurve* X,
748 const cmsToneCurve* Y, cmsUInt32Number nResultingPoints)
750 cmsToneCurve* out = NULL;
751 cmsToneCurve* Yreversed = NULL;
752 cmsFloat32Number t, x;
753 cmsFloat32Number* Res = NULL;
754 cmsUInt32Number i;
757 _cmsAssert(X != NULL);
758 _cmsAssert(Y != NULL);
760 Yreversed = cmsReverseToneCurveEx(nResultingPoints, Y);
761 if (Yreversed == NULL) goto Error;
763 Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number));
764 if (Res == NULL) goto Error;
766 //Iterate
767 for (i=0; i < nResultingPoints; i++) {
769 t = (cmsFloat32Number) i / (nResultingPoints-1);
770 x = cmsEvalToneCurveFloat(X, t);
771 Res[i] = cmsEvalToneCurveFloat(Yreversed, x);
774 // Allocate space for output
775 out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res);
777 Error:
779 if (Res != NULL) _cmsFree(ContextID, Res);
780 if (Yreversed != NULL) cmsFreeToneCurve(Yreversed);
782 return out;
787 // Get the surrounding nodes. This is tricky on non-monotonic tables
788 static
789 int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)
791 int i;
792 int y0, y1;
794 // A 1 point table is not allowed
795 if (p -> Domain[0] < 1) return -1;
797 // Let's see if ascending or descending.
798 if (LutTable[0] < LutTable[p ->Domain[0]]) {
800 // Table is overall ascending
801 for (i=p->Domain[0]-1; i >=0; --i) {
803 y0 = LutTable[i];
804 y1 = LutTable[i+1];
806 if (y0 <= y1) { // Increasing
807 if (In >= y0 && In <= y1) return i;
809 else
810 if (y1 < y0) { // Decreasing
811 if (In >= y1 && In <= y0) return i;
815 else {
816 // Table is overall descending
817 for (i=0; i < (int) p -> Domain[0]; i++) {
819 y0 = LutTable[i];
820 y1 = LutTable[i+1];
822 if (y0 <= y1) { // Increasing
823 if (In >= y0 && In <= y1) return i;
825 else
826 if (y1 < y0) { // Decreasing
827 if (In >= y1 && In <= y0) return i;
832 return -1;
835 // Reverse a gamma table
836 cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InCurve)
838 cmsToneCurve *out;
839 cmsFloat64Number a = 0, b = 0, y, x1, y1, x2, y2;
840 int i, j;
841 int Ascending;
843 _cmsAssert(InCurve != NULL);
845 // Try to reverse it analytically whatever possible
846 if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 && InCurve -> Segments[0].Type <= 5) {
848 return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID,
849 -(InCurve -> Segments[0].Type),
850 InCurve -> Segments[0].Params);
853 // Nope, reverse the table.
854 out = cmsBuildTabulatedToneCurve16(InCurve ->InterpParams->ContextID, nResultSamples, NULL);
855 if (out == NULL)
856 return NULL;
858 // We want to know if this is an ascending or descending table
859 Ascending = !cmsIsToneCurveDescending(InCurve);
861 // Iterate across Y axis
862 for (i=0; i < nResultSamples; i++) {
864 y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1);
866 // Find interval in which y is within.
867 j = GetInterval(y, InCurve->Table16, InCurve->InterpParams);
868 if (j >= 0) {
871 // Get limits of interval
872 x1 = InCurve ->Table16[j];
873 x2 = InCurve ->Table16[j+1];
875 y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1);
876 y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1);
878 // If collapsed, then use any
879 if (x1 == x2) {
881 out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1);
882 continue;
884 } else {
886 // Interpolate
887 a = (y2 - y1) / (x2 - x1);
888 b = y2 - a * x2;
892 out ->Table16[i] = _cmsQuickSaturateWord(a* y + b);
896 return out;
899 // Reverse a gamma table
900 cmsToneCurve* CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma)
902 _cmsAssert(InGamma != NULL);
904 return cmsReverseToneCurveEx(4096, InGamma);
907 // From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
908 // differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
910 // Smoothing and interpolation with second differences.
912 // Input: weights (w), data (y): vector from 1 to m.
913 // Input: smoothing parameter (lambda), length (m).
914 // Output: smoothed vector (z): vector from 1 to m.
916 static
917 cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[], cmsFloat32Number z[], cmsFloat32Number lambda, int m)
919 int i, i1, i2;
920 cmsFloat32Number *c, *d, *e;
921 cmsBool st;
924 c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
925 d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
926 e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));
928 if (c != NULL && d != NULL && e != NULL) {
931 d[1] = w[1] + lambda;
932 c[1] = -2 * lambda / d[1];
933 e[1] = lambda /d[1];
934 z[1] = w[1] * y[1];
935 d[2] = w[2] + 5 * lambda - d[1] * c[1] * c[1];
936 c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];
937 e[2] = lambda / d[2];
938 z[2] = w[2] * y[2] - c[1] * z[1];
940 for (i = 3; i < m - 1; i++) {
941 i1 = i - 1; i2 = i - 2;
942 d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
943 c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];
944 e[i] = lambda / d[i];
945 z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];
948 i1 = m - 2; i2 = m - 3;
950 d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
951 c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];
952 z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];
953 i1 = m - 1; i2 = m - 2;
955 d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];
956 z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];
957 z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
959 for (i = m - 2; 1<= i; i--)
960 z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
962 st = TRUE;
964 else st = FALSE;
966 if (c != NULL) _cmsFree(ContextID, c);
967 if (d != NULL) _cmsFree(ContextID, d);
968 if (e != NULL) _cmsFree(ContextID, e);
970 return st;
973 // Smooths a curve sampled at regular intervals.
974 cmsBool CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda)
976 cmsFloat32Number w[MAX_NODES_IN_CURVE], y[MAX_NODES_IN_CURVE], z[MAX_NODES_IN_CURVE];
977 int i, nItems, Zeros, Poles;
979 if (Tab == NULL) return FALSE;
981 if (cmsIsToneCurveLinear(Tab)) return TRUE; // Nothing to do
983 nItems = Tab -> nEntries;
985 if (nItems >= MAX_NODES_IN_CURVE) {
986 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: too many points.");
987 return FALSE;
990 memset(w, 0, nItems * sizeof(cmsFloat32Number));
991 memset(y, 0, nItems * sizeof(cmsFloat32Number));
992 memset(z, 0, nItems * sizeof(cmsFloat32Number));
994 for (i=0; i < nItems; i++)
996 y[i+1] = (cmsFloat32Number) Tab -> Table16[i];
997 w[i+1] = 1.0;
1000 if (!smooth2(Tab ->InterpParams->ContextID, w, y, z, (cmsFloat32Number) lambda, nItems)) return FALSE;
1002 // Do some reality - checking...
1003 Zeros = Poles = 0;
1004 for (i=nItems; i > 1; --i) {
1006 if (z[i] == 0.) Zeros++;
1007 if (z[i] >= 65535.) Poles++;
1008 if (z[i] < z[i-1]) {
1009 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic.");
1010 return FALSE;
1014 if (Zeros > (nItems / 3)) {
1015 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros.");
1016 return FALSE;
1018 if (Poles > (nItems / 3)) {
1019 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles.");
1020 return FALSE;
1023 // Seems ok
1024 for (i=0; i < nItems; i++) {
1026 // Clamp to cmsUInt16Number
1027 Tab -> Table16[i] = _cmsQuickSaturateWord(z[i+1]);
1030 return TRUE;
1033 // Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting
1034 // in a linear table. This way assures it is linear in 12 bits, which should be enought in most cases.
1035 cmsBool CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve)
1037 cmsUInt32Number i;
1038 int diff;
1040 _cmsAssert(Curve != NULL);
1042 for (i=0; i < Curve ->nEntries; i++) {
1044 diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries));
1045 if (diff > 0x0f)
1046 return FALSE;
1049 return TRUE;
1052 // Same, but for monotonicity
1053 cmsBool CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t)
1055 int n;
1056 int i, last;
1057 cmsBool lDescending;
1059 _cmsAssert(t != NULL);
1061 // Degenerated curves are monotonic? Ok, let's pass them
1062 n = t ->nEntries;
1063 if (n < 2) return TRUE;
1065 // Curve direction
1066 lDescending = cmsIsToneCurveDescending(t);
1068 if (lDescending) {
1070 last = t ->Table16[0];
1072 for (i = 1; i < n; i++) {
1074 if (t ->Table16[i] - last > 2) // We allow some ripple
1075 return FALSE;
1076 else
1077 last = t ->Table16[i];
1081 else {
1083 last = t ->Table16[n-1];
1085 for (i = n-2; i >= 0; --i) {
1087 if (t ->Table16[i] - last > 2)
1088 return FALSE;
1089 else
1090 last = t ->Table16[i];
1095 return TRUE;
1098 // Same, but for descending tables
1099 cmsBool CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t)
1101 _cmsAssert(t != NULL);
1103 return t ->Table16[0] > t ->Table16[t ->nEntries-1];
1107 // Another info fn: is out gamma table multisegment?
1108 cmsBool CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* t)
1110 _cmsAssert(t != NULL);
1112 return t -> nSegments > 1;
1115 cmsInt32Number CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t)
1117 _cmsAssert(t != NULL);
1119 if (t -> nSegments != 1) return 0;
1120 return t ->Segments[0].Type;
1123 // We need accuracy this time
1124 cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v)
1126 _cmsAssert(Curve != NULL);
1128 // Check for 16 bits table. If so, this is a limited-precision tone curve
1129 if (Curve ->nSegments == 0) {
1131 cmsUInt16Number In, Out;
1133 In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0);
1134 Out = cmsEvalToneCurve16(Curve, In);
1136 return (cmsFloat32Number) (Out / 65535.0);
1139 return (cmsFloat32Number) EvalSegmentedFn(Curve, v);
1142 // We need xput over here
1143 cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v)
1145 cmsUInt16Number out;
1147 _cmsAssert(Curve != NULL);
1149 Curve ->InterpParams ->Interpolation.Lerp16(&v, &out, Curve ->InterpParams);
1150 return out;
1154 // Least squares fitting.
1155 // A mathematical procedure for finding the best-fitting curve to a given set of points by
1156 // minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.
1157 // The sum of the squares of the offsets is used instead of the offset absolute values because
1158 // this allows the residuals to be treated as a continuous differentiable quantity.
1160 // y = f(x) = x ^ g
1162 // R = (yi - (xi^g))
1163 // R2 = (yi - (xi^g))2
1164 // SUM R2 = SUM (yi - (xi^g))2
1166 // dR2/dg = -2 SUM x^g log(x)(y - x^g)
1167 // solving for dR2/dg = 0
1169 // g = 1/n * SUM(log(y) / log(x))
1171 cmsFloat64Number CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision)
1173 cmsFloat64Number gamma, sum, sum2;
1174 cmsFloat64Number n, x, y, Std;
1175 cmsUInt32Number i;
1177 _cmsAssert(t != NULL);
1179 sum = sum2 = n = 0;
1181 // Excluding endpoints
1182 for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) {
1184 x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1);
1185 y = (cmsFloat64Number) cmsEvalToneCurveFloat(t, (cmsFloat32Number) x);
1187 // Avoid 7% on lower part to prevent
1188 // artifacts due to linear ramps
1190 if (y > 0. && y < 1. && x > 0.07) {
1192 gamma = log(y) / log(x);
1193 sum += gamma;
1194 sum2 += gamma * gamma;
1195 n++;
1199 // Take a look on SD to see if gamma isn't exponential at all
1200 Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));
1202 if (Std > Precision)
1203 return -1.0;
1205 return (sum / n); // The mean