1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2010 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 // Read tags using low-level functions, provides necessary glue code to adapt versions, etc.
30 
31 // LUT tags
32 static const cmsTagSignature Device2PCS16[]   =  {cmsSigAToB0Tag,     // Perceptual
33                                                   cmsSigAToB1Tag,     // Relative colorimetric
34                                                   cmsSigAToB2Tag,     // Saturation
35                                                   cmsSigAToB1Tag };   // Absolute colorimetric
36 
37 static const cmsTagSignature Device2PCSFloat[] = {cmsSigDToB0Tag,     // Perceptual
38                                                   cmsSigDToB1Tag,     // Relative colorimetric
39                                                   cmsSigDToB2Tag,     // Saturation
40                                                   cmsSigDToB3Tag };   // Absolute colorimetric
41 
42 static const cmsTagSignature PCS2Device16[]    = {cmsSigBToA0Tag,     // Perceptual
43                                                   cmsSigBToA1Tag,     // Relative colorimetric
44                                                   cmsSigBToA2Tag,     // Saturation
45                                                   cmsSigBToA1Tag };   // Absolute colorimetric
46 
47 static const cmsTagSignature PCS2DeviceFloat[] = {cmsSigBToD0Tag,     // Perceptual
48                                                   cmsSigBToD1Tag,     // Relative colorimetric
49                                                   cmsSigBToD2Tag,     // Saturation
50                                                   cmsSigBToD3Tag };   // Absolute colorimetric
51 
52 
53 // Factors to convert from 1.15 fixed point to 0..1.0 range and vice-versa
54 #define InpAdj   (1.0/MAX_ENCODEABLE_XYZ)     // (65536.0/(65535.0*2.0))
55 #define OutpAdj  (MAX_ENCODEABLE_XYZ)         // ((2.0*65535.0)/65536.0)
56 
57 // Several resources for gray conversions.
58 static const cmsFloat64Number GrayInputMatrix[] = { (InpAdj*cmsD50X),  (InpAdj*cmsD50Y),  (InpAdj*cmsD50Z) };
59 static const cmsFloat64Number OneToThreeInputMatrix[] = { 1, 1, 1 };
60 static const cmsFloat64Number PickYMatrix[] = { 0, (OutpAdj*cmsD50Y), 0 };
61 static const cmsFloat64Number PickLstarMatrix[] = { 1, 0, 0 };
62 
63 // Get a media white point fixing some issues found in certain old profiles
_cmsReadMediaWhitePoint(cmsCIEXYZ * Dest,cmsHPROFILE hProfile)64 cmsBool  _cmsReadMediaWhitePoint(cmsCIEXYZ* Dest, cmsHPROFILE hProfile)
65 {
66     cmsCIEXYZ* Tag;
67 
68     _cmsAssert(Dest != NULL);
69 
70     Tag = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
71 
72     // If no wp, take D50
73     if (Tag == NULL) {
74         *Dest = *cmsD50_XYZ();
75         return TRUE;
76     }
77 
78     // V2 display profiles should give D50
79     if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
80 
81         if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
82             *Dest = *cmsD50_XYZ();
83             return TRUE;
84         }
85     }
86 
87     // All seems ok
88     *Dest = *Tag;
89     return TRUE;
90 }
91 
92 
93 // Chromatic adaptation matrix. Fix some issues as well
_cmsReadCHAD(cmsMAT3 * Dest,cmsHPROFILE hProfile)94 cmsBool  _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile)
95 {
96     cmsMAT3* Tag;
97 
98     _cmsAssert(Dest != NULL);
99 
100     Tag = (cmsMAT3*) cmsReadTag(hProfile, cmsSigChromaticAdaptationTag);
101 
102     if (Tag != NULL) {
103 
104         *Dest = *Tag;
105         return TRUE;
106     }
107 
108     // No CHAD available, default it to identity
109     _cmsMAT3identity(Dest);
110 
111     // V2 display profiles should give D50
112     if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
113 
114         if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
115 
116             cmsCIEXYZ* White = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
117 
118             if (White == NULL) {
119 
120                 _cmsMAT3identity(Dest);
121                 return TRUE;
122             }
123 
124             return _cmsAdaptationMatrix(Dest, NULL, cmsD50_XYZ(), White);
125         }
126     }
127 
128     return TRUE;
129 }
130 
131 
132 // Auxiliar, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
133 static
ReadICCMatrixRGB2XYZ(cmsMAT3 * r,cmsHPROFILE hProfile)134 cmsBool ReadICCMatrixRGB2XYZ(cmsMAT3* r, cmsHPROFILE hProfile)
135 {
136     cmsCIEXYZ *PtrRed, *PtrGreen, *PtrBlue;
137 
138     _cmsAssert(r != NULL);
139 
140     PtrRed   = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigRedColorantTag);
141     PtrGreen = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigGreenColorantTag);
142     PtrBlue  = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigBlueColorantTag);
143 
144     if (PtrRed == NULL || PtrGreen == NULL || PtrBlue == NULL)
145         return FALSE;
146 
147     _cmsVEC3init(&r -> v[0], PtrRed -> X, PtrGreen -> X,  PtrBlue -> X);
148     _cmsVEC3init(&r -> v[1], PtrRed -> Y, PtrGreen -> Y,  PtrBlue -> Y);
149     _cmsVEC3init(&r -> v[2], PtrRed -> Z, PtrGreen -> Z,  PtrBlue -> Z);
150 
151     return TRUE;
152 }
153 
154 
155 // Gray input pipeline
156 static
BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)157 cmsPipeline* BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)
158 {
159     cmsToneCurve *GrayTRC;
160     cmsPipeline* Lut;
161     cmsContext ContextID = cmsGetProfileContextID(hProfile);
162 
163     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
164     if (GrayTRC == NULL) return NULL;
165 
166     Lut = cmsPipelineAlloc(ContextID, 1, 3);
167     if (Lut == NULL) return NULL;
168 
169     if (cmsGetPCS(hProfile) == cmsSigLabData) {
170 
171         // In this case we implement the profile as an  identity matrix plus 3 tone curves
172         cmsUInt16Number Zero[2] = { 0x8080, 0x8080 };
173         cmsToneCurve* EmptyTab;
174         cmsToneCurve* LabCurves[3];
175 
176         EmptyTab = cmsBuildTabulatedToneCurve16(ContextID, 2, Zero);
177 
178         if (EmptyTab == NULL) {
179 
180                  cmsPipelineFree(Lut);
181                  return NULL;
182         }
183 
184         LabCurves[0] = GrayTRC;
185         LabCurves[1] = EmptyTab;
186         LabCurves[2] = EmptyTab;
187 
188         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, OneToThreeInputMatrix, NULL));
189         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, LabCurves));
190 
191         cmsFreeToneCurve(EmptyTab);
192 
193     }
194     else  {
195        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &GrayTRC));
196        cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, GrayInputMatrix, NULL));
197     }
198 
199     return Lut;
200 }
201 
202 // RGB Matrix shaper
203 static
BuildRGBInputMatrixShaper(cmsHPROFILE hProfile)204 cmsPipeline* BuildRGBInputMatrixShaper(cmsHPROFILE hProfile)
205 {
206     cmsPipeline* Lut;
207     cmsMAT3 Mat;
208     cmsToneCurve *Shapes[3];
209     cmsContext ContextID = cmsGetProfileContextID(hProfile);
210     int i, j;
211 
212     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile)) return NULL;
213 
214     // XYZ PCS in encoded in 1.15 format, and the matrix output comes in 0..0xffff range, so
215     // we need to adjust the output by a factor of (0x10000/0xffff) to put data in
216     // a 1.16 range, and then a >> 1 to obtain 1.15. The total factor is (65536.0)/(65535.0*2)
217 
218     for (i=0; i < 3; i++)
219         for (j=0; j < 3; j++)
220             Mat.v[i].n[j] *= InpAdj;
221 
222 
223     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
224     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
225     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
226 
227     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
228         return NULL;
229 
230     Lut = cmsPipelineAlloc(ContextID, 3, 3);
231     if (Lut != NULL) {
232 
233         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, Shapes));
234         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL));
235     }
236 
237     return Lut;
238 }
239 
240 // Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc
241 // is adjusted here in order to create a LUT that takes care of all those details
_cmsReadInputLUT(cmsHPROFILE hProfile,int Intent)242 cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
243 {
244     cmsTagTypeSignature OriginalType;
245     cmsTagSignature tag16    = Device2PCS16[Intent];
246     cmsTagSignature tagFloat = Device2PCSFloat[Intent];
247     cmsContext ContextID = cmsGetProfileContextID(hProfile);
248 
249     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
250 
251         // Floating point LUT are always V4, so no adjustment is required
252         return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
253     }
254 
255     // Revert to perceptual if no tag is found
256     if (!cmsIsTag(hProfile, tag16)) {
257         tag16 = Device2PCS16[0];
258     }
259 
260     if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
261 
262         // Check profile version and LUT type. Do the necessary adjustments if needed
263 
264         // First read the tag
265         cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
266         if (Lut == NULL) return NULL;
267 
268         // After reading it, we have now info about the original type
269         OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
270 
271         // The profile owns the Lut, so we need to copy it
272         Lut = cmsPipelineDup(Lut);
273 
274         // We need to adjust data only for Lab16 on output
275         if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
276             return Lut;
277 
278         // Add a matrix for conversion V2 to V4 Lab PCS
279         cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
280         return Lut;
281     }
282 
283     // Lut was not found, try to create a matrix-shaper
284 
285     // Check if this is a grayscale profile.
286     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
287 
288         // if so, build appropiate conversion tables.
289         // The tables are the PCS iluminant, scaled across GrayTRC
290         return BuildGrayInputMatrixPipeline(hProfile);
291     }
292 
293     // Not gray, create a normal matrix-shaper
294     return BuildRGBInputMatrixShaper(hProfile);
295 }
296 
297 // ---------------------------------------------------------------------------------------------------------------
298 
299 // Gray output pipeline.
300 // XYZ -> Gray or Lab -> Gray. Since we only know the GrayTRC, we need to do some assumptions. Gray component will be
301 // given by Y on XYZ PCS and by L* on Lab PCS, Both across inverse TRC curve.
302 // The complete pipeline on XYZ is Matrix[3:1] -> Tone curve and in Lab Matrix[3:1] -> Tone Curve as well.
303 
304 static
BuildGrayOutputPipeline(cmsHPROFILE hProfile)305 cmsPipeline* BuildGrayOutputPipeline(cmsHPROFILE hProfile)
306 {
307     cmsToneCurve *GrayTRC, *RevGrayTRC;
308     cmsPipeline* Lut;
309     cmsContext ContextID = cmsGetProfileContextID(hProfile);
310 
311     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
312     if (GrayTRC == NULL) return NULL;
313 
314     RevGrayTRC = cmsReverseToneCurve(GrayTRC);
315     if (RevGrayTRC == NULL) return NULL;
316 
317     Lut = cmsPipelineAlloc(ContextID, 3, 1);
318     if (Lut == NULL) {
319         cmsFreeToneCurve(RevGrayTRC);
320         return NULL;
321     }
322 
323     if (cmsGetPCS(hProfile) == cmsSigLabData) {
324 
325         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickLstarMatrix, NULL));
326     }
327     else  {
328         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickYMatrix, NULL));
329     }
330 
331     cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC));
332     cmsFreeToneCurve(RevGrayTRC);
333 
334     return Lut;
335 }
336 
337 
338 
339 
340 static
BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)341 cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
342 {
343     cmsPipeline* Lut;
344     cmsToneCurve *Shapes[3], *InvShapes[3];
345     cmsMAT3 Mat, Inv;
346     int i, j;
347     cmsContext ContextID = cmsGetProfileContextID(hProfile);
348 
349     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile))
350         return NULL;
351 
352     if (!_cmsMAT3inverse(&Mat, &Inv))
353         return NULL;
354 
355     // XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so
356     // we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of
357     // (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0;
358 
359     for (i=0; i < 3; i++)
360         for (j=0; j < 3; j++)
361             Inv.v[i].n[j] *= OutpAdj;
362 
363     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
364     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
365     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
366 
367     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
368         return NULL;
369 
370     InvShapes[0] = cmsReverseToneCurve(Shapes[0]);
371     InvShapes[1] = cmsReverseToneCurve(Shapes[1]);
372     InvShapes[2] = cmsReverseToneCurve(Shapes[2]);
373 
374     if (!InvShapes[0] || !InvShapes[1] || !InvShapes[2]) {
375         return NULL;
376     }
377 
378     Lut = cmsPipelineAlloc(ContextID, 3, 3);
379     if (Lut != NULL) {
380 
381         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL));
382         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes));
383     }
384 
385     cmsFreeToneCurveTriple(InvShapes);
386     return Lut;
387 }
388 
389 
390 // Change CLUT interpolation to trilinear
391 static
ChangeInterpolationToTrilinear(cmsPipeline * Lut)392 void ChangeInterpolationToTrilinear(cmsPipeline* Lut)
393 {
394     cmsStage* Stage;
395 
396     for (Stage = cmsPipelineGetPtrToFirstStage(Lut);
397         Stage != NULL;
398         Stage = cmsStageNext(Stage)) {
399 
400             if (cmsStageType(Stage) == cmsSigCLutElemType) {
401 
402                 _cmsStageCLutData* CLUT = (_cmsStageCLutData*) Stage ->Data;
403 
404                 CLUT ->Params->dwFlags |= CMS_LERP_FLAGS_TRILINEAR;
405                 _cmsSetInterpolationRoutine(CLUT ->Params);
406             }
407     }
408 }
409 
410 // Create an output MPE LUT from agiven profile. Version mismatches are handled here
_cmsReadOutputLUT(cmsHPROFILE hProfile,int Intent)411 cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent)
412 {
413     cmsTagTypeSignature OriginalType;
414     cmsTagSignature tag16    = PCS2Device16[Intent];
415     cmsTagSignature tagFloat = PCS2DeviceFloat[Intent];
416     cmsContext ContextID     = cmsGetProfileContextID(hProfile);
417 
418     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
419 
420         // Floating point LUT are always V4, so no adjustment is required
421         return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
422     }
423 
424     // Revert to perceptual if no tag is found
425     if (!cmsIsTag(hProfile, tag16)) {
426         tag16 = PCS2Device16[0];
427     }
428 
429     if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
430 
431         // Check profile version and LUT type. Do the necessary adjustments if needed
432 
433         // First read the tag
434         cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
435         if (Lut == NULL) return NULL;
436 
437         // After reading it, we have info about the original type
438         OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
439 
440         // The profile owns the Lut, so we need to copy it
441         Lut = cmsPipelineDup(Lut);
442         if (Lut == NULL) return NULL;
443 
444         // Now it is time for a controversial stuff. I found that for 3D LUTS using
445         // Lab used as indexer space,  trilinear interpolation should be used
446         if (cmsGetPCS(hProfile) == cmsSigLabData)
447                              ChangeInterpolationToTrilinear(Lut);
448 
449         // We need to adjust data only for Lab and Lut16 type
450         if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
451             return Lut;
452 
453         // Add a matrix for conversion V4 to V2 Lab PCS
454         cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
455         return Lut;
456     }
457 
458     // Lut not found, try to create a matrix-shaper
459 
460     // Check if this is a grayscale profile.
461      if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
462 
463               // if so, build appropiate conversion tables.
464               // The tables are the PCS iluminant, scaled across GrayTRC
465               return BuildGrayOutputPipeline(hProfile);
466     }
467 
468     // Not gray, create a normal matrix-shaper
469     return BuildRGBOutputMatrixShaper(hProfile);
470 }
471 
472 // ---------------------------------------------------------------------------------------------------------------
473 
474 // This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The
475 // tag name here may default to AToB0
_cmsReadDevicelinkLUT(cmsHPROFILE hProfile,int Intent)476 cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
477 {
478     cmsPipeline* Lut;
479     cmsTagTypeSignature OriginalType;
480     cmsTagSignature tag16    = Device2PCS16[Intent];
481     cmsTagSignature tagFloat = Device2PCSFloat[Intent];
482     cmsContext ContextID = cmsGetProfileContextID(hProfile);
483 
484     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
485 
486         // Floating point LUT are always V4, no adjustment is required
487         return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
488     }
489 
490     tagFloat = Device2PCSFloat[0];
491     if (cmsIsTag(hProfile, tagFloat)) {
492 
493         return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
494     }
495 
496     if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
497 
498         tag16    = Device2PCS16[0];
499         if (!cmsIsTag(hProfile, tag16)) return NULL;
500     }
501 
502     // Check profile version and LUT type. Do the necessary adjustments if needed
503 
504     // Read the tag
505     Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
506     if (Lut == NULL) return NULL;
507 
508     // The profile owns the Lut, so we need to copy it
509     Lut = cmsPipelineDup(Lut);
510     if (Lut == NULL) return NULL;
511 
512      // Now it is time for a controversial stuff. I found that for 3D LUTS using
513      // Lab used as indexer space,  trilinear interpolation should be used
514     if (cmsGetColorSpace(hProfile) == cmsSigLabData)
515                         ChangeInterpolationToTrilinear(Lut);
516 
517     // After reading it, we have info about the original type
518     OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
519 
520     // We need to adjust data for Lab16 on output
521     if (OriginalType != cmsSigLut16Type) return Lut;
522 
523     // Here it is possible to get Lab on both sides
524 
525     if (cmsGetPCS(hProfile) == cmsSigLabData) {
526             cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
527     }
528 
529     if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
530             cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
531     }
532 
533     return Lut;
534 
535 
536 }
537 
538 // ---------------------------------------------------------------------------------------------------------------
539 
540 // Returns TRUE if the profile is implemented as matrix-shaper
cmsIsMatrixShaper(cmsHPROFILE hProfile)541 cmsBool  CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile)
542 {
543     switch (cmsGetColorSpace(hProfile)) {
544 
545     case cmsSigGrayData:
546 
547         return cmsIsTag(hProfile, cmsSigGrayTRCTag);
548 
549     case cmsSigRgbData:
550 
551         return (cmsIsTag(hProfile, cmsSigRedColorantTag) &&
552                 cmsIsTag(hProfile, cmsSigGreenColorantTag) &&
553                 cmsIsTag(hProfile, cmsSigBlueColorantTag) &&
554                 cmsIsTag(hProfile, cmsSigRedTRCTag) &&
555                 cmsIsTag(hProfile, cmsSigGreenTRCTag) &&
556                 cmsIsTag(hProfile, cmsSigBlueTRCTag));
557 
558     default:
559 
560         return FALSE;
561     }
562 }
563 
564 // Returns TRUE if the intent is implemented as CLUT
cmsIsCLUT(cmsHPROFILE hProfile,cmsUInt32Number Intent,cmsUInt32Number UsedDirection)565 cmsBool  CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
566 {
567     const cmsTagSignature* TagTable;
568 
569     // For devicelinks, the supported intent is that one stated in the header
570     if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
571             return (cmsGetHeaderRenderingIntent(hProfile) == Intent);
572     }
573 
574     switch (UsedDirection) {
575 
576        case LCMS_USED_AS_INPUT: TagTable = Device2PCS16; break;
577        case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device16; break;
578 
579        // For proofing, we need rel. colorimetric in output. Let's do some recursion
580        case LCMS_USED_AS_PROOF:
581            return cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_INPUT) &&
582                   cmsIsIntentSupported(hProfile, INTENT_RELATIVE_COLORIMETRIC, LCMS_USED_AS_OUTPUT);
583 
584        default:
585            cmsSignalError(cmsGetProfileContextID(hProfile), cmsERROR_RANGE, "Unexpected direction (%d)", UsedDirection);
586            return FALSE;
587     }
588 
589     return cmsIsTag(hProfile, TagTable[Intent]);
590 
591 }
592 
593 
594 // Return info about supported intents
cmsIsIntentSupported(cmsHPROFILE hProfile,cmsUInt32Number Intent,cmsUInt32Number UsedDirection)595 cmsBool  CMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
596                                         cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
597 {
598 
599     if (cmsIsCLUT(hProfile, Intent, UsedDirection)) return TRUE;
600 
601     // Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper
602     // does not fully support relative colorimetric because they cannot deal with non-zero black points, but
603     // many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter
604     // the accuracy would be less than optimal in rel.col and v2 case.
605 
606     return cmsIsMatrixShaper(hProfile);
607 }
608 
609 
610 // ---------------------------------------------------------------------------------------------------------------
611 
612 // Read both, profile sequence description and profile sequence id if present. Then combine both to
613 // create qa unique structure holding both. Shame on ICC to store things in such complicated way.
614 
_cmsReadProfileSequence(cmsHPROFILE hProfile)615 cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile)
616 {
617     cmsSEQ* ProfileSeq;
618     cmsSEQ* ProfileId;
619     cmsSEQ* NewSeq;
620     cmsUInt32Number i;
621 
622     // Take profile sequence description first
623     ProfileSeq = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceDescTag);
624 
625     // Take profile sequence ID
626     ProfileId  = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceIdTag);
627 
628     if (ProfileSeq == NULL && ProfileId == NULL) return NULL;
629 
630     if (ProfileSeq == NULL) return cmsDupProfileSequenceDescription(ProfileId);
631     if (ProfileId  == NULL) return cmsDupProfileSequenceDescription(ProfileSeq);
632 
633     // We have to mix both together. For that they must agree
634     if (ProfileSeq ->n != ProfileId ->n) return cmsDupProfileSequenceDescription(ProfileSeq);
635 
636     NewSeq = cmsDupProfileSequenceDescription(ProfileSeq);
637 
638     // Ok, proceed to the mixing
639     for (i=0; i < ProfileSeq ->n; i++) {
640 
641         memmove(&NewSeq ->seq[i].ProfileID, &ProfileId ->seq[i].ProfileID, sizeof(cmsProfileID));
642         NewSeq ->seq[i].Description = cmsMLUdup(ProfileId ->seq[i].Description);
643     }
644 
645     return NewSeq;
646 }
647 
648 // Dump the contents of profile sequence in both tags (if v4 available)
_cmsWriteProfileSequence(cmsHPROFILE hProfile,const cmsSEQ * seq)649 cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq)
650 {
651     if (!cmsWriteTag(hProfile, cmsSigProfileSequenceDescTag, seq)) return FALSE;
652 
653     if (cmsGetProfileVersion(hProfile) >= 4.0) {
654 
655             if (!cmsWriteTag(hProfile, cmsSigProfileSequenceIdTag, seq)) return FALSE;
656     }
657 
658     return TRUE;
659 }
660 
661 
662 // Auxiliar, read and duplicate a MLU if found.
663 static
GetMLUFromProfile(cmsHPROFILE h,cmsTagSignature sig)664 cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
665 {
666     cmsMLU* mlu = (cmsMLU*) cmsReadTag(h, sig);
667     if (mlu == NULL) return NULL;
668 
669     return cmsMLUdup(mlu);
670 }
671 
672 // Create a sequence description out of an array of profiles
_cmsCompileProfileSequence(cmsContext ContextID,cmsUInt32Number nProfiles,cmsHPROFILE hProfiles[])673 cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[])
674 {
675     cmsUInt32Number i;
676     cmsSEQ* seq = cmsAllocProfileSequenceDescription(ContextID, nProfiles);
677 
678     if (seq == NULL) return NULL;
679 
680     for (i=0; i < nProfiles; i++) {
681 
682         cmsPSEQDESC* ps = &seq ->seq[i];
683         cmsHPROFILE h = hProfiles[i];
684         cmsTechnologySignature* techpt;
685 
686         cmsGetHeaderAttributes(h, &ps ->attributes);
687         cmsGetHeaderProfileID(h, ps ->ProfileID.ID8);
688         ps ->deviceMfg   = cmsGetHeaderManufacturer(h);
689         ps ->deviceModel = cmsGetHeaderModel(h);
690 
691         techpt = (cmsTechnologySignature*) cmsReadTag(h, cmsSigTechnologyTag);
692         if (techpt == NULL)
693             ps ->technology   =  (cmsTechnologySignature) 0;
694         else
695             ps ->technology   = *techpt;
696 
697         ps ->Manufacturer = GetMLUFromProfile(h,  cmsSigDeviceMfgDescTag);
698         ps ->Model        = GetMLUFromProfile(h,  cmsSigDeviceModelDescTag);
699         ps ->Description  = GetMLUFromProfile(h, cmsSigProfileDescriptionTag);
700 
701     }
702 
703     return seq;
704 }
705 
706 // -------------------------------------------------------------------------------------------------------------------
707 
708 
709 static
GetInfo(cmsHPROFILE hProfile,cmsInfoType Info)710 const cmsMLU* GetInfo(cmsHPROFILE hProfile, cmsInfoType Info)
711 {
712     cmsTagSignature sig;
713 
714     switch (Info) {
715 
716     case cmsInfoDescription:
717         sig = cmsSigProfileDescriptionTag;
718         break;
719 
720     case cmsInfoManufacturer:
721         sig = cmsSigDeviceMfgDescTag;
722         break;
723 
724     case cmsInfoModel:
725         sig = cmsSigDeviceModelDescTag;
726          break;
727 
728     case cmsInfoCopyright:
729         sig = cmsSigCopyrightTag;
730         break;
731 
732     default: return NULL;
733     }
734 
735 
736     return (cmsMLU*) cmsReadTag(hProfile, sig);
737 }
738 
739 
740 
cmsGetProfileInfo(cmsHPROFILE hProfile,cmsInfoType Info,const char LanguageCode[3],const char CountryCode[3],wchar_t * Buffer,cmsUInt32Number BufferSize)741 cmsUInt32Number CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info,
742                                             const char LanguageCode[3], const char CountryCode[3],
743                                             wchar_t* Buffer, cmsUInt32Number BufferSize)
744 {
745     const cmsMLU* mlu = GetInfo(hProfile, Info);
746     if (mlu == NULL) return 0;
747 
748     return cmsMLUgetWide(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
749 }
750 
751 
cmsGetProfileInfoASCII(cmsHPROFILE hProfile,cmsInfoType Info,const char LanguageCode[3],const char CountryCode[3],char * Buffer,cmsUInt32Number BufferSize)752 cmsUInt32Number  CMSEXPORT cmsGetProfileInfoASCII(cmsHPROFILE hProfile, cmsInfoType Info,
753                                                           const char LanguageCode[3], const char CountryCode[3],
754                                                           char* Buffer, cmsUInt32Number BufferSize)
755 {
756     const cmsMLU* mlu = GetInfo(hProfile, Info);
757     if (mlu == NULL) return 0;
758 
759     return cmsMLUgetASCII(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
760 }
761