cmsps2.c 47.3 KB
Newer Older
D
duke 已提交
1 2 3 4 5
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
6
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
7
 * particular file as subject to the "Classpath" exception as provided
8
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
9 10 11 12 13 14 15 16 17 18 19
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
20 21 22
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
23 24 25 26 27 28 29
 */

// This file is available under and governed by the GNU General Public
// License version 2 only, as published by the Free Software Foundation.
// However, the following notice accompanied the original version of this
// file:
//
30
//---------------------------------------------------------------------------------
D
duke 已提交
31
//
32
//  Little Color Management System
P
prr 已提交
33
//  Copyright (c) 1998-2017 Marti Maria Saguer
D
duke 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
52 53 54
//
//---------------------------------------------------------------------------------
//
D
duke 已提交
55

56
#include "lcms2_internal.h"
D
duke 已提交
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

// PostScript ColorRenderingDictionary and ColorSpaceArray


#define MAXPSCOLS   60      // Columns on tables

/*
    Implementation
    --------------

  PostScript does use XYZ as its internal PCS. But since PostScript
  interpolation tables are limited to 8 bits, I use Lab as a way to
  improve the accuracy, favoring perceptual results. So, for the creation
  of each CRD, CSA the profiles are converted to Lab via a device
  link between  profile -> Lab or Lab -> profile. The PS code necessary to
  convert Lab <-> XYZ is also included.



  Color Space Arrays (CSA)
  ==================================================================================

79
  In order to obtain precision, code chooses between three ways to implement
D
duke 已提交
80
  the device -> XYZ transform. These cases identifies monochrome profiles (often
81
  implemented as a set of curves), matrix-shaper and Pipeline-based.
D
duke 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

  Monochrome
  -----------

  This is implemented as /CIEBasedA CSA. The prelinearization curve is
  placed into /DecodeA section, and matrix equals to D50. Since here is
  no interpolation tables, I do the conversion directly to XYZ

  NOTE: CLUT-based monochrome profiles are NOT supported. So, cmsFLAGS_MATRIXINPUT
  flag is forced on such profiles.

    [ /CIEBasedA
      <<
            /DecodeA { transfer function } bind
            /MatrixA [D50]
97
            /RangeLMN [ 0.0 cmsD50X 0.0 cmsD50Y 0.0 cmsD50Z ]
D
duke 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110
            /WhitePoint [D50]
            /BlackPoint [BP]
            /RenderingIntent (intent)
      >>
    ]

   On simpler profiles, the PCS is already XYZ, so no conversion is required.


   Matrix-shaper based
   -------------------

   This is implemented both with /CIEBasedABC or /CIEBasedDEF on dependig
111
   of profile implementation. Since here there are no interpolation tables, I do
D
duke 已提交
112 113 114 115 116 117 118 119
   the conversion directly to XYZ



    [ /CIEBasedABC
            <<
                /DecodeABC [ {transfer1} {transfer2} {transfer3} ]
                /MatrixABC [Matrix]
120
                /RangeLMN [ 0.0 cmsD50X 0.0 cmsD50Y 0.0 cmsD50Z ]
D
duke 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
                /DecodeLMN [ { / 2} dup dup ]
                /WhitePoint [D50]
                /BlackPoint [BP]
                /RenderingIntent (intent)
            >>
    ]


    CLUT based
    ----------

     Lab is used in such cases.

    [ /CIEBasedDEF
            <<
            /DecodeDEF [ <prelinearization> ]
            /Table [ p p p [<...>]]
            /RangeABC [ 0 1 0 1 0 1]
            /DecodeABC[ <postlinearization> ]
140 141
            /RangeLMN [ -0.236 1.254 0 1 -0.635 1.640 ]
               % -128/500 1+127/500 0 1  -127/200 1+128/200
D
duke 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
            /MatrixABC [ 1 1 1 1 0 0 0 0 -1]
            /WhitePoint [D50]
            /BlackPoint [BP]
            /RenderingIntent (intent)
    ]


  Color Rendering Dictionaries (CRD)
  ==================================
  These are always implemented as CLUT, and always are using Lab. Since CRD are expected to
  be used as resources, the code adds the definition as well.

  <<
    /ColorRenderingType 1
    /WhitePoint [ D50 ]
    /BlackPoint [BP]
    /MatrixPQR [ Bradford ]
    /RangePQR [-0.125 1.375 -0.125 1.375 -0.125 1.375 ]
    /TransformPQR [
    {4 index 3 get div 2 index 3 get mul exch pop exch pop exch pop exch pop } bind
    {4 index 4 get div 2 index 4 get mul exch pop exch pop exch pop exch pop } bind
    {4 index 5 get div 2 index 5 get mul exch pop exch pop exch pop exch pop } bind
    ]
    /MatrixABC <...>
    /EncodeABC <...>
    /RangeABC  <.. used for  XYZ -> Lab>
    /EncodeLMN
    /RenderTable [ p p p [<...>]]

    /RenderingIntent (Perceptual)
  >>
  /Current exch /ColorRendering defineresource pop


  The following stages are used to convert from XYZ to Lab
  --------------------------------------------------------

  Input is given at LMN stage on X, Y, Z

  Encode LMN gives us f(X/Xn), f(Y/Yn), f(Z/Zn)

  /EncodeLMN [

    { 0.964200  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind
    { 1.000000  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind
    { 0.824900  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind

    ]


  MatrixABC is used to compute f(Y/Yn), f(X/Xn) - f(Y/Yn), f(Y/Yn) - f(Z/Zn)

  | 0  1  0|
  | 1 -1  0|
  | 0  1 -1|

  /MatrixABC [ 0 1 0 1 -1 1 0 0 -1 ]

 EncodeABC finally gives Lab values.

  /EncodeABC [
    { 116 mul  16 sub 100 div  } bind
    { 500 mul 128 add 255 div  } bind
    { 200 mul 128 add 255 div  } bind
    ]

  The following stages are used to convert Lab to XYZ
  ----------------------------------------------------

    /RangeABC [ 0 1 0 1 0 1]
    /DecodeABC [ { 100 mul 16 add 116 div } bind
                 { 255 mul 128 sub 500 div } bind
                 { 255 mul 128 sub 200 div } bind
               ]

    /MatrixABC [ 1 1 1 1 0 0 0 0 -1]
    /DecodeLMN [
                {dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.964200 mul} bind
                {dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse } bind
                {dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.824900 mul} bind
                ]


*/

/*

 PostScript algorithms discussion.
 =========================================================================================================

  1D interpolation algorithm


  1D interpolation (float)
  ------------------------

    val2 = Domain * Value;

    cell0 = (int) floor(val2);
    cell1 = (int) ceil(val2);

    rest = val2 - cell0;

    y0 = LutTable[cell0] ;
    y1 = LutTable[cell1] ;

    y = y0 + (y1 - y0) * rest;



  PostScript code                   Stack
  ================================================

  {                                 % v
    <check 0..1.0>
    [array]                         % v tab
    dup                             % v tab tab
    length 1 sub                    % v tab dom

    3 -1 roll                       % tab dom v

    mul                             % tab val2
    dup                             % tab val2 val2
    dup                             % tab val2 val2 val2
    floor cvi                       % tab val2 val2 cell0
    exch                            % tab val2 cell0 val2
    ceiling cvi                     % tab val2 cell0 cell1

    3 index                         % tab val2 cell0 cell1 tab
    exch                            % tab val2 cell0 tab cell1
    get                             % tab val2 cell0 y1

    4 -1 roll                       % val2 cell0 y1 tab
    3 -1 roll                       % val2 y1 tab cell0
    get                             % val2 y1 y0

    dup                             % val2 y1 y0 y0
    3 1 roll                        % val2 y0 y1 y0

    sub                             % val2 y0 (y1-y0)
    3 -1 roll                       % y0 (y1-y0) val2
    dup                             % y0 (y1-y0) val2 val2
    floor cvi                       % y0 (y1-y0) val2 floor(val2)
    sub                             % y0 (y1-y0) rest
    mul                             % y0 t1
    add                             % y
    65535 div                       % result

  } bind


*/


