1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 // This file is available under and governed by the GNU General Public
  26 // License version 2 only, as published by the Free Software Foundation.
  27 // However, the following notice accompanied the original version of this
  28 // file:
  29 //
  30 //---------------------------------------------------------------------------------
  31 //
  32 //  Little Color Management System
  33 //  Copyright (c) 1998-2023 Marti Maria Saguer
  34 //
  35 // Permission is hereby granted, free of charge, to any person obtaining
  36 // a copy of this software and associated documentation files (the "Software"),
  37 // to deal in the Software without restriction, including without limitation
  38 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
  39 // and/or sell copies of the Software, and to permit persons to whom the Software
  40 // is furnished to do so, subject to the following conditions:
  41 //
  42 // The above copyright notice and this permission notice shall be included in
  43 // all copies or substantial portions of the Software.
  44 //
  45 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  46 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
  47 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  48 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  49 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  50 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  51 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  52 //
  53 //---------------------------------------------------------------------------------
  54 //
  55 
  56 #include "lcms2_internal.h"
  57 
  58 // Read tags using low-level functions, provides necessary glue code to adapt versions, etc.
  59 
  60 // LUT tags
  61 static const cmsTagSignature Device2PCS16[]   =  {cmsSigAToB0Tag,     // Perceptual
  62                                                   cmsSigAToB1Tag,     // Relative colorimetric
  63                                                   cmsSigAToB2Tag,     // Saturation
  64                                                   cmsSigAToB1Tag };   // Absolute colorimetric
  65 
  66 static const cmsTagSignature Device2PCSFloat[] = {cmsSigDToB0Tag,     // Perceptual
  67                                                   cmsSigDToB1Tag,     // Relative colorimetric
  68                                                   cmsSigDToB2Tag,     // Saturation
  69                                                   cmsSigDToB3Tag };   // Absolute colorimetric
  70 
  71 static const cmsTagSignature PCS2Device16[]    = {cmsSigBToA0Tag,     // Perceptual
  72                                                   cmsSigBToA1Tag,     // Relative colorimetric
  73                                                   cmsSigBToA2Tag,     // Saturation
  74                                                   cmsSigBToA1Tag };   // Absolute colorimetric
  75 
  76 static const cmsTagSignature PCS2DeviceFloat[] = {cmsSigBToD0Tag,     // Perceptual
  77                                                   cmsSigBToD1Tag,     // Relative colorimetric
  78                                                   cmsSigBToD2Tag,     // Saturation
  79                                                   cmsSigBToD3Tag };   // Absolute colorimetric
  80 
  81 
  82 // Factors to convert from 1.15 fixed point to 0..1.0 range and vice-versa
  83 #define InpAdj   (1.0/MAX_ENCODEABLE_XYZ)     // (65536.0/(65535.0*2.0))
  84 #define OutpAdj  (MAX_ENCODEABLE_XYZ)         // ((2.0*65535.0)/65536.0)
  85 
  86 // Several resources for gray conversions.
  87 static const cmsFloat64Number GrayInputMatrix[] = { (InpAdj*cmsD50X),  (InpAdj*cmsD50Y),  (InpAdj*cmsD50Z) };
  88 static const cmsFloat64Number OneToThreeInputMatrix[] = { 1, 1, 1 };
  89 static const cmsFloat64Number PickYMatrix[] = { 0, (OutpAdj*cmsD50Y), 0 };
  90 static const cmsFloat64Number PickLstarMatrix[] = { 1, 0, 0 };
  91 
  92 // Get a media white point fixing some issues found in certain old profiles
  93 cmsBool  _cmsReadMediaWhitePoint(cmsCIEXYZ* Dest, cmsHPROFILE hProfile)
  94 {
  95     cmsCIEXYZ* Tag;
  96 
  97     _cmsAssert(Dest != NULL);
  98 
  99     Tag = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
 100 
 101     // If no wp, take D50
 102     if (Tag == NULL) {
 103         *Dest = *cmsD50_XYZ();
 104         return TRUE;
 105     }
 106 
 107     // V2 display profiles should give D50
 108     if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
 109 
 110         if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
 111             *Dest = *cmsD50_XYZ();
 112             return TRUE;
 113         }
 114     }
 115 
 116     // All seems ok
 117     *Dest = *Tag;
 118     return TRUE;
 119 }
 120 
 121 
 122 // Chromatic adaptation matrix. Fix some issues as well
 123 cmsBool  _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile)
 124 {
 125     cmsMAT3* Tag;
 126 
 127     _cmsAssert(Dest != NULL);
 128 
 129     Tag = (cmsMAT3*) cmsReadTag(hProfile, cmsSigChromaticAdaptationTag);
 130 
 131     if (Tag != NULL) {
 132         *Dest = *Tag;
 133         return TRUE;
 134     }
 135 
 136     // No CHAD available, default it to identity
 137     _cmsMAT3identity(Dest);
 138 
 139     // V2 display profiles should give D50
 140     if (cmsGetEncodedICCversion(hProfile) < 0x4000000) {
 141 
 142         if (cmsGetDeviceClass(hProfile) == cmsSigDisplayClass) {
 143 
 144             cmsCIEXYZ* White = (cmsCIEXYZ*) cmsReadTag(hProfile, cmsSigMediaWhitePointTag);
 145 
 146             if (White == NULL) {
 147 
 148                 _cmsMAT3identity(Dest);
 149                 return TRUE;
 150             }
 151 
 152             return _cmsAdaptationMatrix(Dest, NULL, White, cmsD50_XYZ());
 153         }
 154     }
 155 
 156     return TRUE;
 157 }
 158 
 159 
 160 // Auxiliary, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
 161 static
 162 cmsBool ReadICCMatrixRGB2XYZ(cmsMAT3* r, cmsHPROFILE hProfile)
 163 {
 164     cmsCIEXYZ *PtrRed, *PtrGreen, *PtrBlue;
 165 
 166     _cmsAssert(r != NULL);
 167 
 168     PtrRed   = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigRedColorantTag);
 169     PtrGreen = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigGreenColorantTag);
 170     PtrBlue  = (cmsCIEXYZ *) cmsReadTag(hProfile, cmsSigBlueColorantTag);
 171 
 172     if (PtrRed == NULL || PtrGreen == NULL || PtrBlue == NULL)
 173         return FALSE;
 174 
 175     _cmsVEC3init(&r -> v[0], PtrRed -> X, PtrGreen -> X,  PtrBlue -> X);
 176     _cmsVEC3init(&r -> v[1], PtrRed -> Y, PtrGreen -> Y,  PtrBlue -> Y);
 177     _cmsVEC3init(&r -> v[2], PtrRed -> Z, PtrGreen -> Z,  PtrBlue -> Z);
 178 
 179     return TRUE;
 180 }
 181 
 182 
 183 // Gray input pipeline
 184 static
 185 cmsPipeline* BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)
 186 {
 187     cmsToneCurve *GrayTRC;
 188     cmsPipeline* Lut;
 189     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 190 
 191     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
 192     if (GrayTRC == NULL) return NULL;
 193 
 194     Lut = cmsPipelineAlloc(ContextID, 1, 3);
 195     if (Lut == NULL)
 196         goto Error;
 197 
 198     if (cmsGetPCS(hProfile) == cmsSigLabData) {
 199 
 200         // In this case we implement the profile as an  identity matrix plus 3 tone curves
 201         cmsUInt16Number Zero[2] = { 0x8080, 0x8080 };
 202         cmsToneCurve* EmptyTab;
 203         cmsToneCurve* LabCurves[3];
 204 
 205         EmptyTab = cmsBuildTabulatedToneCurve16(ContextID, 2, Zero);
 206 
 207         if (EmptyTab == NULL)
 208             goto Error;
 209 
 210         LabCurves[0] = GrayTRC;
 211         LabCurves[1] = EmptyTab;
 212         LabCurves[2] = EmptyTab;
 213 
 214         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, OneToThreeInputMatrix, NULL)) ||
 215             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, LabCurves))) {
 216                 cmsFreeToneCurve(EmptyTab);
 217                 goto Error;
 218         }
 219 
 220         cmsFreeToneCurve(EmptyTab);
 221 
 222     }
 223     else  {
 224 
 225         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &GrayTRC)) ||
 226             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3,  1, GrayInputMatrix, NULL)))
 227             goto Error;
 228     }
 229 
 230     return Lut;
 231 
 232 Error:
 233     cmsPipelineFree(Lut);
 234     return NULL;
 235 }
 236 
 237 // RGB Matrix shaper
 238 static
 239 cmsPipeline* BuildRGBInputMatrixShaper(cmsHPROFILE hProfile)
 240 {
 241     cmsPipeline* Lut;
 242     cmsMAT3 Mat;
 243     cmsToneCurve *Shapes[3];
 244     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 245     int i, j;
 246 
 247     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile)) return NULL;
 248 
 249     // XYZ PCS in encoded in 1.15 format, and the matrix output comes in 0..0xffff range, so
 250     // we need to adjust the output by a factor of (0x10000/0xffff) to put data in
 251     // a 1.16 range, and then a >> 1 to obtain 1.15. The total factor is (65536.0)/(65535.0*2)
 252 
 253     for (i=0; i < 3; i++)
 254         for (j=0; j < 3; j++)
 255             Mat.v[i].n[j] *= InpAdj;
 256 
 257 
 258     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
 259     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
 260     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
 261 
 262     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
 263         return NULL;
 264 
 265     Lut = cmsPipelineAlloc(ContextID, 3, 3);
 266     if (Lut != NULL) {
 267 
 268         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, Shapes)) ||
 269             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL)))
 270             goto Error;
 271 
 272         // Note that it is certainly possible a single profile would have a LUT based
 273         // tag for output working in lab and a matrix-shaper for the fallback cases.
 274         // This is not allowed by the spec, but this code is tolerant to those cases
 275         if (cmsGetPCS(hProfile) == cmsSigLabData) {
 276 
 277             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocXYZ2Lab(ContextID)))
 278                 goto Error;
 279         }
 280 
 281     }
 282 
 283     return Lut;
 284 
 285 Error:
 286     cmsPipelineFree(Lut);
 287     return NULL;
 288 }
 289 
 290 
 291 
 292 // Read the DToAX tag, adjusting the encoding of Lab or XYZ if needed
 293 static
 294 cmsPipeline* _cmsReadFloatInputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
 295 {
 296     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
 297     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
 298     cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
 299     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
 300 
 301     if (Lut == NULL) return NULL;
 302 
 303     // input and output of transform are in lcms 0..1 encoding.  If XYZ or Lab spaces are used,
 304     //  these need to be normalized into the appropriate ranges (Lab = 100,0,0, XYZ=1.0,1.0,1.0)
 305     if ( spc == cmsSigLabData)
 306     {
 307         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
 308             goto Error;
 309     }
 310     else if (spc == cmsSigXYZData)
 311     {
 312         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
 313             goto Error;
 314     }
 315 
 316     if ( PCS == cmsSigLabData)
 317     {
 318         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
 319             goto Error;
 320     }
 321     else if( PCS == cmsSigXYZData)
 322     {
 323         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
 324             goto Error;
 325     }
 326 
 327     return Lut;
 328 
 329 Error:
 330     cmsPipelineFree(Lut);
 331     return NULL;
 332 }
 333 
 334 
 335 // Read and create a BRAND NEW MPE LUT from a given profile. All stuff dependent of version, etc
 336 // is adjusted here in order to create a LUT that takes care of all those details.
 337 // We add intent = 0xffffffff as a way to read matrix shaper always, no matter of other LUT
 338 cmsPipeline* CMSEXPORT _cmsReadInputLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent)
 339 {
 340     cmsTagTypeSignature OriginalType;
 341     cmsTagSignature tag16;
 342     cmsTagSignature tagFloat;
 343     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 344 
 345     // On named color, take the appropriate tag
 346     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 347 
 348         cmsPipeline* Lut;
 349         cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
 350 
 351         if (nc == NULL) return NULL;
 352 
 353         Lut = cmsPipelineAlloc(ContextID, 0, 0);
 354         if (Lut == NULL)
 355             return NULL;
 356 
 357         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, TRUE)) ||
 358             !cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID))) {
 359             cmsPipelineFree(Lut);
 360             return NULL;
 361         }
 362         return Lut;
 363     }
 364 
 365     // This is an attempt to reuse this function to retrieve the matrix-shaper as pipeline no
 366     // matter other LUT are present and have precedence. Intent = 0xffffffff can be used for that.
 367     if (Intent <= INTENT_ABSOLUTE_COLORIMETRIC) {
 368 
 369         tag16 = Device2PCS16[Intent];
 370         tagFloat = Device2PCSFloat[Intent];
 371 
 372         if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 373 
 374             // Floating point LUT are always V4, but the encoding range is no
 375             // longer 0..1.0, so we need to add an stage depending on the color space
 376             return _cmsReadFloatInputTag(hProfile, tagFloat);
 377         }
 378 
 379         // Revert to perceptual if no tag is found
 380         if (!cmsIsTag(hProfile, tag16)) {
 381             tag16 = Device2PCS16[0];
 382         }
 383 
 384         if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
 385 
 386             // Check profile version and LUT type. Do the necessary adjustments if needed
 387 
 388             // First read the tag
 389             cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
 390             if (Lut == NULL) return NULL;
 391 
 392             // After reading it, we have now info about the original type
 393             OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 394 
 395             // The profile owns the Lut, so we need to copy it
 396             Lut = cmsPipelineDup(Lut);
 397 
 398             // We need to adjust data only for Lab16 on output
 399             if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
 400                 return Lut;
 401 
 402             // If the input is Lab, add also a conversion at the begin
 403             if (cmsGetColorSpace(hProfile) == cmsSigLabData &&
 404                 !cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
 405                 goto Error;
 406 
 407             // Add a matrix for conversion V2 to V4 Lab PCS
 408             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
 409                 goto Error;
 410 
 411             return Lut;
 412 Error:
 413             cmsPipelineFree(Lut);
 414             return NULL;
 415         }
 416     }
 417 
 418     // Lut was not found, try to create a matrix-shaper
 419 
 420     // Check if this is a grayscale profile.
 421     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 422 
 423         // if so, build appropriate conversion tables.
 424         // The tables are the PCS iluminant, scaled across GrayTRC
 425         return BuildGrayInputMatrixPipeline(hProfile);
 426     }
 427 
 428     // Not gray, create a normal matrix-shaper
 429     return BuildRGBInputMatrixShaper(hProfile);
 430 }
 431 
 432 // ---------------------------------------------------------------------------------------------------------------
 433 
 434 // Gray output pipeline.
 435 // XYZ -> Gray or Lab -> Gray. Since we only know the GrayTRC, we need to do some assumptions. Gray component will be
 436 // given by Y on XYZ PCS and by L* on Lab PCS, Both across inverse TRC curve.
 437 // The complete pipeline on XYZ is Matrix[3:1] -> Tone curve and in Lab Matrix[3:1] -> Tone Curve as well.
 438 
 439 static
 440 cmsPipeline* BuildGrayOutputPipeline(cmsHPROFILE hProfile)
 441 {
 442     cmsToneCurve *GrayTRC, *RevGrayTRC;
 443     cmsPipeline* Lut;
 444     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 445 
 446     GrayTRC = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGrayTRCTag);
 447     if (GrayTRC == NULL) return NULL;
 448 
 449     RevGrayTRC = cmsReverseToneCurve(GrayTRC);
 450     if (RevGrayTRC == NULL) return NULL;
 451 
 452     Lut = cmsPipelineAlloc(ContextID, 3, 1);
 453     if (Lut == NULL) {
 454         cmsFreeToneCurve(RevGrayTRC);
 455         return NULL;
 456     }
 457 
 458     if (cmsGetPCS(hProfile) == cmsSigLabData) {
 459 
 460         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickLstarMatrix, NULL)))
 461             goto Error;
 462     }
 463     else  {
 464         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1,  3, PickYMatrix, NULL)))
 465             goto Error;
 466     }
 467 
 468     if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC)))
 469         goto Error;
 470 
 471     cmsFreeToneCurve(RevGrayTRC);
 472     return Lut;
 473 
 474 Error:
 475     cmsFreeToneCurve(RevGrayTRC);
 476     cmsPipelineFree(Lut);
 477     return NULL;
 478 }
 479 
 480 
 481 static
 482 cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
 483 {
 484     cmsPipeline* Lut;
 485     cmsToneCurve *Shapes[3], *InvShapes[3];
 486     cmsMAT3 Mat, Inv;
 487     int i, j;
 488     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 489 
 490     if (!ReadICCMatrixRGB2XYZ(&Mat, hProfile))
 491         return NULL;
 492 
 493     if (!_cmsMAT3inverse(&Mat, &Inv))
 494         return NULL;
 495 
 496     // XYZ PCS in encoded in 1.15 format, and the matrix input should come in 0..0xffff range, so
 497     // we need to adjust the input by a << 1 to obtain a 1.16 fixed and then by a factor of
 498     // (0xffff/0x10000) to put data in 0..0xffff range. Total factor is (2.0*65535.0)/65536.0;
 499 
 500     for (i=0; i < 3; i++)
 501         for (j=0; j < 3; j++)
 502             Inv.v[i].n[j] *= OutpAdj;
 503 
 504     Shapes[0] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigRedTRCTag);
 505     Shapes[1] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigGreenTRCTag);
 506     Shapes[2] = (cmsToneCurve *) cmsReadTag(hProfile, cmsSigBlueTRCTag);
 507 
 508     if (!Shapes[0] || !Shapes[1] || !Shapes[2])
 509         return NULL;
 510 
 511     InvShapes[0] = cmsReverseToneCurve(Shapes[0]);
 512     InvShapes[1] = cmsReverseToneCurve(Shapes[1]);
 513     InvShapes[2] = cmsReverseToneCurve(Shapes[2]);
 514 
 515     if (!InvShapes[0] || !InvShapes[1] || !InvShapes[2]) {
 516         return NULL;
 517     }
 518 
 519     Lut = cmsPipelineAlloc(ContextID, 3, 3);
 520     if (Lut != NULL) {
 521 
 522         // Note that it is certainly possible a single profile would have a LUT based
 523         // tag for output working in lab and a matrix-shaper for the fallback cases.
 524         // This is not allowed by the spec, but this code is tolerant to those cases
 525         if (cmsGetPCS(hProfile) == cmsSigLabData) {
 526 
 527             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLab2XYZ(ContextID)))
 528                 goto Error;
 529         }
 530 
 531         if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL)) ||
 532             !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes)))
 533             goto Error;
 534     }
 535 
 536     cmsFreeToneCurveTriple(InvShapes);
 537     return Lut;
 538 Error:
 539     cmsFreeToneCurveTriple(InvShapes);
 540     cmsPipelineFree(Lut);
 541     return NULL;
 542 }
 543 
 544 
 545 // Change CLUT interpolation to trilinear
 546 static
 547 void ChangeInterpolationToTrilinear(cmsPipeline* Lut)
 548 {
 549     cmsStage* Stage;
 550 
 551     for (Stage = cmsPipelineGetPtrToFirstStage(Lut);
 552         Stage != NULL;
 553         Stage = cmsStageNext(Stage)) {
 554 
 555             if (cmsStageType(Stage) == cmsSigCLutElemType) {
 556 
 557                 _cmsStageCLutData* CLUT = (_cmsStageCLutData*) Stage ->Data;
 558 
 559                 CLUT ->Params->dwFlags |= CMS_LERP_FLAGS_TRILINEAR;
 560                 _cmsSetInterpolationRoutine(Lut->ContextID, CLUT ->Params);
 561             }
 562     }
 563 }
 564 
 565 
 566 // Read the DToAX tag, adjusting the encoding of Lab or XYZ if needed
 567 static
 568 cmsPipeline* _cmsReadFloatOutputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
 569 {
 570     cmsContext ContextID       = cmsGetProfileContextID(hProfile);
 571     cmsPipeline* Lut           = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
 572     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
 573     cmsColorSpaceSignature dataSpace = cmsGetColorSpace(hProfile);
 574 
 575     if (Lut == NULL) return NULL;
 576 
 577     // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
 578     // and since the formatter has already accommodated to 0..1.0, we should undo this change
 579     if ( PCS == cmsSigLabData)
 580     {
 581         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
 582             goto Error;
 583     }
 584     else
 585         if (PCS == cmsSigXYZData)
 586         {
 587             if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
 588                 goto Error;
 589         }
 590 
 591     // the output can be Lab or XYZ, in which case normalisation is needed on the end of the pipeline
 592     if ( dataSpace == cmsSigLabData)
 593     {
 594         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
 595             goto Error;
 596     }
 597     else if (dataSpace == cmsSigXYZData)
 598     {
 599         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
 600             goto Error;
 601     }
 602 
 603     return Lut;
 604 
 605 Error:
 606     cmsPipelineFree(Lut);
 607     return NULL;
 608 }
 609 
 610 // Create an output MPE LUT from a given profile. Version mismatches are handled here
 611 cmsPipeline* CMSEXPORT _cmsReadOutputLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent)
 612 {
 613     cmsTagTypeSignature OriginalType;
 614     cmsTagSignature tag16;
 615     cmsTagSignature tagFloat;
 616     cmsContext ContextID  = cmsGetProfileContextID(hProfile);
 617 
 618 
 619     if (Intent <= INTENT_ABSOLUTE_COLORIMETRIC) {
 620 
 621         tag16 = PCS2Device16[Intent];
 622         tagFloat = PCS2DeviceFloat[Intent];
 623 
 624         if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 625 
 626             // Floating point LUT are always V4
 627             return _cmsReadFloatOutputTag(hProfile, tagFloat);
 628         }
 629 
 630         // Revert to perceptual if no tag is found
 631         if (!cmsIsTag(hProfile, tag16)) {
 632             tag16 = PCS2Device16[0];
 633         }
 634 
 635         if (cmsIsTag(hProfile, tag16)) { // Is there any LUT-Based table?
 636 
 637             // Check profile version and LUT type. Do the necessary adjustments if needed
 638 
 639             // First read the tag
 640             cmsPipeline* Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
 641             if (Lut == NULL) return NULL;
 642 
 643             // After reading it, we have info about the original type
 644             OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 645 
 646             // The profile owns the Lut, so we need to copy it
 647             Lut = cmsPipelineDup(Lut);
 648             if (Lut == NULL) return NULL;
 649 
 650             // Now it is time for a controversial stuff. I found that for 3D LUTS using
 651             // Lab used as indexer space,  trilinear interpolation should be used
 652             if (cmsGetPCS(hProfile) == cmsSigLabData)
 653                 ChangeInterpolationToTrilinear(Lut);
 654 
 655             // We need to adjust data only for Lab and Lut16 type
 656             if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
 657                 return Lut;
 658 
 659             // Add a matrix for conversion V4 to V2 Lab PCS
 660             if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
 661                 goto Error;
 662 
 663             // If the output is Lab, add also a conversion at the end
 664             if (cmsGetColorSpace(hProfile) == cmsSigLabData)
 665                 if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
 666                     goto Error;
 667 
 668             return Lut;
 669 Error:
 670             cmsPipelineFree(Lut);
 671             return NULL;
 672         }
 673     }
 674 
 675     // Lut not found, try to create a matrix-shaper
 676 
 677     // Check if this is a grayscale profile.
 678     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 679 
 680         // if so, build appropriate conversion tables.
 681         // The tables are the PCS iluminant, scaled across GrayTRC
 682         return BuildGrayOutputPipeline(hProfile);
 683     }
 684 
 685     // Not gray, create a normal matrix-shaper, which only operates in XYZ space
 686     return BuildRGBOutputMatrixShaper(hProfile);
 687 }
 688 
 689 // ---------------------------------------------------------------------------------------------------------------
 690 
 691 // Read the AToD0 tag, adjusting the encoding of Lab or XYZ if needed
 692 static
 693 cmsPipeline* _cmsReadFloatDevicelinkTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
 694 {
 695     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 696     cmsPipeline* Lut = cmsPipelineDup((cmsPipeline*)cmsReadTag(hProfile, tagFloat));
 697     cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
 698     cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
 699 
 700     if (Lut == NULL) return NULL;
 701 
 702     if (spc == cmsSigLabData)
 703     {
 704         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
 705             goto Error;
 706     }
 707     else
 708         if (spc == cmsSigXYZData)
 709         {
 710             if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
 711                 goto Error;
 712         }
 713 
 714     if (PCS == cmsSigLabData)
 715     {
 716         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
 717             goto Error;
 718     }
 719     else
 720         if (PCS == cmsSigXYZData)
 721         {
 722             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
 723                 goto Error;
 724         }
 725 
 726     return Lut;
 727 Error:
 728     cmsPipelineFree(Lut);
 729     return NULL;
 730 }
 731 
 732 // This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The
 733 // tag name here may default to AToB0
 734 cmsPipeline* CMSEXPORT _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent)
 735 {
 736     cmsPipeline* Lut;
 737     cmsTagTypeSignature OriginalType;
 738     cmsTagSignature tag16;
 739     cmsTagSignature tagFloat;
 740     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 741 
 742 
 743     if (Intent > INTENT_ABSOLUTE_COLORIMETRIC)
 744         return NULL;
 745 
 746     tag16 = Device2PCS16[Intent];
 747     tagFloat = Device2PCSFloat[Intent];
 748 
 749     // On named color, take the appropriate tag
 750     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 751 
 752         cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*)cmsReadTag(hProfile, cmsSigNamedColor2Tag);
 753 
 754         if (nc == NULL) return NULL;
 755 
 756         Lut = cmsPipelineAlloc(ContextID, 0, 0);
 757         if (Lut == NULL)
 758             goto Error;
 759 
 760         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, FALSE)))
 761             goto Error;
 762 
 763         if (cmsGetColorSpace(hProfile) == cmsSigLabData)
 764             if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
 765                 goto Error;
 766 
 767         return Lut;
 768     Error:
 769         cmsPipelineFree(Lut);
 770         return NULL;
 771     }
 772 
 773 
 774     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 775 
 776         // Floating point LUT are always V
 777         return _cmsReadFloatDevicelinkTag(hProfile, tagFloat);
 778     }
 779 
 780     tagFloat = Device2PCSFloat[0];
 781     if (cmsIsTag(hProfile, tagFloat)) {
 782 
 783         return cmsPipelineDup((cmsPipeline*)cmsReadTag(hProfile, tagFloat));
 784     }
 785 
 786     if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
 787 
 788         tag16 = Device2PCS16[0];
 789         if (!cmsIsTag(hProfile, tag16)) return NULL;
 790     }
 791 
 792     // Check profile version and LUT type. Do the necessary adjustments if needed
 793 
 794     // Read the tag
 795     Lut = (cmsPipeline*)cmsReadTag(hProfile, tag16);
 796     if (Lut == NULL) return NULL;
 797 
 798     // The profile owns the Lut, so we need to copy it
 799     Lut = cmsPipelineDup(Lut);
 800     if (Lut == NULL) return NULL;
 801 
 802     // Now it is time for a controversial stuff. I found that for 3D LUTS using
 803     // Lab used as indexer space,  trilinear interpolation should be used
 804     if (cmsGetPCS(hProfile) == cmsSigLabData)
 805         ChangeInterpolationToTrilinear(Lut);
 806 
 807     // After reading it, we have info about the original type
 808     OriginalType = _cmsGetTagTrueType(hProfile, tag16);
 809 
 810     // We need to adjust data for Lab16 on output
 811     if (OriginalType != cmsSigLut16Type) return Lut;
 812 
 813     // Here it is possible to get Lab on both sides
 814 
 815     if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
 816         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
 817             goto Error2;
 818     }
 819 
 820     if (cmsGetPCS(hProfile) == cmsSigLabData) {
 821         if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
 822             goto Error2;
 823     }
 824 
 825     return Lut;
 826 
 827 Error2:
 828     cmsPipelineFree(Lut);
 829     return NULL;
 830 }
 831 
 832 // ---------------------------------------------------------------------------------------------------------------
 833 
 834 // Returns TRUE if the profile is implemented as matrix-shaper
 835 cmsBool  CMSEXPORT cmsIsMatrixShaper(cmsHPROFILE hProfile)
 836 {
 837     switch (cmsGetColorSpace(hProfile)) {
 838 
 839     case cmsSigGrayData:
 840 
 841         return cmsIsTag(hProfile, cmsSigGrayTRCTag);
 842 
 843     case cmsSigRgbData:
 844 
 845         return (cmsIsTag(hProfile, cmsSigRedColorantTag) &&
 846                 cmsIsTag(hProfile, cmsSigGreenColorantTag) &&
 847                 cmsIsTag(hProfile, cmsSigBlueColorantTag) &&
 848                 cmsIsTag(hProfile, cmsSigRedTRCTag) &&
 849                 cmsIsTag(hProfile, cmsSigGreenTRCTag) &&
 850                 cmsIsTag(hProfile, cmsSigBlueTRCTag));
 851 
 852     default:
 853 
 854         return FALSE;
 855     }
 856 }
 857 
 858 // Returns TRUE if the intent is implemented as CLUT
 859 cmsBool  CMSEXPORT cmsIsCLUT(cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
 860 {
 861     const cmsTagSignature* TagTable;
 862 
 863     // For devicelinks, the supported intent is that one stated in the header
 864     if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
 865             return (cmsGetHeaderRenderingIntent(hProfile) == Intent);
 866     }
 867 
 868     switch (UsedDirection) {
 869 
 870        case LCMS_USED_AS_INPUT: TagTable = Device2PCS16; break;
 871        case LCMS_USED_AS_OUTPUT:TagTable = PCS2Device16; break;
 872 
 873        // For proofing, we need rel. colorimetric in output. Let's do some recursion
 874        case LCMS_USED_AS_PROOF:
 875            return cmsIsIntentSupported(hProfile, Intent, LCMS_USED_AS_INPUT) &&
 876                   cmsIsIntentSupported(hProfile, INTENT_RELATIVE_COLORIMETRIC, LCMS_USED_AS_OUTPUT);
 877 
 878        default:
 879            cmsSignalError(cmsGetProfileContextID(hProfile), cmsERROR_RANGE, "Unexpected direction (%d)", UsedDirection);
 880            return FALSE;
 881     }
 882 
 883     // Extended intents are not strictly CLUT-based
 884     if (Intent > INTENT_ABSOLUTE_COLORIMETRIC)
 885         return FALSE;
 886 
 887     return cmsIsTag(hProfile, TagTable[Intent]);
 888 
 889 }
 890 
 891 
 892 // Return info about supported intents
 893 cmsBool  CMSEXPORT cmsIsIntentSupported(cmsHPROFILE hProfile,
 894                                         cmsUInt32Number Intent, cmsUInt32Number UsedDirection)
 895 {
 896 
 897     if (cmsIsCLUT(hProfile, Intent, UsedDirection)) return TRUE;
 898 
 899     // Is there any matrix-shaper? If so, the intent is supported. This is a bit odd, since V2 matrix shaper
 900     // does not fully support relative colorimetric because they cannot deal with non-zero black points, but
 901     // many profiles claims that, and this is certainly not true for V4 profiles. Lets answer "yes" no matter
 902     // the accuracy would be less than optimal in rel.col and v2 case.
 903 
 904     return cmsIsMatrixShaper(hProfile);
 905 }
 906 
 907 
 908 // ---------------------------------------------------------------------------------------------------------------
 909 
 910 // Read both, profile sequence description and profile sequence id if present. Then combine both to
 911 // create qa unique structure holding both. Shame on ICC to store things in such complicated way.
 912 cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile)
 913 {
 914     cmsSEQ* ProfileSeq;
 915     cmsSEQ* ProfileId;
 916     cmsSEQ* NewSeq;
 917     cmsUInt32Number i;
 918 
 919     // Take profile sequence description first
 920     ProfileSeq = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceDescTag);
 921 
 922     // Take profile sequence ID
 923     ProfileId  = (cmsSEQ*) cmsReadTag(hProfile, cmsSigProfileSequenceIdTag);
 924 
 925     if (ProfileSeq == NULL && ProfileId == NULL) return NULL;
 926 
 927     if (ProfileSeq == NULL) return cmsDupProfileSequenceDescription(ProfileId);
 928     if (ProfileId  == NULL) return cmsDupProfileSequenceDescription(ProfileSeq);
 929 
 930     // We have to mix both together. For that they must agree
 931     if (ProfileSeq ->n != ProfileId ->n) return cmsDupProfileSequenceDescription(ProfileSeq);
 932 
 933     NewSeq = cmsDupProfileSequenceDescription(ProfileSeq);
 934 
 935     // Ok, proceed to the mixing
 936     if (NewSeq != NULL) {
 937         for (i=0; i < ProfileSeq ->n; i++) {
 938 
 939             memmove(&NewSeq ->seq[i].ProfileID, &ProfileId ->seq[i].ProfileID, sizeof(cmsProfileID));
 940             NewSeq ->seq[i].Description = cmsMLUdup(ProfileId ->seq[i].Description);
 941         }
 942     }
 943     return NewSeq;
 944 }
 945 
 946 // Dump the contents of profile sequence in both tags (if v4 available)
 947 cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq)
 948 {
 949     if (!cmsWriteTag(hProfile, cmsSigProfileSequenceDescTag, seq)) return FALSE;
 950 
 951     if (cmsGetEncodedICCversion(hProfile) >= 0x4000000) {
 952 
 953             if (!cmsWriteTag(hProfile, cmsSigProfileSequenceIdTag, seq)) return FALSE;
 954     }
 955 
 956     return TRUE;
 957 }
 958 
 959 
 960 // Auxiliary, read and duplicate a MLU if found.
 961 static
 962 cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
 963 {
 964     cmsMLU* mlu = (cmsMLU*) cmsReadTag(h, sig);
 965     if (mlu == NULL) return NULL;
 966 
 967     return cmsMLUdup(mlu);
 968 }
 969 
 970 // Create a sequence description out of an array of profiles
 971 cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[])
 972 {
 973     cmsUInt32Number i;
 974     cmsSEQ* seq = cmsAllocProfileSequenceDescription(ContextID, nProfiles);
 975 
 976     if (seq == NULL) return NULL;
 977 
 978     for (i=0; i < nProfiles; i++) {
 979 
 980         cmsPSEQDESC* ps = &seq ->seq[i];
 981         cmsHPROFILE h = hProfiles[i];
 982         cmsTechnologySignature* techpt;
 983 
 984         cmsGetHeaderAttributes(h, &ps ->attributes);
 985         cmsGetHeaderProfileID(h, ps ->ProfileID.ID8);
 986         ps ->deviceMfg   = cmsGetHeaderManufacturer(h);
 987         ps ->deviceModel = cmsGetHeaderModel(h);
 988 
 989         techpt = (cmsTechnologySignature*) cmsReadTag(h, cmsSigTechnologyTag);
 990         if (techpt == NULL)
 991             ps ->technology   =  (cmsTechnologySignature) 0;
 992         else
 993             ps ->technology   = *techpt;
 994 
 995         ps ->Manufacturer = GetMLUFromProfile(h,  cmsSigDeviceMfgDescTag);
 996         ps ->Model        = GetMLUFromProfile(h,  cmsSigDeviceModelDescTag);
 997         ps ->Description  = GetMLUFromProfile(h, cmsSigProfileDescriptionTag);
 998 
 999     }
1000 
1001     return seq;
1002 }
1003 
1004 // -------------------------------------------------------------------------------------------------------------------
1005 
1006 
1007 static
1008 const cmsMLU* GetInfo(cmsHPROFILE hProfile, cmsInfoType Info)
1009 {
1010     cmsTagSignature sig;
1011 
1012     switch (Info) {
1013 
1014     case cmsInfoDescription:
1015         sig = cmsSigProfileDescriptionTag;
1016         break;
1017 
1018     case cmsInfoManufacturer:
1019         sig = cmsSigDeviceMfgDescTag;
1020         break;
1021 
1022     case cmsInfoModel:
1023         sig = cmsSigDeviceModelDescTag;
1024          break;
1025 
1026     case cmsInfoCopyright:
1027         sig = cmsSigCopyrightTag;
1028         break;
1029 
1030     default: return NULL;
1031     }
1032 
1033 
1034     return (cmsMLU*) cmsReadTag(hProfile, sig);
1035 }
1036 
1037 
1038 
1039 cmsUInt32Number CMSEXPORT cmsGetProfileInfo(cmsHPROFILE hProfile, cmsInfoType Info,
1040                                             const char LanguageCode[3], const char CountryCode[3],
1041                                             wchar_t* Buffer, cmsUInt32Number BufferSize)
1042 {
1043     const cmsMLU* mlu = GetInfo(hProfile, Info);
1044     if (mlu == NULL) return 0;
1045 
1046     return cmsMLUgetWide(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
1047 }
1048 
1049 
1050 cmsUInt32Number  CMSEXPORT cmsGetProfileInfoASCII(cmsHPROFILE hProfile, cmsInfoType Info,
1051                                                           const char LanguageCode[3], const char CountryCode[3],
1052                                                           char* Buffer, cmsUInt32Number BufferSize)
1053 {
1054     const cmsMLU* mlu = GetInfo(hProfile, Info);
1055     if (mlu == NULL) return 0;
1056 
1057     return cmsMLUgetASCII(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
1058 }
1059 
1060 cmsUInt32Number  CMSEXPORT cmsGetProfileInfoUTF8(cmsHPROFILE hProfile, cmsInfoType Info,
1061                                                           const char LanguageCode[3], const char CountryCode[3],
1062                                                           char* Buffer, cmsUInt32Number BufferSize)
1063 {
1064     const cmsMLU* mlu = GetInfo(hProfile, Info);
1065     if (mlu == NULL) return 0;
1066 
1067     return cmsMLUgetUTF8(mlu, LanguageCode, CountryCode, Buffer, BufferSize);
1068 }