Path: blob/master/src/java.desktop/share/native/liblcms/cmssamp.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//5455#include "lcms2_internal.h"565758#define cmsmin(a, b) (((a) < (b)) ? (a) : (b))59#define cmsmax(a, b) (((a) > (b)) ? (a) : (b))6061// This file contains routines for resampling and LUT optimization, black point detection62// and black preservation.6364// Black point detection -------------------------------------------------------------------------656667// PCS -> PCS round trip transform, always uses relative intent on the device -> pcs68static69cmsHTRANSFORM CreateRoundtripXForm(cmsHPROFILE hProfile, cmsUInt32Number nIntent)70{71cmsContext ContextID = cmsGetProfileContextID(hProfile);72cmsHPROFILE hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);73cmsHTRANSFORM xform;74cmsBool BPC[4] = { FALSE, FALSE, FALSE, FALSE };75cmsFloat64Number States[4] = { 1.0, 1.0, 1.0, 1.0 };76cmsHPROFILE hProfiles[4];77cmsUInt32Number Intents[4];7879hProfiles[0] = hLab; hProfiles[1] = hProfile; hProfiles[2] = hProfile; hProfiles[3] = hLab;80Intents[0] = INTENT_RELATIVE_COLORIMETRIC; Intents[1] = nIntent; Intents[2] = INTENT_RELATIVE_COLORIMETRIC; Intents[3] = INTENT_RELATIVE_COLORIMETRIC;8182xform = cmsCreateExtendedTransform(ContextID, 4, hProfiles, BPC, Intents,83States, NULL, 0, TYPE_Lab_DBL, TYPE_Lab_DBL, cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);8485cmsCloseProfile(hLab);86return xform;87}8889// Use darker colorants to obtain black point. This works in the relative colorimetric intent and90// assumes more ink results in darker colors. No ink limit is assumed.91static92cmsBool BlackPointAsDarkerColorant(cmsHPROFILE hInput,93cmsUInt32Number Intent,94cmsCIEXYZ* BlackPoint,95cmsUInt32Number dwFlags)96{97cmsUInt16Number *Black;98cmsHTRANSFORM xform;99cmsColorSpaceSignature Space;100cmsUInt32Number nChannels;101cmsUInt32Number dwFormat;102cmsHPROFILE hLab;103cmsCIELab Lab;104cmsCIEXYZ BlackXYZ;105cmsContext ContextID = cmsGetProfileContextID(hInput);106107// If the profile does not support input direction, assume Black point 0108if (!cmsIsIntentSupported(hInput, Intent, LCMS_USED_AS_INPUT)) {109110BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;111return FALSE;112}113114// Create a formatter which has n channels and no floating point115dwFormat = cmsFormatterForColorspaceOfProfile(hInput, 2, FALSE);116117// Try to get black by using black colorant118Space = cmsGetColorSpace(hInput);119120// This function returns darker colorant in 16 bits for several spaces121if (!_cmsEndPointsBySpace(Space, NULL, &Black, &nChannels)) {122123BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;124return FALSE;125}126127if (nChannels != T_CHANNELS(dwFormat)) {128BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;129return FALSE;130}131132// Lab will be used as the output space, but lab2 will avoid recursion133hLab = cmsCreateLab2ProfileTHR(ContextID, NULL);134if (hLab == NULL) {135BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;136return FALSE;137}138139// Create the transform140xform = cmsCreateTransformTHR(ContextID, hInput, dwFormat,141hLab, TYPE_Lab_DBL, Intent, cmsFLAGS_NOOPTIMIZE|cmsFLAGS_NOCACHE);142cmsCloseProfile(hLab);143144if (xform == NULL) {145146// Something went wrong. Get rid of open resources and return zero as black147BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;148return FALSE;149}150151// Convert black to Lab152cmsDoTransform(xform, Black, &Lab, 1);153154// Force it to be neutral, clip to max. L* of 50155Lab.a = Lab.b = 0;156if (Lab.L > 50) Lab.L = 50;157158// Free the resources159cmsDeleteTransform(xform);160161// Convert from Lab (which is now clipped) to XYZ.162cmsLab2XYZ(NULL, &BlackXYZ, &Lab);163164if (BlackPoint != NULL)165*BlackPoint = BlackXYZ;166167return TRUE;168169cmsUNUSED_PARAMETER(dwFlags);170}171172// Get a black point of output CMYK profile, discounting any ink-limiting embedded173// in the profile. For doing that, we use perceptual intent in input direction:174// Lab (0, 0, 0) -> [Perceptual] Profile -> CMYK -> [Rel. colorimetric] Profile -> Lab175static176cmsBool BlackPointUsingPerceptualBlack(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile)177{178cmsHTRANSFORM hRoundTrip;179cmsCIELab LabIn, LabOut;180cmsCIEXYZ BlackXYZ;181182// Is the intent supported by the profile?183if (!cmsIsIntentSupported(hProfile, INTENT_PERCEPTUAL, LCMS_USED_AS_INPUT)) {184185BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;186return TRUE;187}188189hRoundTrip = CreateRoundtripXForm(hProfile, INTENT_PERCEPTUAL);190if (hRoundTrip == NULL) {191BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;192return FALSE;193}194195LabIn.L = LabIn.a = LabIn.b = 0;196cmsDoTransform(hRoundTrip, &LabIn, &LabOut, 1);197198// Clip Lab to reasonable limits199if (LabOut.L > 50) LabOut.L = 50;200LabOut.a = LabOut.b = 0;201202cmsDeleteTransform(hRoundTrip);203204// Convert it to XYZ205cmsLab2XYZ(NULL, &BlackXYZ, &LabOut);206207if (BlackPoint != NULL)208*BlackPoint = BlackXYZ;209210return TRUE;211}212213// This function shouldn't exist at all -- there is such quantity of broken214// profiles on black point tag, that we must somehow fix chromaticity to215// avoid huge tint when doing Black point compensation. This function does216// just that. There is a special flag for using black point tag, but turned217// off by default because it is bogus on most profiles. The detection algorithm218// involves to turn BP to neutral and to use only L component.219cmsBool CMSEXPORT cmsDetectBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)220{221cmsProfileClassSignature devClass;222223// Make sure the device class is adequate224devClass = cmsGetDeviceClass(hProfile);225if (devClass == cmsSigLinkClass ||226devClass == cmsSigAbstractClass ||227devClass == cmsSigNamedColorClass) {228BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;229return FALSE;230}231232// Make sure intent is adequate233if (Intent != INTENT_PERCEPTUAL &&234Intent != INTENT_RELATIVE_COLORIMETRIC &&235Intent != INTENT_SATURATION) {236BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;237return FALSE;238}239240// v4 + perceptual & saturation intents does have its own black point, and it is241// well specified enough to use it. Black point tag is deprecated in V4.242if ((cmsGetEncodedICCversion(hProfile) >= 0x4000000) &&243(Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {244245// Matrix shaper share MRC & perceptual intents246if (cmsIsMatrixShaper(hProfile))247return BlackPointAsDarkerColorant(hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, 0);248249// Get Perceptual black out of v4 profiles. That is fixed for perceptual & saturation intents250BlackPoint -> X = cmsPERCEPTUAL_BLACK_X;251BlackPoint -> Y = cmsPERCEPTUAL_BLACK_Y;252BlackPoint -> Z = cmsPERCEPTUAL_BLACK_Z;253254return TRUE;255}256257258#ifdef CMS_USE_PROFILE_BLACK_POINT_TAG259260// v2, v4 rel/abs colorimetric261if (cmsIsTag(hProfile, cmsSigMediaBlackPointTag) &&262Intent == INTENT_RELATIVE_COLORIMETRIC) {263264cmsCIEXYZ *BlackPtr, BlackXYZ, UntrustedBlackPoint, TrustedBlackPoint, MediaWhite;265cmsCIELab Lab;266267// If black point is specified, then use it,268269BlackPtr = cmsReadTag(hProfile, cmsSigMediaBlackPointTag);270if (BlackPtr != NULL) {271272BlackXYZ = *BlackPtr;273_cmsReadMediaWhitePoint(&MediaWhite, hProfile);274275// Black point is absolute XYZ, so adapt to D50 to get PCS value276cmsAdaptToIlluminant(&UntrustedBlackPoint, &MediaWhite, cmsD50_XYZ(), &BlackXYZ);277278// Force a=b=0 to get rid of any chroma279cmsXYZ2Lab(NULL, &Lab, &UntrustedBlackPoint);280Lab.a = Lab.b = 0;281if (Lab.L > 50) Lab.L = 50; // Clip to L* <= 50282cmsLab2XYZ(NULL, &TrustedBlackPoint, &Lab);283284if (BlackPoint != NULL)285*BlackPoint = TrustedBlackPoint;286287return TRUE;288}289}290#endif291292// That is about v2 profiles.293294// If output profile, discount ink-limiting and that's all295if (Intent == INTENT_RELATIVE_COLORIMETRIC &&296(cmsGetDeviceClass(hProfile) == cmsSigOutputClass) &&297(cmsGetColorSpace(hProfile) == cmsSigCmykData))298return BlackPointUsingPerceptualBlack(BlackPoint, hProfile);299300// Nope, compute BP using current intent.301return BlackPointAsDarkerColorant(hProfile, Intent, BlackPoint, dwFlags);302}303304305306// ---------------------------------------------------------------------------------------------------------307308// Least Squares Fit of a Quadratic Curve to Data309// http://www.personal.psu.edu/jhm/f90/lectures/lsq2.html310311static312cmsFloat64Number RootOfLeastSquaresFitQuadraticCurve(int n, cmsFloat64Number x[], cmsFloat64Number y[])313{314double sum_x = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0;315double sum_y = 0, sum_yx = 0, sum_yx2 = 0;316double d, a, b, c;317int i;318cmsMAT3 m;319cmsVEC3 v, res;320321if (n < 4) return 0;322323for (i=0; i < n; i++) {324325double xn = x[i];326double yn = y[i];327328sum_x += xn;329sum_x2 += xn*xn;330sum_x3 += xn*xn*xn;331sum_x4 += xn*xn*xn*xn;332333sum_y += yn;334sum_yx += yn*xn;335sum_yx2 += yn*xn*xn;336}337338_cmsVEC3init(&m.v[0], n, sum_x, sum_x2);339_cmsVEC3init(&m.v[1], sum_x, sum_x2, sum_x3);340_cmsVEC3init(&m.v[2], sum_x2, sum_x3, sum_x4);341342_cmsVEC3init(&v, sum_y, sum_yx, sum_yx2);343344if (!_cmsMAT3solve(&res, &m, &v)) return 0;345346347a = res.n[2];348b = res.n[1];349c = res.n[0];350351if (fabs(a) < 1.0E-10) {352353return cmsmin(0, cmsmax(50, -c/b ));354}355else {356357d = b*b - 4.0 * a * c;358if (d <= 0) {359return 0;360}361else {362363double rt = (-b + sqrt(d)) / (2.0 * a);364365return cmsmax(0, cmsmin(50, rt));366}367}368369}370371372373// Calculates the black point of a destination profile.374// This algorithm comes from the Adobe paper disclosing its black point compensation method.375cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)376{377cmsColorSpaceSignature ColorSpace;378cmsHTRANSFORM hRoundTrip = NULL;379cmsCIELab InitialLab, destLab, Lab;380cmsFloat64Number inRamp[256], outRamp[256];381cmsFloat64Number MinL, MaxL;382cmsBool NearlyStraightMidrange = TRUE;383cmsFloat64Number yRamp[256];384cmsFloat64Number x[256], y[256];385cmsFloat64Number lo, hi;386int n, l;387cmsProfileClassSignature devClass;388389// Make sure the device class is adequate390devClass = cmsGetDeviceClass(hProfile);391if (devClass == cmsSigLinkClass ||392devClass == cmsSigAbstractClass ||393devClass == cmsSigNamedColorClass) {394BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;395return FALSE;396}397398// Make sure intent is adequate399if (Intent != INTENT_PERCEPTUAL &&400Intent != INTENT_RELATIVE_COLORIMETRIC &&401Intent != INTENT_SATURATION) {402BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;403return FALSE;404}405406407// v4 + perceptual & saturation intents does have its own black point, and it is408// well specified enough to use it. Black point tag is deprecated in V4.409if ((cmsGetEncodedICCversion(hProfile) >= 0x4000000) &&410(Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {411412// Matrix shaper share MRC & perceptual intents413if (cmsIsMatrixShaper(hProfile))414return BlackPointAsDarkerColorant(hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, 0);415416// Get Perceptual black out of v4 profiles. That is fixed for perceptual & saturation intents417BlackPoint -> X = cmsPERCEPTUAL_BLACK_X;418BlackPoint -> Y = cmsPERCEPTUAL_BLACK_Y;419BlackPoint -> Z = cmsPERCEPTUAL_BLACK_Z;420return TRUE;421}422423424// Check if the profile is lut based and gray, rgb or cmyk (7.2 in Adobe's document)425ColorSpace = cmsGetColorSpace(hProfile);426if (!cmsIsCLUT(hProfile, Intent, LCMS_USED_AS_OUTPUT ) ||427(ColorSpace != cmsSigGrayData &&428ColorSpace != cmsSigRgbData &&429ColorSpace != cmsSigCmykData)) {430431// In this case, handle as input case432return cmsDetectBlackPoint(BlackPoint, hProfile, Intent, dwFlags);433}434435// It is one of the valid cases!, use Adobe algorithm436437438// Set a first guess, that should work on good profiles.439if (Intent == INTENT_RELATIVE_COLORIMETRIC) {440441cmsCIEXYZ IniXYZ;442443// calculate initial Lab as source black point444if (!cmsDetectBlackPoint(&IniXYZ, hProfile, Intent, dwFlags)) {445return FALSE;446}447448// convert the XYZ to lab449cmsXYZ2Lab(NULL, &InitialLab, &IniXYZ);450451} else {452453// set the initial Lab to zero, that should be the black point for perceptual and saturation454InitialLab.L = 0;455InitialLab.a = 0;456InitialLab.b = 0;457}458459460// Step 2461// ======462463// Create a roundtrip. Define a Transform BT for all x in L*a*b*464hRoundTrip = CreateRoundtripXForm(hProfile, Intent);465if (hRoundTrip == NULL) return FALSE;466467// Compute ramps468469for (l=0; l < 256; l++) {470471Lab.L = (cmsFloat64Number) (l * 100.0) / 255.0;472Lab.a = cmsmin(50, cmsmax(-50, InitialLab.a));473Lab.b = cmsmin(50, cmsmax(-50, InitialLab.b));474475cmsDoTransform(hRoundTrip, &Lab, &destLab, 1);476477inRamp[l] = Lab.L;478outRamp[l] = destLab.L;479}480481// Make monotonic482for (l = 254; l > 0; --l) {483outRamp[l] = cmsmin(outRamp[l], outRamp[l+1]);484}485486// Check487if (! (outRamp[0] < outRamp[255])) {488489cmsDeleteTransform(hRoundTrip);490BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;491return FALSE;492}493494495// Test for mid range straight (only on relative colorimetric)496NearlyStraightMidrange = TRUE;497MinL = outRamp[0]; MaxL = outRamp[255];498if (Intent == INTENT_RELATIVE_COLORIMETRIC) {499500for (l=0; l < 256; l++) {501502if (! ((inRamp[l] <= MinL + 0.2 * (MaxL - MinL) ) ||503(fabs(inRamp[l] - outRamp[l]) < 4.0 )))504NearlyStraightMidrange = FALSE;505}506507// If the mid range is straight (as determined above) then the508// DestinationBlackPoint shall be the same as initialLab.509// Otherwise, the DestinationBlackPoint shall be determined510// using curve fitting.511if (NearlyStraightMidrange) {512513cmsLab2XYZ(NULL, BlackPoint, &InitialLab);514cmsDeleteTransform(hRoundTrip);515return TRUE;516}517}518519520// curve fitting: The round-trip curve normally looks like a nearly constant section at the black point,521// with a corner and a nearly straight line to the white point.522for (l=0; l < 256; l++) {523524yRamp[l] = (outRamp[l] - MinL) / (MaxL - MinL);525}526527// find the black point using the least squares error quadratic curve fitting528if (Intent == INTENT_RELATIVE_COLORIMETRIC) {529lo = 0.1;530hi = 0.5;531}532else {533534// Perceptual and saturation535lo = 0.03;536hi = 0.25;537}538539// Capture shadow points for the fitting.540n = 0;541for (l=0; l < 256; l++) {542543cmsFloat64Number ff = yRamp[l];544545if (ff >= lo && ff < hi) {546x[n] = inRamp[l];547y[n] = yRamp[l];548n++;549}550}551552553// No suitable points554if (n < 3 ) {555cmsDeleteTransform(hRoundTrip);556BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;557return FALSE;558}559560561// fit and get the vertex of quadratic curve562Lab.L = RootOfLeastSquaresFitQuadraticCurve(n, x, y);563564if (Lab.L < 0.0) { // clip to zero L* if the vertex is negative565Lab.L = 0;566}567568Lab.a = InitialLab.a;569Lab.b = InitialLab.b;570571cmsLab2XYZ(NULL, BlackPoint, &Lab);572573cmsDeleteTransform(hRoundTrip);574return TRUE;575}576577578