// This struct holds the memory block currently being write
typedef struct {
298 299
    _cmsStageCLutData* Pipeline;
    cmsIOHANDLER* m;
D
duke 已提交
300

301 302
    int FirstComponent;
    int SecondComponent;
D
duke 已提交
303

304 305 306 307
    const char* PreMaj;
    const char* PostMaj;
    const char* PreMin;
    const char* PostMin;
D
duke 已提交
308

309
    int  FixWhite;    // Force mapping of pure white
D
duke 已提交
310

311
    cmsColorSpaceSignature  ColorSpace;  // ColorSpace of profile
D
duke 已提交
312 313


314
} cmsPsSamplerCargo;
D
duke 已提交
315

316
static int _cmsPSActualColumn = 0;
D
duke 已提交
317 318 319 320


// Convert to byte
static
321
cmsUInt8Number Word2Byte(cmsUInt16Number w)
D
duke 已提交
322
{
323
    return (cmsUInt8Number) floor((cmsFloat64Number) w / 257.0 + 0.5);
D
duke 已提交
324 325 326 327
}


// Convert to byte (using ICC2 notation)
328
/*
D
duke 已提交
329
static
330
cmsUInt8Number L2Byte(cmsUInt16Number w)
D
duke 已提交
331
{
B
bae 已提交
332
    int ww = w + 0x0080;
D
duke 已提交
333

B
bae 已提交
334
    if (ww > 0xFFFF) return 0xFF;
D
duke 已提交
335

336
    return (cmsUInt8Number) ((cmsUInt16Number) (ww >> 8) & 0xFF);
D
duke 已提交
337
}
338
*/
D
duke 已提交
339 340 341 342

// Write a cooked byte

static
343
void WriteByte(cmsIOHANDLER* m, cmsUInt8Number b)
D
duke 已提交
344
{
345 346
    _cmsIOPrintf(m, "%02x", b);
    _cmsPSActualColumn += 2;
D
duke 已提交
347

348
    if (_cmsPSActualColumn > MAXPSCOLS) {
D
duke 已提交
349

350 351 352
        _cmsIOPrintf(m, "\n");
        _cmsPSActualColumn = 0;
    }
D
duke 已提交
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
}

// ----------------------------------------------------------------- PostScript generation


// Removes offending Carriage returns
static
char* RemoveCR(const char* txt)
{
    static char Buffer[2048];
    char* pt;

    strncpy(Buffer, txt, 2047);
    Buffer[2047] = 0;
    for (pt = Buffer; *pt; pt++)
            if (*pt == '\n' || *pt == '\r') *pt = ' ';

    return Buffer;

}

static
375
void EmitHeader(cmsIOHANDLER* m, const char* Title, cmsHPROFILE hProfile)
D
duke 已提交
376 377
{
    time_t timer;
378 379
    cmsMLU *Description, *Copyright;
    char DescASCII[256], CopyrightASCII[256];
D
duke 已提交
380 381 382

    time(&timer);

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    Description = (cmsMLU*) cmsReadTag(hProfile, cmsSigProfileDescriptionTag);
    Copyright   = (cmsMLU*) cmsReadTag(hProfile, cmsSigCopyrightTag);

    DescASCII[0] = DescASCII[255] = 0;
    CopyrightASCII[0] = CopyrightASCII[255] = 0;

    if (Description != NULL) cmsMLUgetASCII(Description,  cmsNoLanguage, cmsNoCountry, DescASCII,       255);
    if (Copyright != NULL)   cmsMLUgetASCII(Copyright,    cmsNoLanguage, cmsNoCountry, CopyrightASCII,  255);

    _cmsIOPrintf(m, "%%!PS-Adobe-3.0\n");
    _cmsIOPrintf(m, "%%\n");
    _cmsIOPrintf(m, "%% %s\n", Title);
    _cmsIOPrintf(m, "%% Source: %s\n", RemoveCR(DescASCII));
    _cmsIOPrintf(m, "%%         %s\n", RemoveCR(CopyrightASCII));
    _cmsIOPrintf(m, "%% Created: %s", ctime(&timer)); // ctime appends a \n!!!
    _cmsIOPrintf(m, "%%\n");
    _cmsIOPrintf(m, "%%%%BeginResource\n");
D
duke 已提交
400 401 402 403 404 405 406 407

}


// Emits White & Black point. White point is always D50, Black point is the device
// Black point adapted to D50.

static
408
void EmitWhiteBlackD50(cmsIOHANDLER* m, cmsCIEXYZ* BlackPoint)
D
duke 已提交
409 410
{

411
    _cmsIOPrintf(m, "/BlackPoint [%f %f %f]\n", BlackPoint -> X,
D
duke 已提交
412 413 414
                                          BlackPoint -> Y,
                                          BlackPoint -> Z);

415
    _cmsIOPrintf(m, "/WhitePoint [%f %f %f]\n", cmsD50_XYZ()->X,
D
duke 已提交
416 417 418 419 420 421
                                          cmsD50_XYZ()->Y,
                                          cmsD50_XYZ()->Z);
}


static
422
void EmitRangeCheck(cmsIOHANDLER* m)
D
duke 已提交
423
{
424 425
    _cmsIOPrintf(m, "dup 0.0 lt { pop 0.0 } if "
                    "dup 1.0 gt { pop 1.0 } if ");
D
duke 已提交
426 427 428 429 430 431

}

// Does write the intent

static
P
prr 已提交
432
void EmitIntent(cmsIOHANDLER* m, cmsUInt32Number RenderingIntent)
D
duke 已提交
433 434 435 436 437 438 439 440 441 442 443 444 445
{
    const char *intent;

    switch (RenderingIntent) {

        case INTENT_PERCEPTUAL:            intent = "Perceptual"; break;
        case INTENT_RELATIVE_COLORIMETRIC: intent = "RelativeColorimetric"; break;
        case INTENT_ABSOLUTE_COLORIMETRIC: intent = "AbsoluteColorimetric"; break;
        case INTENT_SATURATION:            intent = "Saturation"; break;

        default: intent = "Undefined"; break;
    }

446
    _cmsIOPrintf(m, "/RenderingIntent (%s)\n", intent );
D
duke 已提交
447 448 449 450 451 452 453 454 455 456 457
}

//
//  Convert L* to Y
//
//      Y = Yn*[ (L* + 16) / 116] ^ 3   if (L*) >= 6 / 29
//        = Yn*( L* / 116) / 7.787      if (L*) < 6 / 29
//

/*
static
458
void EmitL2Y(cmsIOHANDLER* m)
D
duke 已提交
459
{
460
    _cmsIOPrintf(m,
D
duke 已提交
461 462 463 464 465 466 467 468 469 470 471 472 473
            "{ "
                "100 mul 16 add 116 div "               // (L * 100 + 16) / 116
                 "dup 6 29 div ge "                     // >= 6 / 29 ?
                 "{ dup dup mul mul } "                 // yes, ^3 and done
                 "{ 4 29 div sub 108 841 div mul } "    // no, slope limiting
            "ifelse } bind ");
}
*/


// Lab -> XYZ, see the discussion above

static
474
void EmitLab2XYZ(cmsIOHANDLER* m)
D
duke 已提交
475
{
476 477 478 479 480 481 482 483 484 485 486 487 488
    _cmsIOPrintf(m, "/RangeABC [ 0 1 0 1 0 1]\n");
    _cmsIOPrintf(m, "/DecodeABC [\n");
    _cmsIOPrintf(m, "{100 mul  16 add 116 div } bind\n");
    _cmsIOPrintf(m, "{255 mul 128 sub 500 div } bind\n");
    _cmsIOPrintf(m, "{255 mul 128 sub 200 div } bind\n");
    _cmsIOPrintf(m, "]\n");
    _cmsIOPrintf(m, "/MatrixABC [ 1 1 1 1 0 0 0 0 -1]\n");
    _cmsIOPrintf(m, "/RangeLMN [ -0.236 1.254 0 1 -0.635 1.640 ]\n");
    _cmsIOPrintf(m, "/DecodeLMN [\n");
    _cmsIOPrintf(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.964200 mul} bind\n");
    _cmsIOPrintf(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse } bind\n");
    _cmsIOPrintf(m, "{dup 6 29 div ge {dup dup mul mul} {4 29 div sub 108 841 div mul} ifelse 0.824900 mul} bind\n");
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
489 490 491 492 493 494 495
}



// Outputs a table of words. It does use 16 bits

