1 //---------------------------------------------------------------------------------
3 // Little Color Management System
4 // Copyright (c) 1998-2023 Marti Maria Saguer
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:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
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.
24 //---------------------------------------------------------------------------------
27 #include "lcms2_internal.h"
30 // This is the default routine for ICC-style intents. A user may decide to override it by using a plugin.
31 // Supported intents are perceptual, relative colorimetric, saturation and ICC-absolute colorimetric
33 cmsPipeline* DefaultICCintents(cmsContext ContextID,
34 cmsUInt32Number nProfiles,
35 cmsUInt32Number Intents[],
36 cmsHPROFILE hProfiles[],
38 cmsFloat64Number AdaptationStates[],
39 cmsUInt32Number dwFlags);
41 //---------------------------------------------------------------------------------
43 // This is the entry for black-preserving K-only intents, which are non-ICC. Last profile have to be a output profile
44 // to do the trick (no devicelinks allowed at that position)
46 cmsPipeline* BlackPreservingKOnlyIntents(cmsContext ContextID,
47 cmsUInt32Number nProfiles,
48 cmsUInt32Number Intents[],
49 cmsHPROFILE hProfiles[],
51 cmsFloat64Number AdaptationStates[],
52 cmsUInt32Number dwFlags);
54 //---------------------------------------------------------------------------------
56 // This is the entry for black-plane preserving, which are non-ICC. Again, Last profile have to be a output profile
57 // to do the trick (no devicelinks allowed at that position)
59 cmsPipeline* BlackPreservingKPlaneIntents(cmsContext ContextID,
60 cmsUInt32Number nProfiles,
61 cmsUInt32Number Intents[],
62 cmsHPROFILE hProfiles[],
64 cmsFloat64Number AdaptationStates[],
65 cmsUInt32Number dwFlags);
67 //---------------------------------------------------------------------------------
70 // This is a structure holding implementations for all supported intents.
71 typedef struct _cms_intents_list {
73 cmsUInt32Number Intent;
74 char Description[256];
76 struct _cms_intents_list* Next;
82 static cmsIntentsList DefaultIntents[] = {
84 { INTENT_PERCEPTUAL, "Perceptual", DefaultICCintents, &DefaultIntents[1] },
85 { INTENT_RELATIVE_COLORIMETRIC, "Relative colorimetric", DefaultICCintents, &DefaultIntents[2] },
86 { INTENT_SATURATION, "Saturation", DefaultICCintents, &DefaultIntents[3] },
87 { INTENT_ABSOLUTE_COLORIMETRIC, "Absolute colorimetric", DefaultICCintents, &DefaultIntents[4] },
88 { INTENT_PRESERVE_K_ONLY_PERCEPTUAL, "Perceptual preserving black ink", BlackPreservingKOnlyIntents, &DefaultIntents[5] },
89 { INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC, "Relative colorimetric preserving black ink", BlackPreservingKOnlyIntents, &DefaultIntents[6] },
90 { INTENT_PRESERVE_K_ONLY_SATURATION, "Saturation preserving black ink", BlackPreservingKOnlyIntents, &DefaultIntents[7] },
91 { INTENT_PRESERVE_K_PLANE_PERCEPTUAL, "Perceptual preserving black plane", BlackPreservingKPlaneIntents, &DefaultIntents[8] },
92 { INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC,"Relative colorimetric preserving black plane", BlackPreservingKPlaneIntents, &DefaultIntents[9] },
93 { INTENT_PRESERVE_K_PLANE_SATURATION, "Saturation preserving black plane", BlackPreservingKPlaneIntents, NULL }
97 // A pointer to the beginning of the list
98 _cmsIntentsPluginChunkType _cmsIntentsPluginChunk = { NULL };
100 // Duplicates the zone of memory used by the plug-in in the new context
102 void DupPluginIntentsList(struct _cmsContext_struct* ctx,
103 const struct _cmsContext_struct* src)
105 _cmsIntentsPluginChunkType newHead = { NULL };
106 cmsIntentsList* entry;
107 cmsIntentsList* Anterior = NULL;
108 _cmsIntentsPluginChunkType* head = (_cmsIntentsPluginChunkType*) src->chunks[IntentPlugin];
110 // Walk the list copying all nodes
111 for (entry = head->Intents;
113 entry = entry ->Next) {
115 cmsIntentsList *newEntry = ( cmsIntentsList *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(cmsIntentsList));
117 if (newEntry == NULL)
120 // We want to keep the linked list order, so this is a little bit tricky
121 newEntry -> Next = NULL;
123 Anterior -> Next = newEntry;
127 if (newHead.Intents == NULL)
128 newHead.Intents = newEntry;
131 ctx ->chunks[IntentPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsIntentsPluginChunkType));
134 void _cmsAllocIntentsPluginChunk(struct _cmsContext_struct* ctx,
135 const struct _cmsContext_struct* src)
139 // Copy all linked list
140 DupPluginIntentsList(ctx, src);
143 static _cmsIntentsPluginChunkType IntentsPluginChunkType = { NULL };
144 ctx ->chunks[IntentPlugin] = _cmsSubAllocDup(ctx ->MemPool, &IntentsPluginChunkType, sizeof(_cmsIntentsPluginChunkType));
149 // Search the list for a suitable intent. Returns NULL if not found
151 cmsIntentsList* SearchIntent(cmsContext ContextID, cmsUInt32Number Intent)
153 _cmsIntentsPluginChunkType* ctx = ( _cmsIntentsPluginChunkType*) _cmsContextGetClientChunk(ContextID, IntentPlugin);
156 for (pt = ctx -> Intents; pt != NULL; pt = pt -> Next)
157 if (pt ->Intent == Intent) return pt;
159 for (pt = DefaultIntents; pt != NULL; pt = pt -> Next)
160 if (pt ->Intent == Intent) return pt;
165 // Black point compensation. Implemented as a linear scaling in XYZ. Black points
166 // should come relative to the white point. Fills an matrix/offset element m
167 // which is organized as a 4x4 matrix.
169 void ComputeBlackPointCompensation(const cmsCIEXYZ* BlackPointIn,
170 const cmsCIEXYZ* BlackPointOut,
171 cmsMAT3* m, cmsVEC3* off)
173 cmsFloat64Number ax, ay, az, bx, by, bz, tx, ty, tz;
175 // Now we need to compute a matrix plus an offset m and of such of
176 // [m]*bpin + off = bpout
177 // [m]*D50 + off = D50
179 // This is a linear scaling in the form ax+b, where
180 // a = (bpout - D50) / (bpin - D50)
181 // b = - D50* (bpout - bpin) / (bpin - D50)
183 tx = BlackPointIn->X - cmsD50_XYZ()->X;
184 ty = BlackPointIn->Y - cmsD50_XYZ()->Y;
185 tz = BlackPointIn->Z - cmsD50_XYZ()->Z;
187 ax = (BlackPointOut->X - cmsD50_XYZ()->X) / tx;
188 ay = (BlackPointOut->Y - cmsD50_XYZ()->Y) / ty;
189 az = (BlackPointOut->Z - cmsD50_XYZ()->Z) / tz;
191 bx = - cmsD50_XYZ()-> X * (BlackPointOut->X - BlackPointIn->X) / tx;
192 by = - cmsD50_XYZ()-> Y * (BlackPointOut->Y - BlackPointIn->Y) / ty;
193 bz = - cmsD50_XYZ()-> Z * (BlackPointOut->Z - BlackPointIn->Z) / tz;
195 _cmsVEC3init(&m ->v[0], ax, 0, 0);
196 _cmsVEC3init(&m ->v[1], 0, ay, 0);
197 _cmsVEC3init(&m ->v[2], 0, 0, az);
198 _cmsVEC3init(off, bx, by, bz);
203 // Approximate a blackbody illuminant based on CHAD information
205 cmsFloat64Number CHAD2Temp(const cmsMAT3* Chad)
207 // Convert D50 across inverse CHAD to get the absolute white point
210 cmsCIExyY DestChromaticity;
211 cmsFloat64Number TempK;
215 if (!_cmsMAT3inverse(&m1, &m2)) return FALSE;
217 s.n[VX] = cmsD50_XYZ() -> X;
218 s.n[VY] = cmsD50_XYZ() -> Y;
219 s.n[VZ] = cmsD50_XYZ() -> Z;
221 _cmsMAT3eval(&d, &m2, &s);
227 cmsXYZ2xyY(&DestChromaticity, &Dest);
229 if (!cmsTempFromWhitePoint(&TempK, &DestChromaticity))
235 // Compute a CHAD based on a given temperature
237 void Temp2CHAD(cmsMAT3* Chad, cmsFloat64Number Temp)
240 cmsCIExyY ChromaticityOfWhite;
242 cmsWhitePointFromTemp(&ChromaticityOfWhite, Temp);
243 cmsxyY2XYZ(&White, &ChromaticityOfWhite);
244 _cmsAdaptationMatrix(Chad, NULL, &White, cmsD50_XYZ());
247 // Join scalings to obtain relative input to absolute and then to relative output.
248 // Result is stored in a 3x3 matrix
250 cmsBool ComputeAbsoluteIntent(cmsFloat64Number AdaptationState,
251 const cmsCIEXYZ* WhitePointIn,
252 const cmsMAT3* ChromaticAdaptationMatrixIn,
253 const cmsCIEXYZ* WhitePointOut,
254 const cmsMAT3* ChromaticAdaptationMatrixOut,
257 cmsMAT3 Scale, m1, m2, m3, m4;
259 // TODO: Follow Marc Mahy's recommendation to check if CHAD is same by using M1*M2 == M2*M1. If so, do nothing.
260 // TODO: Add support for ArgyllArts tag
263 if (AdaptationState == 1.0) {
265 // Observer is fully adapted. Keep chromatic adaptation.
266 // That is the standard V4 behaviour
267 _cmsVEC3init(&m->v[0], WhitePointIn->X / WhitePointOut->X, 0, 0);
268 _cmsVEC3init(&m->v[1], 0, WhitePointIn->Y / WhitePointOut->Y, 0);
269 _cmsVEC3init(&m->v[2], 0, 0, WhitePointIn->Z / WhitePointOut->Z);
274 // Incomplete adaptation. This is an advanced feature.
275 _cmsVEC3init(&Scale.v[0], WhitePointIn->X / WhitePointOut->X, 0, 0);
276 _cmsVEC3init(&Scale.v[1], 0, WhitePointIn->Y / WhitePointOut->Y, 0);
277 _cmsVEC3init(&Scale.v[2], 0, 0, WhitePointIn->Z / WhitePointOut->Z);
280 if (AdaptationState == 0.0) {
282 m1 = *ChromaticAdaptationMatrixOut;
283 _cmsMAT3per(&m2, &m1, &Scale);
284 // m2 holds CHAD from output white to D50 times abs. col. scaling
286 // Observer is not adapted, undo the chromatic adaptation
287 _cmsMAT3per(m, &m2, ChromaticAdaptationMatrixOut);
289 m3 = *ChromaticAdaptationMatrixIn;
290 if (!_cmsMAT3inverse(&m3, &m4)) return FALSE;
291 _cmsMAT3per(m, &m2, &m4);
296 cmsFloat64Number TempSrc, TempDest, Temp;
298 m1 = *ChromaticAdaptationMatrixIn;
299 if (!_cmsMAT3inverse(&m1, &m2)) return FALSE;
300 _cmsMAT3per(&m3, &m2, &Scale);
301 // m3 holds CHAD from input white to D50 times abs. col. scaling
303 TempSrc = CHAD2Temp(ChromaticAdaptationMatrixIn);
304 TempDest = CHAD2Temp(ChromaticAdaptationMatrixOut);
306 if (TempSrc < 0.0 || TempDest < 0.0) return FALSE; // Something went wrong
308 if (_cmsMAT3isIdentity(&Scale) && fabs(TempSrc - TempDest) < 0.01) {
314 Temp = (1.0 - AdaptationState) * TempDest + AdaptationState * TempSrc;
316 // Get a CHAD from whatever output temperature to D50. This replaces output CHAD
317 Temp2CHAD(&MixedCHAD, Temp);
319 _cmsMAT3per(m, &m3, &MixedCHAD);
327 // Just to see if m matrix should be applied
329 cmsBool IsEmptyLayer(cmsMAT3* m, cmsVEC3* off)
331 cmsFloat64Number diff = 0;
335 if (m == NULL && off == NULL) return TRUE; // NULL is allowed as an empty layer
336 if (m == NULL && off != NULL) return FALSE; // This is an internal error
338 _cmsMAT3identity(&Ident);
340 for (i=0; i < 3*3; i++)
341 diff += fabs(((cmsFloat64Number*)m)[i] - ((cmsFloat64Number*)&Ident)[i]);
343 for (i=0; i < 3; i++)
344 diff += fabs(((cmsFloat64Number*)off)[i]);
347 return (diff < 0.002);
351 // Compute the conversion layer
353 cmsBool ComputeConversion(cmsUInt32Number i,
354 cmsHPROFILE hProfiles[],
355 cmsUInt32Number Intent,
357 cmsFloat64Number AdaptationState,
358 cmsMAT3* m, cmsVEC3* off)
363 // m and off are set to identity and this is detected latter on
365 _cmsVEC3init(off, 0, 0, 0);
367 // If intent is abs. colorimetric,
368 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC) {
370 cmsCIEXYZ WhitePointIn, WhitePointOut;
371 cmsMAT3 ChromaticAdaptationMatrixIn, ChromaticAdaptationMatrixOut;
373 if (!_cmsReadMediaWhitePoint(&WhitePointIn, hProfiles[i - 1])) return FALSE;
374 if (!_cmsReadCHAD(&ChromaticAdaptationMatrixIn, hProfiles[i - 1])) return FALSE;
376 if (!_cmsReadMediaWhitePoint(&WhitePointOut, hProfiles[i])) return FALSE;
377 if (!_cmsReadCHAD(&ChromaticAdaptationMatrixOut, hProfiles[i])) return FALSE;
379 if (!ComputeAbsoluteIntent(AdaptationState,
380 &WhitePointIn, &ChromaticAdaptationMatrixIn,
381 &WhitePointOut, &ChromaticAdaptationMatrixOut, m)) return FALSE;
385 // Rest of intents may apply BPC.
389 cmsCIEXYZ BlackPointIn = { 0, 0, 0}, BlackPointOut = { 0, 0, 0 };
391 cmsDetectBlackPoint(&BlackPointIn, hProfiles[i-1], Intent, 0);
392 cmsDetectDestinationBlackPoint(&BlackPointOut, hProfiles[i], Intent, 0);
394 // If black points are equal, then do nothing
395 if (BlackPointIn.X != BlackPointOut.X ||
396 BlackPointIn.Y != BlackPointOut.Y ||
397 BlackPointIn.Z != BlackPointOut.Z)
398 ComputeBlackPointCompensation(&BlackPointIn, &BlackPointOut, m, off);
402 // Offset should be adjusted because the encoding. We encode XYZ normalized to 0..1.0,
403 // to do that, we divide by MAX_ENCODEABLE_XZY. The conversion stage goes XYZ -> XYZ so
404 // we have first to convert from encoded to XYZ and then convert back to encoded.
408 // y = y'c; y' = y / c
409 // y' = (Mx'c + Off) /c = Mx' + (Off / c)
411 for (k=0; k < 3; k++) {
412 off ->n[k] /= MAX_ENCODEABLE_XYZ;
419 // Add a conversion stage if needed. If a matrix/offset m is given, it applies to XYZ space
421 cmsBool AddConversion(cmsPipeline* Result, cmsColorSpaceSignature InPCS, cmsColorSpaceSignature OutPCS, cmsMAT3* m, cmsVEC3* off)
423 cmsFloat64Number* m_as_dbl = (cmsFloat64Number*) m;
424 cmsFloat64Number* off_as_dbl = (cmsFloat64Number*) off;
426 // Handle PCS mismatches. A specialized stage is added to the LUT in such case
429 case cmsSigXYZData: // Input profile operates in XYZ
433 case cmsSigXYZData: // XYZ -> XYZ
434 if (!IsEmptyLayer(m, off) &&
435 !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)))
439 case cmsSigLabData: // XYZ -> Lab
440 if (!IsEmptyLayer(m, off) &&
441 !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)))
443 if (!cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID)))
448 return FALSE; // Colorspace mismatch
452 case cmsSigLabData: // Input profile operates in Lab
456 case cmsSigXYZData: // Lab -> XYZ
458 if (!cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID)))
460 if (!IsEmptyLayer(m, off) &&
461 !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)))
465 case cmsSigLabData: // Lab -> Lab
467 if (!IsEmptyLayer(m, off)) {
468 if (!cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID)) ||
469 !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)) ||
470 !cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID)))
476 return FALSE; // Mismatch
480 // On colorspaces other than PCS, check for same space
482 if (InPCS != OutPCS) return FALSE;
490 // Is a given space compatible with another?
492 cmsBool ColorSpaceIsCompatible(cmsColorSpaceSignature a, cmsColorSpaceSignature b)
494 // If they are same, they are compatible.
495 if (a == b) return TRUE;
497 // Check for MCH4 substitution of CMYK
498 if ((a == cmsSig4colorData) && (b == cmsSigCmykData)) return TRUE;
499 if ((a == cmsSigCmykData) && (b == cmsSig4colorData)) return TRUE;
501 // Check for XYZ/Lab. Those spaces are interchangeable as they can be computed one from other.
502 if ((a == cmsSigXYZData) && (b == cmsSigLabData)) return TRUE;
503 if ((a == cmsSigLabData) && (b == cmsSigXYZData)) return TRUE;
509 // Default handler for ICC-style intents
511 cmsPipeline* DefaultICCintents(cmsContext ContextID,
512 cmsUInt32Number nProfiles,
513 cmsUInt32Number TheIntents[],
514 cmsHPROFILE hProfiles[],
516 cmsFloat64Number AdaptationStates[],
517 cmsUInt32Number dwFlags)
519 cmsPipeline* Lut = NULL;
521 cmsHPROFILE hProfile;
524 cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut = cmsSigLabData, CurrentColorSpace;
525 cmsProfileClassSignature ClassSig;
526 cmsUInt32Number i, Intent;
529 if (nProfiles == 0) return NULL;
531 // Allocate an empty LUT for holding the result. 0 as channel count means 'undefined'
532 Result = cmsPipelineAlloc(ContextID, 0, 0);
533 if (Result == NULL) return NULL;
535 CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
537 for (i=0; i < nProfiles; i++) {
539 cmsBool lIsDeviceLink, lIsInput;
541 hProfile = hProfiles[i];
542 ClassSig = cmsGetDeviceClass(hProfile);
543 lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass );
545 // First profile is used as input unless devicelink or abstract
546 if ((i == 0) && !lIsDeviceLink) {
550 // Else use profile in the input direction if current space is not PCS
551 lIsInput = (CurrentColorSpace != cmsSigXYZData) &&
552 (CurrentColorSpace != cmsSigLabData);
555 Intent = TheIntents[i];
557 if (lIsInput || lIsDeviceLink) {
559 ColorSpaceIn = cmsGetColorSpace(hProfile);
560 ColorSpaceOut = cmsGetPCS(hProfile);
564 ColorSpaceIn = cmsGetPCS(hProfile);
565 ColorSpaceOut = cmsGetColorSpace(hProfile);
568 if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) {
570 cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch");
574 // If devicelink is found, then no custom intent is allowed and we can
575 // read the LUT to be applied. Settings don't apply here.
576 if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) {
578 // Get the involved LUT from the profile
579 Lut = _cmsReadDevicelinkLUT(hProfile, Intent);
580 if (Lut == NULL) goto Error;
582 // What about abstract profiles?
583 if (ClassSig == cmsSigAbstractClass && i > 0) {
584 if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
587 _cmsMAT3identity(&m);
588 _cmsVEC3init(&off, 0, 0, 0);
592 if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
598 // Input direction means non-pcs connection, so proceed like devicelinks
599 Lut = _cmsReadInputLUT(hProfile, Intent);
600 if (Lut == NULL) goto Error;
604 // Output direction means PCS connection. Intent may apply here
605 Lut = _cmsReadOutputLUT(hProfile, Intent);
606 if (Lut == NULL) goto Error;
609 if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
610 if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
615 // Concatenate to the output LUT
616 if (!cmsPipelineCat(Result, Lut))
619 cmsPipelineFree(Lut);
622 // Update current space
623 CurrentColorSpace = ColorSpaceOut;
626 // Check for non-negatives clip
627 if (dwFlags & cmsFLAGS_NONEGATIVES) {
629 if (ColorSpaceOut == cmsSigGrayData ||
630 ColorSpaceOut == cmsSigRgbData ||
631 ColorSpaceOut == cmsSigCmykData) {
633 cmsStage* clip = _cmsStageClipNegatives(Result->ContextID, cmsChannelsOfColorSpace(ColorSpaceOut));
634 if (clip == NULL) goto Error;
636 if (!cmsPipelineInsertStage(Result, cmsAT_END, clip))
646 if (Lut != NULL) cmsPipelineFree(Lut);
647 if (Result != NULL) cmsPipelineFree(Result);
650 cmsUNUSED_PARAMETER(dwFlags);
654 // Wrapper for DLL calling convention
655 cmsPipeline* CMSEXPORT _cmsDefaultICCintents(cmsContext ContextID,
656 cmsUInt32Number nProfiles,
657 cmsUInt32Number TheIntents[],
658 cmsHPROFILE hProfiles[],
660 cmsFloat64Number AdaptationStates[],
661 cmsUInt32Number dwFlags)
663 return DefaultICCintents(ContextID, nProfiles, TheIntents, hProfiles, BPC, AdaptationStates, dwFlags);
666 // Black preserving intents ---------------------------------------------------------------------------------------------
668 // Translate black-preserving intents to ICC ones
670 cmsUInt32Number TranslateNonICCIntents(cmsUInt32Number Intent)
673 case INTENT_PRESERVE_K_ONLY_PERCEPTUAL:
674 case INTENT_PRESERVE_K_PLANE_PERCEPTUAL:
675 return INTENT_PERCEPTUAL;
677 case INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC:
678 case INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC:
679 return INTENT_RELATIVE_COLORIMETRIC;
681 case INTENT_PRESERVE_K_ONLY_SATURATION:
682 case INTENT_PRESERVE_K_PLANE_SATURATION:
683 return INTENT_SATURATION;
685 default: return Intent;
689 // Sampler for Black-only preserving CMYK->CMYK transforms
692 cmsPipeline* cmyk2cmyk; // The original transform
693 cmsToneCurve* KTone; // Black-to-black tone curve
698 // Preserve black only if that is the only ink used
700 int BlackPreservingGrayOnlySampler(CMSREGISTER const cmsUInt16Number In[], CMSREGISTER cmsUInt16Number Out[], CMSREGISTER void* Cargo)
702 GrayOnlyParams* bp = (GrayOnlyParams*) Cargo;
704 // If going across black only, keep black only
705 if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
707 // TAC does not apply because it is black ink!
708 Out[0] = Out[1] = Out[2] = 0;
709 Out[3] = cmsEvalToneCurve16(bp->KTone, In[3]);
713 // Keep normal transform for other colors
714 bp ->cmyk2cmyk ->Eval16Fn(In, Out, bp ->cmyk2cmyk->Data);
719 // Check whatever the profile is a CMYK->CMYK devicelink
721 cmsBool is_cmyk_devicelink(cmsHPROFILE hProfile)
723 return cmsGetDeviceClass(hProfile) == cmsSigLinkClass &&
724 cmsGetColorSpace(hProfile) == cmsSigCmykData &&
725 cmsGetColorSpace(hProfile) == cmsSigCmykData;
728 // This is the entry for black-preserving K-only intents, which are non-ICC
730 cmsPipeline* BlackPreservingKOnlyIntents(cmsContext ContextID,
731 cmsUInt32Number nProfiles,
732 cmsUInt32Number TheIntents[],
733 cmsHPROFILE hProfiles[],
735 cmsFloat64Number AdaptationStates[],
736 cmsUInt32Number dwFlags)
740 cmsUInt32Number ICCIntents[256];
742 cmsUInt32Number i, nGridPoints;
743 cmsUInt32Number lastProfilePos;
744 cmsUInt32Number preservationProfilesCount;
745 cmsHPROFILE hLastProfile;
749 if (nProfiles < 1 || nProfiles > 255) return NULL;
751 // Translate black-preserving intents to ICC ones
752 for (i=0; i < nProfiles; i++)
753 ICCIntents[i] = TranslateNonICCIntents(TheIntents[i]);
756 // Trim all CMYK devicelinks at the end
757 lastProfilePos = nProfiles - 1;
758 hLastProfile = hProfiles[lastProfilePos];
760 // Skip CMYK->CMYK devicelinks on ending
761 while (is_cmyk_devicelink(hLastProfile))
763 if (lastProfilePos < 2)
766 hLastProfile = hProfiles[--lastProfilePos];
770 preservationProfilesCount = lastProfilePos + 1;
772 // Check for non-cmyk profiles
773 if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
774 !(cmsGetColorSpace(hLastProfile) == cmsSigCmykData ||
775 cmsGetDeviceClass(hLastProfile) == cmsSigOutputClass))
776 return DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
778 // Allocate an empty LUT for holding the result
779 Result = cmsPipelineAlloc(ContextID, 4, 4);
780 if (Result == NULL) return NULL;
782 memset(&bp, 0, sizeof(bp));
784 // Create a LUT holding normal ICC transform
785 bp.cmyk2cmyk = DefaultICCintents(ContextID,
786 preservationProfilesCount,
793 if (bp.cmyk2cmyk == NULL) goto Error;
795 // Now, compute the tone curve
796 bp.KTone = _cmsBuildKToneCurve(ContextID,
798 preservationProfilesCount,
805 if (bp.KTone == NULL) goto Error;
808 // How many gridpoints are we going to use?
809 nGridPoints = _cmsReasonableGridpointsByColorspace(cmsSigCmykData, dwFlags);
811 // Create the CLUT. 16 bits
812 CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
813 if (CLUT == NULL) goto Error;
815 // This is the one and only MPE in this LUT
816 if (!cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT))
819 // Sample it. We cannot afford pre/post linearization this time.
820 if (!cmsStageSampleCLut16bit(CLUT, BlackPreservingGrayOnlySampler, (void*) &bp, 0))
824 // Insert possible devicelinks at the end
825 for (i = lastProfilePos + 1; i < nProfiles; i++)
827 cmsPipeline* devlink = _cmsReadDevicelinkLUT(hProfiles[i], ICCIntents[i]);
831 if (!cmsPipelineCat(Result, devlink))
836 // Get rid of xform and tone curve
837 cmsPipelineFree(bp.cmyk2cmyk);
838 cmsFreeToneCurve(bp.KTone);
844 if (bp.cmyk2cmyk != NULL) cmsPipelineFree(bp.cmyk2cmyk);
845 if (bp.KTone != NULL) cmsFreeToneCurve(bp.KTone);
846 if (Result != NULL) cmsPipelineFree(Result);
851 // K Plane-preserving CMYK to CMYK ------------------------------------------------------------------------------------
855 cmsPipeline* cmyk2cmyk; // The original transform
856 cmsHTRANSFORM hProofOutput; // Output CMYK to Lab (last profile)
857 cmsHTRANSFORM cmyk2Lab; // The input chain
858 cmsToneCurve* KTone; // Black-to-black tone curve
859 cmsPipeline* LabK2cmyk; // The output profile
860 cmsFloat64Number MaxError;
862 cmsHTRANSFORM hRoundTrip;
863 cmsFloat64Number MaxTAC;
866 } PreserveKPlaneParams;
869 // The CLUT will be stored at 16 bits, but calculations are performed at cmsFloat32Number precision
871 int BlackPreservingSampler(CMSREGISTER const cmsUInt16Number In[], CMSREGISTER cmsUInt16Number Out[], CMSREGISTER void* Cargo)
874 cmsFloat32Number Inf[4], Outf[4];
875 cmsFloat32Number LabK[4];
876 cmsFloat64Number SumCMY, SumCMYK, Error, Ratio;
877 cmsCIELab ColorimetricLab, BlackPreservingLab;
878 PreserveKPlaneParams* bp = (PreserveKPlaneParams*) Cargo;
880 // Convert from 16 bits to floating point
881 for (i=0; i < 4; i++)
882 Inf[i] = (cmsFloat32Number) (In[i] / 65535.0);
884 // Get the K across Tone curve
885 LabK[3] = cmsEvalToneCurveFloat(bp ->KTone, Inf[3]);
887 // If going across black only, keep black only
888 if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
890 Out[0] = Out[1] = Out[2] = 0;
891 Out[3] = _cmsQuickSaturateWord(LabK[3] * 65535.0);
895 // Try the original transform,
896 cmsPipelineEvalFloat(Inf, Outf, bp ->cmyk2cmyk);
898 // Store a copy of the floating point result into 16-bit
899 for (i=0; i < 4; i++)
900 Out[i] = _cmsQuickSaturateWord(Outf[i] * 65535.0);
902 // Maybe K is already ok (mostly on K=0)
903 if (fabsf(Outf[3] - LabK[3]) < (3.0 / 65535.0)) {
907 // K differ, measure and keep Lab measurement for further usage
908 // this is done in relative colorimetric intent
909 cmsDoTransform(bp->hProofOutput, Out, &ColorimetricLab, 1);
911 // Is not black only and the transform doesn't keep black.
912 // Obtain the Lab of output CMYK. After that we have Lab + K
913 cmsDoTransform(bp ->cmyk2Lab, Outf, LabK, 1);
915 // Obtain the corresponding CMY using reverse interpolation
916 // (K is fixed in LabK[3])
917 if (!cmsPipelineEvalReverseFloat(LabK, Outf, Outf, bp ->LabK2cmyk)) {
919 // Cannot find a suitable value, so use colorimetric xform
920 // which is already stored in Out[]
924 // Make sure to pass through K (which now is fixed)
927 // Apply TAC if needed
928 SumCMY = (cmsFloat64Number) Outf[0] + Outf[1] + Outf[2];
929 SumCMYK = SumCMY + Outf[3];
931 if (SumCMYK > bp ->MaxTAC) {
933 Ratio = 1 - ((SumCMYK - bp->MaxTAC) / SumCMY);
940 Out[0] = _cmsQuickSaturateWord(Outf[0] * Ratio * 65535.0); // C
941 Out[1] = _cmsQuickSaturateWord(Outf[1] * Ratio * 65535.0); // M
942 Out[2] = _cmsQuickSaturateWord(Outf[2] * Ratio * 65535.0); // Y
943 Out[3] = _cmsQuickSaturateWord(Outf[3] * 65535.0);
945 // Estimate the error (this goes 16 bits to Lab DBL)
946 cmsDoTransform(bp->hProofOutput, Out, &BlackPreservingLab, 1);
947 Error = cmsDeltaE(&ColorimetricLab, &BlackPreservingLab);
948 if (Error > bp -> MaxError)
949 bp->MaxError = Error;
956 // This is the entry for black-plane preserving, which are non-ICC
958 cmsPipeline* BlackPreservingKPlaneIntents(cmsContext ContextID,
959 cmsUInt32Number nProfiles,
960 cmsUInt32Number TheIntents[],
961 cmsHPROFILE hProfiles[],
963 cmsFloat64Number AdaptationStates[],
964 cmsUInt32Number dwFlags)
966 PreserveKPlaneParams bp;
968 cmsPipeline* Result = NULL;
969 cmsUInt32Number ICCIntents[256];
971 cmsUInt32Number i, nGridPoints;
972 cmsUInt32Number lastProfilePos;
973 cmsUInt32Number preservationProfilesCount;
974 cmsHPROFILE hLastProfile;
978 if (nProfiles < 1 || nProfiles > 255) return NULL;
980 // Translate black-preserving intents to ICC ones
981 for (i=0; i < nProfiles; i++)
982 ICCIntents[i] = TranslateNonICCIntents(TheIntents[i]);
984 // Trim all CMYK devicelinks at the end
985 lastProfilePos = nProfiles - 1;
986 hLastProfile = hProfiles[lastProfilePos];
988 // Skip CMYK->CMYK devicelinks on ending
989 while (is_cmyk_devicelink(hLastProfile))
991 if (lastProfilePos < 2)
994 hLastProfile = hProfiles[--lastProfilePos];
997 preservationProfilesCount = lastProfilePos + 1;
999 // Check for non-cmyk profiles
1000 if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
1001 !(cmsGetColorSpace(hLastProfile) == cmsSigCmykData ||
1002 cmsGetDeviceClass(hLastProfile) == cmsSigOutputClass))
1003 return DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
1005 // Allocate an empty LUT for holding the result
1006 Result = cmsPipelineAlloc(ContextID, 4, 4);
1007 if (Result == NULL) return NULL;
1009 memset(&bp, 0, sizeof(bp));
1011 // We need the input LUT of the last profile, assuming this one is responsible of
1012 // black generation. This LUT will be searched in inverse order.
1013 bp.LabK2cmyk = _cmsReadInputLUT(hLastProfile, INTENT_RELATIVE_COLORIMETRIC);
1014 if (bp.LabK2cmyk == NULL) goto Cleanup;
1016 // Get total area coverage (in 0..1 domain)
1017 bp.MaxTAC = cmsDetectTAC(hLastProfile) / 100.0;
1018 if (bp.MaxTAC <= 0) goto Cleanup;
1021 // Create a LUT holding normal ICC transform
1022 bp.cmyk2cmyk = DefaultICCintents(ContextID,
1023 preservationProfilesCount,
1029 if (bp.cmyk2cmyk == NULL) goto Cleanup;
1031 // Now the tone curve
1032 bp.KTone = _cmsBuildKToneCurve(ContextID, 4096, preservationProfilesCount,
1038 if (bp.KTone == NULL) goto Cleanup;
1040 // To measure the output, Last profile to Lab
1041 hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
1042 bp.hProofOutput = cmsCreateTransformTHR(ContextID, hLastProfile,
1043 CHANNELS_SH(4)|BYTES_SH(2), hLab, TYPE_Lab_DBL,
1044 INTENT_RELATIVE_COLORIMETRIC,
1045 cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
1046 if ( bp.hProofOutput == NULL) goto Cleanup;
1048 // Same as anterior, but lab in the 0..1 range
1049 bp.cmyk2Lab = cmsCreateTransformTHR(ContextID, hLastProfile,
1050 FLOAT_SH(1)|CHANNELS_SH(4)|BYTES_SH(4), hLab,
1051 FLOAT_SH(1)|CHANNELS_SH(3)|BYTES_SH(4),
1052 INTENT_RELATIVE_COLORIMETRIC,
1053 cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
1054 if (bp.cmyk2Lab == NULL) goto Cleanup;
1055 cmsCloseProfile(hLab);
1057 // Error estimation (for debug only)
1060 // How many gridpoints are we going to use?
1061 nGridPoints = _cmsReasonableGridpointsByColorspace(cmsSigCmykData, dwFlags);
1064 CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
1065 if (CLUT == NULL) goto Cleanup;
1067 if (!cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT))
1070 cmsStageSampleCLut16bit(CLUT, BlackPreservingSampler, (void*) &bp, 0);
1072 // Insert possible devicelinks at the end
1073 for (i = lastProfilePos + 1; i < nProfiles; i++)
1075 cmsPipeline* devlink = _cmsReadDevicelinkLUT(hProfiles[i], ICCIntents[i]);
1076 if (devlink == NULL)
1079 if (!cmsPipelineCat(Result, devlink))
1086 if (bp.cmyk2cmyk) cmsPipelineFree(bp.cmyk2cmyk);
1087 if (bp.cmyk2Lab) cmsDeleteTransform(bp.cmyk2Lab);
1088 if (bp.hProofOutput) cmsDeleteTransform(bp.hProofOutput);
1090 if (bp.KTone) cmsFreeToneCurve(bp.KTone);
1091 if (bp.LabK2cmyk) cmsPipelineFree(bp.LabK2cmyk);
1098 // Link routines ------------------------------------------------------------------------------------------------------
1100 // Chain several profiles into a single LUT. It just checks the parameters and then calls the handler
1101 // for the first intent in chain. The handler may be user-defined. Is up to the handler to deal with the
1102 // rest of intents in chain. A maximum of 255 profiles at time are supported, which is pretty reasonable.
1103 cmsPipeline* _cmsLinkProfiles(cmsContext ContextID,
1104 cmsUInt32Number nProfiles,
1105 cmsUInt32Number TheIntents[],
1106 cmsHPROFILE hProfiles[],
1108 cmsFloat64Number AdaptationStates[],
1109 cmsUInt32Number dwFlags)
1112 cmsIntentsList* Intent;
1114 // Make sure a reasonable number of profiles is provided
1115 if (nProfiles <= 0 || nProfiles > 255) {
1116 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't link '%d' profiles", nProfiles);
1120 for (i=0; i < nProfiles; i++) {
1122 // Check if black point is really needed or allowed. Note that
1123 // following Adobe's document:
1124 // BPC does not apply to devicelink profiles, nor to abs colorimetric,
1125 // and applies always on V4 perceptual and saturation.
1127 if (TheIntents[i] == INTENT_ABSOLUTE_COLORIMETRIC)
1130 if (TheIntents[i] == INTENT_PERCEPTUAL || TheIntents[i] == INTENT_SATURATION) {
1132 // Force BPC for V4 profiles in perceptual and saturation
1133 if (cmsGetEncodedICCversion(hProfiles[i]) >= 0x4000000)
1138 // Search for a handler. The first intent in the chain defines the handler. That would
1139 // prevent using multiple custom intents in a multiintent chain, but the behaviour of
1140 // this case would present some issues if the custom intent tries to do things like
1141 // preserve primaries. This solution is not perfect, but works well on most cases.
1143 Intent = SearchIntent(ContextID, TheIntents[0]);
1144 if (Intent == NULL) {
1145 cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported intent '%d'", TheIntents[0]);
1150 return Intent ->Link(ContextID, nProfiles, TheIntents, hProfiles, BPC, AdaptationStates, dwFlags);
1153 // -------------------------------------------------------------------------------------------------
1155 // Get information about available intents. nMax is the maximum space for the supplied "Codes"
1156 // and "Descriptions" the function returns the total number of intents, which may be greater
1157 // than nMax, although the matrices are not populated beyond this level.
1158 cmsUInt32Number CMSEXPORT cmsGetSupportedIntentsTHR(cmsContext ContextID, cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
1160 _cmsIntentsPluginChunkType* ctx = ( _cmsIntentsPluginChunkType*) _cmsContextGetClientChunk(ContextID, IntentPlugin);
1162 cmsUInt32Number nIntents;
1164 for (nIntents=0, pt = DefaultIntents; pt != NULL; pt = pt -> Next)
1166 if (nIntents < nMax) {
1168 Codes[nIntents] = pt ->Intent;
1170 if (Descriptions != NULL)
1171 Descriptions[nIntents] = pt ->Description;
1177 for (pt = ctx->Intents; pt != NULL; pt = pt -> Next)
1179 if (nIntents < nMax) {
1181 Codes[nIntents] = pt ->Intent;
1183 if (Descriptions != NULL)
1184 Descriptions[nIntents] = pt ->Description;
1193 cmsUInt32Number CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
1195 return cmsGetSupportedIntentsTHR(NULL, nMax, Codes, Descriptions);
1198 // The plug-in registration. User can add new intents or override default routines
1199 cmsBool _cmsRegisterRenderingIntentPlugin(cmsContext id, cmsPluginBase* Data)
1201 _cmsIntentsPluginChunkType* ctx = ( _cmsIntentsPluginChunkType*) _cmsContextGetClientChunk(id, IntentPlugin);
1202 cmsPluginRenderingIntent* Plugin = (cmsPluginRenderingIntent*) Data;
1205 // Do we have to reset the custom intents?
1208 ctx->Intents = NULL;
1212 fl = (cmsIntentsList*) _cmsPluginMalloc(id, sizeof(cmsIntentsList));
1213 if (fl == NULL) return FALSE;
1216 fl ->Intent = Plugin ->Intent;
1217 strncpy(fl ->Description, Plugin ->Description, sizeof(fl ->Description)-1);
1218 fl ->Description[sizeof(fl ->Description)-1] = 0;
1220 fl ->Link = Plugin ->Link;
1222 fl ->Next = ctx ->Intents;