1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2020 Marti Maria Saguer
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24 //---------------------------------------------------------------------------------
25 //
26 
27 #include "lcms2_internal.h"
28 
29 
30 #define cmsmin(a, b) (((a) < (b)) ? (a) : (b))
31 #define cmsmax(a, b) (((a) > (b)) ? (a) : (b))
32 
33 // This file contains routines for resampling and LUT optimization, black point detection
34 // and black preservation.
35 
36 // Black point detection -------------------------------------------------------------------------
37 
38 
39 // PCS -> PCS round trip transform, always uses relative intent on the device -> pcs
40 static
CreateRoundtripXForm(cmsContext ContextID,cmsHPROFILE hProfile,cmsUInt32Number nIntent)41 cmsHTRANSFORM CreateRoundtripXForm(cmsContext ContextID, cmsHPROFILE hProfile, cmsUInt32Number nIntent)
42 {
43     cmsHPROFILE hLab = cmsCreateLab4Profile(ContextID, NULL);
44     cmsHTRANSFORM xform;
45     cmsBool BPC[4] = { FALSE, FALSE, FALSE, FALSE };
46     cmsFloat64Number States[4] = { 1.0, 1.0, 1.0, 1.0 };
47     cmsHPROFILE hProfiles[4];
48     cmsUInt32Number Intents[4];
49 
50     hProfiles[0] = hLab; hProfiles[1] = hProfile; hProfiles[2] = hProfile; hProfiles[3] = hLab;
51     Intents[0]   = INTENT_RELATIVE_COLORIMETRIC; Intents[1] = nIntent; Intents[2] = INTENT_RELATIVE_COLORIMETRIC; Intents[3] = INTENT_RELATIVE_COLORIMETRIC;
52 
53     xform =  cmsCreateExtendedTransform(ContextID, 4, hProfiles, BPC, Intents,
54         States, NULL, 0, TYPE_Lab_DBL, TYPE_Lab_DBL, cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
55 
56     cmsCloseProfile(ContextID, hLab);
57     return xform;
58 }
59 
60 // Use darker colorants to obtain black point. This works in the relative colorimetric intent and
61 // assumes more ink results in darker colors. No ink limit is assumed.
62 static
BlackPointAsDarkerColorant(cmsContext ContextID,cmsHPROFILE hInput,cmsUInt32Number Intent,cmsCIEXYZ * BlackPoint,cmsUInt32Number dwFlags)63 cmsBool  BlackPointAsDarkerColorant(cmsContext ContextID,
64                                     cmsHPROFILE hInput,
65                                     cmsUInt32Number Intent,
66                                     cmsCIEXYZ* BlackPoint,
67                                     cmsUInt32Number dwFlags)
68 {
69     cmsUInt16Number *Black;
70     cmsHTRANSFORM xform;
71     cmsColorSpaceSignature Space;
72     cmsUInt32Number nChannels;
73     cmsUInt32Number dwFormat;
74     cmsHPROFILE hLab;
75     cmsCIELab  Lab;
76     cmsCIEXYZ  BlackXYZ;
77 
78     // If the profile does not support input direction, assume Black point 0
79     if (!cmsIsIntentSupported(ContextID, hInput, Intent, LCMS_USED_AS_INPUT)) {
80 
81         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
82         return FALSE;
83     }
84 
85     // Create a formatter which has n channels and floating point
86     dwFormat = cmsFormatterForColorspaceOfProfile(ContextID, hInput, 2, FALSE);
87 
88    // Try to get black by using black colorant
89     Space = cmsGetColorSpace(ContextID, hInput);
90 
91     // This function returns darker colorant in 16 bits for several spaces
92     if (!_cmsEndPointsBySpace(Space, NULL, &Black, &nChannels)) {
93 
94         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
95         return FALSE;
96     }
97 
98     if (nChannels != T_CHANNELS(dwFormat)) {
99        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
100        return FALSE;
101     }
102 
103     // Lab will be used as the output space, but lab2 will avoid recursion
104     hLab = cmsCreateLab2Profile(ContextID, NULL);
105     if (hLab == NULL) {
106        BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
107        return FALSE;
108     }
109 
110     // Create the transform
111     xform = cmsCreateTransform(ContextID, hInput, dwFormat,
112                                 hLab, TYPE_Lab_DBL, Intent, cmsFLAGS_NOOPTIMIZE|cmsFLAGS_NOCACHE);
113     cmsCloseProfile(ContextID, hLab);
114 
115     if (xform == NULL) {
116 
117         // Something went wrong. Get rid of open resources and return zero as black
118         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
119         return FALSE;
120     }
121 
122     // Convert black to Lab
123     cmsDoTransform(ContextID, xform, Black, &Lab, 1);
124 
125     // Force it to be neutral, clip to max. L* of 50
126     Lab.a = Lab.b = 0;
127     if (Lab.L > 50) Lab.L = 50;
128 
129     // Free the resources
130     cmsDeleteTransform(ContextID, xform);
131 
132     // Convert from Lab (which is now clipped) to XYZ.
133     cmsLab2XYZ(ContextID, NULL, &BlackXYZ, &Lab);
134 
135     if (BlackPoint != NULL)
136         *BlackPoint = BlackXYZ;
137 
138     return TRUE;
139 
140     cmsUNUSED_PARAMETER(dwFlags);
141 }
142 
143 // Get a black point of output CMYK profile, discounting any ink-limiting embedded
144 // in the profile. For doing that, we use perceptual intent in input direction:
145 // Lab (0, 0, 0) -> [Perceptual] Profile -> CMYK -> [Rel. colorimetric] Profile -> Lab
146 static
BlackPointUsingPerceptualBlack(cmsContext ContextID,cmsCIEXYZ * BlackPoint,cmsHPROFILE hProfile)147 cmsBool BlackPointUsingPerceptualBlack(cmsContext ContextID, cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile)
148 {
149     cmsHTRANSFORM hRoundTrip;
150     cmsCIELab LabIn, LabOut;
151     cmsCIEXYZ  BlackXYZ;
152 
153      // Is the intent supported by the profile?
154     if (!cmsIsIntentSupported(ContextID, hProfile, INTENT_PERCEPTUAL, LCMS_USED_AS_INPUT)) {
155 
156         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
157         return TRUE;
158     }
159 
160     hRoundTrip = CreateRoundtripXForm(ContextID, hProfile, INTENT_PERCEPTUAL);
161     if (hRoundTrip == NULL) {
162         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
163         return FALSE;
164     }
165 
166     LabIn.L = LabIn.a = LabIn.b = 0;
167     cmsDoTransform(ContextID, hRoundTrip, &LabIn, &LabOut, 1);
168 
169     // Clip Lab to reasonable limits
170     if (LabOut.L > 50) LabOut.L = 50;
171     LabOut.a = LabOut.b = 0;
172 
173     cmsDeleteTransform(ContextID, hRoundTrip);
174 
175     // Convert it to XYZ
176     cmsLab2XYZ(ContextID, NULL, &BlackXYZ, &LabOut);
177 
178     if (BlackPoint != NULL)
179         *BlackPoint = BlackXYZ;
180 
181     return TRUE;
182 }
183 
184 // This function shouldn't exist at all -- there is such quantity of broken
185 // profiles on black point tag, that we must somehow fix chromaticity to
186 // avoid huge tint when doing Black point compensation. This function does
187 // just that. There is a special flag for using black point tag, but turned
188 // off by default because it is bogus on most profiles. The detection algorithm
189 // involves to turn BP to neutral and to use only L component.
cmsDetectBlackPoint(cmsContext ContextID,cmsCIEXYZ * BlackPoint,cmsHPROFILE hProfile,cmsUInt32Number Intent,cmsUInt32Number dwFlags)190 cmsBool CMSEXPORT cmsDetectBlackPoint(cmsContext ContextID, cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
191 {
192     cmsProfileClassSignature devClass;
193 
194     // Make sure the device class is adequate
195     devClass = cmsGetDeviceClass(ContextID, hProfile);
196     if (devClass == cmsSigLinkClass ||
197         devClass == cmsSigAbstractClass ||
198         devClass == cmsSigNamedColorClass) {
199             BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
200             return FALSE;
201     }
202 
203     // Make sure intent is adequate
204     if (Intent != INTENT_PERCEPTUAL &&
205         Intent != INTENT_RELATIVE_COLORIMETRIC &&
206         Intent != INTENT_SATURATION) {
207             BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
208             return FALSE;
209     }
210 
211     // v4 + perceptual & saturation intents does have its own black point, and it is
212     // well specified enough to use it. Black point tag is deprecated in V4.
213     if ((cmsGetEncodedICCversion(ContextID, hProfile) >= 0x4000000) &&
214         (Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {
215 
216             // Matrix shaper share MRC & perceptual intents
217             if (cmsIsMatrixShaper(ContextID, hProfile))
218                 return BlackPointAsDarkerColorant(ContextID, hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, 0);
219 
220             // Get Perceptual black out of v4 profiles. That is fixed for perceptual & saturation intents
221             BlackPoint -> X = cmsPERCEPTUAL_BLACK_X;
222             BlackPoint -> Y = cmsPERCEPTUAL_BLACK_Y;
223             BlackPoint -> Z = cmsPERCEPTUAL_BLACK_Z;
224 
225             return TRUE;
226     }
227 
228 
229 #ifdef CMS_USE_PROFILE_BLACK_POINT_TAG
230 
231     // v2, v4 rel/abs colorimetric
232     if (cmsIsTag(ContextID, hProfile, cmsSigMediaBlackPointTag) &&
233         Intent == INTENT_RELATIVE_COLORIMETRIC) {
234 
235             cmsCIEXYZ *BlackPtr, BlackXYZ, UntrustedBlackPoint, TrustedBlackPoint, MediaWhite;
236             cmsCIELab Lab;
237 
238             // If black point is specified, then use it,
239 
240             BlackPtr = cmsReadTag(ContextID, hProfile, cmsSigMediaBlackPointTag);
241             if (BlackPtr != NULL) {
242 
243                 BlackXYZ = *BlackPtr;
244                 _cmsReadMediaWhitePoint(ContextID, &MediaWhite, hProfile);
245 
246                 // Black point is absolute XYZ, so adapt to D50 to get PCS value
247                 cmsAdaptToIlluminant(ContextID, &UntrustedBlackPoint, &MediaWhite, cmsD50_XYZ(ContextID), &BlackXYZ);
248 
249                 // Force a=b=0 to get rid of any chroma
250                 cmsXYZ2Lab(ContextID, NULL, &Lab, &UntrustedBlackPoint);
251                 Lab.a = Lab.b = 0;
252                 if (Lab.L > 50) Lab.L = 50; // Clip to L* <= 50
253                 cmsLab2XYZ(ContextID, NULL, &TrustedBlackPoint, &Lab);
254 
255                 if (BlackPoint != NULL)
256                     *BlackPoint = TrustedBlackPoint;
257 
258                 return TRUE;
259             }
260     }
261 #endif
262 
263     // That is about v2 profiles.
264 
265     // If output profile, discount ink-limiting and that's all
266     if (Intent == INTENT_RELATIVE_COLORIMETRIC &&
267         (cmsGetDeviceClass(ContextID, hProfile) == cmsSigOutputClass) &&
268         (cmsGetColorSpace(ContextID, hProfile)  == cmsSigCmykData))
269         return BlackPointUsingPerceptualBlack(ContextID, BlackPoint, hProfile);
270 
271     // Nope, compute BP using current intent.
272     return BlackPointAsDarkerColorant(ContextID, hProfile, Intent, BlackPoint, dwFlags);
273 }
274 
275 
276 
277 // ---------------------------------------------------------------------------------------------------------
278 
279 // Least Squares Fit of a Quadratic Curve to Data
280 // http://www.personal.psu.edu/jhm/f90/lectures/lsq2.html
281 
282 static
RootOfLeastSquaresFitQuadraticCurve(cmsContext ContextID,int n,cmsFloat64Number x[],cmsFloat64Number y[])283 cmsFloat64Number RootOfLeastSquaresFitQuadraticCurve(cmsContext ContextID, int n, cmsFloat64Number x[], cmsFloat64Number y[])
284 {
285     double sum_x = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0;
286     double sum_y = 0, sum_yx = 0, sum_yx2 = 0;
287     double d, a, b, c;
288     int i;
289     cmsMAT3 m;
290     cmsVEC3 v, res;
291 
292     if (n < 4) return 0;
293 
294     for (i=0; i < n; i++) {
295 
296         double xn = x[i];
297         double yn = y[i];
298 
299         sum_x  += xn;
300         sum_x2 += xn*xn;
301         sum_x3 += xn*xn*xn;
302         sum_x4 += xn*xn*xn*xn;
303 
304         sum_y += yn;
305         sum_yx += yn*xn;
306         sum_yx2 += yn*xn*xn;
307     }
308 
309     _cmsVEC3init(ContextID, &m.v[0], n,      sum_x,  sum_x2);
310     _cmsVEC3init(ContextID, &m.v[1], sum_x,  sum_x2, sum_x3);
311     _cmsVEC3init(ContextID, &m.v[2], sum_x2, sum_x3, sum_x4);
312 
313     _cmsVEC3init(ContextID, &v, sum_y, sum_yx, sum_yx2);
314 
315     if (!_cmsMAT3solve(ContextID, &res, &m, &v)) return 0;
316 
317 
318     a = res.n[2];
319     b = res.n[1];
320     c = res.n[0];
321 
322     if (fabs(a) < 1.0E-10) {
323 
324         return cmsmin(0, cmsmax(50, -c/b ));
325     }
326     else {
327 
328          d = b*b - 4.0 * a * c;
329          if (d <= 0) {
330              return 0;
331          }
332          else {
333 
334              double rt = (-b + sqrt(d)) / (2.0 * a);
335 
336              return cmsmax(0, cmsmin(50, rt));
337          }
338    }
339 
340 }
341 
342 
343 
344 // Calculates the black point of a destination profile.
345 // This algorithm comes from the Adobe paper disclosing its black point compensation method.
cmsDetectDestinationBlackPoint(cmsContext ContextID,cmsCIEXYZ * BlackPoint,cmsHPROFILE hProfile,cmsUInt32Number Intent,cmsUInt32Number dwFlags)346 cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsContext ContextID, cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
347 {
348     cmsColorSpaceSignature ColorSpace;
349     cmsHTRANSFORM hRoundTrip = NULL;
350     cmsCIELab InitialLab, destLab, Lab;
351     cmsFloat64Number inRamp[256], outRamp[256];
352     cmsFloat64Number MinL, MaxL;
353     cmsBool NearlyStraightMidrange = TRUE;
354     cmsFloat64Number yRamp[256];
355     cmsFloat64Number x[256], y[256];
356     cmsFloat64Number lo, hi;
357     int n, l;
358     cmsProfileClassSignature devClass;
359 
360     // Make sure the device class is adequate
361     devClass = cmsGetDeviceClass(ContextID, hProfile);
362     if (devClass == cmsSigLinkClass ||
363         devClass == cmsSigAbstractClass ||
364         devClass == cmsSigNamedColorClass) {
365             BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
366             return FALSE;
367     }
368 
369     // Make sure intent is adequate
370     if (Intent != INTENT_PERCEPTUAL &&
371         Intent != INTENT_RELATIVE_COLORIMETRIC &&
372         Intent != INTENT_SATURATION) {
373             BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
374             return FALSE;
375     }
376 
377 
378     // v4 + perceptual & saturation intents does have its own black point, and it is
379     // well specified enough to use it. Black point tag is deprecated in V4.
380     if ((cmsGetEncodedICCversion(ContextID, hProfile) >= 0x4000000) &&
381         (Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {
382 
383             // Matrix shaper share MRC & perceptual intents
384             if (cmsIsMatrixShaper(ContextID, hProfile))
385                 return BlackPointAsDarkerColorant(ContextID, hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, 0);
386 
387             // Get Perceptual black out of v4 profiles. That is fixed for perceptual & saturation intents
388             BlackPoint -> X = cmsPERCEPTUAL_BLACK_X;
389             BlackPoint -> Y = cmsPERCEPTUAL_BLACK_Y;
390             BlackPoint -> Z = cmsPERCEPTUAL_BLACK_Z;
391             return TRUE;
392     }
393 
394 
395     // Check if the profile is lut based and gray, rgb or cmyk (7.2 in Adobe's document)
396     ColorSpace = cmsGetColorSpace(ContextID, hProfile);
397     if (!cmsIsCLUT(ContextID, hProfile, Intent, LCMS_USED_AS_OUTPUT ) ||
398         (ColorSpace != cmsSigGrayData &&
399          ColorSpace != cmsSigRgbData  &&
400          ColorSpace != cmsSigCmykData)) {
401 
402         // In this case, handle as input case
403         return cmsDetectBlackPoint(ContextID, BlackPoint, hProfile, Intent, dwFlags);
404     }
405 
406     // It is one of the valid cases!, use Adobe algorithm
407 
408 
409     // Set a first guess, that should work on good profiles.
410     if (Intent == INTENT_RELATIVE_COLORIMETRIC) {
411 
412         cmsCIEXYZ IniXYZ;
413 
414         // calculate initial Lab as source black point
415         if (!cmsDetectBlackPoint(ContextID, &IniXYZ, hProfile, Intent, dwFlags)) {
416             return FALSE;
417         }
418 
419         // convert the XYZ to lab
420         cmsXYZ2Lab(ContextID, NULL, &InitialLab, &IniXYZ);
421 
422     } else {
423 
424         // set the initial Lab to zero, that should be the black point for perceptual and saturation
425         InitialLab.L = 0;
426         InitialLab.a = 0;
427         InitialLab.b = 0;
428     }
429 
430 
431     // Step 2
432     // ======
433 
434     // Create a roundtrip. Define a Transform BT for all x in L*a*b*
435     hRoundTrip = CreateRoundtripXForm(ContextID, hProfile, Intent);
436     if (hRoundTrip == NULL)  return FALSE;
437 
438     // Compute ramps
439 
440     for (l=0; l < 256; l++) {
441 
442         Lab.L = (cmsFloat64Number) (l * 100.0) / 255.0;
443         Lab.a = cmsmin(50, cmsmax(-50, InitialLab.a));
444         Lab.b = cmsmin(50, cmsmax(-50, InitialLab.b));
445 
446         cmsDoTransform(ContextID, hRoundTrip, &Lab, &destLab, 1);
447 
448         inRamp[l]  = Lab.L;
449         outRamp[l] = destLab.L;
450     }
451 
452     // Make monotonic
453     for (l = 254; l > 0; --l) {
454         outRamp[l] = cmsmin(outRamp[l], outRamp[l+1]);
455     }
456 
457     // Check
458     if (! (outRamp[0] < outRamp[255])) {
459 
460         cmsDeleteTransform(ContextID, hRoundTrip);
461         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
462         return FALSE;
463     }
464 
465 
466     // Test for mid range straight (only on relative colorimetric)
467     NearlyStraightMidrange = TRUE;
468     MinL = outRamp[0]; MaxL = outRamp[255];
469     if (Intent == INTENT_RELATIVE_COLORIMETRIC) {
470 
471         for (l=0; l < 256; l++) {
472 
473             if (! ((inRamp[l] <= MinL + 0.2 * (MaxL - MinL) ) ||
474                 (fabs(inRamp[l] - outRamp[l]) < 4.0 )))
475                 NearlyStraightMidrange = FALSE;
476         }
477 
478         // If the mid range is straight (as determined above) then the
479         // DestinationBlackPoint shall be the same as initialLab.
480         // Otherwise, the DestinationBlackPoint shall be determined
481         // using curve fitting.
482         if (NearlyStraightMidrange) {
483 
484             cmsLab2XYZ(ContextID, NULL, BlackPoint, &InitialLab);
485             cmsDeleteTransform(ContextID, hRoundTrip);
486             return TRUE;
487         }
488     }
489 
490 
491     // curve fitting: The round-trip curve normally looks like a nearly constant section at the black point,
492     // with a corner and a nearly straight line to the white point.
493     for (l=0; l < 256; l++) {
494 
495         yRamp[l] = (outRamp[l] - MinL) / (MaxL - MinL);
496     }
497 
498     // find the black point using the least squares error quadratic curve fitting
499     if (Intent == INTENT_RELATIVE_COLORIMETRIC) {
500         lo = 0.1;
501         hi = 0.5;
502     }
503     else {
504 
505         // Perceptual and saturation
506         lo = 0.03;
507         hi = 0.25;
508     }
509 
510     // Capture shadow points for the fitting.
511     n = 0;
512     for (l=0; l < 256; l++) {
513 
514         cmsFloat64Number ff = yRamp[l];
515 
516         if (ff >= lo && ff < hi) {
517             x[n] = inRamp[l];
518             y[n] = yRamp[l];
519             n++;
520         }
521     }
522 
523 
524     // No suitable points
525     if (n < 3 ) {
526         cmsDeleteTransform(ContextID, hRoundTrip);
527         BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
528         return FALSE;
529     }
530 
531 
532     // fit and get the vertex of quadratic curve
533     Lab.L = RootOfLeastSquaresFitQuadraticCurve(ContextID, n, x, y);
534 
535     if (Lab.L < 0.0) { // clip to zero L* if the vertex is negative
536         Lab.L = 0;
537     }
538 
539     Lab.a = InitialLab.a;
540     Lab.b = InitialLab.b;
541 
542     cmsLab2XYZ(ContextID, NULL, BlackPoint, &Lab);
543 
544     cmsDeleteTransform(ContextID, hRoundTrip);
545     return TRUE;
546 }
547