static
496
void Emit1Gamma(cmsIOHANDLER* m, cmsToneCurve* Table)
D
duke 已提交
497
{
498 499
    cmsUInt32Number i;
    cmsFloat64Number gamma;
D
duke 已提交
500

B
bae 已提交
501
    if (Table == NULL) return; // Error
D
duke 已提交
502

503
    if (Table ->nEntries <= 0) return;  // Empty table
D
duke 已提交
504 505

    // Suppress whole if identity
506
    if (cmsIsToneCurveLinear(Table)) return;
D
duke 已提交
507 508

    // Check if is really an exponential. If so, emit "exp"
509
    gamma = cmsEstimateGamma(Table, 0.001);
D
duke 已提交
510
     if (gamma > 0) {
511
            _cmsIOPrintf(m, "{ %g exp } bind ", gamma);
D
duke 已提交
512 513 514
            return;
     }

515
    _cmsIOPrintf(m, "{ ");
D
duke 已提交
516 517 518 519 520 521 522 523 524

    // Bounds check
    EmitRangeCheck(m);

    // Emit intepolation code

    // PostScript code                      Stack
    // ===============                      ========================
                                            // v
525
    _cmsIOPrintf(m, " [");
D
duke 已提交
526

527 528
    for (i=0; i < Table->nEntries; i++) {
        _cmsIOPrintf(m, "%d ", Table->Table16[i]);
D
duke 已提交
529 530
    }

531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    _cmsIOPrintf(m, "] ");                        // v tab

    _cmsIOPrintf(m, "dup ");                      // v tab tab
    _cmsIOPrintf(m, "length 1 sub ");             // v tab dom
    _cmsIOPrintf(m, "3 -1 roll ");                // tab dom v
    _cmsIOPrintf(m, "mul ");                      // tab val2
    _cmsIOPrintf(m, "dup ");                      // tab val2 val2
    _cmsIOPrintf(m, "dup ");                      // tab val2 val2 val2
    _cmsIOPrintf(m, "floor cvi ");                // tab val2 val2 cell0
    _cmsIOPrintf(m, "exch ");                     // tab val2 cell0 val2
    _cmsIOPrintf(m, "ceiling cvi ");              // tab val2 cell0 cell1
    _cmsIOPrintf(m, "3 index ");                  // tab val2 cell0 cell1 tab
    _cmsIOPrintf(m, "exch ");                     // tab val2 cell0 tab cell1
    _cmsIOPrintf(m, "get ");                      // tab val2 cell0 y1
    _cmsIOPrintf(m, "4 -1 roll ");                // val2 cell0 y1 tab
    _cmsIOPrintf(m, "3 -1 roll ");                // val2 y1 tab cell0
    _cmsIOPrintf(m, "get ");                      // val2 y1 y0
    _cmsIOPrintf(m, "dup ");                      // val2 y1 y0 y0
    _cmsIOPrintf(m, "3 1 roll ");                 // val2 y0 y1 y0
    _cmsIOPrintf(m, "sub ");                      // val2 y0 (y1-y0)
    _cmsIOPrintf(m, "3 -1 roll ");                // y0 (y1-y0) val2
    _cmsIOPrintf(m, "dup ");                      // y0 (y1-y0) val2 val2
    _cmsIOPrintf(m, "floor cvi ");                // y0 (y1-y0) val2 floor(val2)
    _cmsIOPrintf(m, "sub ");                      // y0 (y1-y0) rest
    _cmsIOPrintf(m, "mul ");                      // y0 t1
    _cmsIOPrintf(m, "add ");                      // y
    _cmsIOPrintf(m, "65535 div ");                // result

    _cmsIOPrintf(m, " } bind ");
D
duke 已提交
560 561 562 563 564 565
}


// Compare gamma table

static
P
prr 已提交
566
cmsBool GammaTableEquals(cmsUInt16Number* g1, cmsUInt16Number* g2, cmsUInt32Number nEntries)
D
duke 已提交
567
{
568
    return memcmp(g1, g2, nEntries* sizeof(cmsUInt16Number)) == 0;
D
duke 已提交
569 570 571 572 573 574
}


// Does write a set of gamma curves

static
P
prr 已提交
575
void EmitNGamma(cmsIOHANDLER* m, cmsUInt32Number n, cmsToneCurve* g[])
D
duke 已提交
576
{
P
prr 已提交
577
    cmsUInt32Number i;
D
duke 已提交
578 579 580

    for( i=0; i < n; i++ )
    {
B
bae 已提交
581 582
        if (g[i] == NULL) return; // Error

583
        if (i > 0 && GammaTableEquals(g[i-1]->Table16, g[i]->Table16, g[i]->nEntries)) {
D
duke 已提交
584

585
            _cmsIOPrintf(m, "dup ");
D
duke 已提交
586 587
        }
        else {
588
            Emit1Gamma(m, g[i]);
D
duke 已提交
589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
        }
    }

}





// Following code dumps a LUT onto memory stream


// This is the sampler. Intended to work in SAMPLER_INSPECT mode,
// that is, the callback will be called for each knot with
//
//          In[]  The grid location coordinates, normalized to 0..ffff
605
//          Out[] The Pipeline values, normalized to 0..ffff
D
duke 已提交
606 607 608
//
//  Returning a value other than 0 does terminate the sampling process
//
609
//  Each row contains Pipeline values for all but first component. So, I
D
duke 已提交
610
//  detect row changing by keeping a copy of last value of first
611
//  component. -1 is used to mark beginning of whole block.
D
duke 已提交
612 613

static
614
int OutputValueSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
D
duke 已提交
615
{
616 617
    cmsPsSamplerCargo* sc = (cmsPsSamplerCargo*) Cargo;
    cmsUInt32Number i;
D
duke 已提交
618 619 620 621


    if (sc -> FixWhite) {

622
        if (In[0] == 0xFFFF) {  // Only in L* = 100, ab = [-8..8]
D
duke 已提交
623

624 625
            if ((In[1] >= 0x7800 && In[1] <= 0x8800) &&
                (In[2] >= 0x7800 && In[2] <= 0x8800)) {
D
duke 已提交
626

627 628 629
                cmsUInt16Number* Black;
                cmsUInt16Number* White;
                cmsUInt32Number nOutputs;
D
duke 已提交
630 631 632 633

                if (!_cmsEndPointsBySpace(sc ->ColorSpace, &White, &Black, &nOutputs))
                        return 0;

634
                for (i=0; i < nOutputs; i++)
D
duke 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648
                        Out[i] = White[i];
            }


        }
    }


    // Hadle the parenthesis on rows

    if (In[0] != sc ->FirstComponent) {

            if (sc ->FirstComponent != -1) {

649
                    _cmsIOPrintf(sc ->m, sc ->PostMin);
D
duke 已提交
650
                    sc ->SecondComponent = -1;
651
                    _cmsIOPrintf(sc ->m, sc ->PostMaj);
D
duke 已提交
652 653 654
            }

            // Begin block
655
            _cmsPSActualColumn = 0;
D
duke 已提交
656

657
            _cmsIOPrintf(sc ->m, sc ->PreMaj);
D
duke 已提交
658 659 660 661 662 663 664 665
            sc ->FirstComponent = In[0];
    }


      if (In[1] != sc ->SecondComponent) {

            if (sc ->SecondComponent != -1) {

666
                    _cmsIOPrintf(sc ->m, sc ->PostMin);
D
duke 已提交
667 668
            }

669
            _cmsIOPrintf(sc ->m, sc ->PreMin);
D
duke 已提交
670 671 672
            sc ->SecondComponent = In[1];
    }

673
      // Dump table.
D
duke 已提交
674

675
      for (i=0; i < sc -> Pipeline ->Params->nOutputs; i++) {
D
duke 已提交
676

677 678
          cmsUInt16Number wWordOut = Out[i];
          cmsUInt8Number wByteOut;           // Value as byte
D
duke 已提交
679

B
bae 已提交
680

681
          // We always deal with Lab4
D
duke 已提交
682

683 684 685
          wByteOut = Word2Byte(wWordOut);
          WriteByte(sc -> m, wByteOut);
      }
D
duke 已提交
686

687
      return 1;
D
duke 已提交
688 689
}

690
// Writes a Pipeline on memstream. Could be 8 or 16 bits based
D
duke 已提交
691 692

static
693 694 695 696 697 698
void WriteCLUT(cmsIOHANDLER* m, cmsStage* mpe, const char* PreMaj,
                                             const char* PostMaj,
                                             const char* PreMin,
                                             const char* PostMin,
                                             int FixWhite,
                                             cmsColorSpaceSignature ColorSpace)
