Path: blob/master/src/java.desktop/share/native/liblcms/cmsgamma.c
41149 views
/*1* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.2*3* This code is free software; you can redistribute it and/or modify it4* under the terms of the GNU General Public License version 2 only, as5* published by the Free Software Foundation. Oracle designates this6* particular file as subject to the "Classpath" exception as provided7* by Oracle in the LICENSE file that accompanied this code.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*/2324// This file is available under and governed by the GNU General Public25// License version 2 only, as published by the Free Software Foundation.26// However, the following notice accompanied the original version of this27// file:28//29//---------------------------------------------------------------------------------30//31// Little Color Management System32// Copyright (c) 1998-2020 Marti Maria Saguer33//34// Permission is hereby granted, free of charge, to any person obtaining35// a copy of this software and associated documentation files (the "Software"),36// to deal in the Software without restriction, including without limitation37// the rights to use, copy, modify, merge, publish, distribute, sublicense,38// and/or sell copies of the Software, and to permit persons to whom the Software39// is furnished to do so, subject to the following conditions:40//41// The above copyright notice and this permission notice shall be included in42// all copies or substantial portions of the Software.43//44// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,45// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO46// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND47// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE48// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION49// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION50// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.51//52//---------------------------------------------------------------------------------53//54#include "lcms2_internal.h"5556// Tone curves are powerful constructs that can contain curves specified in diverse ways.57// The curve is stored in segments, where each segment can be sampled or specified by parameters.58// a 16.bit simplification of the *whole* curve is kept for optimization purposes. For float operation,59// each segment is evaluated separately. Plug-ins may be used to define new parametric schemes,60// each plug-in may define up to MAX_TYPES_IN_LCMS_PLUGIN functions types. For defining a function,61// the plug-in should provide the type id, how many parameters each type has, and a pointer to62// a procedure that evaluates the function. In the case of reverse evaluation, the evaluator will63// be called with the type id as a negative value, and a sampled version of the reversed curve64// will be built.6566// ----------------------------------------------------------------- Implementation67// Maxim number of nodes68#define MAX_NODES_IN_CURVE 409769#define MINUS_INF (-1E22F)70#define PLUS_INF (+1E22F)7172// The list of supported parametric curves73typedef struct _cmsParametricCurvesCollection_st {7475cmsUInt32Number nFunctions; // Number of supported functions in this chunk76cmsInt32Number FunctionTypes[MAX_TYPES_IN_LCMS_PLUGIN]; // The identification types77cmsUInt32Number ParameterCount[MAX_TYPES_IN_LCMS_PLUGIN]; // Number of parameters for each function7879cmsParametricCurveEvaluator Evaluator; // The evaluator8081struct _cmsParametricCurvesCollection_st* Next; // Next in list8283} _cmsParametricCurvesCollection;8485// This is the default (built-in) evaluator86static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);8788// The built-in list89static _cmsParametricCurvesCollection DefaultCurves = {9010, // # of curve types91{ 1, 2, 3, 4, 5, 6, 7, 8, 108, 109 }, // Parametric curve ID92{ 1, 3, 4, 5, 7, 4, 5, 5, 1, 1 }, // Parameters by type93DefaultEvalParametricFn, // Evaluator94NULL // Next in chain95};9697// Duplicates the zone of memory used by the plug-in in the new context98static99void DupPluginCurvesList(struct _cmsContext_struct* ctx,100const struct _cmsContext_struct* src)101{102_cmsCurvesPluginChunkType newHead = { NULL };103_cmsParametricCurvesCollection* entry;104_cmsParametricCurvesCollection* Anterior = NULL;105_cmsCurvesPluginChunkType* head = (_cmsCurvesPluginChunkType*) src->chunks[CurvesPlugin];106107_cmsAssert(head != NULL);108109// Walk the list copying all nodes110for (entry = head->ParametricCurves;111entry != NULL;112entry = entry ->Next) {113114_cmsParametricCurvesCollection *newEntry = ( _cmsParametricCurvesCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsParametricCurvesCollection));115116if (newEntry == NULL)117return;118119// We want to keep the linked list order, so this is a little bit tricky120newEntry -> Next = NULL;121if (Anterior)122Anterior -> Next = newEntry;123124Anterior = newEntry;125126if (newHead.ParametricCurves == NULL)127newHead.ParametricCurves = newEntry;128}129130ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsCurvesPluginChunkType));131}132133// The allocator have to follow the chain134void _cmsAllocCurvesPluginChunk(struct _cmsContext_struct* ctx,135const struct _cmsContext_struct* src)136{137_cmsAssert(ctx != NULL);138139if (src != NULL) {140141// Copy all linked list142DupPluginCurvesList(ctx, src);143}144else {145static _cmsCurvesPluginChunkType CurvesPluginChunk = { NULL };146ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx ->MemPool, &CurvesPluginChunk, sizeof(_cmsCurvesPluginChunkType));147}148}149150151// The linked list head152_cmsCurvesPluginChunkType _cmsCurvesPluginChunk = { NULL };153154// As a way to install new parametric curves155cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext ContextID, cmsPluginBase* Data)156{157_cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);158cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;159_cmsParametricCurvesCollection* fl;160161if (Data == NULL) {162163ctx -> ParametricCurves = NULL;164return TRUE;165}166167fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsParametricCurvesCollection));168if (fl == NULL) return FALSE;169170// Copy the parameters171fl ->Evaluator = Plugin ->Evaluator;172fl ->nFunctions = Plugin ->nFunctions;173174// Make sure no mem overwrites175if (fl ->nFunctions > MAX_TYPES_IN_LCMS_PLUGIN)176fl ->nFunctions = MAX_TYPES_IN_LCMS_PLUGIN;177178// Copy the data179memmove(fl->FunctionTypes, Plugin ->FunctionTypes, fl->nFunctions * sizeof(cmsUInt32Number));180memmove(fl->ParameterCount, Plugin ->ParameterCount, fl->nFunctions * sizeof(cmsUInt32Number));181182// Keep linked list183fl ->Next = ctx->ParametricCurves;184ctx->ParametricCurves = fl;185186// All is ok187return TRUE;188}189190191// Search in type list, return position or -1 if not found192static193int IsInSet(int Type, _cmsParametricCurvesCollection* c)194{195int i;196197for (i=0; i < (int) c ->nFunctions; i++)198if (abs(Type) == c ->FunctionTypes[i]) return i;199200return -1;201}202203204// Search for the collection which contains a specific type205static206_cmsParametricCurvesCollection *GetParametricCurveByType(cmsContext ContextID, int Type, int* index)207{208_cmsParametricCurvesCollection* c;209int Position;210_cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin);211212for (c = ctx->ParametricCurves; c != NULL; c = c ->Next) {213214Position = IsInSet(Type, c);215216if (Position != -1) {217if (index != NULL)218*index = Position;219return c;220}221}222// If none found, revert for defaults223for (c = &DefaultCurves; c != NULL; c = c ->Next) {224225Position = IsInSet(Type, c);226227if (Position != -1) {228if (index != NULL)229*index = Position;230return c;231}232}233234return NULL;235}236237// Low level allocate, which takes care of memory details. nEntries may be zero, and in this case238// no optimation curve is computed. nSegments may also be zero in the inverse case, where only the239// optimization curve is given. Both features simultaneously is an error240static241cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsUInt32Number nEntries,242cmsUInt32Number nSegments, const cmsCurveSegment* Segments,243const cmsUInt16Number* Values)244{245cmsToneCurve* p;246cmsUInt32Number i;247248// We allow huge tables, which are then restricted for smoothing operations249if (nEntries > 65530) {250cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve of more than 65530 entries");251return NULL;252}253254if (nEntries == 0 && nSegments == 0) {255cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table");256return NULL;257}258259// Allocate all required pointers, etc.260p = (cmsToneCurve*) _cmsMallocZero(ContextID, sizeof(cmsToneCurve));261if (!p) return NULL;262263// In this case, there are no segments264if (nSegments == 0) {265p ->Segments = NULL;266p ->Evals = NULL;267}268else {269p ->Segments = (cmsCurveSegment*) _cmsCalloc(ContextID, nSegments, sizeof(cmsCurveSegment));270if (p ->Segments == NULL) goto Error;271272p ->Evals = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator));273if (p ->Evals == NULL) goto Error;274}275276p -> nSegments = nSegments;277278// This 16-bit table contains a limited precision representation of the whole curve and is kept for279// increasing xput on certain operations.280if (nEntries == 0) {281p ->Table16 = NULL;282}283else {284p ->Table16 = (cmsUInt16Number*) _cmsCalloc(ContextID, nEntries, sizeof(cmsUInt16Number));285if (p ->Table16 == NULL) goto Error;286}287288p -> nEntries = nEntries;289290// Initialize members if requested291if (Values != NULL && (nEntries > 0)) {292293for (i=0; i < nEntries; i++)294p ->Table16[i] = Values[i];295}296297// Initialize the segments stuff. The evaluator for each segment is located and a pointer to it298// is placed in advance to maximize performance.299if (Segments != NULL && (nSegments > 0)) {300301_cmsParametricCurvesCollection *c;302303p ->SegInterp = (cmsInterpParams**) _cmsCalloc(ContextID, nSegments, sizeof(cmsInterpParams*));304if (p ->SegInterp == NULL) goto Error;305306for (i=0; i < nSegments; i++) {307308// Type 0 is a special marker for table-based curves309if (Segments[i].Type == 0)310p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT);311312memmove(&p ->Segments[i], &Segments[i], sizeof(cmsCurveSegment));313314if (Segments[i].Type == 0 && Segments[i].SampledPoints != NULL)315p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints);316else317p ->Segments[i].SampledPoints = NULL;318319320c = GetParametricCurveByType(ContextID, Segments[i].Type, NULL);321if (c != NULL)322p ->Evals[i] = c ->Evaluator;323}324}325326p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);327if (p->InterpParams != NULL)328return p;329330Error:331if (p -> SegInterp) _cmsFree(ContextID, p -> SegInterp);332if (p -> Segments) _cmsFree(ContextID, p -> Segments);333if (p -> Evals) _cmsFree(ContextID, p -> Evals);334if (p ->Table16) _cmsFree(ContextID, p ->Table16);335_cmsFree(ContextID, p);336return NULL;337}338339340// Generates a sigmoidal function with desired steepness.341cmsINLINE double sigmoid_base(double k, double t)342{343return (1.0 / (1.0 + exp(-k * t))) - 0.5;344}345346cmsINLINE double inverted_sigmoid_base(double k, double t)347{348return -log((1.0 / (t + 0.5)) - 1.0) / k;349}350351cmsINLINE double sigmoid_factory(double k, double t)352{353double correction = 0.5 / sigmoid_base(k, 1);354355return correction * sigmoid_base(k, 2.0 * t - 1.0) + 0.5;356}357358cmsINLINE double inverse_sigmoid_factory(double k, double t)359{360double correction = 0.5 / sigmoid_base(k, 1);361362return (inverted_sigmoid_base(k, (t - 0.5) / correction) + 1.0) / 2.0;363}364365366// Parametric Fn using floating point367static368cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)369{370cmsFloat64Number e, Val, disc;371372switch (Type) {373374// X = Y ^ Gamma375case 1:376if (R < 0) {377378if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)379Val = R;380else381Val = 0;382}383else384Val = pow(R, Params[0]);385break;386387// Type 1 Reversed: X = Y ^1/gamma388case -1:389if (R < 0) {390391if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE)392Val = R;393else394Val = 0;395}396else397{398if (fabs(Params[0]) < MATRIX_DET_TOLERANCE)399Val = PLUS_INF;400else401Val = pow(R, 1 / Params[0]);402}403break;404405// CIE 122-1966406// Y = (aX + b)^Gamma | X >= -b/a407// Y = 0 | else408case 2:409{410411if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)412{413Val = 0;414}415else416{417disc = -Params[2] / Params[1];418419if (R >= disc) {420421e = Params[1] * R + Params[2];422423if (e > 0)424Val = pow(e, Params[0]);425else426Val = 0;427}428else429Val = 0;430}431}432break;433434// Type 2 Reversed435// X = (Y ^1/g - b) / a436case -2:437{438if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||439fabs(Params[1]) < MATRIX_DET_TOLERANCE)440{441Val = 0;442}443else444{445if (R < 0)446Val = 0;447else448Val = (pow(R, 1.0 / Params[0]) - Params[2]) / Params[1];449450if (Val < 0)451Val = 0;452}453}454break;455456457// IEC 61966-3458// Y = (aX + b)^Gamma | X <= -b/a459// Y = c | else460case 3:461{462if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)463{464Val = 0;465}466else467{468disc = -Params[2] / Params[1];469if (disc < 0)470disc = 0;471472if (R >= disc) {473474e = Params[1] * R + Params[2];475476if (e > 0)477Val = pow(e, Params[0]) + Params[3];478else479Val = 0;480}481else482Val = Params[3];483}484}485break;486487488// Type 3 reversed489// X=((Y-c)^1/g - b)/a | (Y>=c)490// X=-b/a | (Y<c)491case -3:492{493if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)494{495Val = 0;496}497else498{499if (R >= Params[3]) {500501e = R - Params[3];502503if (e > 0)504Val = (pow(e, 1 / Params[0]) - Params[2]) / Params[1];505else506Val = 0;507}508else {509Val = -Params[2] / Params[1];510}511}512}513break;514515516// IEC 61966-2.1 (sRGB)517// Y = (aX + b)^Gamma | X >= d518// Y = cX | X < d519case 4:520if (R >= Params[4]) {521522e = Params[1]*R + Params[2];523524if (e > 0)525Val = pow(e, Params[0]);526else527Val = 0;528}529else530Val = R * Params[3];531break;532533// Type 4 reversed534// X=((Y^1/g-b)/a) | Y >= (ad+b)^g535// X=Y/c | Y< (ad+b)^g536case -4:537{538if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||539fabs(Params[1]) < MATRIX_DET_TOLERANCE ||540fabs(Params[3]) < MATRIX_DET_TOLERANCE)541{542Val = 0;543}544else545{546e = Params[1] * Params[4] + Params[2];547if (e < 0)548disc = 0;549else550disc = pow(e, Params[0]);551552if (R >= disc) {553554Val = (pow(R, 1.0 / Params[0]) - Params[2]) / Params[1];555}556else {557Val = R / Params[3];558}559}560}561break;562563564// Y = (aX + b)^Gamma + e | X >= d565// Y = cX + f | X < d566case 5:567if (R >= Params[4]) {568569e = Params[1]*R + Params[2];570571if (e > 0)572Val = pow(e, Params[0]) + Params[5];573else574Val = Params[5];575}576else577Val = R*Params[3] + Params[6];578break;579580581// Reversed type 5582// X=((Y-e)1/g-b)/a | Y >=(ad+b)^g+e), cd+f583// X=(Y-f)/c | else584case -5:585{586if (fabs(Params[1]) < MATRIX_DET_TOLERANCE ||587fabs(Params[3]) < MATRIX_DET_TOLERANCE)588{589Val = 0;590}591else592{593disc = Params[3] * Params[4] + Params[6];594if (R >= disc) {595596e = R - Params[5];597if (e < 0)598Val = 0;599else600Val = (pow(e, 1.0 / Params[0]) - Params[2]) / Params[1];601}602else {603Val = (R - Params[6]) / Params[3];604}605}606}607break;608609610// Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf611// Type 6 is basically identical to type 5 without d612613// Y = (a * X + b) ^ Gamma + c614case 6:615e = Params[1]*R + Params[2];616617if (e < 0)618Val = Params[3];619else620Val = pow(e, Params[0]) + Params[3];621break;622623// ((Y - c) ^1/Gamma - b) / a624case -6:625{626if (fabs(Params[1]) < MATRIX_DET_TOLERANCE)627{628Val = 0;629}630else631{632e = R - Params[3];633if (e < 0)634Val = 0;635else636Val = (pow(e, 1.0 / Params[0]) - Params[2]) / Params[1];637}638}639break;640641642// Y = a * log (b * X^Gamma + c) + d643case 7:644645e = Params[2] * pow(R, Params[0]) + Params[3];646if (e <= 0)647Val = Params[4];648else649Val = Params[1]*log10(e) + Params[4];650break;651652// (Y - d) / a = log(b * X ^Gamma + c)653// pow(10, (Y-d) / a) = b * X ^Gamma + c654// pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X655case -7:656{657if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||658fabs(Params[1]) < MATRIX_DET_TOLERANCE ||659fabs(Params[2]) < MATRIX_DET_TOLERANCE)660{661Val = 0;662}663else664{665Val = pow((pow(10.0, (R - Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]);666}667}668break;669670671//Y = a * b^(c*X+d) + e672case 8:673Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]);674break;675676677// Y = (log((y-e) / a) / log(b) - d ) / c678// a=0, b=1, c=2, d=3, e=4,679case -8:680681disc = R - Params[4];682if (disc < 0) Val = 0;683else684{685if (fabs(Params[0]) < MATRIX_DET_TOLERANCE ||686fabs(Params[2]) < MATRIX_DET_TOLERANCE)687{688Val = 0;689}690else691{692Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2];693}694}695break;696697698// S-Shaped: (1 - (1-x)^1/g)^1/g699case 108:700if (fabs(Params[0]) < MATRIX_DET_TOLERANCE)701Val = 0;702else703Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]);704break;705706// y = (1 - (1-x)^1/g)^1/g707// y^g = (1 - (1-x)^1/g)708// 1 - y^g = (1-x)^1/g709// (1 - y^g)^g = 1 - x710// 1 - (1 - y^g)^g711case -108:712Val = 1 - pow(1 - pow(R, Params[0]), Params[0]);713break;714715// Sigmoidals716case 109:717Val = sigmoid_factory(Params[0], R);718break;719720case -109:721Val = inverse_sigmoid_factory(Params[0], R);722break;723724default:725// Unsupported parametric curve. Should never reach here726return 0;727}728729return Val;730}731732// Evaluate a segmented function for a single value. Return -Inf if no valid segment found .733// If fn type is 0, perform an interpolation on the table734static735cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)736{737int i;738cmsFloat32Number Out32;739cmsFloat64Number Out;740741for (i = (int) g->nSegments - 1; i >= 0; --i) {742743// Check for domain744if ((R > g->Segments[i].x0) && (R <= g->Segments[i].x1)) {745746// Type == 0 means segment is sampled747if (g->Segments[i].Type == 0) {748749cmsFloat32Number R1 = (cmsFloat32Number)(R - g->Segments[i].x0) / (g->Segments[i].x1 - g->Segments[i].x0);750751// Setup the table (TODO: clean that)752g->SegInterp[i]->Table = g->Segments[i].SampledPoints;753754g->SegInterp[i]->Interpolation.LerpFloat(&R1, &Out32, g->SegInterp[i]);755Out = (cmsFloat64Number) Out32;756757}758else {759Out = g->Evals[i](g->Segments[i].Type, g->Segments[i].Params, R);760}761762if (isinf(Out))763return PLUS_INF;764else765{766if (isinf(-Out))767return MINUS_INF;768}769770return Out;771}772}773774return MINUS_INF;775}776777// Access to estimated low-res table778cmsUInt32Number CMSEXPORT cmsGetToneCurveEstimatedTableEntries(const cmsToneCurve* t)779{780_cmsAssert(t != NULL);781return t ->nEntries;782}783784const cmsUInt16Number* CMSEXPORT cmsGetToneCurveEstimatedTable(const cmsToneCurve* t)785{786_cmsAssert(t != NULL);787return t ->Table16;788}789790791// Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the792// floating point description empty.793cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsUInt32Number nEntries, const cmsUInt16Number Values[])794{795return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values);796}797798static799cmsUInt32Number EntriesByGamma(cmsFloat64Number Gamma)800{801if (fabs(Gamma - 1.0) < 0.001) return 2;802return 4096;803}804805806// Create a segmented gamma, fill the table807cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,808cmsUInt32Number nSegments, const cmsCurveSegment Segments[])809{810cmsUInt32Number i;811cmsFloat64Number R, Val;812cmsToneCurve* g;813cmsUInt32Number nGridPoints = 4096;814815_cmsAssert(Segments != NULL);816817// Optimizatin for identity curves.818if (nSegments == 1 && Segments[0].Type == 1) {819820nGridPoints = EntriesByGamma(Segments[0].Params[0]);821}822823g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL);824if (g == NULL) return NULL;825826// Once we have the floating point version, we can approximate a 16 bit table of 4096 entries827// for performance reasons. This table would normally not be used except on 8/16 bits transforms.828for (i = 0; i < nGridPoints; i++) {829830R = (cmsFloat64Number) i / (nGridPoints-1);831832Val = EvalSegmentedFn(g, R);833834// Round and saturate835g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0);836}837838return g;839}840841// Use a segmented curve to store the floating point table842cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])843{844cmsCurveSegment Seg[3];845846// A segmented tone curve should have function segments in the first and last positions847// Initialize segmented curve part up to 0 to constant value = samples[0]848Seg[0].x0 = MINUS_INF;849Seg[0].x1 = 0;850Seg[0].Type = 6;851852Seg[0].Params[0] = 1;853Seg[0].Params[1] = 0;854Seg[0].Params[2] = 0;855Seg[0].Params[3] = values[0];856Seg[0].Params[4] = 0;857858// From zero to 1859Seg[1].x0 = 0;860Seg[1].x1 = 1.0;861Seg[1].Type = 0;862863Seg[1].nGridPoints = nEntries;864Seg[1].SampledPoints = (cmsFloat32Number*) values;865866// Final segment is constant = lastsample867Seg[2].x0 = 1.0;868Seg[2].x1 = PLUS_INF;869Seg[2].Type = 6;870871Seg[2].Params[0] = 1;872Seg[2].Params[1] = 0;873Seg[2].Params[2] = 0;874Seg[2].Params[3] = values[nEntries-1];875Seg[2].Params[4] = 0;876877878return cmsBuildSegmentedToneCurve(ContextID, 3, Seg);879}880881// Parametric curves882//883// Parameters goes as: Curve, a, b, c, d, e, f884// Type is the ICC type +1885// if type is negative, then the curve is analytically inverted886cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])887{888cmsCurveSegment Seg0;889int Pos = 0;890cmsUInt32Number size;891_cmsParametricCurvesCollection* c = GetParametricCurveByType(ContextID, Type, &Pos);892893_cmsAssert(Params != NULL);894895if (c == NULL) {896cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type);897return NULL;898}899900memset(&Seg0, 0, sizeof(Seg0));901902Seg0.x0 = MINUS_INF;903Seg0.x1 = PLUS_INF;904Seg0.Type = Type;905906size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number);907memmove(Seg0.Params, Params, size);908909return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0);910}911912913914// Build a gamma table based on gamma constant915cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma)916{917return cmsBuildParametricToneCurve(ContextID, 1, &Gamma);918}919920921// Free all memory taken by the gamma curve922void CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve)923{924cmsContext ContextID;925926if (Curve == NULL) return;927928ContextID = Curve ->InterpParams->ContextID;929930_cmsFreeInterpParams(Curve ->InterpParams);931932if (Curve -> Table16)933_cmsFree(ContextID, Curve ->Table16);934935if (Curve ->Segments) {936937cmsUInt32Number i;938939for (i=0; i < Curve ->nSegments; i++) {940941if (Curve ->Segments[i].SampledPoints) {942_cmsFree(ContextID, Curve ->Segments[i].SampledPoints);943}944945if (Curve ->SegInterp[i] != 0)946_cmsFreeInterpParams(Curve->SegInterp[i]);947}948949_cmsFree(ContextID, Curve ->Segments);950_cmsFree(ContextID, Curve ->SegInterp);951}952953if (Curve -> Evals)954_cmsFree(ContextID, Curve -> Evals);955956_cmsFree(ContextID, Curve);957}958959// Utility function, free 3 gamma tables960void CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3])961{962963_cmsAssert(Curve != NULL);964965if (Curve[0] != NULL) cmsFreeToneCurve(Curve[0]);966if (Curve[1] != NULL) cmsFreeToneCurve(Curve[1]);967if (Curve[2] != NULL) cmsFreeToneCurve(Curve[2]);968969Curve[0] = Curve[1] = Curve[2] = NULL;970}971972973// Duplicate a gamma table974cmsToneCurve* CMSEXPORT cmsDupToneCurve(const cmsToneCurve* In)975{976if (In == NULL) return NULL;977978return AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);979}980981// Joins two curves for X and Y. Curves should be monotonic.982// We want to get983//984// y = Y^-1(X(t))985//986cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID,987const cmsToneCurve* X,988const cmsToneCurve* Y, cmsUInt32Number nResultingPoints)989{990cmsToneCurve* out = NULL;991cmsToneCurve* Yreversed = NULL;992cmsFloat32Number t, x;993cmsFloat32Number* Res = NULL;994cmsUInt32Number i;995996997_cmsAssert(X != NULL);998_cmsAssert(Y != NULL);9991000Yreversed = cmsReverseToneCurveEx(nResultingPoints, Y);1001if (Yreversed == NULL) goto Error;10021003Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number));1004if (Res == NULL) goto Error;10051006//Iterate1007for (i=0; i < nResultingPoints; i++) {10081009t = (cmsFloat32Number) i / (cmsFloat32Number)(nResultingPoints-1);1010x = cmsEvalToneCurveFloat(X, t);1011Res[i] = cmsEvalToneCurveFloat(Yreversed, x);1012}10131014// Allocate space for output1015out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res);10161017Error:10181019if (Res != NULL) _cmsFree(ContextID, Res);1020if (Yreversed != NULL) cmsFreeToneCurve(Yreversed);10211022return out;1023}1024102510261027// Get the surrounding nodes. This is tricky on non-monotonic tables1028static1029int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)1030{1031int i;1032int y0, y1;10331034// A 1 point table is not allowed1035if (p -> Domain[0] < 1) return -1;10361037// Let's see if ascending or descending.1038if (LutTable[0] < LutTable[p ->Domain[0]]) {10391040// Table is overall ascending1041for (i = (int) p->Domain[0] - 1; i >= 0; --i) {10421043y0 = LutTable[i];1044y1 = LutTable[i+1];10451046if (y0 <= y1) { // Increasing1047if (In >= y0 && In <= y1) return i;1048}1049else1050if (y1 < y0) { // Decreasing1051if (In >= y1 && In <= y0) return i;1052}1053}1054}1055else {1056// Table is overall descending1057for (i=0; i < (int) p -> Domain[0]; i++) {10581059y0 = LutTable[i];1060y1 = LutTable[i+1];10611062if (y0 <= y1) { // Increasing1063if (In >= y0 && In <= y1) return i;1064}1065else1066if (y1 < y0) { // Decreasing1067if (In >= y1 && In <= y0) return i;1068}1069}1070}10711072return -1;1073}10741075// Reverse a gamma table1076cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsUInt32Number nResultSamples, const cmsToneCurve* InCurve)1077{1078cmsToneCurve *out;1079cmsFloat64Number a = 0, b = 0, y, x1, y1, x2, y2;1080int i, j;1081int Ascending;10821083_cmsAssert(InCurve != NULL);10841085// Try to reverse it analytically whatever possible10861087if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 &&1088/* InCurve -> Segments[0].Type <= 5 */1089GetParametricCurveByType(InCurve ->InterpParams->ContextID, InCurve ->Segments[0].Type, NULL) != NULL) {10901091return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID,1092-(InCurve -> Segments[0].Type),1093InCurve -> Segments[0].Params);1094}10951096// Nope, reverse the table.1097out = cmsBuildTabulatedToneCurve16(InCurve ->InterpParams->ContextID, nResultSamples, NULL);1098if (out == NULL)1099return NULL;11001101// We want to know if this is an ascending or descending table1102Ascending = !cmsIsToneCurveDescending(InCurve);11031104// Iterate across Y axis1105for (i=0; i < (int) nResultSamples; i++) {11061107y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1);11081109// Find interval in which y is within.1110j = GetInterval(y, InCurve->Table16, InCurve->InterpParams);1111if (j >= 0) {111211131114// Get limits of interval1115x1 = InCurve ->Table16[j];1116x2 = InCurve ->Table16[j+1];11171118y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1);1119y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1);11201121// If collapsed, then use any1122if (x1 == x2) {11231124out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1);1125continue;11261127} else {11281129// Interpolate1130a = (y2 - y1) / (x2 - x1);1131b = y2 - a * x2;1132}1133}11341135out ->Table16[i] = _cmsQuickSaturateWord(a* y + b);1136}113711381139return out;1140}11411142// Reverse a gamma table1143cmsToneCurve* CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma)1144{1145_cmsAssert(InGamma != NULL);11461147return cmsReverseToneCurveEx(4096, InGamma);1148}11491150// From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite1151// differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.1152//1153// Smoothing and interpolation with second differences.1154//1155// Input: weights (w), data (y): vector from 1 to m.1156// Input: smoothing parameter (lambda), length (m).1157// Output: smoothed vector (z): vector from 1 to m.11581159static1160cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[],1161cmsFloat32Number z[], cmsFloat32Number lambda, int m)1162{1163int i, i1, i2;1164cmsFloat32Number *c, *d, *e;1165cmsBool st;116611671168c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));1169d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));1170e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number));11711172if (c != NULL && d != NULL && e != NULL) {117311741175d[1] = w[1] + lambda;1176c[1] = -2 * lambda / d[1];1177e[1] = lambda /d[1];1178z[1] = w[1] * y[1];1179d[2] = w[2] + 5 * lambda - d[1] * c[1] * c[1];1180c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2];1181e[2] = lambda / d[2];1182z[2] = w[2] * y[2] - c[1] * z[1];11831184for (i = 3; i < m - 1; i++) {1185i1 = i - 1; i2 = i - 2;1186d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];1187c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i];1188e[i] = lambda / d[i];1189z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2];1190}11911192i1 = m - 2; i2 = m - 3;11931194d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];1195c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1];1196z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2];1197i1 = m - 1; i2 = m - 2;11981199d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2];1200z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m];1201z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];12021203for (i = m - 2; 1<= i; i--)1204z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];12051206st = TRUE;1207}1208else st = FALSE;12091210if (c != NULL) _cmsFree(ContextID, c);1211if (d != NULL) _cmsFree(ContextID, d);1212if (e != NULL) _cmsFree(ContextID, e);12131214return st;1215}12161217// Smooths a curve sampled at regular intervals.1218cmsBool CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda)1219{1220cmsBool SuccessStatus = TRUE;1221cmsFloat32Number *w, *y, *z;1222cmsUInt32Number i, nItems, Zeros, Poles;1223cmsBool notCheck = FALSE;12241225if (Tab != NULL && Tab->InterpParams != NULL)1226{1227cmsContext ContextID = Tab->InterpParams->ContextID;12281229if (!cmsIsToneCurveLinear(Tab)) // Only non-linear curves need smoothing1230{1231nItems = Tab->nEntries;1232if (nItems < MAX_NODES_IN_CURVE)1233{1234// Allocate one more item than needed1235w = (cmsFloat32Number *)_cmsCalloc(ContextID, nItems + 1, sizeof(cmsFloat32Number));1236y = (cmsFloat32Number *)_cmsCalloc(ContextID, nItems + 1, sizeof(cmsFloat32Number));1237z = (cmsFloat32Number *)_cmsCalloc(ContextID, nItems + 1, sizeof(cmsFloat32Number));12381239if (w != NULL && y != NULL && z != NULL) // Ensure no memory allocation failure1240{1241memset(w, 0, (nItems + 1) * sizeof(cmsFloat32Number));1242memset(y, 0, (nItems + 1) * sizeof(cmsFloat32Number));1243memset(z, 0, (nItems + 1) * sizeof(cmsFloat32Number));12441245for (i = 0; i < nItems; i++)1246{1247y[i + 1] = (cmsFloat32Number)Tab->Table16[i];1248w[i + 1] = 1.0;1249}12501251if (lambda < 0)1252{1253notCheck = TRUE;1254lambda = -lambda;1255}12561257if (smooth2(ContextID, w, y, z, (cmsFloat32Number)lambda, (int)nItems))1258{1259// Do some reality - checking...12601261Zeros = Poles = 0;1262for (i = nItems; i > 1; --i)1263{1264if (z[i] == 0.) Zeros++;1265if (z[i] >= 65535.) Poles++;1266if (z[i] < z[i - 1])1267{1268cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic.");1269SuccessStatus = notCheck;1270break;1271}1272}12731274if (SuccessStatus && Zeros > (nItems / 3))1275{1276cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros.");1277SuccessStatus = notCheck;1278}12791280if (SuccessStatus && Poles > (nItems / 3))1281{1282cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles.");1283SuccessStatus = notCheck;1284}12851286if (SuccessStatus) // Seems ok1287{1288for (i = 0; i < nItems; i++)1289{1290// Clamp to cmsUInt16Number1291Tab->Table16[i] = _cmsQuickSaturateWord(z[i + 1]);1292}1293}1294}1295else // Could not smooth1296{1297cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Function smooth2 failed.");1298SuccessStatus = FALSE;1299}1300}1301else // One or more buffers could not be allocated1302{1303cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Could not allocate memory.");1304SuccessStatus = FALSE;1305}13061307if (z != NULL)1308_cmsFree(ContextID, z);13091310if (y != NULL)1311_cmsFree(ContextID, y);13121313if (w != NULL)1314_cmsFree(ContextID, w);1315}1316else // too many items in the table1317{1318cmsSignalError(ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Too many points.");1319SuccessStatus = FALSE;1320}1321}1322}1323else // Tab parameter or Tab->InterpParams is NULL1324{1325// Can't signal an error here since the ContextID is not known at this point1326SuccessStatus = FALSE;1327}13281329return SuccessStatus;1330}13311332// Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting1333// in a linear table. This way assures it is linear in 12 bits, which should be enough in most cases.1334cmsBool CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve)1335{1336int i;1337int diff;13381339_cmsAssert(Curve != NULL);13401341for (i=0; i < (int) Curve ->nEntries; i++) {13421343diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries));1344if (diff > 0x0f)1345return FALSE;1346}13471348return TRUE;1349}13501351// Same, but for monotonicity1352cmsBool CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t)1353{1354cmsUInt32Number n;1355int i, last;1356cmsBool lDescending;13571358_cmsAssert(t != NULL);13591360// Degenerated curves are monotonic? Ok, let's pass them1361n = t ->nEntries;1362if (n < 2) return TRUE;13631364// Curve direction1365lDescending = cmsIsToneCurveDescending(t);13661367if (lDescending) {13681369last = t ->Table16[0];13701371for (i = 1; i < (int) n; i++) {13721373if (t ->Table16[i] - last > 2) // We allow some ripple1374return FALSE;1375else1376last = t ->Table16[i];13771378}1379}1380else {13811382last = t ->Table16[n-1];13831384for (i = (int) n - 2; i >= 0; --i) {13851386if (t ->Table16[i] - last > 2)1387return FALSE;1388else1389last = t ->Table16[i];13901391}1392}13931394return TRUE;1395}13961397// Same, but for descending tables1398cmsBool CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t)1399{1400_cmsAssert(t != NULL);14011402return t ->Table16[0] > t ->Table16[t ->nEntries-1];1403}140414051406// Another info fn: is out gamma table multisegment?1407cmsBool CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* t)1408{1409_cmsAssert(t != NULL);14101411return t -> nSegments > 1;1412}14131414cmsInt32Number CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t)1415{1416_cmsAssert(t != NULL);14171418if (t -> nSegments != 1) return 0;1419return t ->Segments[0].Type;1420}14211422// We need accuracy this time1423cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v)1424{1425_cmsAssert(Curve != NULL);14261427// Check for 16 bits table. If so, this is a limited-precision tone curve1428if (Curve ->nSegments == 0) {14291430cmsUInt16Number In, Out;14311432In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0);1433Out = cmsEvalToneCurve16(Curve, In);14341435return (cmsFloat32Number) (Out / 65535.0);1436}14371438return (cmsFloat32Number) EvalSegmentedFn(Curve, v);1439}14401441// We need xput over here1442cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v)1443{1444cmsUInt16Number out;14451446_cmsAssert(Curve != NULL);14471448Curve ->InterpParams ->Interpolation.Lerp16(&v, &out, Curve ->InterpParams);1449return out;1450}145114521453// Least squares fitting.1454// A mathematical procedure for finding the best-fitting curve to a given set of points by1455// minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.1456// The sum of the squares of the offsets is used instead of the offset absolute values because1457// this allows the residuals to be treated as a continuous differentiable quantity.1458//1459// y = f(x) = x ^ g1460//1461// R = (yi - (xi^g))1462// R2 = (yi - (xi^g))21463// SUM R2 = SUM (yi - (xi^g))21464//1465// dR2/dg = -2 SUM x^g log(x)(y - x^g)1466// solving for dR2/dg = 01467//1468// g = 1/n * SUM(log(y) / log(x))14691470cmsFloat64Number CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision)1471{1472cmsFloat64Number gamma, sum, sum2;1473cmsFloat64Number n, x, y, Std;1474cmsUInt32Number i;14751476_cmsAssert(t != NULL);14771478sum = sum2 = n = 0;14791480// Excluding endpoints1481for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) {14821483x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1);1484y = (cmsFloat64Number) cmsEvalToneCurveFloat(t, (cmsFloat32Number) x);14851486// Avoid 7% on lower part to prevent1487// artifacts due to linear ramps14881489if (y > 0. && y < 1. && x > 0.07) {14901491gamma = log(y) / log(x);1492sum += gamma;1493sum2 += gamma * gamma;1494n++;1495}1496}14971498// Take a look on SD to see if gamma isn't exponential at all1499Std = sqrt((n * sum2 - sum * sum) / (n*(n-1)));15001501if (Std > Precision)1502return -1.0;15031504return (sum / n); // The mean1505}150615071508// Retrieve parameters on one-segment tone curves15091510cmsFloat64Number* CMSEXPORT cmsGetToneCurveParams(const cmsToneCurve* t)1511{1512_cmsAssert(t != NULL);15131514if (t->nSegments != 1) return NULL;1515return t->Segments[0].Params;1516}151715181519