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