Imported Upstream version 2.4
[platform/upstream/lcms2.git] / src / cmscnvrt.c
1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2012 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 // Link several profiles to obtain a single LUT modelling the whole color transform. Intents, Black point
31 // compensation and Adaptation parameters may vary across profiles. BPC and Adaptation refers to the PCS
32 // after the profile. I.e, BPC[0] refers to connexion between profile(0) and profile(1)
33 cmsPipeline* _cmsLinkProfiles(cmsContext     ContextID,
34                               cmsUInt32Number nProfiles,
35                               cmsUInt32Number Intents[],
36                               cmsHPROFILE     hProfiles[],
37                               cmsBool         BPC[],
38                               cmsFloat64Number AdaptationStates[],
39                               cmsUInt32Number dwFlags);
40
41 //---------------------------------------------------------------------------------
42
43 // This is the default routine for ICC-style intents. A user may decide to override it by using a plugin.
44 // Supported intents are perceptual, relative colorimetric, saturation and ICC-absolute colorimetric
45 static
46 cmsPipeline* DefaultICCintents(cmsContext     ContextID,
47                                cmsUInt32Number nProfiles,
48                                cmsUInt32Number Intents[],
49                                cmsHPROFILE     hProfiles[],
50                                cmsBool         BPC[],
51                                cmsFloat64Number AdaptationStates[],
52                                cmsUInt32Number dwFlags);
53
54 //---------------------------------------------------------------------------------
55
56 // This is the entry for black-preserving K-only intents, which are non-ICC. Last profile have to be a output profile
57 // to do the trick (no devicelinks allowed at that position)
58 static
59 cmsPipeline*  BlackPreservingKOnlyIntents(cmsContext     ContextID,
60                                           cmsUInt32Number nProfiles,
61                                           cmsUInt32Number Intents[],
62                                           cmsHPROFILE     hProfiles[],
63                                           cmsBool         BPC[],
64                                           cmsFloat64Number AdaptationStates[],
65                                           cmsUInt32Number dwFlags);
66
67 //---------------------------------------------------------------------------------
68
69 // This is the entry for black-plane preserving, which are non-ICC. Again, Last profile have to be a output profile
70 // to do the trick (no devicelinks allowed at that position)
71 static
72 cmsPipeline*  BlackPreservingKPlaneIntents(cmsContext     ContextID,
73                                            cmsUInt32Number nProfiles,
74                                            cmsUInt32Number Intents[],
75                                            cmsHPROFILE     hProfiles[],
76                                            cmsBool         BPC[],
77                                            cmsFloat64Number AdaptationStates[],
78                                            cmsUInt32Number dwFlags);
79
80 //---------------------------------------------------------------------------------
81
82
83 // This is a structure holding implementations for all supported intents.
84 typedef struct _cms_intents_list {
85
86     cmsUInt32Number Intent;
87     char            Description[256];
88     cmsIntentFn     Link;
89     struct _cms_intents_list*  Next;
90
91 } cmsIntentsList;
92
93
94 // Built-in intents
95 static cmsIntentsList DefaultIntents[] = {
96
97     { INTENT_PERCEPTUAL,                            "Perceptual",                                   DefaultICCintents,            &DefaultIntents[1] },
98     { INTENT_RELATIVE_COLORIMETRIC,                 "Relative colorimetric",                        DefaultICCintents,            &DefaultIntents[2] },
99     { INTENT_SATURATION,                            "Saturation",                                   DefaultICCintents,            &DefaultIntents[3] },
100     { INTENT_ABSOLUTE_COLORIMETRIC,                 "Absolute colorimetric",                        DefaultICCintents,            &DefaultIntents[4] },
101     { INTENT_PRESERVE_K_ONLY_PERCEPTUAL,            "Perceptual preserving black ink",              BlackPreservingKOnlyIntents,  &DefaultIntents[5] },
102     { INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC, "Relative colorimetric preserving black ink",   BlackPreservingKOnlyIntents,  &DefaultIntents[6] },
103     { INTENT_PRESERVE_K_ONLY_SATURATION,            "Saturation preserving black ink",              BlackPreservingKOnlyIntents,  &DefaultIntents[7] },
104     { INTENT_PRESERVE_K_PLANE_PERCEPTUAL,           "Perceptual preserving black plane",            BlackPreservingKPlaneIntents, &DefaultIntents[8] },
105     { INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC,"Relative colorimetric preserving black plane", BlackPreservingKPlaneIntents, &DefaultIntents[9] },
106     { INTENT_PRESERVE_K_PLANE_SATURATION,           "Saturation preserving black plane",            BlackPreservingKPlaneIntents, NULL }
107 };
108
109
110 // A pointer to the begining of the list
111 static cmsIntentsList *Intents = DefaultIntents;
112
113 // Search the list for a suitable intent. Returns NULL if not found
114 static
115 cmsIntentsList* SearchIntent(cmsUInt32Number Intent)
116 {
117     cmsIntentsList* pt;
118
119     for (pt = Intents; pt != NULL; pt = pt -> Next)
120         if (pt ->Intent == Intent) return pt;
121
122     return NULL;
123 }
124
125 // Black point compensation. Implemented as a linear scaling in XYZ. Black points
126 // should come relative to the white point. Fills an matrix/offset element m
127 // which is organized as a 4x4 matrix.
128 static
129 void ComputeBlackPointCompensation(const cmsCIEXYZ* BlackPointIn,
130                                    const cmsCIEXYZ* BlackPointOut,
131                                    cmsMAT3* m, cmsVEC3* off)
132 {
133   cmsFloat64Number ax, ay, az, bx, by, bz, tx, ty, tz;
134
135    // Now we need to compute a matrix plus an offset m and of such of
136    // [m]*bpin + off = bpout
137    // [m]*D50  + off = D50
138    //
139    // This is a linear scaling in the form ax+b, where
140    // a = (bpout - D50) / (bpin - D50)
141    // b = - D50* (bpout - bpin) / (bpin - D50)
142
143    tx = BlackPointIn->X - cmsD50_XYZ()->X;
144    ty = BlackPointIn->Y - cmsD50_XYZ()->Y;
145    tz = BlackPointIn->Z - cmsD50_XYZ()->Z;
146
147    ax = (BlackPointOut->X - cmsD50_XYZ()->X) / tx;
148    ay = (BlackPointOut->Y - cmsD50_XYZ()->Y) / ty;
149    az = (BlackPointOut->Z - cmsD50_XYZ()->Z) / tz;
150
151    bx = - cmsD50_XYZ()-> X * (BlackPointOut->X - BlackPointIn->X) / tx;
152    by = - cmsD50_XYZ()-> Y * (BlackPointOut->Y - BlackPointIn->Y) / ty;
153    bz = - cmsD50_XYZ()-> Z * (BlackPointOut->Z - BlackPointIn->Z) / tz;
154
155    _cmsVEC3init(&m ->v[0], ax, 0,  0);
156    _cmsVEC3init(&m ->v[1], 0, ay,  0);
157    _cmsVEC3init(&m ->v[2], 0,  0,  az);
158    _cmsVEC3init(off, bx, by, bz);
159
160 }
161
162
163 // Approximate a blackbody illuminant based on CHAD information
164 static
165 cmsFloat64Number CHAD2Temp(const cmsMAT3* Chad)
166 {
167     // Convert D50 across inverse CHAD to get the absolute white point
168     cmsVEC3 d, s;
169     cmsCIEXYZ Dest;
170     cmsCIExyY DestChromaticity;
171     cmsFloat64Number TempK;
172     cmsMAT3 m1, m2;
173
174     m1 = *Chad;
175     if (!_cmsMAT3inverse(&m1, &m2)) return FALSE;
176
177     s.n[VX] = cmsD50_XYZ() -> X;
178     s.n[VY] = cmsD50_XYZ() -> Y;
179     s.n[VZ] = cmsD50_XYZ() -> Z;
180
181     _cmsMAT3eval(&d, &m2, &s);
182
183     Dest.X = d.n[VX];
184     Dest.Y = d.n[VY];
185     Dest.Z = d.n[VZ];
186
187     cmsXYZ2xyY(&DestChromaticity, &Dest);
188
189     if (!cmsTempFromWhitePoint(&TempK, &DestChromaticity))
190         return -1.0;
191
192     return TempK;
193 }
194
195 // Compute a CHAD based on a given temperature
196 static
197     void Temp2CHAD(cmsMAT3* Chad, cmsFloat64Number Temp)
198 {
199     cmsCIEXYZ White;
200     cmsCIExyY ChromaticityOfWhite;
201
202     cmsWhitePointFromTemp(&ChromaticityOfWhite, Temp);
203     cmsxyY2XYZ(&White, &ChromaticityOfWhite);
204     _cmsAdaptationMatrix(Chad, NULL, &White, cmsD50_XYZ());
205 }
206
207 // Join scalings to obtain relative input to absolute and then to relative output.
208 // Result is stored in a 3x3 matrix
209 static
210 cmsBool  ComputeAbsoluteIntent(cmsFloat64Number AdaptationState,
211                                const cmsCIEXYZ* WhitePointIn,
212                                const cmsMAT3* ChromaticAdaptationMatrixIn,
213                                const cmsCIEXYZ* WhitePointOut,
214                                const cmsMAT3* ChromaticAdaptationMatrixOut,
215                                cmsMAT3* m)
216 {
217     cmsMAT3 Scale, m1, m2, m3, m4;
218
219     // Adaptation state
220     if (AdaptationState == 1.0) {
221
222         // Observer is fully adapted. Keep chromatic adaptation.
223         // That is the standard V4 behaviour
224         _cmsVEC3init(&m->v[0], WhitePointIn->X / WhitePointOut->X, 0, 0);
225         _cmsVEC3init(&m->v[1], 0, WhitePointIn->Y / WhitePointOut->Y, 0);
226         _cmsVEC3init(&m->v[2], 0, 0, WhitePointIn->Z / WhitePointOut->Z);
227
228     }
229     else  {
230
231         // Incomplete adaptation. This is an advanced feature.
232         _cmsVEC3init(&Scale.v[0], WhitePointIn->X / WhitePointOut->X, 0, 0);
233         _cmsVEC3init(&Scale.v[1], 0,  WhitePointIn->Y / WhitePointOut->Y, 0);
234         _cmsVEC3init(&Scale.v[2], 0, 0,  WhitePointIn->Z / WhitePointOut->Z);
235
236
237         if (AdaptationState == 0.0) {
238
239             m1 = *ChromaticAdaptationMatrixOut;
240             _cmsMAT3per(&m2, &m1, &Scale);
241             // m2 holds CHAD from output white to D50 times abs. col. scaling
242
243             // Observer is not adapted, undo the chromatic adaptation
244             _cmsMAT3per(m, &m3, ChromaticAdaptationMatrixOut);
245
246             m3 = *ChromaticAdaptationMatrixIn;
247             if (!_cmsMAT3inverse(&m3, &m4)) return FALSE;
248             _cmsMAT3per(m, &m2, &m4);
249
250         } else {
251
252             cmsMAT3 MixedCHAD;
253             cmsFloat64Number TempSrc, TempDest, Temp;
254
255             m1 = *ChromaticAdaptationMatrixIn;
256             if (!_cmsMAT3inverse(&m1, &m2)) return FALSE;
257             _cmsMAT3per(&m3, &m2, &Scale);
258             // m3 holds CHAD from input white to D50 times abs. col. scaling
259
260             TempSrc  = CHAD2Temp(ChromaticAdaptationMatrixIn);
261             TempDest = CHAD2Temp(ChromaticAdaptationMatrixOut);
262
263             if (TempSrc < 0.0 || TempDest < 0.0) return FALSE; // Something went wrong
264
265             if (_cmsMAT3isIdentity(&Scale) && fabs(TempSrc - TempDest) < 0.01) {
266
267                 _cmsMAT3identity(m);
268                 return TRUE;
269             }
270
271             Temp = (1.0 - AdaptationState) * TempDest + AdaptationState * TempSrc;
272
273             // Get a CHAD from whatever output temperature to D50. This replaces output CHAD
274             Temp2CHAD(&MixedCHAD, Temp);
275
276             _cmsMAT3per(m, &m3, &MixedCHAD);
277         }
278
279     }
280     return TRUE;
281
282 }
283
284 // Just to see if m matrix should be applied
285 static
286 cmsBool IsEmptyLayer(cmsMAT3* m, cmsVEC3* off)
287 {
288     cmsFloat64Number diff = 0;
289     cmsMAT3 Ident;
290     int i;
291
292     if (m == NULL && off == NULL) return TRUE;  // NULL is allowed as an empty layer
293     if (m == NULL && off != NULL) return FALSE; // This is an internal error
294
295     _cmsMAT3identity(&Ident);
296
297     for (i=0; i < 3*3; i++)
298         diff += fabs(((cmsFloat64Number*)m)[i] - ((cmsFloat64Number*)&Ident)[i]);
299
300     for (i=0; i < 3; i++)
301         diff += fabs(((cmsFloat64Number*)off)[i]);
302
303
304     return (diff < 0.002);
305 }
306
307
308 // Compute the conversion layer
309 static
310 cmsBool ComputeConversion(int i, cmsHPROFILE hProfiles[],
311                                  cmsUInt32Number Intent,
312                                  cmsBool BPC,
313                                  cmsFloat64Number AdaptationState,
314                                  cmsMAT3* m, cmsVEC3* off)
315 {
316
317     int k;
318
319     // m  and off are set to identity and this is detected latter on
320     _cmsMAT3identity(m);
321     _cmsVEC3init(off, 0, 0, 0);
322
323     // If intent is abs. colorimetric,
324     if (Intent == INTENT_ABSOLUTE_COLORIMETRIC) {
325
326         cmsCIEXYZ WhitePointIn, WhitePointOut;
327         cmsMAT3 ChromaticAdaptationMatrixIn, ChromaticAdaptationMatrixOut;
328
329         _cmsReadMediaWhitePoint(&WhitePointIn,  hProfiles[i-1]);
330         _cmsReadCHAD(&ChromaticAdaptationMatrixIn, hProfiles[i-1]);
331
332         _cmsReadMediaWhitePoint(&WhitePointOut,  hProfiles[i]);
333         _cmsReadCHAD(&ChromaticAdaptationMatrixOut, hProfiles[i]);
334
335         if (!ComputeAbsoluteIntent(AdaptationState,
336                                   &WhitePointIn,  &ChromaticAdaptationMatrixIn,
337                                   &WhitePointOut, &ChromaticAdaptationMatrixOut, m)) return FALSE;
338
339     }
340     else {
341         // Rest of intents may apply BPC.
342
343         if (BPC) {
344
345             cmsCIEXYZ BlackPointIn, BlackPointOut;
346
347             cmsDetectBlackPoint(&BlackPointIn,  hProfiles[i-1], Intent, 0);
348             cmsDetectDestinationBlackPoint(&BlackPointOut, hProfiles[i], Intent, 0);
349
350             // If black points are equal, then do nothing
351             if (BlackPointIn.X != BlackPointOut.X ||
352                 BlackPointIn.Y != BlackPointOut.Y ||
353                 BlackPointIn.Z != BlackPointOut.Z)
354                     ComputeBlackPointCompensation(&BlackPointIn, &BlackPointOut, m, off);
355         }
356     }
357
358     // Offset should be adjusted because the encoding. We encode XYZ normalized to 0..1.0,
359     // to do that, we divide by MAX_ENCODEABLE_XZY. The conversion stage goes XYZ -> XYZ so
360     // we have first to convert from encoded to XYZ and then convert back to encoded.
361     // y = Mx + Off
362     // x = x'c
363     // y = M x'c + Off
364     // y = y'c; y' = y / c
365     // y' = (Mx'c + Off) /c = Mx' + (Off / c)
366
367     for (k=0; k < 3; k++) {
368         off ->n[k] /= MAX_ENCODEABLE_XYZ;
369     }
370
371     return TRUE;
372 }
373
374
375 // Add a conversion stage if needed. If a matrix/offset m is given, it applies to XYZ space
376 static
377 cmsBool AddConversion(cmsPipeline* Result, cmsColorSpaceSignature InPCS, cmsColorSpaceSignature OutPCS, cmsMAT3* m, cmsVEC3* off)
378 {
379     cmsFloat64Number* m_as_dbl = (cmsFloat64Number*) m;
380     cmsFloat64Number* off_as_dbl = (cmsFloat64Number*) off;
381
382     // Handle PCS mismatches. A specialized stage is added to the LUT in such case
383     switch (InPCS) {
384
385         case cmsSigXYZData: // Input profile operates in XYZ
386
387             switch (OutPCS) {
388
389             case cmsSigXYZData:  // XYZ -> XYZ
390                 if (!IsEmptyLayer(m, off))
391                     cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
392                 break;
393
394             case cmsSigLabData:  // XYZ -> Lab
395                 if (!IsEmptyLayer(m, off))
396                     cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
397                 cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID));
398                 break;
399
400             default:
401                 return FALSE;   // Colorspace mismatch
402                 }
403                 break;
404
405
406         case cmsSigLabData: // Input profile operates in Lab
407
408             switch (OutPCS) {
409
410             case cmsSigXYZData:  // Lab -> XYZ
411
412                 cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID));
413                 if (!IsEmptyLayer(m, off))
414                     cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
415                 break;
416
417             case cmsSigLabData:  // Lab -> Lab
418
419                 if (!IsEmptyLayer(m, off)) {
420                     cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID));
421                     cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
422                     cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID));
423                 }
424                 break;
425
426             default:
427                 return FALSE;  // Mismatch
428             }
429             break;
430
431
432             // On colorspaces other than PCS, check for same space
433         default:
434             if (InPCS != OutPCS) return FALSE;
435             break;
436     }
437
438     return TRUE;
439 }
440
441
442 // Is a given space compatible with another?
443 static
444 cmsBool ColorSpaceIsCompatible(cmsColorSpaceSignature a, cmsColorSpaceSignature b)
445 {
446     // If they are same, they are compatible.
447     if (a == b) return TRUE;
448
449     // Check for MCH4 substitution of CMYK
450     if ((a == cmsSig4colorData) && (b == cmsSigCmykData)) return TRUE;
451     if ((a == cmsSigCmykData) && (b == cmsSig4colorData)) return TRUE;
452
453     // Check for XYZ/Lab. Those spaces are interchangeable as they can be computed one from other.
454     if ((a == cmsSigXYZData) && (b == cmsSigLabData)) return TRUE;
455     if ((a == cmsSigLabData) && (b == cmsSigXYZData)) return TRUE;
456
457     return FALSE;
458 }
459
460
461 // Default handler for ICC-style intents
462 static
463 cmsPipeline* DefaultICCintents(cmsContext       ContextID,
464                                cmsUInt32Number  nProfiles,
465                                cmsUInt32Number  TheIntents[],
466                                cmsHPROFILE      hProfiles[],
467                                cmsBool          BPC[],
468                                cmsFloat64Number AdaptationStates[],
469                                cmsUInt32Number  dwFlags)
470 {
471     cmsPipeline* Lut, *Result;
472     cmsHPROFILE hProfile;
473     cmsMAT3 m;
474     cmsVEC3 off;
475     cmsColorSpaceSignature ColorSpaceIn, ColorSpaceOut, CurrentColorSpace;
476     cmsProfileClassSignature ClassSig;
477     cmsUInt32Number  i, Intent;
478
479     // For safety
480     if (nProfiles == 0) return NULL;
481
482     // Allocate an empty LUT for holding the result. 0 as channel count means 'undefined'
483     Result = cmsPipelineAlloc(ContextID, 0, 0);
484     if (Result == NULL) return NULL;
485
486     CurrentColorSpace = cmsGetColorSpace(hProfiles[0]);
487
488     for (i=0; i < nProfiles; i++) {
489
490         cmsBool  lIsDeviceLink, lIsInput;
491
492         hProfile      = hProfiles[i];
493         ClassSig      = cmsGetDeviceClass(hProfile);
494         lIsDeviceLink = (ClassSig == cmsSigLinkClass || ClassSig == cmsSigAbstractClass );
495
496         // First profile is used as input unless devicelink or abstract
497         if ((i == 0) && !lIsDeviceLink) {
498             lIsInput = TRUE;
499         }
500         else {
501           // Else use profile in the input direction if current space is not PCS
502         lIsInput      = (CurrentColorSpace != cmsSigXYZData) &&
503                         (CurrentColorSpace != cmsSigLabData);
504         }
505
506         Intent        = TheIntents[i];
507
508         if (lIsInput || lIsDeviceLink) {
509
510             ColorSpaceIn    = cmsGetColorSpace(hProfile);
511             ColorSpaceOut   = cmsGetPCS(hProfile);
512         }
513         else {
514
515             ColorSpaceIn    = cmsGetPCS(hProfile);
516             ColorSpaceOut   = cmsGetColorSpace(hProfile);
517         }
518
519         if (!ColorSpaceIsCompatible(ColorSpaceIn, CurrentColorSpace)) {
520
521             cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "ColorSpace mismatch");
522             goto Error;
523         }
524
525         // If devicelink is found, then no custom intent is allowed and we can
526         // read the LUT to be applied. Settings don't apply here.
527         if (lIsDeviceLink || ((ClassSig == cmsSigNamedColorClass) && (nProfiles == 1))) {
528
529             // Get the involved LUT from the profile
530             Lut = _cmsReadDevicelinkLUT(hProfile, Intent);
531             if (Lut == NULL) goto Error;
532
533             // What about abstract profiles?
534              if (ClassSig == cmsSigAbstractClass && i > 0) {
535                 if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
536              }
537              else {
538                 _cmsMAT3identity(&m);
539                 _cmsVEC3init(&off, 0, 0, 0);
540              }
541
542
543             if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
544
545         }
546         else {
547
548             if (lIsInput) {
549                 // Input direction means non-pcs connection, so proceed like devicelinks
550                 Lut = _cmsReadInputLUT(hProfile, Intent);
551                 if (Lut == NULL) goto Error;
552             }
553             else {
554
555                 // Output direction means PCS connection. Intent may apply here
556                 Lut = _cmsReadOutputLUT(hProfile, Intent);
557                 if (Lut == NULL) goto Error;
558
559
560                 if (!ComputeConversion(i, hProfiles, Intent, BPC[i], AdaptationStates[i], &m, &off)) goto Error;
561                 if (!AddConversion(Result, CurrentColorSpace, ColorSpaceIn, &m, &off)) goto Error;
562
563             }
564         }
565
566         // Concatenate to the output LUT
567         cmsPipelineCat(Result, Lut);
568         cmsPipelineFree(Lut);
569
570         // Update current space
571         CurrentColorSpace = ColorSpaceOut;
572     }
573
574     return Result;
575
576 Error:
577
578     if (Result != NULL) cmsPipelineFree(Result);
579     return NULL;
580
581     cmsUNUSED_PARAMETER(dwFlags);
582 }
583
584
585 // Wrapper for DLL calling convention
586 cmsPipeline*  CMSEXPORT _cmsDefaultICCintents(cmsContext     ContextID,
587                                               cmsUInt32Number nProfiles,
588                                               cmsUInt32Number TheIntents[],
589                                               cmsHPROFILE     hProfiles[],
590                                               cmsBool         BPC[],
591                                               cmsFloat64Number AdaptationStates[],
592                                               cmsUInt32Number dwFlags)
593 {
594     return DefaultICCintents(ContextID, nProfiles, TheIntents, hProfiles, BPC, AdaptationStates, dwFlags);
595 }
596
597 // Black preserving intents ---------------------------------------------------------------------------------------------
598
599 // Translate black-preserving intents to ICC ones
600 static
601 int TranslateNonICCIntents(int Intent)
602 {
603     switch (Intent) {
604         case INTENT_PRESERVE_K_ONLY_PERCEPTUAL:
605         case INTENT_PRESERVE_K_PLANE_PERCEPTUAL:
606             return INTENT_PERCEPTUAL;
607
608         case INTENT_PRESERVE_K_ONLY_RELATIVE_COLORIMETRIC:
609         case INTENT_PRESERVE_K_PLANE_RELATIVE_COLORIMETRIC:
610             return INTENT_RELATIVE_COLORIMETRIC;
611
612         case INTENT_PRESERVE_K_ONLY_SATURATION:
613         case INTENT_PRESERVE_K_PLANE_SATURATION:
614             return INTENT_SATURATION;
615
616         default: return Intent;
617     }
618 }
619
620 // Sampler for Black-only preserving CMYK->CMYK transforms
621
622 typedef struct {
623     cmsPipeline*    cmyk2cmyk;      // The original transform
624     cmsToneCurve*   KTone;          // Black-to-black tone curve
625
626 } GrayOnlyParams;
627
628
629 // Preserve black only if that is the only ink used
630 static
631 int BlackPreservingGrayOnlySampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
632 {
633     GrayOnlyParams* bp = (GrayOnlyParams*) Cargo;
634
635     // If going across black only, keep black only
636     if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
637
638         // TAC does not apply because it is black ink!
639         Out[0] = Out[1] = Out[2] = 0;
640         Out[3] = cmsEvalToneCurve16(bp->KTone, In[3]);
641         return TRUE;
642     }
643
644     // Keep normal transform for other colors
645     bp ->cmyk2cmyk ->Eval16Fn(In, Out, bp ->cmyk2cmyk->Data);
646     return TRUE;
647 }
648
649 // This is the entry for black-preserving K-only intents, which are non-ICC
650 static
651 cmsPipeline*  BlackPreservingKOnlyIntents(cmsContext     ContextID,
652                                           cmsUInt32Number nProfiles,
653                                           cmsUInt32Number TheIntents[],
654                                           cmsHPROFILE     hProfiles[],
655                                           cmsBool         BPC[],
656                                           cmsFloat64Number AdaptationStates[],
657                                           cmsUInt32Number dwFlags)
658 {
659     GrayOnlyParams  bp;
660     cmsPipeline*    Result;
661     cmsUInt32Number ICCIntents[256];
662     cmsStage*         CLUT;
663     cmsUInt32Number i, nGridPoints;
664
665
666     // Sanity check
667     if (nProfiles < 1 || nProfiles > 255) return NULL;
668
669     // Translate black-preserving intents to ICC ones
670     for (i=0; i < nProfiles; i++)
671         ICCIntents[i] = TranslateNonICCIntents(TheIntents[i]);
672
673     // Check for non-cmyk profiles
674     if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
675         cmsGetColorSpace(hProfiles[nProfiles-1]) != cmsSigCmykData)
676            return DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
677
678     memset(&bp, 0, sizeof(bp));
679
680     // Allocate an empty LUT for holding the result
681     Result = cmsPipelineAlloc(ContextID, 4, 4);
682     if (Result == NULL) return NULL;
683
684     // Create a LUT holding normal ICC transform
685     bp.cmyk2cmyk = DefaultICCintents(ContextID,
686         nProfiles,
687         ICCIntents,
688         hProfiles,
689         BPC,
690         AdaptationStates,
691         dwFlags);
692
693     if (bp.cmyk2cmyk == NULL) goto Error;
694
695     // Now, compute the tone curve
696     bp.KTone = _cmsBuildKToneCurve(ContextID,
697         4096,
698         nProfiles,
699         ICCIntents,
700         hProfiles,
701         BPC,
702         AdaptationStates,
703         dwFlags);
704
705     if (bp.KTone == NULL) goto Error;
706
707
708     // How many gridpoints are we going to use?
709     nGridPoints = _cmsReasonableGridpointsByColorspace(cmsSigCmykData, dwFlags);
710
711     // Create the CLUT. 16 bits
712     CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
713     if (CLUT == NULL) goto Error;
714
715     // This is the one and only MPE in this LUT
716     cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT);
717
718     // Sample it. We cannot afford pre/post linearization this time.
719     if (!cmsStageSampleCLut16bit(CLUT, BlackPreservingGrayOnlySampler, (void*) &bp, 0))
720         goto Error;
721
722     // Get rid of xform and tone curve
723     cmsPipelineFree(bp.cmyk2cmyk);
724     cmsFreeToneCurve(bp.KTone);
725
726     return Result;
727
728 Error:
729
730     if (bp.cmyk2cmyk != NULL) cmsPipelineFree(bp.cmyk2cmyk);
731     if (bp.KTone != NULL)  cmsFreeToneCurve(bp.KTone);
732     if (Result != NULL) cmsPipelineFree(Result);
733     return NULL;
734
735 }
736
737 // K Plane-preserving CMYK to CMYK ------------------------------------------------------------------------------------
738
739 typedef struct {
740
741     cmsPipeline*     cmyk2cmyk;     // The original transform
742     cmsHTRANSFORM    hProofOutput;  // Output CMYK to Lab (last profile)
743     cmsHTRANSFORM    cmyk2Lab;      // The input chain
744     cmsToneCurve*    KTone;         // Black-to-black tone curve
745     cmsPipeline*     LabK2cmyk;     // The output profile
746     cmsFloat64Number MaxError;
747
748     cmsHTRANSFORM    hRoundTrip;
749     cmsFloat64Number MaxTAC;
750
751
752 } PreserveKPlaneParams;
753
754
755 // The CLUT will be stored at 16 bits, but calculations are performed at cmsFloat32Number precision
756 static
757 int BlackPreservingSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
758 {
759     int i;
760     cmsFloat32Number Inf[4], Outf[4];
761     cmsFloat32Number LabK[4];
762     cmsFloat64Number SumCMY, SumCMYK, Error, Ratio;
763     cmsCIELab ColorimetricLab, BlackPreservingLab;
764     PreserveKPlaneParams* bp = (PreserveKPlaneParams*) Cargo;
765
766     // Convert from 16 bits to floating point
767     for (i=0; i < 4; i++)
768         Inf[i] = (cmsFloat32Number) (In[i] / 65535.0);
769
770     // Get the K across Tone curve
771     LabK[3] = cmsEvalToneCurveFloat(bp ->KTone, Inf[3]);
772
773     // If going across black only, keep black only
774     if (In[0] == 0 && In[1] == 0 && In[2] == 0) {
775
776         Out[0] = Out[1] = Out[2] = 0;
777         Out[3] = _cmsQuickSaturateWord(LabK[3] * 65535.0);
778         return TRUE;
779     }
780
781     // Try the original transform,
782     cmsPipelineEvalFloat( Inf, Outf, bp ->cmyk2cmyk);
783
784     // Store a copy of the floating point result into 16-bit
785     for (i=0; i < 4; i++)
786             Out[i] = _cmsQuickSaturateWord(Outf[i] * 65535.0);
787
788     // Maybe K is already ok (mostly on K=0)
789     if ( fabs(Outf[3] - LabK[3]) < (3.0 / 65535.0) ) {
790         return TRUE;
791     }
792
793     // K differ, mesure and keep Lab measurement for further usage
794     // this is done in relative colorimetric intent
795     cmsDoTransform(bp->hProofOutput, Out, &ColorimetricLab, 1);
796
797     // Is not black only and the transform doesn't keep black.
798     // Obtain the Lab of output CMYK. After that we have Lab + K
799     cmsDoTransform(bp ->cmyk2Lab, Outf, LabK, 1);
800
801     // Obtain the corresponding CMY using reverse interpolation
802     // (K is fixed in LabK[3])
803     if (!cmsPipelineEvalReverseFloat(LabK, Outf, Outf, bp ->LabK2cmyk)) {
804
805         // Cannot find a suitable value, so use colorimetric xform
806         // which is already stored in Out[]
807         return TRUE;
808     }
809
810     // Make sure to pass thru K (which now is fixed)
811     Outf[3] = LabK[3];
812
813     // Apply TAC if needed
814     SumCMY   = Outf[0]  + Outf[1] + Outf[2];
815     SumCMYK  = SumCMY + Outf[3];
816
817     if (SumCMYK > bp ->MaxTAC) {
818
819         Ratio = 1 - ((SumCMYK - bp->MaxTAC) / SumCMY);
820         if (Ratio < 0)
821             Ratio = 0;
822     }
823     else
824        Ratio = 1.0;
825
826     Out[0] = _cmsQuickSaturateWord(Outf[0] * Ratio * 65535.0);     // C
827     Out[1] = _cmsQuickSaturateWord(Outf[1] * Ratio * 65535.0);     // M
828     Out[2] = _cmsQuickSaturateWord(Outf[2] * Ratio * 65535.0);     // Y
829     Out[3] = _cmsQuickSaturateWord(Outf[3] * 65535.0);
830
831     // Estimate the error (this goes 16 bits to Lab DBL)
832     cmsDoTransform(bp->hProofOutput, Out, &BlackPreservingLab, 1);
833     Error = cmsDeltaE(&ColorimetricLab, &BlackPreservingLab);
834     if (Error > bp -> MaxError)
835         bp->MaxError = Error;
836
837     return TRUE;
838 }
839
840 // This is the entry for black-plane preserving, which are non-ICC
841 static
842 cmsPipeline* BlackPreservingKPlaneIntents(cmsContext     ContextID,
843                                           cmsUInt32Number nProfiles,
844                                           cmsUInt32Number TheIntents[],
845                                           cmsHPROFILE     hProfiles[],
846                                           cmsBool         BPC[],
847                                           cmsFloat64Number AdaptationStates[],
848                                           cmsUInt32Number dwFlags)
849 {
850     PreserveKPlaneParams bp;
851     cmsPipeline*    Result = NULL;
852     cmsUInt32Number ICCIntents[256];
853     cmsStage*         CLUT;
854     cmsUInt32Number i, nGridPoints;
855     cmsHPROFILE hLab;
856
857     // Sanity check
858     if (nProfiles < 1 || nProfiles > 255) return NULL;
859
860     // Translate black-preserving intents to ICC ones
861     for (i=0; i < nProfiles; i++)
862         ICCIntents[i] = TranslateNonICCIntents(TheIntents[i]);
863
864     // Check for non-cmyk profiles
865     if (cmsGetColorSpace(hProfiles[0]) != cmsSigCmykData ||
866         !(cmsGetColorSpace(hProfiles[nProfiles-1]) == cmsSigCmykData ||
867         cmsGetDeviceClass(hProfiles[nProfiles-1]) == cmsSigOutputClass))
868            return  DefaultICCintents(ContextID, nProfiles, ICCIntents, hProfiles, BPC, AdaptationStates, dwFlags);
869
870     // Allocate an empty LUT for holding the result
871     Result = cmsPipelineAlloc(ContextID, 4, 4);
872     if (Result == NULL) return NULL;
873
874
875     memset(&bp, 0, sizeof(bp));
876
877     // We need the input LUT of the last profile, assuming this one is responsible of
878     // black generation. This LUT will be seached in inverse order.
879     bp.LabK2cmyk = _cmsReadInputLUT(hProfiles[nProfiles-1], INTENT_RELATIVE_COLORIMETRIC);
880     if (bp.LabK2cmyk == NULL) goto Cleanup;
881
882     // Get total area coverage (in 0..1 domain)
883     bp.MaxTAC = cmsDetectTAC(hProfiles[nProfiles-1]) / 100.0;
884     if (bp.MaxTAC <= 0) goto Cleanup;
885
886
887     // Create a LUT holding normal ICC transform
888     bp.cmyk2cmyk = DefaultICCintents(ContextID,
889                                          nProfiles,
890                                          ICCIntents,
891                                          hProfiles,
892                                          BPC,
893                                          AdaptationStates,
894                                          dwFlags);
895     if (bp.cmyk2cmyk == NULL) goto Cleanup;
896
897     // Now the tone curve
898     bp.KTone = _cmsBuildKToneCurve(ContextID, 4096, nProfiles,
899                                    ICCIntents,
900                                    hProfiles,
901                                    BPC,
902                                    AdaptationStates,
903                                    dwFlags);
904     if (bp.KTone == NULL) goto Cleanup;
905
906     // To measure the output, Last profile to Lab
907     hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
908     bp.hProofOutput = cmsCreateTransformTHR(ContextID, hProfiles[nProfiles-1],
909                                          CHANNELS_SH(4)|BYTES_SH(2), hLab, TYPE_Lab_DBL,
910                                          INTENT_RELATIVE_COLORIMETRIC,
911                                          cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
912     if ( bp.hProofOutput == NULL) goto Cleanup;
913
914     // Same as anterior, but lab in the 0..1 range
915     bp.cmyk2Lab = cmsCreateTransformTHR(ContextID, hProfiles[nProfiles-1],
916                                          FLOAT_SH(1)|CHANNELS_SH(4)|BYTES_SH(4), hLab,
917                                          FLOAT_SH(1)|CHANNELS_SH(3)|BYTES_SH(4),
918                                          INTENT_RELATIVE_COLORIMETRIC,
919                                          cmsFLAGS_NOCACHE|cmsFLAGS_NOOPTIMIZE);
920     if (bp.cmyk2Lab == NULL) goto Cleanup;
921     cmsCloseProfile(hLab);
922
923     // Error estimation (for debug only)
924     bp.MaxError = 0;
925
926     // How many gridpoints are we going to use?
927     nGridPoints = _cmsReasonableGridpointsByColorspace(cmsSigCmykData, dwFlags);
928
929
930     CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
931     if (CLUT == NULL) goto Cleanup;
932
933     cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT);
934
935     cmsStageSampleCLut16bit(CLUT, BlackPreservingSampler, (void*) &bp, 0);
936
937 Cleanup:
938
939     if (bp.cmyk2cmyk) cmsPipelineFree(bp.cmyk2cmyk);
940     if (bp.cmyk2Lab) cmsDeleteTransform(bp.cmyk2Lab);
941     if (bp.hProofOutput) cmsDeleteTransform(bp.hProofOutput);
942
943     if (bp.KTone) cmsFreeToneCurve(bp.KTone);
944     if (bp.LabK2cmyk) cmsPipelineFree(bp.LabK2cmyk);
945
946     return Result;
947 }
948
949 // Link routines ------------------------------------------------------------------------------------------------------
950
951 // Chain several profiles into a single LUT. It just checks the parameters and then calls the handler
952 // for the first intent in chain. The handler may be user-defined. Is up to the handler to deal with the
953 // rest of intents in chain. A maximum of 255 profiles at time are supported, which is pretty reasonable.
954 cmsPipeline* _cmsLinkProfiles(cmsContext     ContextID,
955                               cmsUInt32Number nProfiles,
956                               cmsUInt32Number TheIntents[],
957                               cmsHPROFILE     hProfiles[],
958                               cmsBool         BPC[],
959                               cmsFloat64Number AdaptationStates[],
960                               cmsUInt32Number dwFlags)
961 {
962     cmsUInt32Number i;
963     cmsIntentsList* Intent;
964
965     // Make sure a reasonable number of profiles is provided
966     if (nProfiles <= 0 || nProfiles > 255) {
967          cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't link '%d' profiles", nProfiles);
968         return NULL;
969     }
970
971     for (i=0; i < nProfiles; i++) {
972
973         // Check if black point is really needed or allowed. Note that
974         // following Adobe's document:
975         // BPC does not apply to devicelink profiles, nor to abs colorimetric,
976         // and applies always on V4 perceptual and saturation.
977
978         if (TheIntents[i] == INTENT_ABSOLUTE_COLORIMETRIC)
979             BPC[i] = FALSE;
980
981         if (TheIntents[i] == INTENT_PERCEPTUAL || TheIntents[i] == INTENT_SATURATION) {
982
983             // Force BPC for V4 profiles in perceptual and saturation
984             if (cmsGetProfileVersion(hProfiles[i]) >= 4.0)
985                 BPC[i] = TRUE;
986         }
987     }
988
989     // Search for a handler. The first intent in the chain defines the handler. That would
990     // prevent using multiple custom intents in a multiintent chain, but the behaviour of
991     // this case would present some issues if the custom intent tries to do things like
992     // preserve primaries. This solution is not perfect, but works well on most cases.
993
994     Intent = SearchIntent(TheIntents[0]);
995     if (Intent == NULL) {
996         cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Unsupported intent '%d'", TheIntents[0]);
997         return NULL;
998     }
999
1000     // Call the handler
1001     return Intent ->Link(ContextID, nProfiles, TheIntents, hProfiles, BPC, AdaptationStates, dwFlags);
1002 }
1003
1004 // -------------------------------------------------------------------------------------------------
1005
1006 // Get information about available intents. nMax is the maximum space for the supplied "Codes"
1007 // and "Descriptions" the function returns the total number of intents, which may be greater
1008 // than nMax, although the matrices are not populated beyond this level.
1009 cmsUInt32Number CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32Number* Codes, char** Descriptions)
1010 {
1011     cmsIntentsList* pt;
1012     cmsUInt32Number nIntents;
1013
1014     for (nIntents=0, pt = Intents; pt != NULL; pt = pt -> Next)
1015     {
1016         if (nIntents < nMax) {
1017             if (Codes != NULL)
1018                 Codes[nIntents] = pt ->Intent;
1019
1020             if (Descriptions != NULL)
1021                 Descriptions[nIntents] = pt ->Description;
1022         }
1023
1024         nIntents++;
1025     }
1026
1027     return nIntents;
1028 }
1029
1030 // The plug-in registration. User can add new intents or override default routines
1031 cmsBool  _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Data)
1032 {
1033     cmsPluginRenderingIntent* Plugin = (cmsPluginRenderingIntent*) Data;
1034     cmsIntentsList* fl;
1035
1036     // Do we have to reset the intents?
1037     if (Data == NULL) {
1038
1039        Intents = DefaultIntents;
1040        return TRUE;
1041     }
1042
1043     fl = SearchIntent(Plugin ->Intent);
1044
1045     if (fl == NULL) {
1046         fl = (cmsIntentsList*) _cmsPluginMalloc(sizeof(cmsIntentsList));
1047         if (fl == NULL) return FALSE;
1048     }
1049
1050     fl ->Intent  = Plugin ->Intent;
1051     strncpy(fl ->Description, Plugin ->Description, 255);
1052     fl ->Description[255] = 0;
1053
1054     fl ->Link    = Plugin ->Link;
1055
1056     fl ->Next = Intents;
1057     Intents = fl;
1058
1059     return TRUE;
1060 }
1061