Switch to libcms2-2.6
[openjpeg.git] / thirdparty / liblcms2 / 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         *Dest = *Tag;
104         return TRUE;
105     }
106
107     // No CHAD available, default it to identity
108     _cmsMAT3identity(Dest);
109
110     // V2 display profiles should give D50
111     if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
112
113         if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
114
115             cmsCIEXYZ* White = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
116
117             if (White == NULL) {
118
119                 _cmsMAT3identity(Dest);
120                 return TRUE;
121             }
122
123             return _cmsAdaptationMatrix(Dest, NULL, White, cmsD50_XYZ());
124         }
125     }
126
127     return TRUE;
128 }
129
130
131 // Auxiliar, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
132 static
133 cmsBool ReadICCMatrixRGB2XYZ(cmsMAT3* r, cmsHPROFILE hProfile)
134 {
135     cmsCIEXYZ *PtrRed, *PtrGreen, *PtrBlue;
136
137     _cmsAssert(r != NULL);
138
139     PtrRed   = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigRedColorantTag);
140     PtrGreen = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigGreenColorantTag);
141     PtrBlue  = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigBlueColorantTag);
142
143     if (PtrRed == NULL || PtrGreen == NULL || PtrBlue == NULL)
144         return FALSE;
145
146     _cmsVEC3init(&r -> v[0], PtrRed -> X, PtrGreen -> X,  PtrBlue -> X);
147     _cmsVEC3init(&r -> v[1], PtrRed -> Y, PtrGreen -> Y,  PtrBlue -> Y);
148     _cmsVEC3init(&r -> v[2], PtrRed -> Z, PtrGreen -> Z,  PtrBlue -> Z);
149
150     return TRUE;
151 }
152
153
154 // Gray input pipeline
155 static
156 cmsPipeline* BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)
157 {
158     cmsToneCurve *GrayTRC;
159     cmsPipeline* Lut;
160     cmsContext ContextID = cmsGetProfileContextID(hProfile);
161
162     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
163     if (GrayTRC == NULL) return NULL;
164
165     Lut = cmsPipelineAlloc(ContextID, 1, 3);
166     if (Lut == NULL)
167         goto Error;
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             goto Error;
180
181         LabCurves[0] = GrayTRC;
182         LabCurves[1] = EmptyTab;
183         LabCurves[2] = EmptyTab;
184
185         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, OneToThreeInputMatrix, NULL)) ||
186             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, LabCurves))) {
187                 cmsFreeToneCurve(EmptyTab);
188                 goto Error;
189         }
190
191         cmsFreeToneCurve(EmptyTab);
192
193     }
194     else  {
195
196         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &GrayTRC)) ||
197             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, GrayInputMatrix, NULL)))
198             goto Error;
199     }
200
201     return Lut;
202
203 Error:
204     cmsFreeToneCurve(GrayTRC);
205     cmsPipelineFree(Lut);
206     return NULL;
207 }
208
209 // RGB Matrix shaper
210 static
211 cmsPipeline* BuildRGBInputMatrixShaper(cmsHPROFILE hProfile)
212 {
213     cmsPipeline* Lut;
214     cmsMAT3 Mat;
215     cmsToneCurve *Shapes[3];
216     cmsContext ContextID = cmsGetProfileContextID(hProfile);
217     int i, j;
218
219     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile)) return NULL;
220
221     // XYZ PCS in encoded in 1.15 format, and the matrix output comes in 0..0xffff range, so
222     // we need to adjust the output by a factor of (0x10000/0xffff) to put data in
223     // a 1.16 range, and then a >> 1 to obtain 1.15. The total factor is (65536.0)/(65535.0*2)
224
225     for (i=0; i < 3; i++)
226         for (j=0; j < 3; j++)
227             Mat.v[i].n[j] *= InpAdj;
228
229
230     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
231     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
232     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
233
234     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
235         return NULL;
236
237     Lut = cmsPipelineAlloc(ContextID, 3, 3);
238     if (Lut != NULL) {
239
240         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, Shapes)) ||
241             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL)))
242             goto Error;
243
244         // Note that it is certainly possible a single profile would have a LUT based
245         // tag for output working in lab and a matrix-shaper for the fallback cases. 
246         // This is not allowed by the spec, but this code is tolerant to those cases    
247         if (cmsGetPCS(hProfile) == cmsSigLabData) {
248
249             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocXYZ2Lab(ContextID)))
250                 goto Error;
251         }
252
253     }
254
255     return Lut;
256
257 Error:
258     cmsPipelineFree(Lut);
259     return NULL;
260 }
261
262
263
264 // Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded
265 static
266 cmsPipeline* _cmsReadFloatInputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
267 {
268     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
269     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
270     cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
271     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
272     
273     if (Lut == NULL) return NULL;
274     
275     // input and output of transform are in lcms 0..1 encoding.  If XYZ or Lab spaces are used, 
276     //  these need to be normalized into the appropriate ranges (Lab = 100,0,0, XYZ=1.0,1.0,1.0)
277     if ( spc == cmsSigLabData)
278     {
279         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
280             goto Error;
281     }
282     else if (spc == cmsSigXYZData)
283     {
284         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
285             goto Error;
286     }
287     
288     if ( PCS == cmsSigLabData)
289     {
290         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
291             goto Error;
292     }
293     else if( PCS == cmsSigXYZData)
294     {
295         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
296             goto Error;
297     }
298     
299     return Lut;
300
301 Error:
302     cmsPipelineFree(Lut);
303     return NULL;
304 }
305
306
307 // Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc
308 // is adjusted here in order to create a LUT that takes care of all those details.
309 // We add intent = -1 as a way to read matrix shaper always, no matter of other LUT
310 cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
311 {
312     cmsTagTypeSignature OriginalType;
313     cmsTagSignature tag16    = Device2PCS16[Intent];
314     cmsTagSignature tagFloat = Device2PCSFloat[Intent];
315     cmsContext ContextID = cmsGetProfileContextID(hProfile);
316
317     // On named color, take the appropiate tag
318     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
319
320         cmsPipeline* Lut;
321         cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
322
323         if (nc == NULL) return NULL;
324
325         Lut = cmsPipelineAlloc(ContextID, 0, 0);
326         if (Lut == NULL) {
327             cmsFreeNamedColorList(nc);
328             return NULL;
329         }
330
331         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, TRUE)) ||
332             !cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID))) {
333             cmsPipelineFree(Lut);
334             return NULL;
335         }
336         return Lut;
337     }
338
339     // This is an attempt to reuse this funtion to retrieve the matrix-shaper as pipeline no
340     // matter other LUT are present and have precedence. Intent = -1 means just this.
341     if (Intent != -1) {
342
343         if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
344
345             // Floating point LUT are always V4, but the encoding range is no
346             // longer 0..1.0, so we need to add an stage depending on the color space
347             return _cmsReadFloatInputTag(hProfile, tagFloat);
348         }
349
350         // Revert to perceptual if no tag is found
351         if (!cmsIsTag(hProfile, tag16)) {
352             tag16 = Device2PCS16[0];
353         }
354
355         if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
356
357             // Check profile version and LUT type. Do the necessary adjustments if needed
358
359             // First read the tag
360             cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
361             if (Lut == NULL) return NULL;
362
363             // After reading it, we have now info about the original type
364             OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
365
366             // The profile owns the Lut, so we need to copy it
367             Lut = cmsPipelineDup(Lut);
368
369             // We need to adjust data only for Lab16 on output
370             if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
371                 return Lut;
372
373             // If the input is Lab, add also a conversion at the begin
374             if (cmsGetColorSpace(hProfile) == cmsSigLabData &&
375                 !cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
376                 goto Error;
377
378             // Add a matrix for conversion V2 to V4 Lab PCS
379             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
380                 goto Error;
381
382             return Lut;
383 Error:
384             cmsPipelineFree(Lut);
385             return NULL;
386         }
387     }
388
389     // Lut was not found, try to create a matrix-shaper
390
391     // Check if this is a grayscale profile.
392     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
393
394         // if so, build appropiate conversion tables.
395         // The tables are the PCS iluminant, scaled across GrayTRC
396         return BuildGrayInputMatrixPipeline(hProfile);
397     }
398
399     // Not gray, create a normal matrix-shaper
400     return BuildRGBInputMatrixShaper(hProfile);
401 }
402
403 // ---------------------------------------------------------------------------------------------------------------
404
405 // Gray output pipeline.
406 // XYZ -> Gray or Lab -> Gray. Since we only know the GrayTRC, we need to do some assumptions. Gray component will be
407 // given by Y on XYZ PCS and by L* on Lab PCS, Both across inverse TRC curve.
408 // The complete pipeline on XYZ is Matrix[3:1] -> Tone curve and in Lab Matrix[3:1] -> Tone Curve as well.
409
410 static
411 cmsPipeline* BuildGrayOutputPipeline(cmsHPROFILE hProfile)
412 {
413     cmsToneCurve *GrayTRC, *RevGrayTRC;
414     cmsPipeline* Lut;
415     cmsContext ContextID = cmsGetProfileContextID(hProfile);
416
417     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
418     if (GrayTRC == NULL) return NULL;
419
420     RevGrayTRC = cmsReverseToneCurve(GrayTRC);
421     if (RevGrayTRC == NULL) return NULL;
422
423     Lut = cmsPipelineAlloc(ContextID, 3, 1);
424     if (Lut == NULL) {
425         cmsFreeToneCurve(RevGrayTRC);
426         return NULL;
427     }
428
429     if (cmsGetPCS(hProfile) == cmsSigLabData) {
430
431         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickLstarMatrix, NULL)))
432             goto Error;
433     }
434     else  {
435         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickYMatrix, NULL)))
436             goto Error;
437     }
438
439     if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC)))
440         goto Error;
441
442     cmsFreeToneCurve(RevGrayTRC);
443     return Lut;
444
445 Error:
446     cmsFreeToneCurve(RevGrayTRC);
447     cmsPipelineFree(Lut);
448     return NULL;
449 }
450
451
452 static
453 cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
454 {
455     cmsPipeline* Lut;
456     cmsToneCurve *Shapes[3], *InvShapes[3];
457     cmsMAT3 Mat, Inv;
458     int i, j;
459     cmsContext ContextID = cmsGetProfileContextID(hProfile);
460
461     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile))
462         return NULL;
463
464     if (!_cmsMAT3inverse(&Mat, &Inv))
465         return NULL;
466
467     // XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so
468     // we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of
469     // (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0;
470
471     for (i=0; i < 3; i++)
472         for (j=0; j < 3; j++)
473             Inv.v[i].n[j] *= OutpAdj;
474
475     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
476     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
477     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
478
479     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
480         return NULL;
481
482     InvShapes[0] = cmsReverseToneCurve(Shapes[0]);
483     InvShapes[1] = cmsReverseToneCurve(Shapes[1]);
484     InvShapes[2] = cmsReverseToneCurve(Shapes[2]);
485
486     if (!InvShapes[0] || !InvShapes[1] || !InvShapes[2]) {
487         return NULL;
488     }
489
490     Lut = cmsPipelineAlloc(ContextID, 3, 3);
491     if (Lut != NULL) {
492
493         // Note that it is certainly possible a single profile would have a LUT based
494         // tag for output working in lab and a matrix-shaper for the fallback cases. 
495         // This is not allowed by the spec, but this code is tolerant to those cases    
496         if (cmsGetPCS(hProfile) == cmsSigLabData) {
497
498             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLab2XYZ(ContextID)))
499                 goto Error;
500         }
501
502         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL)) ||
503             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes)))
504             goto Error;
505     }
506
507     cmsFreeToneCurveTriple(InvShapes);
508     return Lut;
509 Error:
510     cmsFreeToneCurveTriple(InvShapes);
511     cmsPipelineFree(Lut);
512     return NULL;
513 }
514
515
516 // Change CLUT interpolation to trilinear
517 static
518 void ChangeInterpolationToTrilinear(cmsPipeline* Lut)
519 {
520     cmsStage* Stage;
521
522     for (Stage = cmsPipelineGetPtrToFirstStage(Lut);
523         Stage != NULL;
524         Stage = cmsStageNext(Stage)) {
525
526             if (cmsStageType(Stage) == cmsSigCLutElemType) {
527
528                 _cmsStageCLutData* CLUT = (_cmsStageCLutData*) Stage ->Data;
529
530                 CLUT ->Params->dwFlags |= CMS_LERP_FLAGS_TRILINEAR;
531                 _cmsSetInterpolationRoutine(Lut->ContextID, CLUT ->Params);
532             }
533     }
534 }
535
536
537 // Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded
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         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
553             goto Error;
554     }
555     else
556         if (PCS == cmsSigXYZData)
557         {
558             if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
559                 goto Error;
560         }
561     
562     // the output can be Lab or XYZ, in which case normalisation is needed on the end of the pipeline
563     if ( dataSpace == cmsSigLabData)
564     {
565         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
566             goto Error;
567     }
568     else if (dataSpace == cmsSigXYZData)
569     {
570         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
571             goto Error;
572     }
573     
574     return Lut;
575
576 Error:
577     cmsPipelineFree(Lut);
578     return NULL;
579 }
580
581 // Create an output MPE LUT from agiven profile. Version mismatches are handled here
582 cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent)
583 {
584     cmsTagTypeSignature OriginalType;
585     cmsTagSignature tag16    = PCS2Device16[Intent];
586     cmsTagSignature tagFloat = PCS2DeviceFloat[Intent];
587     cmsContext ContextID     = cmsGetProfileContextID(hProfile);
588
589
590     if (Intent != -1) {
591
592         if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
593
594             // Floating point LUT are always V4
595             return _cmsReadFloatOutputTag(hProfile, tagFloat);
596         }
597
598         // Revert to perceptual if no tag is found
599         if (!cmsIsTag(hProfile, tag16)) {
600             tag16 = PCS2Device16[0];
601         }
602
603         if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
604
605             // Check profile version and LUT type. Do the necessary adjustments if needed
606
607             // First read the tag
608             cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
609             if (Lut == NULL) return NULL;
610
611             // After reading it, we have info about the original type
612             OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
613
614             // The profile owns the Lut, so we need to copy it
615             Lut = cmsPipelineDup(Lut);
616             if (Lut == NULL) return NULL;
617
618             // Now it is time for a controversial stuff. I found that for 3D LUTS using
619             // Lab used as indexer space,  trilinear interpolation should be used
620             if (cmsGetPCS(hProfile) == cmsSigLabData)
621                 ChangeInterpolationToTrilinear(Lut);
622
623             // We need to adjust data only for Lab and Lut16 type
624             if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
625                 return Lut;
626
627             // Add a matrix for conversion V4 to V2 Lab PCS
628             if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
629                 goto Error;
630
631             // If the output is Lab, add also a conversion at the end
632             if (cmsGetColorSpace(hProfile) == cmsSigLabData)
633                 if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
634                     goto Error;
635
636             return Lut;
637 Error:
638             cmsPipelineFree(Lut);
639             return NULL;
640         }
641     }
642
643     // Lut not found, try to create a matrix-shaper
644
645     // Check if this is a grayscale profile.
646     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
647
648         // if so, build appropiate conversion tables.
649         // The tables are the PCS iluminant, scaled across GrayTRC
650         return BuildGrayOutputPipeline(hProfile);
651     }
652
653     // Not gray, create a normal matrix-shaper, which only operates in XYZ space  
654     return BuildRGBOutputMatrixShaper(hProfile);
655 }
656
657 // ---------------------------------------------------------------------------------------------------------------
658
659 // Read the AToD0 tag, adjusting the encoding of Lab or XYZ if neded
660 static
661 cmsPipeline* _cmsReadFloatDevicelinkTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
662 {
663     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
664     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
665     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
666     cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
667
668     if (Lut == NULL) return NULL;
669
670     if (spc == cmsSigLabData)
671     {
672         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
673             goto Error;
674     }
675     else
676         if (spc == cmsSigXYZData)
677         {
678             if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
679                 goto Error;
680         }
681
682         if (PCS == cmsSigLabData)
683         {
684             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
685                 goto Error;
686         }
687         else
688             if (PCS == cmsSigXYZData)
689             {
690                 if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
691                     goto Error;
692             }
693
694     return Lut;
695 Error:
696     cmsPipelineFree(Lut);
697     return NULL;
698 }
699
700 // This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The
701 // tag name here may default to AToB0
702 cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
703 {
704     cmsPipeline* Lut;
705     cmsTagTypeSignature OriginalType;
706     cmsTagSignature tag16    = Device2PCS16[Intent];
707     cmsTagSignature tagFloat = Device2PCSFloat[Intent];
708     cmsContext ContextID = cmsGetProfileContextID(hProfile);
709
710
711     // On named color, take the appropiate tag
712     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
713
714         cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
715
716         if (nc == NULL) return NULL;
717
718         Lut = cmsPipelineAlloc(ContextID, 0, 0);
719         if (Lut == NULL)
720             goto Error;
721
722         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, FALSE)))
723             goto Error;
724
725         if (cmsGetColorSpace(hProfile) == cmsSigLabData)
726             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
727                 goto Error;
728
729         return Lut;
730 Error:
731         cmsPipelineFree(Lut);
732         cmsFreeNamedColorList(nc);
733         return NULL;
734     }
735
736     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
737
738         // Floating point LUT are always V
739         return _cmsReadFloatDevicelinkTag(hProfile, tagFloat);
740     }
741
742     tagFloat = Device2PCSFloat[0];
743     if (cmsIsTag(hProfile, tagFloat)) {
744
745         return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
746     }
747
748     if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
749
750         tag16    = Device2PCS16[0];
751         if (!cmsIsTag(hProfile, tag16)) return NULL;
752     }
753
754     // Check profile version and LUT type. Do the necessary adjustments if needed
755
756     // Read the tag
757     Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
758     if (Lut == NULL) return NULL;
759
760     // The profile owns the Lut, so we need to copy it
761     Lut = cmsPipelineDup(Lut);
762     if (Lut == NULL) return NULL;
763
764     // Now it is time for a controversial stuff. I found that for 3D LUTS using
765     // Lab used as indexer space,  trilinear interpolation should be used
766     if (cmsGetPCS(hProfile) == cmsSigLabData)
767         ChangeInterpolationToTrilinear(Lut);
768
769     // After reading it, we have info about the original type
770     OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
771
772     // We need to adjust data for Lab16 on output
773     if (OriginalType != cmsSigLut16Type) return Lut;
774
775     // Here it is possible to get Lab on both sides
776
777     if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
778         if(!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
779             goto Error2;
780     }
781
782     if (cmsGetPCS(hProfile) == cmsSigLabData) {
783         if(!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
784             goto Error2;
785     }
786
787     return Lut;
788
789 Error2:
790     cmsPipelineFree(Lut);
791     return NULL;
792 }
793
794 // ---------------------------------------------------------------------------------------------------------------
795
796 // Returns TRUE if the profile is implemented as matrix-shaper
797 cmsBool  CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile)
798 {
799     switch (cmsGetColorSpace(hProfile)) {
800
801     case cmsSigGrayData:
802
803         return cmsIsTag(hProfile, cmsSigGrayTRCTag);
804
805     case cmsSigRgbData:
806
807         return (cmsIsTag(hProfile, cmsSigRedColorantTag) &&
808                 cmsIsTag(hProfile, cmsSigGreenColorantTag) &&
809                 cmsIsTag(hProfile, cmsSigBlueColorantTag) &&
810                 cmsIsTag(hProfile, cmsSigRedTRCTag) &&
811                 cmsIsTag(hProfile, cmsSigGreenTRCTag) &&
812                 cmsIsTag(hProfile, cmsSigBlueTRCTag));
813
814     default:
815
816         return FALSE;
817     }
818 }
819
820 // Returns TRUE if the intent is implemented as CLUT
821 cmsBool  CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
822 {
823     const cmsTagSignature* TagTable;
824
825     // For devicelinks, the supported intent is that one stated in the header
826     if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
827             return (cmsGetHeaderRenderingIntent(hProfile) == Intent);
828     }
829
830     switch (UsedDirection) {
831
832        case LCMS_USED_AS_INPUT: TagTable = Device2PCS16; break;
833        case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device16; break;
834
835        // For proofing, we need rel. colorimetric in output. Let's do some recursion
836        case LCMS_USED_AS_PROOF:
837            return cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_INPUT) &&
838                   cmsIsIntentSupported(hProfile, INTENT_RELATIVE_COLORIMETRIC, LCMS_USED_AS_OUTPUT);
839
840        default:
841            cmsSignalError(cmsGetProfileContextID(hProfile), cmsERROR_RANGE, "Unexpected direction (%d)", UsedDirection);
842            return FALSE;
843     }
844
845     return cmsIsTag(hProfile, TagTable[Intent]);
846
847 }
848
849
850 // Return info about supported intents
851 cmsBool  CMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
852                                         cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
853 {
854
855     if (cmsIsCLUT(hProfile, Intent, UsedDirection)) return TRUE;
856
857     // Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper
858     // does not fully support relative colorimetric because they cannot deal with non-zero black points, but
859     // many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter
860     // the accuracy would be less than optimal in rel.col and v2 case.
861
862     return cmsIsMatrixShaper(hProfile);
863 }
864
865
866 // ---------------------------------------------------------------------------------------------------------------
867
868 // Read both, profile sequence description and profile sequence id if present. Then combine both to
869 // create qa unique structure holding both. Shame on ICC to store things in such complicated way.
870 cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile)
871 {
872     cmsSEQ* ProfileSeq;
873     cmsSEQ* ProfileId;
874     cmsSEQ* NewSeq;
875     cmsUInt32Number i;
876
877     // Take profile sequence description first
878     ProfileSeq = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceDescTag);
879
880     // Take profile sequence ID
881     ProfileId  = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceIdTag);
882
883     if (ProfileSeq == NULL && ProfileId == NULL) return NULL;
884
885     if (ProfileSeq == NULL) return cmsDupProfileSequenceDescription(ProfileId);
886     if (ProfileId  == NULL) return cmsDupProfileSequenceDescription(ProfileSeq);
887
888     // We have to mix both together. For that they must agree
889     if (ProfileSeq ->n != ProfileId ->n) return cmsDupProfileSequenceDescription(ProfileSeq);
890
891     NewSeq = cmsDupProfileSequenceDescription(ProfileSeq);
892
893     // Ok, proceed to the mixing
894     if (NewSeq != NULL) {
895         for (i=0; i < ProfileSeq ->n; i++) {
896
897             memmove(&NewSeq ->seq[i].ProfileID, &ProfileId ->seq[i].ProfileID, sizeof(cmsProfileID));
898             NewSeq ->seq[i].Description = cmsMLUdup(ProfileId ->seq[i].Description);
899         }
900     }
901     return NewSeq;
902 }
903
904 // Dump the contents of profile sequence in both tags (if v4 available)
905 cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq)
906 {
907     if (!cmsWriteTag(hProfile, cmsSigProfileSequenceDescTag, seq)) return FALSE;
908
909     if (cmsGetProfileVersion(hProfile) >= 4.0) {
910
911             if (!cmsWriteTag(hProfile, cmsSigProfileSequenceIdTag, seq)) return FALSE;
912     }
913
914     return TRUE;
915 }
916
917
918 // Auxiliar, read and duplicate a MLU if found.
919 static
920 cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
921 {
922     cmsMLU* mlu = (cmsMLU*) cmsReadTag(h, sig);
923     if (mlu == NULL) return NULL;
924
925     return cmsMLUdup(mlu);
926 }
927
928 // Create a sequence description out of an array of profiles
929 cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[])
930 {
931     cmsUInt32Number i;
932     cmsSEQ* seq = cmsAllocProfileSequenceDescription(ContextID, nProfiles);
933
934     if (seq == NULL) return NULL;
935
936     for (i=0; i < nProfiles; i++) {
937
938         cmsPSEQDESC* ps = &seq ->seq[i];
939         cmsHPROFILE h = hProfiles[i];
940         cmsTechnologySignature* techpt;
941
942         cmsGetHeaderAttributes(h, &ps ->attributes);
943         cmsGetHeaderProfileID(h, ps ->ProfileID.ID8);
944         ps ->deviceMfg   = cmsGetHeaderManufacturer(h);
945         ps ->deviceModel = cmsGetHeaderModel(h);
946
947         techpt = (cmsTechnologySignature*) cmsReadTag(h, cmsSigTechnologyTag);
948         if (techpt == NULL)
949             ps ->technology   =  (cmsTechnologySignature) 0;
950         else
951             ps ->technology   = *techpt;
952
953         ps ->Manufacturer = GetMLUFromProfile(h,  cmsSigDeviceMfgDescTag);
954         ps ->Model        = GetMLUFromProfile(h,  cmsSigDeviceModelDescTag);
955         ps ->Description  = GetMLUFromProfile(h, cmsSigProfileDescriptionTag);
956
957     }
958
959     return seq;
960 }
961
962 // -------------------------------------------------------------------------------------------------------------------
963
964
965 static
966 const cmsMLU* GetInfo(cmsHPROFILE hProfile, cmsInfoType Info)
967 {
968     cmsTagSignature sig;
969
970     switch (Info) {
971
972     case cmsInfoDescription:
973         sig = cmsSigProfileDescriptionTag;
974         break;
975
976     case cmsInfoManufacturer:
977         sig = cmsSigDeviceMfgDescTag;
978         break;
979
980     case cmsInfoModel:
981         sig = cmsSigDeviceModelDescTag;
982          break;
983
984     case cmsInfoCopyright:
985         sig = cmsSigCopyrightTag;
986         break;
987
988     default: return NULL;
989     }
990
991
992     return (cmsMLU*) cmsReadTag(hProfile, sig);
993 }
994
995
996
997 cmsUInt32Number CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info,
998                                             const char LanguageCode[3], const char CountryCode[3],
999                                             wchar_t* Buffer, cmsUInt32Number BufferSize)
1000 {
1001     const cmsMLU* mlu = GetInfo(hProfile, Info);
1002     if (mlu == NULL) return 0;
1003
1004     return cmsMLUgetWide(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
1005 }
1006
1007
1008 cmsUInt32Number  CMSEXPORT cmsGetProfileInfoASCII(cmsHPROFILE hProfile, cmsInfoType Info,
1009                                                           const char LanguageCode[3], const char CountryCode[3],
1010                                                           char* Buffer, cmsUInt32Number BufferSize)
1011 {
1012     const cmsMLU* mlu = GetInfo(hProfile, Info);
1013     if (mlu == NULL) return 0;
1014
1015     return cmsMLUgetASCII(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
1016 }