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