Tizen 2.0 Release
[external/lcms.git] / src / cmsio1.c
1 //---------------------------------------------------------------------------------
2 //
3 //  Little Color Management System
4 //  Copyright (c) 1998-2011 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
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
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, White, cmsD50_XYZ());
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
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
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
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
241
242 // Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded
243 static
244 cmsPipeline* _cmsReadFloatInputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
245 {
246     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
247     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
248     cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
249
250     if (Lut == NULL) return NULL;
251
252     // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
253     // and since the formatter has already accomodated to 0..1.0, we should undo this change
254     if ( spc == cmsSigLabData)
255     {
256         cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID));
257     }
258     else
259         if (spc == cmsSigXYZData)
260         {
261             cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID));
262         }
263     
264     return Lut;
265 }
266
267
268 // Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc
269 // is adjusted here in order to create a LUT that takes care of all those details
270 cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
271 {
272     cmsTagTypeSignature OriginalType;
273     cmsTagSignature tag16    = Device2PCS16[Intent];
274     cmsTagSignature tagFloat = Device2PCSFloat[Intent];
275     cmsContext ContextID = cmsGetProfileContextID(hProfile);
276
277     // On named color, take the appropiate tag
278     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
279
280         cmsPipeline* Lut; 
281         cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
282
283         if (nc == NULL) return NULL;
284
285         Lut = cmsPipelineAlloc(ContextID, 0, 0);
286         if (Lut == NULL) {
287             cmsFreeNamedColorList(nc);
288             return NULL;
289         }
290
291         cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, TRUE));
292         cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
293         return Lut;
294     }
295
296     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
297
298         // Floating point LUT are always V4, but the encoding range is no 
299         // longer 0..1.0, so we need to add an stage depending on the color space        
300          return _cmsReadFloatInputTag(hProfile, tagFloat);
301     }
302
303     // Revert to perceptual if no tag is found
304     if (!cmsIsTag(hProfile, tag16)) {
305         tag16 = Device2PCS16[0];
306     }
307
308     if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
309
310         // Check profile version and LUT type. Do the necessary adjustments if needed
311
312         // First read the tag
313         cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
314         if (Lut == NULL) return NULL;
315
316         // After reading it, we have now info about the original type
317         OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
318
319         // The profile owns the Lut, so we need to copy it
320         Lut = cmsPipelineDup(Lut);
321
322         // We need to adjust data only for Lab16 on output
323         if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData) 
324             return Lut;
325
326         // If the input is Lab, add also a conversion at the begin
327         if (cmsGetColorSpace(hProfile) == cmsSigLabData)
328             cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
329
330         // Add a matrix for conversion V2 to V4 Lab PCS
331         cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
332         return Lut;
333     }   
334
335     // Lut was not found, try to create a matrix-shaper
336
337     // Check if this is a grayscale profile.
338     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
339
340         // if so, build appropiate conversion tables. 
341         // The tables are the PCS iluminant, scaled across GrayTRC
342         return BuildGrayInputMatrixPipeline(hProfile);              
343     }
344
345     // Not gray, create a normal matrix-shaper 
346     return BuildRGBInputMatrixShaper(hProfile);
347 }
348
349 // ---------------------------------------------------------------------------------------------------------------
350
351 // Gray output pipeline. 
352 // XYZ -> Gray or Lab -> Gray. Since we only know the GrayTRC, we need to do some assumptions. Gray component will be
353 // given by Y on XYZ PCS and by L* on Lab PCS, Both across inverse TRC curve.
354 // The complete pipeline on XYZ is Matrix[3:1] -> Tone curve and in Lab Matrix[3:1] -> Tone Curve as well.
355
356 static
357 cmsPipeline* BuildGrayOutputPipeline(cmsHPROFILE hProfile)
358 {
359     cmsToneCurve *GrayTRC, *RevGrayTRC;
360     cmsPipeline* Lut;
361     cmsContext ContextID = cmsGetProfileContextID(hProfile);
362
363     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);       
364     if (GrayTRC == NULL) return NULL;
365
366     RevGrayTRC = cmsReverseToneCurve(GrayTRC);
367     if (RevGrayTRC == NULL) return NULL;
368
369     Lut = cmsPipelineAlloc(ContextID, 3, 1);
370     if (Lut == NULL) {
371         cmsFreeToneCurve(RevGrayTRC);
372         return NULL;
373     }
374
375     if (cmsGetPCS(hProfile) == cmsSigLabData) {
376
377         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickLstarMatrix, NULL));
378     }
379     else  {
380         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickYMatrix, NULL));
381     }
382
383     cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC));
384     cmsFreeToneCurve(RevGrayTRC);
385
386     return Lut;
387 }
388
389
390
391
392 static
393 cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
394 {
395     cmsPipeline* Lut;
396     cmsToneCurve *Shapes[3], *InvShapes[3];
397     cmsMAT3 Mat, Inv;
398     int i, j;
399     cmsContext ContextID = cmsGetProfileContextID(hProfile);
400
401     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile))
402         return NULL;
403
404     if (!_cmsMAT3inverse(&Mat, &Inv))
405         return NULL;
406
407     // XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so
408     // we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of 
409     // (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0;
410
411     for (i=0; i < 3; i++)
412         for (j=0; j < 3; j++)
413             Inv.v[i].n[j] *= OutpAdj;
414
415     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);        
416     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
417     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
418
419     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
420         return NULL;
421
422     InvShapes[0] = cmsReverseToneCurve(Shapes[0]);
423     InvShapes[1] = cmsReverseToneCurve(Shapes[1]);
424     InvShapes[2] = cmsReverseToneCurve(Shapes[2]);
425
426     if (!InvShapes[0] || !InvShapes[1] || !InvShapes[2]) {      
427         return NULL;
428     }
429
430     Lut = cmsPipelineAlloc(ContextID, 3, 3);
431     if (Lut != NULL) {
432
433         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL));
434         cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes));
435     }
436
437     cmsFreeToneCurveTriple(InvShapes);
438     return Lut;
439 }
440
441
442 // Change CLUT interpolation to trilinear
443 static
444 void ChangeInterpolationToTrilinear(cmsPipeline* Lut)
445 {
446     cmsStage* Stage;
447
448     for (Stage = cmsPipelineGetPtrToFirstStage(Lut);
449         Stage != NULL;
450         Stage = cmsStageNext(Stage)) {
451
452             if (cmsStageType(Stage) == cmsSigCLutElemType) {
453
454                 _cmsStageCLutData* CLUT = (_cmsStageCLutData*) Stage ->Data;
455
456                 CLUT ->Params->dwFlags |= CMS_LERP_FLAGS_TRILINEAR;
457                 _cmsSetInterpolationRoutine(CLUT ->Params);
458             }
459     }
460 }
461
462
463 // Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded
464 static
465 cmsPipeline* _cmsReadFloatOutputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
466 {
467     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
468     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
469     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
470
471     if (Lut == NULL) return NULL;
472
473     // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
474     // and since the formatter has already accomodated to 0..1.0, we should undo this change
475     if ( PCS == cmsSigLabData)
476     {
477         cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID));
478     }
479     else
480         if (PCS == cmsSigXYZData)
481         {
482             cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID));
483         }
484     
485     return Lut;
486 }
487
488 // Create an output MPE LUT from agiven profile. Version mismatches are handled here
489 cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent)
490 {
491     cmsTagTypeSignature OriginalType;
492     cmsTagSignature tag16    = PCS2Device16[Intent];
493     cmsTagSignature tagFloat = PCS2DeviceFloat[Intent];
494     cmsContext ContextID     = cmsGetProfileContextID(hProfile);
495
496     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
497
498         // Floating point LUT are always V4
499         return _cmsReadFloatOutputTag(hProfile, tagFloat);
500     }
501
502     // Revert to perceptual if no tag is found
503     if (!cmsIsTag(hProfile, tag16)) {
504         tag16 = PCS2Device16[0];
505     }
506
507     if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
508
509         // Check profile version and LUT type. Do the necessary adjustments if needed
510
511         // First read the tag
512         cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
513         if (Lut == NULL) return NULL;
514
515         // After reading it, we have info about the original type
516         OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
517
518         // The profile owns the Lut, so we need to copy it
519         Lut = cmsPipelineDup(Lut);
520         if (Lut == NULL) return NULL;
521
522         // Now it is time for a controversial stuff. I found that for 3D LUTS using 
523         // Lab used as indexer space,  trilinear interpolation should be used         
524         if (cmsGetPCS(hProfile) == cmsSigLabData)
525                              ChangeInterpolationToTrilinear(Lut);       
526
527         // We need to adjust data only for Lab and Lut16 type
528         if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData) 
529             return Lut;
530
531         // Add a matrix for conversion V4 to V2 Lab PCS
532         cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
533
534         // If the output is Lab, add also a conversion at the end
535         if (cmsGetColorSpace(hProfile) == cmsSigLabData)
536             cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
537
538         return Lut;
539     }   
540
541     // Lut not found, try to create a matrix-shaper
542
543     // Check if this is a grayscale profile.
544      if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
545
546               // if so, build appropiate conversion tables. 
547               // The tables are the PCS iluminant, scaled across GrayTRC
548               return BuildGrayOutputPipeline(hProfile);              
549     }
550
551     // Not gray, create a normal matrix-shaper 
552     return BuildRGBOutputMatrixShaper(hProfile);
553 }
554
555 // ---------------------------------------------------------------------------------------------------------------
556
557 // Read the AToD0 tag, adjusting the encoding of Lab or XYZ if neded
558 static
559 cmsPipeline* _cmsReadFloatDevicelinkTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
560 {
561     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
562     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
563     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
564     cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
565
566     if (Lut == NULL) return NULL;
567
568     if (spc == cmsSigLabData)
569     {
570         cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID));
571     }
572     else
573         if (spc == cmsSigXYZData)
574         {
575             cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID));
576         }
577
578         if (PCS == cmsSigLabData)
579         {
580             cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID));
581         }
582         else
583             if (PCS == cmsSigXYZData)
584             {
585                 cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID));
586             }
587
588             return Lut;
589 }
590
591 // This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The 
592 // tag name here may default to AToB0
593 cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
594 {
595     cmsPipeline* Lut;
596     cmsTagTypeSignature OriginalType;
597     cmsTagSignature tag16    = Device2PCS16[Intent];
598     cmsTagSignature tagFloat = Device2PCSFloat[Intent];
599     cmsContext ContextID = cmsGetProfileContextID(hProfile);
600
601
602     // On named color, take the appropiate tag
603     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
604  
605         cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
606
607         if (nc == NULL) return NULL;
608
609         Lut = cmsPipelineAlloc(ContextID, 0, 0);
610         if (Lut == NULL) {
611             cmsFreeNamedColorList(nc);
612             return NULL;
613         }
614
615         cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, FALSE));
616         if (cmsGetColorSpace(hProfile) == cmsSigLabData)
617               cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
618         return Lut;
619     }
620
621     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
622
623         // Floating point LUT are always V        
624         return _cmsReadFloatDevicelinkTag(hProfile, tagFloat);
625     }
626
627     tagFloat = Device2PCSFloat[0];
628     if (cmsIsTag(hProfile, tagFloat)) {  
629         
630         return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
631     }
632
633     if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
634         
635         tag16    = Device2PCS16[0];
636         if (!cmsIsTag(hProfile, tag16)) return NULL;        
637     }
638
639     // Check profile version and LUT type. Do the necessary adjustments if needed
640
641     // Read the tag
642     Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
643     if (Lut == NULL) return NULL;
644
645     // The profile owns the Lut, so we need to copy it
646     Lut = cmsPipelineDup(Lut);
647     if (Lut == NULL) return NULL;
648
649      // Now it is time for a controversial stuff. I found that for 3D LUTS using 
650      // Lab used as indexer space,  trilinear interpolation should be used         
651     if (cmsGetColorSpace(hProfile) == cmsSigLabData)
652                         ChangeInterpolationToTrilinear(Lut);    
653
654     // After reading it, we have info about the original type
655     OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
656
657     // We need to adjust data for Lab16 on output
658     if (OriginalType != cmsSigLut16Type) return Lut;
659         
660     // Here it is possible to get Lab on both sides
661
662     if (cmsGetPCS(hProfile) == cmsSigLabData) {
663             cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
664     }
665
666     if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
667             cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
668     }
669
670     return Lut;
671
672
673 }
674
675 // ---------------------------------------------------------------------------------------------------------------
676
677 // Returns TRUE if the profile is implemented as matrix-shaper
678 cmsBool  CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile)
679 {    
680     switch (cmsGetColorSpace(hProfile)) {
681
682     case cmsSigGrayData:
683         
684         return cmsIsTag(hProfile, cmsSigGrayTRCTag);
685
686     case cmsSigRgbData:
687
688         return (cmsIsTag(hProfile, cmsSigRedColorantTag) &&
689                 cmsIsTag(hProfile, cmsSigGreenColorantTag) &&
690                 cmsIsTag(hProfile, cmsSigBlueColorantTag) &&
691                 cmsIsTag(hProfile, cmsSigRedTRCTag) &&
692                 cmsIsTag(hProfile, cmsSigGreenTRCTag) &&
693                 cmsIsTag(hProfile, cmsSigBlueTRCTag));
694
695     default:
696
697         return FALSE;
698     }
699 }
700
701 // Returns TRUE if the intent is implemented as CLUT
702 cmsBool  CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
703 {    
704     const cmsTagSignature* TagTable;
705
706     // For devicelinks, the supported intent is that one stated in the header
707     if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
708             return (cmsGetHeaderRenderingIntent(hProfile) == Intent);
709     }
710
711     switch (UsedDirection) {
712
713        case LCMS_USED_AS_INPUT: TagTable = Device2PCS16; break;
714        case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device16; break; 
715
716        // For proofing, we need rel. colorimetric in output. Let's do some recursion
717        case LCMS_USED_AS_PROOF: 
718            return cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_INPUT) &&
719                   cmsIsIntentSupported(hProfile, INTENT_RELATIVE_COLORIMETRIC, LCMS_USED_AS_OUTPUT);
720
721        default:
722            cmsSignalError(cmsGetProfileContextID(hProfile), cmsERROR_RANGE, "Unexpected direction (%d)", UsedDirection);
723            return FALSE;
724     }
725
726     return cmsIsTag(hProfile, TagTable[Intent]);
727
728 }
729
730
731 // Return info about supported intents
732 cmsBool  CMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
733                                         cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
734 {
735
736     if (cmsIsCLUT(hProfile, Intent, UsedDirection)) return TRUE;
737
738     // Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper
739     // does not fully support relative colorimetric because they cannot deal with non-zero black points, but
740     // many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter
741     // the accuracy would be less than optimal in rel.col and v2 case.
742
743     return cmsIsMatrixShaper(hProfile);
744 }
745
746
747 // ---------------------------------------------------------------------------------------------------------------
748
749 // Read both, profile sequence description and profile sequence id if present. Then combine both to
750 // create qa unique structure holding both. Shame on ICC to store things in such complicated way.
751 cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile)
752 {
753     cmsSEQ* ProfileSeq;
754     cmsSEQ* ProfileId;
755     cmsSEQ* NewSeq;
756     cmsUInt32Number i;
757
758     // Take profile sequence description first
759     ProfileSeq = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceDescTag);
760
761     // Take profile sequence ID
762     ProfileId  = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceIdTag);
763
764     if (ProfileSeq == NULL && ProfileId == NULL) return NULL;
765
766     if (ProfileSeq == NULL) return cmsDupProfileSequenceDescription(ProfileId);
767     if (ProfileId  == NULL) return cmsDupProfileSequenceDescription(ProfileSeq);
768
769     // We have to mix both together. For that they must agree 
770     if (ProfileSeq ->n != ProfileId ->n) return cmsDupProfileSequenceDescription(ProfileSeq);
771
772     NewSeq = cmsDupProfileSequenceDescription(ProfileSeq);
773
774     // Ok, proceed to the mixing
775     if (NewSeq != NULL) {
776         for (i=0; i < ProfileSeq ->n; i++) {
777
778             memmove(&NewSeq ->seq[i].ProfileID, &ProfileId ->seq[i].ProfileID, sizeof(cmsProfileID));
779             NewSeq ->seq[i].Description = cmsMLUdup(ProfileId ->seq[i].Description);
780         }
781     }
782     return NewSeq;
783 }
784
785 // Dump the contents of profile sequence in both tags (if v4 available)
786 cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq)
787 {
788     if (!cmsWriteTag(hProfile, cmsSigProfileSequenceDescTag, seq)) return FALSE;
789
790     if (cmsGetProfileVersion(hProfile) >= 4.0) {
791
792             if (!cmsWriteTag(hProfile, cmsSigProfileSequenceIdTag, seq)) return FALSE;
793     }
794
795     return TRUE;
796 }
797
798
799 // Auxiliar, read and duplicate a MLU if found.
800 static
801 cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
802 {
803     cmsMLU* mlu = (cmsMLU*) cmsReadTag(h, sig);
804     if (mlu == NULL) return NULL;
805
806     return cmsMLUdup(mlu);
807 }
808
809 // Create a sequence description out of an array of profiles
810 cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[])
811 {
812     cmsUInt32Number i;
813     cmsSEQ* seq = cmsAllocProfileSequenceDescription(ContextID, nProfiles);
814
815     if (seq == NULL) return NULL;
816
817     for (i=0; i < nProfiles; i++) {
818
819         cmsPSEQDESC* ps = &seq ->seq[i];
820         cmsHPROFILE h = hProfiles[i];
821         cmsTechnologySignature* techpt;
822         
823         cmsGetHeaderAttributes(h, &ps ->attributes);
824         cmsGetHeaderProfileID(h, ps ->ProfileID.ID8);       
825         ps ->deviceMfg   = cmsGetHeaderManufacturer(h);
826         ps ->deviceModel = cmsGetHeaderModel(h);
827         
828         techpt = (cmsTechnologySignature*) cmsReadTag(h, cmsSigTechnologyTag);
829         if (techpt == NULL)
830             ps ->technology   =  (cmsTechnologySignature) 0;
831         else
832             ps ->technology   = *techpt;
833                 
834         ps ->Manufacturer = GetMLUFromProfile(h,  cmsSigDeviceMfgDescTag);
835         ps ->Model        = GetMLUFromProfile(h,  cmsSigDeviceModelDescTag);        
836         ps ->Description  = GetMLUFromProfile(h, cmsSigProfileDescriptionTag);
837         
838     }
839
840     return seq;
841 }
842
843 // -------------------------------------------------------------------------------------------------------------------
844
845
846 static
847 const cmsMLU* GetInfo(cmsHPROFILE hProfile, cmsInfoType Info)
848 {
849     cmsTagSignature sig;
850
851     switch (Info) {
852
853     case cmsInfoDescription:
854         sig = cmsSigProfileDescriptionTag; 
855         break;
856
857     case cmsInfoManufacturer:
858         sig = cmsSigDeviceMfgDescTag;
859         break;
860
861     case cmsInfoModel:
862         sig = cmsSigDeviceModelDescTag;
863          break;
864
865     case cmsInfoCopyright:
866         sig = cmsSigCopyrightTag;
867         break;
868
869     default: return NULL;
870     }
871
872
873     return (cmsMLU*) cmsReadTag(hProfile, sig);
874 }
875
876
877
878 cmsUInt32Number CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info, 
879                                             const char LanguageCode[3], const char CountryCode[3], 
880                                             wchar_t* Buffer, cmsUInt32Number BufferSize)
881 {
882     const cmsMLU* mlu = GetInfo(hProfile, Info);
883     if (mlu == NULL) return 0;
884
885     return cmsMLUgetWide(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
886 }
887
888
889 cmsUInt32Number  CMSEXPORT cmsGetProfileInfoASCII(cmsHPROFILE hProfile, cmsInfoType Info, 
890                                                           const char LanguageCode[3], const char CountryCode[3], 
891                                                           char* Buffer, cmsUInt32Number BufferSize)
892 {
893     const cmsMLU* mlu = GetInfo(hProfile, Info);
894     if (mlu == NULL) return 0;
895
896     return cmsMLUgetASCII(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
897 }