D
duke 已提交
699
{
700 701
    cmsUInt32Number i;
    cmsPsSamplerCargo sc;
D
duke 已提交
702 703 704

    sc.FirstComponent = -1;
    sc.SecondComponent = -1;
705
    sc.Pipeline = (_cmsStageCLutData *) mpe ->Data;
D
duke 已提交
706 707 708 709
    sc.m   = m;
    sc.PreMaj = PreMaj;
    sc.PostMaj= PostMaj;

710 711
    sc.PreMin   = PreMin;
    sc.PostMin  = PostMin;
D
duke 已提交
712 713 714
    sc.FixWhite = FixWhite;
    sc.ColorSpace = ColorSpace;

715
    _cmsIOPrintf(m, "[");
D
duke 已提交
716

717 718
    for (i=0; i < sc.Pipeline->Params->nInputs; i++)
        _cmsIOPrintf(m, " %d ", sc.Pipeline->Params->nSamples[i]);
D
duke 已提交
719

720
    _cmsIOPrintf(m, " [\n");
D
duke 已提交
721

722
    cmsStageSampleCLut16bit(mpe, OutputValueSampler, (void*) &sc, SAMPLER_INSPECT);
D
duke 已提交
723

724 725 726
    _cmsIOPrintf(m, PostMin);
    _cmsIOPrintf(m, PostMaj);
    _cmsIOPrintf(m, "] ");
D
duke 已提交
727 728 729 730 731 732 733

}


// Dumps CIEBasedA Color Space Array

static
734
int EmitCIEBasedA(cmsIOHANDLER* m, cmsToneCurve* Curve, cmsCIEXYZ* BlackPoint)
D
duke 已提交
735 736
{

737 738
    _cmsIOPrintf(m, "[ /CIEBasedA\n");
    _cmsIOPrintf(m, "  <<\n");
D
duke 已提交
739

740
    _cmsIOPrintf(m, "/DecodeA ");
D
duke 已提交
741

742
    Emit1Gamma(m, Curve);
D
duke 已提交
743

744
    _cmsIOPrintf(m, " \n");
D
duke 已提交
745

746 747
    _cmsIOPrintf(m, "/MatrixA [ 0.9642 1.0000 0.8249 ]\n");
    _cmsIOPrintf(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
D
duke 已提交
748

749 750
    EmitWhiteBlackD50(m, BlackPoint);
    EmitIntent(m, INTENT_PERCEPTUAL);
D
duke 已提交
751

752 753
    _cmsIOPrintf(m, ">>\n");
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
754

755
    return 1;
D
duke 已提交
756 757 758 759 760 761
}


// Dumps CIEBasedABC Color Space Array

static
762
int EmitCIEBasedABC(cmsIOHANDLER* m, cmsFloat64Number* Matrix, cmsToneCurve** CurveSet, cmsCIEXYZ* BlackPoint)
D
duke 已提交
763 764 765
{
    int i;

766 767 768
    _cmsIOPrintf(m, "[ /CIEBasedABC\n");
    _cmsIOPrintf(m, "<<\n");
    _cmsIOPrintf(m, "/DecodeABC [ ");
D
duke 已提交
769

770
    EmitNGamma(m, 3, CurveSet);
D
duke 已提交
771

772
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
773

774
    _cmsIOPrintf(m, "/MatrixABC [ " );
D
duke 已提交
775

776
    for( i=0; i < 3; i++ ) {
D
duke 已提交
777

B
bae 已提交
778 779 780
        _cmsIOPrintf(m, "%.6f %.6f %.6f ", Matrix[i + 3*0],
                                           Matrix[i + 3*1],
                                           Matrix[i + 3*2]);
781
    }
D
duke 已提交
782 783


784
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
785

786
    _cmsIOPrintf(m, "/RangeLMN [ 0.0 0.9642 0.0 1.0000 0.0 0.8249 ]\n");
D
duke 已提交
787

788 789
    EmitWhiteBlackD50(m, BlackPoint);
    EmitIntent(m, INTENT_PERCEPTUAL);
D
duke 已提交
790

791 792
    _cmsIOPrintf(m, ">>\n");
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
793 794


795
    return 1;
D
duke 已提交
796 797 798 799
}


static
P
prr 已提交
800
int EmitCIEBasedDEF(cmsIOHANDLER* m, cmsPipeline* Pipeline, cmsUInt32Number Intent, cmsCIEXYZ* BlackPoint)
D
duke 已提交
801 802 803 804
{
    const char* PreMaj;
    const char* PostMaj;
    const char* PreMin, *PostMin;
805
    cmsStage* mpe;
D
duke 已提交
806

807 808 809
    mpe = Pipeline ->Elements;

    switch (cmsStageInputChannels(mpe)) {
D
duke 已提交
810 811
    case 3:

812
            _cmsIOPrintf(m, "[ /CIEBasedDEF\n");
D
duke 已提交
813 814 815 816 817
            PreMaj ="<";
            PostMaj= ">\n";
            PreMin = PostMin = "";
            break;
    case 4:
818
            _cmsIOPrintf(m, "[ /CIEBasedDEFG\n");
D
duke 已提交
819 820 821 822 823 824 825 826 827 828
            PreMaj = "[";
            PostMaj = "]\n";
            PreMin = "<";
            PostMin = ">\n";
            break;
    default:
            return 0;

    }

829
    _cmsIOPrintf(m, "<<\n");
D
duke 已提交
830

831
    if (cmsStageType(mpe) == cmsSigCurveSetElemType) {
D
duke 已提交
832

833 834 835 836 837
        _cmsIOPrintf(m, "/DecodeDEF [ ");
        EmitNGamma(m, cmsStageOutputChannels(mpe), _cmsStageGetPtrToCurveSet(mpe));
        _cmsIOPrintf(m, "]\n");

        mpe = mpe ->Next;
D
duke 已提交
838 839
    }

840
    if (cmsStageType(mpe) == cmsSigCLutElemType) {
D
duke 已提交
841

842 843 844
            _cmsIOPrintf(m, "/Table ");
            WriteCLUT(m, mpe, PreMaj, PostMaj, PreMin, PostMin, FALSE, (cmsColorSpaceSignature) 0);
            _cmsIOPrintf(m, "]\n");
D
duke 已提交
845 846 847 848 849 850
    }

    EmitLab2XYZ(m);
    EmitWhiteBlackD50(m, BlackPoint);
    EmitIntent(m, Intent);

851 852
    _cmsIOPrintf(m, "   >>\n");
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
853 854 855 856 857 858 859

    return 1;
}

// Generates a curve from a gray profile

static
P
prr 已提交
860
cmsToneCurve* ExtractGray2Y(cmsContext ContextID, cmsHPROFILE hProfile, cmsUInt32Number Intent)
D
duke 已提交
861
{
862 863 864
    cmsToneCurve* Out = cmsBuildTabulatedToneCurve16(ContextID, 256, NULL);
    cmsHPROFILE hXYZ  = cmsCreateXYZProfile();
    cmsHTRANSFORM xform = cmsCreateTransformTHR(ContextID, hProfile, TYPE_GRAY_8, hXYZ, TYPE_XYZ_DBL, Intent, cmsFLAGS_NOOPTIMIZE);
D
duke 已提交
865 866
    int i;

P
prr 已提交
867
    if (Out != NULL && xform != NULL) {
B
bae 已提交
868
        for (i=0; i < 256; i++) {
D
duke 已提交
869

B
bae 已提交
870 871
            cmsUInt8Number Gray = (cmsUInt8Number) i;
            cmsCIEXYZ XYZ;
D
duke 已提交
872

B
bae 已提交
873
            cmsDoTransform(xform, &Gray, &XYZ, 1);
D
duke 已提交
874

B
bae 已提交
875 876
            Out ->Table16[i] =_cmsQuickSaturateWord(XYZ.Y * 65535.0);
        }
D
duke 已提交
877 878
    }

P
prr 已提交
879 880
    if (xform) cmsDeleteTransform(xform);
    if (hXYZ) cmsCloseProfile(hXYZ);
D
duke 已提交
881 882 883 884 885
    return Out;
}



886
// Because PostScript has only 8 bits in /Table, we should use
D
duke 已提交
887 888 889
// a more perceptually uniform space... I do choose Lab.

static
P
prr 已提交
890
int WriteInputLUT(cmsIOHANDLER* m, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
D
duke 已提交
891 892 893
{
    cmsHPROFILE hLab;
    cmsHTRANSFORM xform;
894 895
    cmsUInt32Number nChannels;
    cmsUInt32Number InputFormat;
D
duke 已提交
896 897 898 899 900 901 902
    int rc;
    cmsHPROFILE Profiles[2];
    cmsCIEXYZ BlackPointAdaptedToD50;

    // Does create a device-link based transform.
    // The DeviceLink is next dumped as working CSA.

903 904
    InputFormat = cmsFormatterForColorspaceOfProfile(hProfile, 2, FALSE);
    nChannels   = T_CHANNELS(InputFormat);
D
duke 已提交
905 906


907
    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, Intent, 0);
D
duke 已提交
908

909 910
    // Adjust output to Lab4
    hLab = cmsCreateLab4ProfileTHR(m ->ContextID, NULL);
D
duke 已提交
911

912 913
    Profiles[0] = hProfile;
    Profiles[1] = hLab;
D
duke 已提交
914

915 916
    xform = cmsCreateMultiprofileTransform(Profiles, 2,  InputFormat, TYPE_Lab_DBL, Intent, 0);
    cmsCloseProfile(hLab);
D
duke 已提交
917 918 919

    if (xform == NULL) {

920 921
        cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Cannot create transform Profile -> Lab");
        return 0;
D
duke 已提交
922 923 924 925 926 927 928
    }

    // Only 1, 3 and 4 channels are allowed

    switch (nChannels) {

    case 1: {
B
bae 已提交
929
            cmsToneCurve* Gray2Y = ExtractGray2Y(m ->ContextID, hProfile, Intent);
930 931
            EmitCIEBasedA(m, Gray2Y, &BlackPointAdaptedToD50);
            cmsFreeToneCurve(Gray2Y);
D
duke 已提交
932 933 934 935 936
            }
            break;

    case 3:
    case 4: {
B
bae 已提交
937
            cmsUInt32Number OutFrm = TYPE_Lab_16;
938 939 940 941 942 943 944
            cmsPipeline* DeviceLink;
            _cmsTRANSFORM* v = (_cmsTRANSFORM*) xform;

            DeviceLink = cmsPipelineDup(v ->Lut);
            if (DeviceLink == NULL) return 0;

            dwFlags |= cmsFLAGS_FORCE_CLUT;
P
prr 已提交
945
            _cmsOptimizePipeline(m->ContextID, &DeviceLink, Intent, &InputFormat, &OutFrm, &dwFlags);
946 947 948

            rc = EmitCIEBasedDEF(m, DeviceLink, Intent, &BlackPointAdaptedToD50);
            cmsPipelineFree(DeviceLink);
P
prr 已提交
949
            if (rc == 0) return 0;
D
duke 已提交
950 951 952 953 954
            }
            break;

    default:

955 956
        cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Only 3, 4 channels supported for CSA. This profile has %d channels.", nChannels);
        return 0;
D
duke 已提交
957 958 959 960
    }


    cmsDeleteTransform(xform);
961

D
duke 已提交
962 963 964
    return 1;
}

965 966 967 968 969 970 971
static
cmsFloat64Number* GetPtrToMatrix(const cmsStage* mpe)
{
    _cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;

    return Data -> Double;
}
D
duke 已提交
972 973 974 975


// Does create CSA based on matrix-shaper. Allowed types are gray and RGB based
static
976
int WriteInputMatrixShaper(cmsIOHANDLER* m, cmsHPROFILE hProfile, cmsStage* Matrix, cmsStage* Shaper)
D
duke 已提交
977
{
978
    cmsColorSpaceSignature ColorSpace;
D
duke 已提交
979 980 981 982 983
    int rc;
    cmsCIEXYZ BlackPointAdaptedToD50;

    ColorSpace = cmsGetColorSpace(hProfile);

984
    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, INTENT_RELATIVE_COLORIMETRIC, 0);
D
duke 已提交
985

986
    if (ColorSpace == cmsSigGrayData) {
D
duke 已提交
987

988
        cmsToneCurve** ShaperCurve = _cmsStageGetPtrToCurveSet(Shaper);
B
bae 已提交
989
        rc = EmitCIEBasedA(m, ShaperCurve[0], &BlackPointAdaptedToD50);
D
duke 已提交
990 991 992

    }
    else
993
        if (ColorSpace == cmsSigRgbData) {
D
duke 已提交
994

B
bae 已提交
995 996 997 998 999
            cmsMAT3 Mat;
            int i, j;

            memmove(&Mat, GetPtrToMatrix(Matrix), sizeof(Mat));

P
prr 已提交
1000 1001
            for (i = 0; i < 3; i++)
                for (j = 0; j < 3; j++)
B
bae 已提交
1002 1003
                    Mat.v[i].n[j] *= MAX_ENCODEABLE_XYZ;

P
prr 已提交
1004 1005 1006
            rc = EmitCIEBasedABC(m, (cmsFloat64Number *)&Mat,
                _cmsStageGetPtrToCurveSet(Shaper),
                &BlackPointAdaptedToD50);
D
duke 已提交
1007
        }
P
prr 已提交
1008
        else {
D
duke 已提交
1009

P
prr 已提交
1010
            cmsSignalError(m->ContextID, cmsERROR_COLORSPACE_CHECK, "Profile is not suitable for CSA. Unsupported colorspace.");
D
duke 已提交
1011 1012 1013
            return 0;
        }

B
bae 已提交
1014
        return rc;
D
duke 已提交
1015 1016 1017 1018 1019 1020 1021 1022
}



