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