/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// This file is available under and governed by the GNU General Public
// License version 2 only, as published by the Free Software Foundation.
// However, the following notice accompanied the original version of this
// file:
//
//---------------------------------------------------------------------------------
//
// Little Color Management System
// Copyright (c) 1998-2012 Marti Maria Saguer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//---------------------------------------------------------------------------------
//
#include "lcms2_internal.h"
// Tone curves are powerful constructs that can contain curves specified in diverse ways.
// The curve is stored in segments, where each segment can be sampled or specified by parameters.
// a 16.bit simplification of the *whole* curve is kept for optimization purposes. For float operation,
// each segment is evaluated separately. Plug-ins may be used to define new parametric schemes,
// each plug-in may define up to MAX_TYPES_IN_LCMS_PLUGIN functions types. For defining a function,
// the plug-in should provide the type id, how many parameters each type has, and a pointer to
// a procedure that evaluates the function. In the case of reverse evaluation, the evaluator will
// be called with the type id as a negative value, and a sampled version of the reversed curve
// will be built.
// ----------------------------------------------------------------- Implementation
// Maxim number of nodes
// The list of supported parametric curves
typedef struct _cmsParametricCurvesCollection_st {
// This is the default (built-in) evaluator
static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R);
// The built-in list
9, // # of curve types
{ 1, 2, 3, 4, 5, 6, 7, 8, 108 }, // Parametric curve ID
{ 1, 3, 4, 5, 7, 4, 5, 5, 1 }, // Parameters by type
DefaultEvalParametricFn, // Evaluator
NULL // Next in chain
};
// The linked list head
// As a way to install new parametric curves
{
return TRUE;
}
// Copy the parameters
// Make sure no mem overwrites
// Copy the data
// Keep linked list
// All is ok
return TRUE;
}
// Search in type list, return position or -1 if not found
static
{
int i;
for (i=0; i < c ->nFunctions; i++)
return -1;
}
// Search for the collection which contains a specific type
static
{
int Position;
if (Position != -1) {
return c;
}
}
return NULL;
}
// Low level allocate, which takes care of memory details. nEntries may be zero, and in this case
// no optimation curve is computed. nSegments may also be zero in the inverse case, where only the
// optimization curve is given. Both features simultaneously is an error
static
const cmsUInt16Number* Values)
{
cmsToneCurve* p;
int i;
// We allow huge tables, which are then restricted for smoothing operations
return NULL;
}
cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table");
return NULL;
}
// Allocate all required pointers, etc.
if (!p) return NULL;
// In this case, there are no segments
if (nSegments <= 0) {
}
else {
p ->Evals = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator));
}
// This 16-bit table contains a limited precision representation of the whole curve and is kept for
// increasing xput on certain operations.
if (nEntries <= 0) {
}
else {
}
// Initialize members if requested
for (i=0; i < nEntries; i++)
}
// Initialize the segments stuff. The evaluator for each segment is located and a pointer to it
// is placed in advance to maximize performance.
for (i=0; i< nSegments; i++) {
// Type 0 is a special marker for table-based curves
p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT);
p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints);
else
if (c != NULL)
}
}
p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);
return p;
return NULL;
}
// Parametric Fn using floating point
static
cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R)
{
switch (Type) {
// X = Y ^ Gamma
case 1:
if (R < 0) {
Val = R;
else
Val = 0;
}
else
break;
// Type 1 Reversed: X = Y ^1/gamma
case -1:
if (R < 0) {
Val = R;
else
Val = 0;
}
else
break;
// CIE 122-1966
// Y = (aX + b)^Gamma | X >= -b/a
// Y = 0 | else
case 2:
if (R >= disc ) {
if (e > 0)
else
Val = 0;
}
else
Val = 0;
break;
// Type 2 Reversed
// X = (Y ^1/g - b) / a
case -2:
if (R < 0)
Val = 0;
else
if (Val < 0)
Val = 0;
break;
// IEC 61966-3
// Y = (aX + b)^Gamma | X <= -b/a
// Y = c | else
case 3:
if (disc < 0)
disc = 0;
if (R >= disc) {
if (e > 0)
else
Val = 0;
}
else
break;
// Type 3 reversed
// X=((Y-c)^1/g - b)/a | (Y>=c)
// X=-b/a | (Y<c)
case -3:
if (R >= Params[3]) {
e = R - Params[3];
if (e > 0)
else
Val = 0;
}
else {
}
break;
// IEC 61966-2.1 (sRGB)
// Y = (aX + b)^Gamma | X >= d
// Y = cX | X < d
case 4:
if (R >= Params[4]) {
if (e > 0)
else
Val = 0;
}
else
break;
// Type 4 reversed
// X=((Y^1/g-b)/a) | Y >= (ad+b)^g
// X=Y/c | Y< (ad+b)^g
case -4:
if (e < 0)
disc = 0;
else
if (R >= disc) {
}
else {
}
break;
// Y = (aX + b)^Gamma + e | X >= d
// Y = cX + f | X < d
case 5:
if (R >= Params[4]) {
if (e > 0)
else
Val = 0;
}
else
break;
// Reversed type 5
// X=((Y-e)1/g-b)/a | Y >=(ad+b)^g+e), cd+f
// X=(Y-f)/c | else
case -5:
if (R >= disc) {
e = R - Params[5];
if (e < 0)
Val = 0;
else
}
else {
}
break;
// Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf
// Type 6 is basically identical to type 5 without d
// Y = (a * X + b) ^ Gamma + c
case 6:
if (e < 0)
Val = 0;
else
break;
// ((Y - c) ^1/Gamma - b) / a
case -6:
e = R - Params[3];
if (e < 0)
Val = 0;
else
break;
// Y = a * log (b * X^Gamma + c) + d
case 7:
if (e <= 0)
Val = 0;
else
break;
// (Y - d) / a = log(b * X ^Gamma + c)
// pow(10, (Y-d) / a) = b * X ^Gamma + c
// pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X
case -7:
break;
//Y = a * b^(c*X+d) + e
case 8:
break;
// Y = (log((y-e) / a) / log(b) - d ) / c
// a=0, b=1, c=2, d=3, e=4,
case -8:
else
break;
// S-Shaped: (1 - (1-x)^1/g)^1/g
case 108:
break;
// y = (1 - (1-x)^1/g)^1/g
// y^g = (1 - (1-x)^1/g)
// 1 - y^g = (1-x)^1/g
// (1 - y^g)^g = 1 - x
// 1 - (1 - y^g)^g
case -108:
break;
default:
// Unsupported parametric curve. Should never reach here
return 0;
}
return Val;
}
// Evaluate a segmented funtion for a single value. Return -1 if no valid segment found .
// If fn type is 0, perform an interpolation on the table
static
{
int i;
for (i = g ->nSegments-1; i >= 0 ; --i) {
// Check for domain
// Type == 0 means segment is sampled
// Setup the table (TODO: clean that)
return Out;
}
else
}
}
return MINUS_INF;
}
// Access to estimated low-res table
{
_cmsAssert(t != NULL);
return t ->nEntries;
}
{
_cmsAssert(t != NULL);
return t ->Table16;
}
// Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the
// floating point description empty.
cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number Values[])
{
}
static
{
return 4096;
}
// Create a segmented gamma, fill the table
{
int i;
cmsToneCurve* g;
// Optimizatin for identity curves.
}
// Once we have the floating point version, we can approximate a 16 bit table of 4096 entries
// for performance reasons. This table would normally not be used except on 8/16 bits transforms.
for (i=0; i < nGridPoints; i++) {
Val = EvalSegmentedFn(g, R);
// Round and saturate
}
return g;
}
// Use a segmented curve to store the floating point table
cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
{
// Initialize segmented curve part up to 0
// From zero to any
}
// Parametric curves
//
// Parameters goes as: Curve, a, b, c, d, e, f
// Type is the ICC type +1
// if type is negative, then the curve is analyticaly inverted
cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[])
{
int Pos = 0;
if (c == NULL) {
return NULL;
}
}
// Build a gamma table based on gamma constant
{
}
// Free all memory taken by the gamma curve
{
}
}
}
}
// Utility function, free 3 gamma tables
{
}
// Duplicate a gamma table
{
return AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16);
}
// Joins two curves for X and Y. Curves should be monotonic.
// We want to get
//
// y = Y^-1(X(t))
//
const cmsToneCurve* X,
{
cmsFloat32Number t, x;
_cmsAssert(X != NULL);
_cmsAssert(Y != NULL);
//Iterate
for (i=0; i < nResultingPoints; i++) {
x = cmsEvalToneCurveFloat(X, t);
}
// Allocate space for output
return out;
}
// Get the surrounding nodes. This is tricky on non-monotonic tables
static
int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p)
{
int i;
// A 1 point table is not allowed
// Let's see if ascending or descending.
// Table is overall ascending
for (i=p->Domain[0]-1; i >=0; --i) {
}
else
}
}
}
else {
// Table is overall descending
for (i=0; i < (int) p -> Domain[0]; i++) {
}
else
}
}
}
return -1;
}
// Reverse a gamma table
cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InCurve)
{
int i, j;
int Ascending;
// Try to reverse it analytically whatever possible
if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 && InCurve -> Segments[0].Type <= 5) {
}
// Nope, reverse the table.
return NULL;
// We want to know if this is an ascending or descending table
// Iterate across Y axis
for (i=0; i < nResultSamples; i++) {
// Find interval in which y is within.
if (j >= 0) {
// Get limits of interval
// If collapsed, then use any
continue;
} else {
// Interpolate
}
}
}
return out;
}
// Reverse a gamma table
{
}
// From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite
// differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press.
//
// Smoothing and interpolation with second differences.
//
// Input: weights (w), data (y): vector from 1 to m.
// Input: smoothing parameter (lambda), length (m).
// Output: smoothed vector (z): vector from 1 to m.
static
cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[], cmsFloat32Number z[], cmsFloat32Number lambda, int m)
{
cmsFloat32Number *c, *d, *e;
z[1] = w[1] * y[1];
z[2] = w[2] * y[2] - c[1] * z[1];
for (i = 3; i < m - 1; i++) {
e[i] = lambda / d[i];
}
z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m];
for (i = m - 2; 1<= i; i--)
z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2];
}
return st;
}
// Smooths a curve sampled at regular intervals.
{
if (nItems >= MAX_NODES_IN_CURVE) {
cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: too many points.");
return FALSE;
}
for (i=0; i < nItems; i++)
{
w[i+1] = 1.0;
}
if (!smooth2(Tab ->InterpParams->ContextID, w, y, z, (cmsFloat32Number) lambda, nItems)) return FALSE;
// Do some reality - checking...
for (i=nItems; i > 1; --i) {
if (z[i] == 0.) Zeros++;
if (z[i] >= 65535.) Poles++;
}
// Seems ok
for (i=0; i < nItems; i++) {
// Clamp to cmsUInt16Number
}
return TRUE;
}
// Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting
// in a linear table. This way assures it is linear in 12 bits, which should be enought in most cases.
{
int diff;
if (diff > 0x0f)
return FALSE;
}
return TRUE;
}
// Same, but for monotonicity
{
int n;
int i, last;
_cmsAssert(t != NULL);
// Degenerated curves are monotonic? Ok, let's pass them
n = t ->nEntries;
if (n < 2) return TRUE;
// Curve direction
if (lDescending) {
for (i = 1; i < n; i++) {
return FALSE;
else
}
}
else {
for (i = n-2; i >= 0; --i) {
return FALSE;
else
}
}
return TRUE;
}
// Same, but for descending tables
{
_cmsAssert(t != NULL);
}
// Another info fn: is out gamma table multisegment?
{
_cmsAssert(t != NULL);
return t -> nSegments > 1;
}
{
_cmsAssert(t != NULL);
if (t -> nSegments != 1) return 0;
}
// We need accuracy this time
{
// Check for 16 bits table. If so, this is a limited-precision tone curve
}
}
// We need xput over here
{
return out;
}
// Least squares fitting.
// A mathematical procedure for finding the best-fitting curve to a given set of points by
// minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve.
// The sum of the squares of the offsets is used instead of the offset absolute values because
// this allows the residuals to be treated as a continuous differentiable quantity.
//
// y = f(x) = x ^ g
//
// R = (yi - (xi^g))
// R2 = (yi - (xi^g))2
// SUM R2 = SUM (yi - (xi^g))2
//
//
// g = 1/n * SUM(log(y) / log(x))
{
_cmsAssert(t != NULL);
// Excluding endpoints
// Avoid 7% on lower part to prevent
// artifacts due to linear ramps
if (y > 0. && y < 1. && x > 0.07) {
n++;
}
}
// Take a look on SD to see if gamma isn't exponential at all
return -1.0;
return (sum / n); // The mean
}