// Creates a PostScript color list from a named profile data.
// This is a HP extension, and it works in Lab instead of XYZ

static
P
prr 已提交
1023
int WriteNamedColorCSA(cmsIOHANDLER* m, cmsHPROFILE hNamedColor, cmsUInt32Number Intent)
D
duke 已提交
1024 1025 1026
{
    cmsHTRANSFORM xform;
    cmsHPROFILE   hLab;
P
prr 已提交
1027 1028
    cmsUInt32Number i, nColors;
    char ColorName[cmsMAX_PATH];
1029
    cmsNAMEDCOLORLIST* NamedColorList;
D
duke 已提交
1030

1031 1032
    hLab  = cmsCreateLab4ProfileTHR(m ->ContextID, NULL);
    xform = cmsCreateTransform(hNamedColor, TYPE_NAMED_COLOR_INDEX, hLab, TYPE_Lab_DBL, Intent, 0);
D
duke 已提交
1033 1034
    if (xform == NULL) return 0;

1035 1036
    NamedColorList = cmsGetNamedColorList(xform);
    if (NamedColorList == NULL) return 0;
D
duke 已提交
1037

1038 1039 1040 1041
    _cmsIOPrintf(m, "<<\n");
    _cmsIOPrintf(m, "(colorlistcomment) (%s)\n", "Named color CSA");
    _cmsIOPrintf(m, "(Prefix) [ (Pantone ) (PANTONE ) ]\n");
    _cmsIOPrintf(m, "(Suffix) [ ( CV) ( CVC) ( C) ]\n");
D
duke 已提交
1042

1043
    nColors   = cmsNamedColorCount(NamedColorList);
D
duke 已提交
1044 1045 1046 1047


    for (i=0; i < nColors; i++) {

1048
        cmsUInt16Number In[1];
D
duke 已提交
1049 1050
        cmsCIELab Lab;

1051
        In[0] = (cmsUInt16Number) i;
D
duke 已提交
1052

1053
        if (!cmsNamedColorInfo(NamedColorList, i, ColorName, NULL, NULL, NULL, NULL))
D
duke 已提交
1054 1055 1056
                continue;

        cmsDoTransform(xform, In, &Lab, 1);
1057
        _cmsIOPrintf(m, "  (%s) [ %.3f %.3f %.3f ]\n", ColorName, Lab.L, Lab.a, Lab.b);
D
duke 已提交
1058 1059 1060 1061
    }



1062
    _cmsIOPrintf(m, ">>\n");
D
duke 已提交
1063 1064 1065 1066 1067 1068 1069 1070

    cmsDeleteTransform(xform);
    cmsCloseProfile(hLab);
    return 1;
}


// Does create a Color Space Array on XYZ colorspace for PostScript usage
1071 1072 1073 1074 1075 1076
static
cmsUInt32Number GenerateCSA(cmsContext ContextID,
                            cmsHPROFILE hProfile,
                            cmsUInt32Number Intent,
                            cmsUInt32Number dwFlags,
                            cmsIOHANDLER* mem)
