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-2010 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 69 static 70 cmsHTRANSFORM 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. 92 static 93 cmsBool 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 176 static 177 cmsBool 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. 220 cmsBool 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 312 static 313 cmsFloat64Number 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 static 374 cmsBool IsMonotonic(int n, const cmsFloat64Number Table[]) 375 { 376 int i; 377 cmsFloat64Number last; 378 379 last = Table[n-1]; 380 381 for (i = n-2; i >= 0; --i) { 382 383 if (Table[i] > last) 384 385 return FALSE; 386 else 387 last = Table[i]; 388 389 } 390 391 return TRUE; 392 } 393 */ 394 395 // Calculates the black point of a destination profile. 396 // This algorithm comes from the Adobe paper disclosing its black point compensation method. 397 cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags) 398 { 399 cmsColorSpaceSignature ColorSpace; 400 cmsHTRANSFORM hRoundTrip = NULL; 401 cmsCIELab InitialLab, destLab, Lab; 402 cmsFloat64Number inRamp[256], outRamp[256]; 403 cmsFloat64Number MinL, MaxL; 404 cmsBool NearlyStraightMidrange = TRUE; 405 cmsFloat64Number yRamp[256]; 406 cmsFloat64Number x[256], y[256]; 407 cmsFloat64Number lo, hi; 408 int n, l; 409 cmsProfileClassSignature devClass; 410 411 // Make sure the device class is adequate 412 devClass = cmsGetDeviceClass(hProfile); 413 if (devClass == cmsSigLinkClass || 414 devClass == cmsSigAbstractClass || 415 devClass == cmsSigNamedColorClass) { 416 BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0; 417 return FALSE; 418 } 419 420 // Make sure intent is adequate 421 if (Intent != INTENT_PERCEPTUAL && 422 Intent != INTENT_RELATIVE_COLORIMETRIC && 423 Intent != INTENT_SATURATION) { 424 BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0; 425 return FALSE; 426 } 427 428 429 // v4 + perceptual & saturation intents does have its own black point, and it is 430 // well specified enough to use it. Black point tag is deprecated in V4. 431 if ((cmsGetEncodedICCversion(hProfile) >= 0x4000000) && 432 (Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) { 433 434 // Matrix shaper share MRC & perceptual intents 435 if (cmsIsMatrixShaper(hProfile)) 436 return BlackPointAsDarkerColorant(hProfile, INTENT_RELATIVE_COLORIMETRIC, BlackPoint, 0); 437 438 // Get Perceptual black out of v4 profiles. That is fixed for perceptual & saturation intents 439 BlackPoint -> X = cmsPERCEPTUAL_BLACK_X; 440 BlackPoint -> Y = cmsPERCEPTUAL_BLACK_Y; 441 BlackPoint -> Z = cmsPERCEPTUAL_BLACK_Z; 442 return TRUE; 443 } 444 445 446 // Check if the profile is lut based and gray, rgb or cmyk (7.2 in Adobe's document) 447 ColorSpace = cmsGetColorSpace(hProfile); 448 if (!cmsIsCLUT(hProfile, Intent, LCMS_USED_AS_OUTPUT ) || 449 (ColorSpace != cmsSigGrayData && 450 ColorSpace != cmsSigRgbData && 451 ColorSpace != cmsSigCmykData)) { 452 453 // In this case, handle as input case 454 return cmsDetectBlackPoint(BlackPoint, hProfile, Intent, dwFlags); 455 } 456 457 // It is one of the valid cases!, use Adobe algorithm 458 459 460 // Set a first guess, that should work on good profiles. 461 if (Intent == INTENT_RELATIVE_COLORIMETRIC) { 462 463 cmsCIEXYZ IniXYZ; 464 465 // calculate initial Lab as source black point 466 if (!cmsDetectBlackPoint(&IniXYZ, hProfile, Intent, dwFlags)) { 467 return FALSE; 468 } 469 470 // convert the XYZ to lab 471 cmsXYZ2Lab(NULL, &InitialLab, &IniXYZ); 472 473 } else { 474 475 // set the initial Lab to zero, that should be the black point for perceptual and saturation 476 InitialLab.L = 0; 477 InitialLab.a = 0; 478 InitialLab.b = 0; 479 } 480 481 482 // Step 2 483 // ====== 484 485 // Create a roundtrip. Define a Transform BT for all x in L*a*b* 486 hRoundTrip = CreateRoundtripXForm(hProfile, Intent); 487 if (hRoundTrip == NULL) return FALSE; 488 489 // Compute ramps 490 491 for (l=0; l < 256; l++) { 492 493 Lab.L = (cmsFloat64Number) (l * 100.0) / 255.0; 494 Lab.a = cmsmin(50, cmsmax(-50, InitialLab.a)); 495 Lab.b = cmsmin(50, cmsmax(-50, InitialLab.b)); 496 497 cmsDoTransform(hRoundTrip, &Lab, &destLab, 1); 498 499 inRamp[l] = Lab.L; 500 outRamp[l] = destLab.L; 501 } 502 503 // Make monotonic 504 for (l = 254; l > 0; --l) { 505 outRamp[l] = cmsmin(outRamp[l], outRamp[l+1]); 506 } 507 508 // Check 509 if (! (outRamp[0] < outRamp[255])) { 510 511 cmsDeleteTransform(hRoundTrip); 512 BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0; 513 return FALSE; 514 } 515 516 517 // Test for mid range straight (only on relative colorimetric) 518 519 NearlyStraightMidrange = TRUE; 520 MinL = outRamp[0]; MaxL = outRamp[255]; 521 if (Intent == INTENT_RELATIVE_COLORIMETRIC) { 522 523 for (l=0; l < 256; l++) { 524 525 if (! ((inRamp[l] <= MinL + 0.2 * (MaxL - MinL) ) || 526 (fabs(inRamp[l] - outRamp[l]) < 4.0 ))) 527 NearlyStraightMidrange = FALSE; 528 } 529 530 // If the mid range is straight (as determined above) then the 531 // DestinationBlackPoint shall be the same as initialLab. 532 // Otherwise, the DestinationBlackPoint shall be determined 533 // using curve fitting. 534 535 if (NearlyStraightMidrange) { 536 537 cmsLab2XYZ(NULL, BlackPoint, &InitialLab); 538 cmsDeleteTransform(hRoundTrip); 539 return TRUE; 540 } 541 } 542 543 544 // curve fitting: The round-trip curve normally looks like a nearly constant section at the black point, 545 // with a corner and a nearly straight line to the white point. 546 547 for (l=0; l < 256; l++) { 548 549 yRamp[l] = (outRamp[l] - MinL) / (MaxL - MinL); 550 } 551 552 // find the black point using the least squares error quadratic curve fitting 553 554 if (Intent == INTENT_RELATIVE_COLORIMETRIC) { 555 lo = 0.1; 556 hi = 0.5; 557 } 558 else { 559 560 // Perceptual and saturation 561 lo = 0.03; 562 hi = 0.25; 563 } 564 565 // Capture shadow points for the fitting. 566 n = 0; 567 for (l=0; l < 256; l++) { 568 569 cmsFloat64Number ff = yRamp[l]; 570 571 if (ff >= lo && ff < hi) { 572 x[n] = inRamp[l]; 573 y[n] = yRamp[l]; 574 n++; 575 } 576 } 577 578 579 // No suitable points 580 if (n < 3 ) { 581 cmsDeleteTransform(hRoundTrip); 582 BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0; 583 return FALSE; 584 } 585 586 587 // fit and get the vertex of quadratic curve 588 Lab.L = RootOfLeastSquaresFitQuadraticCurve(n, x, y); 589 590 if (Lab.L < 0.0) { // clip to zero L* if the vertex is negative 591 Lab.L = 0; 592 } 593 594 Lab.a = InitialLab.a; 595 Lab.b = InitialLab.b; 596 597 cmsLab2XYZ(NULL, BlackPoint, &Lab); 598 599 cmsDeleteTransform(hRoundTrip); 600 return TRUE; 601 }