Coverage Report

Created: 2026-09-14 06:43

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