D
duke 已提交
1077
{
1078 1079 1080
    cmsUInt32Number dwBytesUsed;
    cmsPipeline* lut = NULL;
    cmsStage* Matrix, *Shaper;
D
duke 已提交
1081 1082 1083


    // Is a named color profile?
1084
    if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
D
duke 已提交
1085

1086
        if (!WriteNamedColorCSA(mem, hProfile, Intent)) goto Error;
D
duke 已提交
1087 1088 1089 1090
    }
    else {


1091 1092 1093
        // Any profile class are allowed (including devicelink), but
        // output (PCS) colorspace must be XYZ or Lab
        cmsColorSpaceSignature ColorSpace = cmsGetPCS(hProfile);
D
duke 已提交
1094

1095 1096
        if (ColorSpace != cmsSigXYZData &&
            ColorSpace != cmsSigLabData) {
D
duke 已提交
1097

B
bae 已提交
1098 1099
                cmsSignalError(ContextID, cmsERROR_COLORSPACE_CHECK, "Invalid output color space");
                goto Error;
1100
        }
D
duke 已提交
1101 1102


1103 1104 1105
        // Read the lut with all necessary conversion stages
        lut = _cmsReadInputLUT(hProfile, Intent);
        if (lut == NULL) goto Error;
D
duke 已提交
1106 1107


1108 1109
        // Tone curves + matrix can be implemented without any LUT
        if (cmsPipelineCheckAndRetreiveStages(lut, 2, cmsSigCurveSetElemType, cmsSigMatrixElemType, &Shaper, &Matrix)) {
D
duke 已提交
1110

1111
            if (!WriteInputMatrixShaper(mem, hProfile, Matrix, Shaper)) goto Error;
D
duke 已提交
1112 1113

        }
1114
        else {
B
bae 已提交
1115 1116
           // We need a LUT for the rest
           if (!WriteInputLUT(mem, hProfile, Intent, dwFlags)) goto Error;
1117
        }
D
duke 已提交
1118 1119 1120 1121
    }


    // Done, keep memory usage
1122
    dwBytesUsed = mem ->UsedSpace;
D
duke 已提交
1123

1124 1125
    // Get rid of LUT
    if (lut != NULL) cmsPipelineFree(lut);
D
duke 已提交
1126 1127 1128

    // Finally, return used byte count
    return dwBytesUsed;
1129 1130 1131 1132

Error:
    if (lut != NULL) cmsPipelineFree(lut);
    return 0;
D
duke 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
}

// ------------------------------------------------------ Color Rendering Dictionary (CRD)



/*

  Black point compensation plus chromatic adaptation:

  Step 1 - Chromatic adaptation
  =============================

          WPout
    X = ------- PQR
          Wpin

  Step 2 - Black point compensation
  =================================

          (WPout - BPout)*X - WPout*(BPin - BPout)
    out = ---------------------------------------
                        WPout - BPin


  Algorithm discussion
  ====================

  TransformPQR(WPin, BPin, WPout, BPout, PQR)

  Wpin,etc= { Xws Yws Zws Pws Qws Rws }


  Algorithm             Stack 0...n
  ===========================================================
                        PQR BPout WPout BPin WPin
  4 index 3 get         WPin PQR BPout WPout BPin WPin
  div                   (PQR/WPin) BPout WPout BPin WPin
  2 index 3 get         WPout (PQR/WPin) BPout WPout BPin WPin
  mult                  WPout*(PQR/WPin) BPout WPout BPin WPin

  2 index 3 get         WPout WPout*(PQR/WPin) BPout WPout BPin WPin
  2 index 3 get         BPout WPout WPout*(PQR/WPin) BPout WPout BPin WPin
  sub                   (WPout-BPout) WPout*(PQR/WPin) BPout WPout BPin WPin
  mult                  (WPout-BPout)* WPout*(PQR/WPin) BPout WPout BPin WPin

  2 index 3 get         WPout (BPout-WPout)* WPout*(PQR/WPin) BPout WPout BPin WPin
  4 index 3 get         BPin WPout (BPout-WPout)* WPout*(PQR/WPin) BPout WPout BPin WPin
  3 index 3 get         BPout BPin WPout (BPout-WPout)* WPout*(PQR/WPin) BPout WPout BPin WPin

  sub                   (BPin-BPout) WPout (BPout-WPout)* WPout*(PQR/WPin) BPout WPout BPin WPin
  mult                  (BPin-BPout)*WPout (BPout-WPout)* WPout*(PQR/WPin) BPout WPout BPin WPin
  sub                   (BPout-WPout)* WPout*(PQR/WPin)-(BPin-BPout)*WPout BPout WPout BPin WPin

  3 index 3 get         BPin (BPout-WPout)* WPout*(PQR/WPin)-(BPin-BPout)*WPout BPout WPout BPin WPin
  3 index 3 get         WPout BPin (BPout-WPout)* WPout*(PQR/WPin)-(BPin-BPout)*WPout BPout WPout BPin WPin
  exch
  sub                   (WPout-BPin) (BPout-WPout)* WPout*(PQR/WPin)-(BPin-BPout)*WPout BPout WPout BPin WPin
  div

  exch pop
  exch pop
  exch pop
  exch pop

*/


static
1202
void EmitPQRStage(cmsIOHANDLER* m, cmsHPROFILE hProfile, int DoBPC, int lIsAbsolute)
D
duke 已提交
1203 1204 1205
{


1206
        if (lIsAbsolute) {
D
duke 已提交
1207

1208
            // For absolute colorimetric intent, encode back to relative
1209
            // and generate a relative Pipeline
D
duke 已提交
1210

1211
            // Relative encoding is obtained across XYZpcs*(D50/WhitePoint)
D
duke 已提交
1212

1213 1214
            cmsCIEXYZ White;

1215
            _cmsReadMediaWhitePoint(&White, hProfile);
D
duke 已提交
1216

1217 1218
            _cmsIOPrintf(m,"/MatrixPQR [1 0 0 0 1 0 0 0 1 ]\n");
            _cmsIOPrintf(m,"/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
D
duke 已提交
1219

1220
            _cmsIOPrintf(m, "%% Absolute colorimetric -- encode to relative to maximize LUT usage\n"
D
duke 已提交
1221
                      "/TransformPQR [\n"
1222 1223 1224
                      "{0.9642 mul %g div exch pop exch pop exch pop exch pop} bind\n"
                      "{1.0000 mul %g div exch pop exch pop exch pop exch pop} bind\n"
                      "{0.8249 mul %g div exch pop exch pop exch pop exch pop} bind\n]\n",
B
bae 已提交
1225
                      White.X, White.Y, White.Z);
D
duke 已提交
1226 1227 1228 1229
            return;
        }


1230
        _cmsIOPrintf(m,"%% Bradford Cone Space\n"
1231 1232
                 "/MatrixPQR [0.8951 -0.7502 0.0389 0.2664 1.7135 -0.0685 -0.1614 0.0367 1.0296 ] \n");

1233
        _cmsIOPrintf(m, "/RangePQR [ -0.5 2 -0.5 2 -0.5 2 ]\n");
1234 1235


D
duke 已提交
1236 1237 1238 1239
        // No BPC

        if (!DoBPC) {

1240
            _cmsIOPrintf(m, "%% VonKries-like transform in Bradford Cone Space\n"
D
duke 已提交
1241 1242 1243 1244 1245 1246 1247 1248
                      "/TransformPQR [\n"
                      "{exch pop exch 3 get mul exch pop exch 3 get div} bind\n"
                      "{exch pop exch 4 get mul exch pop exch 4 get div} bind\n"
                      "{exch pop exch 5 get mul exch pop exch 5 get div} bind\n]\n");
        } else {

            // BPC

1249
            _cmsIOPrintf(m, "%% VonKries-like transform in Bradford Cone Space plus BPC\n"
D
duke 已提交
1250 1251
                      "/TransformPQR [\n");

1252
            _cmsIOPrintf(m, "{4 index 3 get div 2 index 3 get mul "
D
duke 已提交
1253 1254 1255 1256 1257
                    "2 index 3 get 2 index 3 get sub mul "
                    "2 index 3 get 4 index 3 get 3 index 3 get sub mul sub "
                    "3 index 3 get 3 index 3 get exch sub div "
                    "exch pop exch pop exch pop exch pop } bind\n");

1258
            _cmsIOPrintf(m, "{4 index 4 get div 2 index 4 get mul "
D
duke 已提交
1259 1260 1261 1262 1263
                    "2 index 4 get 2 index 4 get sub mul "
                    "2 index 4 get 4 index 4 get 3 index 4 get sub mul sub "
                    "3 index 4 get 3 index 4 get exch sub div "
                    "exch pop exch pop exch pop exch pop } bind\n");

1264
            _cmsIOPrintf(m, "{4 index 5 get div 2 index 5 get mul "
D
duke 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276
                    "2 index 5 get 2 index 5 get sub mul "
                    "2 index 5 get 4 index 5 get 3 index 5 get sub mul sub "
                    "3 index 5 get 3 index 5 get exch sub div "
                    "exch pop exch pop exch pop exch pop } bind\n]\n");

        }


}


static
1277
void EmitXYZ2Lab(cmsIOHANDLER* m)
D
duke 已提交
1278
{
1279 1280 1281 1282 1283 1284 1285 1286
    _cmsIOPrintf(m, "/RangeLMN [ -0.635 2.0 0 2 -0.635 2.0 ]\n");
    _cmsIOPrintf(m, "/EncodeLMN [\n");
    _cmsIOPrintf(m, "{ 0.964200  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
    _cmsIOPrintf(m, "{ 1.000000  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
    _cmsIOPrintf(m, "{ 0.824900  div dup 0.008856 le {7.787 mul 16 116 div add}{1 3 div exp} ifelse } bind\n");
    _cmsIOPrintf(m, "]\n");
    _cmsIOPrintf(m, "/MatrixABC [ 0 1 0 1 -1 1 0 0 -1 ]\n");
    _cmsIOPrintf(m, "/EncodeABC [\n");
D
duke 已提交
1287 1288


1289 1290 1291
    _cmsIOPrintf(m, "{ 116 mul  16 sub 100 div  } bind\n");
    _cmsIOPrintf(m, "{ 500 mul 128 add 256 div  } bind\n");
    _cmsIOPrintf(m, "{ 200 mul 128 add 256 div  } bind\n");
D
duke 已提交
1292 1293


1294
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305


}

// Due to impedance mismatch between XYZ and almost all RGB and CMYK spaces
// I choose to dump LUTS in Lab instead of XYZ. There is still a lot of wasted
// space on 3D CLUT, but since space seems not to be a problem here, 33 points
// would give a reasonable accurancy. Note also that CRD tables must operate in
// 8 bits.

static
P
prr 已提交
1306
int WriteOutputLUT(cmsIOHANDLER* m, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
D
duke 已提交
1307 1308 1309
{
    cmsHPROFILE hLab;
    cmsHTRANSFORM xform;
P
prr 已提交
1310
    cmsUInt32Number i, nChannels;
1311 1312 1313
    cmsUInt32Number OutputFormat;
    _cmsTRANSFORM* v;
    cmsPipeline* DeviceLink;
D
duke 已提交
1314 1315
    cmsHPROFILE Profiles[3];
    cmsCIEXYZ BlackPointAdaptedToD50;
P
prr 已提交
1316 1317
    cmsBool lDoBPC = (cmsBool) (dwFlags & cmsFLAGS_BLACKPOINTCOMPENSATION);
    cmsBool lFixWhite = (cmsBool) !(dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP);
1318
    cmsUInt32Number InFrm = TYPE_Lab_16;
P
prr 已提交
1319
    cmsUInt32Number RelativeEncodingIntent;
1320
    cmsColorSpaceSignature ColorSpace;
D
duke 已提交
1321 1322


1323 1324
    hLab = cmsCreateLab4ProfileTHR(m ->ContextID, NULL);
    if (hLab == NULL) return 0;
D
duke 已提交
1325

1326 1327
    OutputFormat = cmsFormatterForColorspaceOfProfile(hProfile, 2, FALSE);
    nChannels    = T_CHANNELS(OutputFormat);
D
duke 已提交
1328

1329
    ColorSpace = cmsGetColorSpace(hProfile);
D
duke 已提交
1330

1331
    // For absolute colorimetric, the LUT is encoded as relative in order to preserve precision.
1332 1333 1334 1335 1336 1337

    RelativeEncodingIntent = Intent;
    if (RelativeEncodingIntent == INTENT_ABSOLUTE_COLORIMETRIC)
        RelativeEncodingIntent = INTENT_RELATIVE_COLORIMETRIC;


1338 1339 1340
    // Use V4 Lab always
    Profiles[0] = hLab;
    Profiles[1] = hProfile;
D
duke 已提交
1341

1342 1343 1344 1345
    xform = cmsCreateMultiprofileTransformTHR(m ->ContextID,
                                              Profiles, 2, TYPE_Lab_DBL,
                                              OutputFormat, RelativeEncodingIntent, 0);
    cmsCloseProfile(hLab);
D
duke 已提交
1346 1347 1348

    if (xform == NULL) {

1349 1350
        cmsSignalError(m ->ContextID, cmsERROR_COLORSPACE_CHECK, "Cannot create transform Lab -> Profile in CRD creation");
        return 0;
D
duke 已提交
1351 1352
    }

1353 1354 1355 1356
    // Get a copy of the internal devicelink
    v = (_cmsTRANSFORM*) xform;
    DeviceLink = cmsPipelineDup(v ->Lut);
    if (DeviceLink == NULL) return 0;
D
duke 已提交
1357 1358


1359 1360
    // We need a CLUT
    dwFlags |= cmsFLAGS_FORCE_CLUT;
P
prr 已提交
1361
    _cmsOptimizePipeline(m->ContextID, &DeviceLink, RelativeEncodingIntent, &InFrm, &OutputFormat, &dwFlags);
D
duke 已提交
1362

1363 1364
    _cmsIOPrintf(m, "<<\n");
    _cmsIOPrintf(m, "/ColorRenderingType 1\n");
D
duke 已提交
1365 1366


1367
    cmsDetectBlackPoint(&BlackPointAdaptedToD50, hProfile, Intent, 0);
D
duke 已提交
1368 1369 1370

    // Emit headers, etc.
    EmitWhiteBlackD50(m, &BlackPointAdaptedToD50);
1371
    EmitPQRStage(m, hProfile, lDoBPC, Intent == INTENT_ABSOLUTE_COLORIMETRIC);
D
duke 已提交
1372 1373 1374 1375 1376 1377 1378 1379 1380
    EmitXYZ2Lab(m);


    // FIXUP: map Lab (100, 0, 0) to perfect white, because the particular encoding for Lab
    // does map a=b=0 not falling into any specific node. Since range a,b goes -128..127,
    // zero is slightly moved towards right, so assure next node (in L=100 slice) is mapped to
    // zero. This would sacrifice a bit of highlights, but failure to do so would cause
    // scum dot. Ouch.

1381 1382 1383
    if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
            lFixWhite = FALSE;

1384
    _cmsIOPrintf(m, "/RenderTable ");
D
duke 已提交
1385 1386


1387 1388 1389
    WriteCLUT(m, cmsPipelineGetPtrToFirstStage(DeviceLink), "<", ">\n", "", "", lFixWhite, ColorSpace);

    _cmsIOPrintf(m, " %d {} bind ", nChannels);
D
duke 已提交
1390 1391

    for (i=1; i < nChannels; i++)
1392
            _cmsIOPrintf(m, "dup ");
D
duke 已提交
1393

1394
    _cmsIOPrintf(m, "]\n");
D
duke 已提交
1395 1396 1397 1398


    EmitIntent(m, Intent);

1399
    _cmsIOPrintf(m, ">>\n");
D
duke 已提交
1400 1401 1402

    if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {

1403
        _cmsIOPrintf(m, "/Current exch /ColorRendering defineresource pop\n");
D
duke 已提交
1404 1405
    }

1406
    cmsPipelineFree(DeviceLink);
D
duke 已提交
1407 1408 1409 1410 1411 1412 1413 1414
    cmsDeleteTransform(xform);

    return 1;
}


// Builds a ASCII string containing colorant list in 0..1.0 range
static
P
prr 已提交
1415
void BuildColorantList(char *Colorant, cmsUInt32Number nColorant, cmsUInt16Number Out[])
D
duke 已提交
1416 1417
{
    char Buff[32];
P
prr 已提交
1418
    cmsUInt32Number j;
D
duke 已提交
1419 1420

    Colorant[0] = 0;
1421 1422
    if (nColorant > cmsMAXCHANNELS)
        nColorant = cmsMAXCHANNELS;
1423

1424
    for (j = 0; j < nColorant; j++) {
D
duke 已提交
1425

1426 1427 1428 1429 1430
        snprintf(Buff, 31, "%.3f", Out[j] / 65535.0);
        Buff[31] = 0;
        strcat(Colorant, Buff);
        if (j < nColorant - 1)
            strcat(Colorant, " ");
D
duke 已提交
1431

1432
    }
D
duke 已提交
1433 1434 1435 1436 1437 1438 1439
}


// Creates a PostScript color list from a named profile data.
// This is a HP extension.

static
P
prr 已提交
1440
int WriteNamedColorCRD(cmsIOHANDLER* m, cmsHPROFILE hNamedColor, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
D
duke 已提交
1441 1442
{
    cmsHTRANSFORM xform;
P
prr 已提交
1443
    cmsUInt32Number i, nColors, nColorant;
1444
    cmsUInt32Number OutputFormat;
P
prr 已提交
1445
    char ColorName[cmsMAX_PATH];
D
duke 已提交
1446
    char Colorant[128];
1447
    cmsNAMEDCOLORLIST* NamedColorList;
D
duke 已提交
1448 1449


1450 1451 1452 1453 1454
    OutputFormat = cmsFormatterForColorspaceOfProfile(hNamedColor, 2, FALSE);
    nColorant    = T_CHANNELS(OutputFormat);


    xform = cmsCreateTransform(hNamedColor, TYPE_NAMED_COLOR_INDEX, NULL, OutputFormat, Intent, dwFlags);
D
duke 已提交
1455 1456 1457
    if (xform == NULL) return 0;


1458 1459
    NamedColorList = cmsGetNamedColorList(xform);
    if (NamedColorList == NULL) return 0;
D
duke 已提交
1460

1461 1462 1463 1464
    _cmsIOPrintf(m, "<<\n");
    _cmsIOPrintf(m, "(colorlistcomment) (%s) \n", "Named profile");
    _cmsIOPrintf(m, "(Prefix) [ (Pantone ) (PANTONE ) ]\n");
    _cmsIOPrintf(m, "(Suffix) [ ( CV) ( CVC) ( C) ]\n");
D
duke 已提交
1465

1466
    nColors   = cmsNamedColorCount(NamedColorList);
D
duke 已提交
1467 1468 1469

    for (i=0; i < nColors; i++) {

1470 1471
        cmsUInt16Number In[1];
        cmsUInt16Number Out[cmsMAXCHANNELS];
D
duke 已提交
1472

1473
        In[0] = (cmsUInt16Number) i;
D
duke 已提交
1474

1475
        if (!cmsNamedColorInfo(NamedColorList, i, ColorName, NULL, NULL, NULL, NULL))
D
duke 已提交
1476 1477 1478 1479
                continue;

        cmsDoTransform(xform, In, Out, 1);
        BuildColorantList(Colorant, nColorant, Out);
1480
        _cmsIOPrintf(m, "  (%s) [ %s ]\n", ColorName, Colorant);
D
duke 已提交
1481 1482
    }

1483
    _cmsIOPrintf(m, "   >>");
D
duke 已提交
1484 1485 1486

    if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {

1487
    _cmsIOPrintf(m, " /Current exch /HPSpotTable defineresource pop\n");
D
duke 已提交
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
    }

    cmsDeleteTransform(xform);
    return 1;
}



// This one does create a Color Rendering Dictionary.
// CRD are always LUT-Based, no matter if profile is
// implemented as matrix-shaper.

1500 1501 1502 1503 1504
static
cmsUInt32Number  GenerateCRD(cmsContext ContextID,
                             cmsHPROFILE hProfile,
                             cmsUInt32Number Intent, cmsUInt32Number dwFlags,
                             cmsIOHANDLER* mem)
D
duke 已提交
1505
{
1506
    cmsUInt32Number dwBytesUsed;
D
duke 已提交
1507 1508 1509

    if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {

1510
        EmitHeader(mem, "Color Rendering Dictionary (CRD)", hProfile);
D
duke 已提交
1511 1512 1513 1514
    }


    // Is a named color profile?
1515
    if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
D
duke 已提交
1516 1517

        if (!WriteNamedColorCRD(mem, hProfile, Intent, dwFlags)) {
1518
            return 0;
D
duke 已提交
1519 1520 1521 1522
        }
    }
    else {

1523
        // CRD are always implemented as LUT
D
duke 已提交
1524

1525 1526 1527
        if (!WriteOutputLUT(mem, hProfile, Intent, dwFlags)) {
            return 0;
        }
D
duke 已提交
1528 1529 1530 1531
    }

    if (!(dwFlags & cmsFLAGS_NODEFAULTRESOURCEDEF)) {

1532 1533
        _cmsIOPrintf(mem, "%%%%EndResource\n");
        _cmsIOPrintf(mem, "\n%% CRD End\n");
D
duke 已提交
1534 1535 1536
    }

    // Done, keep memory usage
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
    dwBytesUsed = mem ->UsedSpace;

    // Finally, return used byte count
    return dwBytesUsed;

    cmsUNUSED_PARAMETER(ContextID);
}




cmsUInt32Number CMSEXPORT cmsGetPostScriptColorResource(cmsContext ContextID,
B
bae 已提交
1549 1550 1551 1552 1553
                                                               cmsPSResourceType Type,
                                                               cmsHPROFILE hProfile,
                                                               cmsUInt32Number Intent,
                                                               cmsUInt32Number dwFlags,
                                                               cmsIOHANDLER* io)
1554 1555 1556 1557 1558 1559
{
    cmsUInt32Number  rc;


    switch (Type) {

B
bae 已提交
1560 1561 1562 1563 1564 1565 1566 1567
        case cmsPS_RESOURCE_CSA:
            rc = GenerateCSA(ContextID, hProfile, Intent, dwFlags, io);
            break;

        default:
        case cmsPS_RESOURCE_CRD:
            rc = GenerateCRD(ContextID, hProfile, Intent, dwFlags, io);
            break;
1568 1569 1570 1571 1572 1573 1574 1575
    }

    return rc;
}



cmsUInt32Number CMSEXPORT cmsGetPostScriptCRD(cmsContext ContextID,
B
bae 已提交
1576
                              cmsHPROFILE hProfile,
1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
                              cmsUInt32Number Intent, cmsUInt32Number dwFlags,
                              void* Buffer, cmsUInt32Number dwBufferLen)
{
    cmsIOHANDLER* mem;
    cmsUInt32Number dwBytesUsed;

    // Set up the serialization engine
    if (Buffer == NULL)
        mem = cmsOpenIOhandlerFromNULL(ContextID);
    else
        mem = cmsOpenIOhandlerFromMem(ContextID, Buffer, dwBufferLen, "w");

    if (!mem) return 0;

    dwBytesUsed =  cmsGetPostScriptColorResource(ContextID, cmsPS_RESOURCE_CRD, hProfile, Intent, dwFlags, mem);
D
duke 已提交
1592 1593

    // Get rid of memory stream
1594
    cmsCloseIOhandler(mem);
D
duke 已提交
1595 1596 1597 1598 1599 1600

    return dwBytesUsed;
}



1601 1602 1603 1604 1605 1606 1607
// Does create a Color Space Array on XYZ colorspace for PostScript usage
cmsUInt32Number CMSEXPORT cmsGetPostScriptCSA(cmsContext ContextID,
                                              cmsHPROFILE hProfile,
                                              cmsUInt32Number Intent,
                                              cmsUInt32Number dwFlags,
                                              void* Buffer,
                                              cmsUInt32Number dwBufferLen)
D
duke 已提交
1608
{
1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
    cmsIOHANDLER* mem;
    cmsUInt32Number dwBytesUsed;

    if (Buffer == NULL)
        mem = cmsOpenIOhandlerFromNULL(ContextID);
    else
        mem = cmsOpenIOhandlerFromMem(ContextID, Buffer, dwBufferLen, "w");

    if (!mem) return 0;

    dwBytesUsed =  cmsGetPostScriptColorResource(ContextID, cmsPS_RESOURCE_CSA, hProfile, Intent, dwFlags, mem);

    // Get rid of memory stream
    cmsCloseIOhandler(mem);

    return dwBytesUsed;

D
duke 已提交
1626
}