1 //--------------------------------------------------------------------------------- 2 // 3 // Little Color Management System 4 // Copyright (c) 1998-2013 Marti Maria Saguer 5 // 6 // Permission is hereby granted, free of charge, to any person obtaining 7 // a copy of this software and associated documentation files (the "Software"), 8 // to deal in the Software without restriction, including without limitation 9 // the rights to use, copy, modify, merge, publish, distribute, sublicense, 10 // and/or sell copies of the Software, and to permit persons to whom the Software 11 // is furnished to do so, subject to the following conditions: 12 // 13 // The above copyright notice and this permission notice shall be included in 14 // all copies or substantial portions of the Software. 15 // 16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 23 // 24 //--------------------------------------------------------------------------------- 25 // 26 #include "lcms2_internal.h" 27 28 // Tone curves are powerful constructs that can contain curves specified in diverse ways. 29 // The curve is stored in segments, where each segment can be sampled or specified by parameters. 30 // a 16.bit simplification of the *whole* curve is kept for optimization purposes. For float operation, 31 // each segment is evaluated separately. Plug-ins may be used to define new parametric schemes, 32 // each plug-in may define up to MAX_TYPES_IN_LCMS_PLUGIN functions types. For defining a function, 33 // the plug-in should provide the type id, how many parameters each type has, and a pointer to 34 // a procedure that evaluates the function. In the case of reverse evaluation, the evaluator will 35 // be called with the type id as a negative value, and a sampled version of the reversed curve 36 // will be built. 37 38 // ----------------------------------------------------------------- Implementation 39 // Maxim number of nodes 40 #define MAX_NODES_IN_CURVE 4097 41 #define MINUS_INF (-1E22F) 42 #define PLUS_INF (+1E22F) 43 44 // The list of supported parametric curves 45 typedef struct _cmsParametricCurvesCollection_st { 46 47 int nFunctions; // Number of supported functions in this chunk 48 int FunctionTypes[MAX_TYPES_IN_LCMS_PLUGIN]; // The identification types 49 int ParameterCount[MAX_TYPES_IN_LCMS_PLUGIN]; // Number of parameters for each function 50 cmsParametricCurveEvaluator Evaluator; // The evaluator 51 52 struct _cmsParametricCurvesCollection_st* Next; // Next in list 53 54 } _cmsParametricCurvesCollection; 55 56 // This is the default (built-in) evaluator 57 static cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R); 58 59 // The built-in list 60 static _cmsParametricCurvesCollection DefaultCurves = { 61 9, // # of curve types 62 { 1, 2, 3, 4, 5, 6, 7, 8, 108 }, // Parametric curve ID 63 { 1, 3, 4, 5, 7, 4, 5, 5, 1 }, // Parameters by type 64 DefaultEvalParametricFn, // Evaluator 65 NULL // Next in chain 66 }; 67 68 // Duplicates the zone of memory used by the plug-in in the new context 69 static 70 void DupPluginCurvesList(struct _cmsContext_struct* ctx, 71 const struct _cmsContext_struct* src) 72 { 73 _cmsCurvesPluginChunkType newHead = { NULL }; 74 _cmsParametricCurvesCollection* entry; 75 _cmsParametricCurvesCollection* Anterior = NULL; 76 _cmsCurvesPluginChunkType* head = (_cmsCurvesPluginChunkType*) src->chunks[CurvesPlugin]; 77 78 _cmsAssert(head != NULL); 79 80 // Walk the list copying all nodes 81 for (entry = head->ParametricCurves; 82 entry != NULL; 83 entry = entry ->Next) { 84 85 _cmsParametricCurvesCollection *newEntry = ( _cmsParametricCurvesCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsParametricCurvesCollection)); 86 87 if (newEntry == NULL) 88 return; 89 90 // We want to keep the linked list order, so this is a little bit tricky 91 newEntry -> Next = NULL; 92 if (Anterior) 93 Anterior -> Next = newEntry; 94 95 Anterior = newEntry; 96 97 if (newHead.ParametricCurves == NULL) 98 newHead.ParametricCurves = newEntry; 99 } 100 101 ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsCurvesPluginChunkType)); 102 } 103 104 // The allocator have to follow the chain 105 void _cmsAllocCurvesPluginChunk(struct _cmsContext_struct* ctx, 106 const struct _cmsContext_struct* src) 107 { 108 _cmsAssert(ctx != NULL); 109 110 if (src != NULL) { 111 112 // Copy all linked list 113 DupPluginCurvesList(ctx, src); 114 } 115 else { 116 static _cmsCurvesPluginChunkType CurvesPluginChunk = { NULL }; 117 ctx ->chunks[CurvesPlugin] = _cmsSubAllocDup(ctx ->MemPool, &CurvesPluginChunk, sizeof(_cmsCurvesPluginChunkType)); 118 } 119 } 120 121 122 // The linked list head 123 _cmsCurvesPluginChunkType _cmsCurvesPluginChunk = { NULL }; 124 125 // As a way to install new parametric curves 126 cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext ContextID, cmsPluginBase* Data) 127 { 128 _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin); 129 cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data; 130 _cmsParametricCurvesCollection* fl; 131 132 if (Data == NULL) { 133 134 ctx -> ParametricCurves = NULL; 135 return TRUE; 136 } 137 138 fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsParametricCurvesCollection)); 139 if (fl == NULL) return FALSE; 140 141 // Copy the parameters 142 fl ->Evaluator = Plugin ->Evaluator; 143 fl ->nFunctions = Plugin ->nFunctions; 144 145 // Make sure no mem overwrites 146 if (fl ->nFunctions > MAX_TYPES_IN_LCMS_PLUGIN) 147 fl ->nFunctions = MAX_TYPES_IN_LCMS_PLUGIN; 148 149 // Copy the data 150 memmove(fl->FunctionTypes, Plugin ->FunctionTypes, fl->nFunctions * sizeof(cmsUInt32Number)); 151 memmove(fl->ParameterCount, Plugin ->ParameterCount, fl->nFunctions * sizeof(cmsUInt32Number)); 152 153 // Keep linked list 154 fl ->Next = ctx->ParametricCurves; 155 ctx->ParametricCurves = fl; 156 157 // All is ok 158 return TRUE; 159 } 160 161 162 // Search in type list, return position or -1 if not found 163 static 164 int IsInSet(int Type, _cmsParametricCurvesCollection* c) 165 { 166 int i; 167 168 for (i=0; i < c ->nFunctions; i++) 169 if (abs(Type) == c ->FunctionTypes[i]) return i; 170 171 return -1; 172 } 173 174 175 // Search for the collection which contains a specific type 176 static 177 _cmsParametricCurvesCollection *GetParametricCurveByType(cmsContext ContextID, int Type, int* index) 178 { 179 _cmsParametricCurvesCollection* c; 180 int Position; 181 _cmsCurvesPluginChunkType* ctx = ( _cmsCurvesPluginChunkType*) _cmsContextGetClientChunk(ContextID, CurvesPlugin); 182 183 for (c = ctx->ParametricCurves; c != NULL; c = c ->Next) { 184 185 Position = IsInSet(Type, c); 186 187 if (Position != -1) { 188 if (index != NULL) 189 *index = Position; 190 return c; 191 } 192 } 193 // If none found, revert for defaults 194 for (c = &DefaultCurves; c != NULL; c = c ->Next) { 195 196 Position = IsInSet(Type, c); 197 198 if (Position != -1) { 199 if (index != NULL) 200 *index = Position; 201 return c; 202 } 203 } 204 205 return NULL; 206 } 207 208 // Low level allocate, which takes care of memory details. nEntries may be zero, and in this case 209 // no optimation curve is computed. nSegments may also be zero in the inverse case, where only the 210 // optimization curve is given. Both features simultaneously is an error 211 static 212 cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsInt32Number nEntries, 213 cmsInt32Number nSegments, const cmsCurveSegment* Segments, 214 const cmsUInt16Number* Values) 215 { 216 cmsToneCurve* p; 217 int i; 218 219 // We allow huge tables, which are then restricted for smoothing operations 220 if (nEntries > 65530 || nEntries < 0) { 221 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve of more than 65530 entries"); 222 return NULL; 223 } 224 225 if (nEntries <= 0 && nSegments <= 0) { 226 cmsSignalError(ContextID, cmsERROR_RANGE, "Couldn't create tone curve with zero segments and no table"); 227 return NULL; 228 } 229 230 // Allocate all required pointers, etc. 231 p = (cmsToneCurve*) _cmsMallocZero(ContextID, sizeof(cmsToneCurve)); 232 if (!p) return NULL; 233 234 // In this case, there are no segments 235 if (nSegments <= 0) { 236 p ->Segments = NULL; 237 p ->Evals = NULL; 238 } 239 else { 240 p ->Segments = (cmsCurveSegment*) _cmsCalloc(ContextID, nSegments, sizeof(cmsCurveSegment)); 241 if (p ->Segments == NULL) goto Error; 242 243 p ->Evals = (cmsParametricCurveEvaluator*) _cmsCalloc(ContextID, nSegments, sizeof(cmsParametricCurveEvaluator)); 244 if (p ->Evals == NULL) goto Error; 245 } 246 247 p -> nSegments = nSegments; 248 249 // This 16-bit table contains a limited precision representation of the whole curve and is kept for 250 // increasing xput on certain operations. 251 if (nEntries <= 0) { 252 p ->Table16 = NULL; 253 } 254 else { 255 p ->Table16 = (cmsUInt16Number*) _cmsCalloc(ContextID, nEntries, sizeof(cmsUInt16Number)); 256 if (p ->Table16 == NULL) goto Error; 257 } 258 259 p -> nEntries = nEntries; 260 261 // Initialize members if requested 262 if (Values != NULL && (nEntries > 0)) { 263 264 for (i=0; i < nEntries; i++) 265 p ->Table16[i] = Values[i]; 266 } 267 268 // Initialize the segments stuff. The evaluator for each segment is located and a pointer to it 269 // is placed in advance to maximize performance. 270 if (Segments != NULL && (nSegments > 0)) { 271 272 _cmsParametricCurvesCollection *c; 273 274 p ->SegInterp = (cmsInterpParams**) _cmsCalloc(ContextID, nSegments, sizeof(cmsInterpParams*)); 275 if (p ->SegInterp == NULL) goto Error; 276 277 for (i=0; i< nSegments; i++) { 278 279 // Type 0 is a special marker for table-based curves 280 if (Segments[i].Type == 0) 281 p ->SegInterp[i] = _cmsComputeInterpParams(ContextID, Segments[i].nGridPoints, 1, 1, NULL, CMS_LERP_FLAGS_FLOAT); 282 283 memmove(&p ->Segments[i], &Segments[i], sizeof(cmsCurveSegment)); 284 285 if (Segments[i].Type == 0 && Segments[i].SampledPoints != NULL) 286 p ->Segments[i].SampledPoints = (cmsFloat32Number*) _cmsDupMem(ContextID, Segments[i].SampledPoints, sizeof(cmsFloat32Number) * Segments[i].nGridPoints); 287 else 288 p ->Segments[i].SampledPoints = NULL; 289 290 291 c = GetParametricCurveByType(ContextID, Segments[i].Type, NULL); 292 if (c != NULL) 293 p ->Evals[i] = c ->Evaluator; 294 } 295 } 296 297 p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS); 298 if (p->InterpParams != NULL) 299 return p; 300 301 Error: 302 if (p -> Segments) _cmsFree(ContextID, p ->Segments); 303 if (p -> Evals) _cmsFree(ContextID, p -> Evals); 304 if (p ->Table16) _cmsFree(ContextID, p ->Table16); 305 _cmsFree(ContextID, p); 306 return NULL; 307 } 308 309 310 // Parametric Fn using floating point 311 static 312 cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Number Params[], cmsFloat64Number R) 313 { 314 cmsFloat64Number e, Val, disc; 315 316 switch (Type) { 317 318 // X = Y ^ Gamma 319 case 1: 320 if (R < 0) { 321 322 if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE) 323 Val = R; 324 else 325 Val = 0; 326 } 327 else 328 Val = pow(R, Params[0]); 329 break; 330 331 // Type 1 Reversed: X = Y ^1/gamma 332 case -1: 333 if (R < 0) { 334 335 if (fabs(Params[0] - 1.0) < MATRIX_DET_TOLERANCE) 336 Val = R; 337 else 338 Val = 0; 339 } 340 else 341 Val = pow(R, 1/Params[0]); 342 break; 343 344 // CIE 122-1966 345 // Y = (aX + b)^Gamma | X >= -b/a 346 // Y = 0 | else 347 case 2: 348 disc = -Params[2] / Params[1]; 349 350 if (R >= disc ) { 351 352 e = Params[1]*R + Params[2]; 353 354 if (e > 0) 355 Val = pow(e, Params[0]); 356 else 357 Val = 0; 358 } 359 else 360 Val = 0; 361 break; 362 363 // Type 2 Reversed 364 // X = (Y ^1/g - b) / a 365 case -2: 366 if (R < 0) 367 Val = 0; 368 else 369 Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1]; 370 371 if (Val < 0) 372 Val = 0; 373 break; 374 375 376 // IEC 61966-3 377 // Y = (aX + b)^Gamma | X <= -b/a 378 // Y = c | else 379 case 3: 380 disc = -Params[2] / Params[1]; 381 if (disc < 0) 382 disc = 0; 383 384 if (R >= disc) { 385 386 e = Params[1]*R + Params[2]; 387 388 if (e > 0) 389 Val = pow(e, Params[0]) + Params[3]; 390 else 391 Val = 0; 392 } 393 else 394 Val = Params[3]; 395 break; 396 397 398 // Type 3 reversed 399 // X=((Y-c)^1/g - b)/a | (Y>=c) 400 // X=-b/a | (Y<c) 401 case -3: 402 if (R >= Params[3]) { 403 404 e = R - Params[3]; 405 406 if (e > 0) 407 Val = (pow(e, 1/Params[0]) - Params[2]) / Params[1]; 408 else 409 Val = 0; 410 } 411 else { 412 Val = -Params[2] / Params[1]; 413 } 414 break; 415 416 417 // IEC 61966-2.1 (sRGB) 418 // Y = (aX + b)^Gamma | X >= d 419 // Y = cX | X < d 420 case 4: 421 if (R >= Params[4]) { 422 423 e = Params[1]*R + Params[2]; 424 425 if (e > 0) 426 Val = pow(e, Params[0]); 427 else 428 Val = 0; 429 } 430 else 431 Val = R * Params[3]; 432 break; 433 434 // Type 4 reversed 435 // X=((Y^1/g-b)/a) | Y >= (ad+b)^g 436 // X=Y/c | Y< (ad+b)^g 437 case -4: 438 e = Params[1] * Params[4] + Params[2]; 439 if (e < 0) 440 disc = 0; 441 else 442 disc = pow(e, Params[0]); 443 444 if (R >= disc) { 445 446 Val = (pow(R, 1.0/Params[0]) - Params[2]) / Params[1]; 447 } 448 else { 449 Val = R / Params[3]; 450 } 451 break; 452 453 454 // Y = (aX + b)^Gamma + e | X >= d 455 // Y = cX + f | X < d 456 case 5: 457 if (R >= Params[4]) { 458 459 e = Params[1]*R + Params[2]; 460 461 if (e > 0) 462 Val = pow(e, Params[0]) + Params[5]; 463 else 464 Val = Params[5]; 465 } 466 else 467 Val = R*Params[3] + Params[6]; 468 break; 469 470 471 // Reversed type 5 472 // X=((Y-e)1/g-b)/a | Y >=(ad+b)^g+e), cd+f 473 // X=(Y-f)/c | else 474 case -5: 475 476 disc = Params[3] * Params[4] + Params[6]; 477 if (R >= disc) { 478 479 e = R - Params[5]; 480 if (e < 0) 481 Val = 0; 482 else 483 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1]; 484 } 485 else { 486 Val = (R - Params[6]) / Params[3]; 487 } 488 break; 489 490 491 // Types 6,7,8 comes from segmented curves as described in ICCSpecRevision_02_11_06_Float.pdf 492 // Type 6 is basically identical to type 5 without d 493 494 // Y = (a * X + b) ^ Gamma + c 495 case 6: 496 e = Params[1]*R + Params[2]; 497 498 if (e < 0) 499 Val = Params[3]; 500 else 501 Val = pow(e, Params[0]) + Params[3]; 502 break; 503 504 // ((Y - c) ^1/Gamma - b) / a 505 case -6: 506 e = R - Params[3]; 507 if (e < 0) 508 Val = 0; 509 else 510 Val = (pow(e, 1.0/Params[0]) - Params[2]) / Params[1]; 511 break; 512 513 514 // Y = a * log (b * X^Gamma + c) + d 515 case 7: 516 517 e = Params[2] * pow(R, Params[0]) + Params[3]; 518 if (e <= 0) 519 Val = Params[4]; 520 else 521 Val = Params[1]*log10(e) + Params[4]; 522 break; 523 524 // (Y - d) / a = log(b * X ^Gamma + c) 525 // pow(10, (Y-d) / a) = b * X ^Gamma + c 526 // pow((pow(10, (Y-d) / a) - c) / b, 1/g) = X 527 case -7: 528 Val = pow((pow(10.0, (R-Params[4]) / Params[1]) - Params[3]) / Params[2], 1.0 / Params[0]); 529 break; 530 531 532 //Y = a * b^(c*X+d) + e 533 case 8: 534 Val = (Params[0] * pow(Params[1], Params[2] * R + Params[3]) + Params[4]); 535 break; 536 537 538 // Y = (log((y-e) / a) / log(b) - d ) / c 539 // a=0, b=1, c=2, d=3, e=4, 540 case -8: 541 542 disc = R - Params[4]; 543 if (disc < 0) Val = 0; 544 else 545 Val = (log(disc / Params[0]) / log(Params[1]) - Params[3]) / Params[2]; 546 break; 547 548 // S-Shaped: (1 - (1-x)^1/g)^1/g 549 case 108: 550 Val = pow(1.0 - pow(1 - R, 1/Params[0]), 1/Params[0]); 551 break; 552 553 // y = (1 - (1-x)^1/g)^1/g 554 // y^g = (1 - (1-x)^1/g) 555 // 1 - y^g = (1-x)^1/g 556 // (1 - y^g)^g = 1 - x 557 // 1 - (1 - y^g)^g 558 case -108: 559 Val = 1 - pow(1 - pow(R, Params[0]), Params[0]); 560 break; 561 562 default: 563 // Unsupported parametric curve. Should never reach here 564 return 0; 565 } 566 567 return Val; 568 } 569 570 // Evaluate a segmented function for a single value. Return -1 if no valid segment found . 571 // If fn type is 0, perform an interpolation on the table 572 static 573 cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R) 574 { 575 int i; 576 577 for (i = g ->nSegments-1; i >= 0 ; --i) { 578 579 // Check for domain 580 if ((R > g ->Segments[i].x0) && (R <= g ->Segments[i].x1)) { 581 582 // Type == 0 means segment is sampled 583 if (g ->Segments[i].Type == 0) { 584 585 cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0) / (g ->Segments[i].x1 - g ->Segments[i].x0); 586 cmsFloat32Number Out; 587 588 // Setup the table (TODO: clean that) 589 g ->SegInterp[i]-> Table = g ->Segments[i].SampledPoints; 590 591 g ->SegInterp[i] -> Interpolation.LerpFloat(&R1, &Out, g ->SegInterp[i]); 592 593 return Out; 594 } 595 else 596 return g ->Evals[i](g->Segments[i].Type, g ->Segments[i].Params, R); 597 } 598 } 599 600 return MINUS_INF; 601 } 602 603 // Access to estimated low-res table 604 cmsUInt32Number CMSEXPORT cmsGetToneCurveEstimatedTableEntries(const cmsToneCurve* t) 605 { 606 _cmsAssert(t != NULL); 607 return t ->nEntries; 608 } 609 610 const cmsUInt16Number* CMSEXPORT cmsGetToneCurveEstimatedTable(const cmsToneCurve* t) 611 { 612 _cmsAssert(t != NULL); 613 return t ->Table16; 614 } 615 616 617 // Create an empty gamma curve, by using tables. This specifies only the limited-precision part, and leaves the 618 // floating point description empty. 619 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurve16(cmsContext ContextID, cmsInt32Number nEntries, const cmsUInt16Number Values[]) 620 { 621 return AllocateToneCurveStruct(ContextID, nEntries, 0, NULL, Values); 622 } 623 624 static 625 int EntriesByGamma(cmsFloat64Number Gamma) 626 { 627 if (fabs(Gamma - 1.0) < 0.001) return 2; 628 return 4096; 629 } 630 631 632 // Create a segmented gamma, fill the table 633 cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID, 634 cmsInt32Number nSegments, const cmsCurveSegment Segments[]) 635 { 636 int i; 637 cmsFloat64Number R, Val; 638 cmsToneCurve* g; 639 int nGridPoints = 4096; 640 641 _cmsAssert(Segments != NULL); 642 643 // Optimizatin for identity curves. 644 if (nSegments == 1 && Segments[0].Type == 1) { 645 646 nGridPoints = EntriesByGamma(Segments[0].Params[0]); 647 } 648 649 g = AllocateToneCurveStruct(ContextID, nGridPoints, nSegments, Segments, NULL); 650 if (g == NULL) return NULL; 651 652 // Once we have the floating point version, we can approximate a 16 bit table of 4096 entries 653 // for performance reasons. This table would normally not be used except on 8/16 bits transforms. 654 for (i=0; i < nGridPoints; i++) { 655 656 R = (cmsFloat64Number) i / (nGridPoints-1); 657 658 Val = EvalSegmentedFn(g, R); 659 660 // Round and saturate 661 g ->Table16[i] = _cmsQuickSaturateWord(Val * 65535.0); 662 } 663 664 return g; 665 } 666 667 // Use a segmented curve to store the floating point table 668 cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[]) 669 { 670 cmsCurveSegment Seg[3]; 671 672 // A segmented tone curve should have function segments in the first and last positions 673 // Initialize segmented curve part up to 0 to constant value = samples[0] 674 Seg[0].x0 = MINUS_INF; 675 Seg[0].x1 = 0; 676 Seg[0].Type = 6; 677 678 Seg[0].Params[0] = 1; 679 Seg[0].Params[1] = 0; 680 Seg[0].Params[2] = 0; 681 Seg[0].Params[3] = values[0]; 682 Seg[0].Params[4] = 0; 683 684 // From zero to 1 685 Seg[1].x0 = 0; 686 Seg[1].x1 = 1.0; 687 Seg[1].Type = 0; 688 689 Seg[1].nGridPoints = nEntries; 690 Seg[1].SampledPoints = (cmsFloat32Number*) values; 691 692 // Final segment is constant = lastsample 693 Seg[2].x0 = 1.0; 694 Seg[2].x1 = PLUS_INF; 695 Seg[2].Type = 6; 696 697 Seg[2].Params[0] = 1; 698 Seg[2].Params[1] = 0; 699 Seg[2].Params[2] = 0; 700 Seg[2].Params[3] = values[nEntries-1]; 701 Seg[2].Params[4] = 0; 702 703 704 return cmsBuildSegmentedToneCurve(ContextID, 3, Seg); 705 } 706 707 // Parametric curves 708 // 709 // Parameters goes as: Curve, a, b, c, d, e, f 710 // Type is the ICC type +1 711 // if type is negative, then the curve is analyticaly inverted 712 cmsToneCurve* CMSEXPORT cmsBuildParametricToneCurve(cmsContext ContextID, cmsInt32Number Type, const cmsFloat64Number Params[]) 713 { 714 cmsCurveSegment Seg0; 715 int Pos = 0; 716 cmsUInt32Number size; 717 _cmsParametricCurvesCollection* c = GetParametricCurveByType(ContextID, Type, &Pos); 718 719 _cmsAssert(Params != NULL); 720 721 if (c == NULL) { 722 cmsSignalError(ContextID, cmsERROR_UNKNOWN_EXTENSION, "Invalid parametric curve type %d", Type); 723 return NULL; 724 } 725 726 memset(&Seg0, 0, sizeof(Seg0)); 727 728 Seg0.x0 = MINUS_INF; 729 Seg0.x1 = PLUS_INF; 730 Seg0.Type = Type; 731 732 size = c->ParameterCount[Pos] * sizeof(cmsFloat64Number); 733 memmove(Seg0.Params, Params, size); 734 735 return cmsBuildSegmentedToneCurve(ContextID, 1, &Seg0); 736 } 737 738 739 740 // Build a gamma table based on gamma constant 741 cmsToneCurve* CMSEXPORT cmsBuildGamma(cmsContext ContextID, cmsFloat64Number Gamma) 742 { 743 return cmsBuildParametricToneCurve(ContextID, 1, &Gamma); 744 } 745 746 747 // Free all memory taken by the gamma curve 748 void CMSEXPORT cmsFreeToneCurve(cmsToneCurve* Curve) 749 { 750 cmsContext ContextID; 751 752 // added by Xiaochuan Liu 753 // Curve->InterpParams may be null 754 if (Curve == NULL || Curve->InterpParams == NULL) return; 755 756 ContextID = Curve ->InterpParams->ContextID; 757 758 _cmsFreeInterpParams(Curve ->InterpParams); 759 Curve ->InterpParams = NULL; 760 761 if (Curve -> Table16) { 762 _cmsFree(ContextID, Curve ->Table16); 763 Curve ->Table16 = NULL; 764 } 765 766 if (Curve ->Segments) { 767 768 cmsUInt32Number i; 769 770 for (i=0; i < Curve ->nSegments; i++) { 771 772 if (Curve ->Segments[i].SampledPoints) { 773 _cmsFree(ContextID, Curve ->Segments[i].SampledPoints); 774 Curve ->Segments[i].SampledPoints = NULL; 775 } 776 777 if (Curve ->SegInterp[i] != 0) { 778 _cmsFreeInterpParams(Curve->SegInterp[i]); 779 Curve->SegInterp[i] = NULL; 780 } 781 } 782 783 _cmsFree(ContextID, Curve ->Segments); 784 Curve ->Segments = NULL; 785 _cmsFree(ContextID, Curve ->SegInterp); 786 Curve ->SegInterp = NULL; 787 } 788 789 if (Curve -> Evals) { 790 _cmsFree(ContextID, Curve -> Evals); 791 Curve -> Evals = NULL; 792 } 793 794 if (Curve) { 795 _cmsFree(ContextID, Curve); 796 Curve = NULL; 797 } 798 } 799 800 // Utility function, free 3 gamma tables 801 void CMSEXPORT cmsFreeToneCurveTriple(cmsToneCurve* Curve[3]) 802 { 803 804 _cmsAssert(Curve != NULL); 805 806 if (Curve[0] != NULL) cmsFreeToneCurve(Curve[0]); 807 if (Curve[1] != NULL) cmsFreeToneCurve(Curve[1]); 808 if (Curve[2] != NULL) cmsFreeToneCurve(Curve[2]); 809 810 Curve[0] = Curve[1] = Curve[2] = NULL; 811 } 812 813 814 // Duplicate a gamma table 815 cmsToneCurve* CMSEXPORT cmsDupToneCurve(const cmsToneCurve* In) 816 { 817 // Xiaochuan Liu 818 // fix openpdf bug(mantis id:0055683, google id:360198) 819 // the function CurveSetElemTypeFree in cmslut.c also needs to check pointer 820 if (In == NULL || In ->InterpParams == NULL || In ->Segments == NULL || In ->Table16 == NULL) return NULL; 821 822 return AllocateToneCurveStruct(In ->InterpParams ->ContextID, In ->nEntries, In ->nSegments, In ->Segments, In ->Table16); 823 } 824 825 // Joins two curves for X and Y. Curves should be monotonic. 826 // We want to get 827 // 828 // y = Y^-1(X(t)) 829 // 830 cmsToneCurve* CMSEXPORT cmsJoinToneCurve(cmsContext ContextID, 831 const cmsToneCurve* X, 832 const cmsToneCurve* Y, cmsUInt32Number nResultingPoints) 833 { 834 cmsToneCurve* out = NULL; 835 cmsToneCurve* Yreversed = NULL; 836 cmsFloat32Number t, x; 837 cmsFloat32Number* Res = NULL; 838 cmsUInt32Number i; 839 840 841 _cmsAssert(X != NULL); 842 _cmsAssert(Y != NULL); 843 844 Yreversed = cmsReverseToneCurveEx(nResultingPoints, Y); 845 if (Yreversed == NULL) goto Error; 846 847 Res = (cmsFloat32Number*) _cmsCalloc(ContextID, nResultingPoints, sizeof(cmsFloat32Number)); 848 if (Res == NULL) goto Error; 849 850 //Iterate 851 for (i=0; i < nResultingPoints; i++) { 852 853 t = (cmsFloat32Number) i / (nResultingPoints-1); 854 x = cmsEvalToneCurveFloat(X, t); 855 Res[i] = cmsEvalToneCurveFloat(Yreversed, x); 856 } 857 858 // Allocate space for output 859 out = cmsBuildTabulatedToneCurveFloat(ContextID, nResultingPoints, Res); 860 861 Error: 862 863 if (Res != NULL) _cmsFree(ContextID, Res); 864 if (Yreversed != NULL) cmsFreeToneCurve(Yreversed); 865 866 return out; 867 } 868 869 870 871 // Get the surrounding nodes. This is tricky on non-monotonic tables 872 static 873 int GetInterval(cmsFloat64Number In, const cmsUInt16Number LutTable[], const struct _cms_interp_struc* p) 874 { 875 int i; 876 int y0, y1; 877 878 // A 1 point table is not allowed 879 if (p -> Domain[0] < 1) return -1; 880 881 // Let's see if ascending or descending. 882 if (LutTable[0] < LutTable[p ->Domain[0]]) { 883 884 // Table is overall ascending 885 for (i=p->Domain[0]-1; i >=0; --i) { 886 887 y0 = LutTable[i]; 888 y1 = LutTable[i+1]; 889 890 if (y0 <= y1) { // Increasing 891 if (In >= y0 && In <= y1) return i; 892 } 893 else 894 if (y1 < y0) { // Decreasing 895 if (In >= y1 && In <= y0) return i; 896 } 897 } 898 } 899 else { 900 // Table is overall descending 901 for (i=0; i < (int) p -> Domain[0]; i++) { 902 903 y0 = LutTable[i]; 904 y1 = LutTable[i+1]; 905 906 if (y0 <= y1) { // Increasing 907 if (In >= y0 && In <= y1) return i; 908 } 909 else 910 if (y1 < y0) { // Decreasing 911 if (In >= y1 && In <= y0) return i; 912 } 913 } 914 } 915 916 return -1; 917 } 918 919 // Reverse a gamma table 920 cmsToneCurve* CMSEXPORT cmsReverseToneCurveEx(cmsInt32Number nResultSamples, const cmsToneCurve* InCurve) 921 { 922 cmsToneCurve *out; 923 cmsFloat64Number a = 0, b = 0, y, x1, y1, x2, y2; 924 int i, j; 925 int Ascending; 926 927 _cmsAssert(InCurve != NULL); 928 929 // Try to reverse it analytically whatever possible 930 931 if (InCurve ->nSegments == 1 && InCurve ->Segments[0].Type > 0 && 932 /* InCurve -> Segments[0].Type <= 5 */ 933 GetParametricCurveByType(InCurve ->InterpParams->ContextID, InCurve ->Segments[0].Type, NULL) != NULL) { 934 935 return cmsBuildParametricToneCurve(InCurve ->InterpParams->ContextID, 936 -(InCurve -> Segments[0].Type), 937 InCurve -> Segments[0].Params); 938 } 939 940 // Nope, reverse the table. 941 out = cmsBuildTabulatedToneCurve16(InCurve ->InterpParams->ContextID, nResultSamples, NULL); 942 if (out == NULL) 943 return NULL; 944 945 // We want to know if this is an ascending or descending table 946 Ascending = !cmsIsToneCurveDescending(InCurve); 947 948 // Iterate across Y axis 949 for (i=0; i < nResultSamples; i++) { 950 951 y = (cmsFloat64Number) i * 65535.0 / (nResultSamples - 1); 952 953 // Find interval in which y is within. 954 j = GetInterval(y, InCurve->Table16, InCurve->InterpParams); 955 if (j >= 0) { 956 957 958 // Get limits of interval 959 x1 = InCurve ->Table16[j]; 960 x2 = InCurve ->Table16[j+1]; 961 962 y1 = (cmsFloat64Number) (j * 65535.0) / (InCurve ->nEntries - 1); 963 y2 = (cmsFloat64Number) ((j+1) * 65535.0 ) / (InCurve ->nEntries - 1); 964 965 // If collapsed, then use any 966 if (x1 == x2) { 967 968 out ->Table16[i] = _cmsQuickSaturateWord(Ascending ? y2 : y1); 969 continue; 970 971 } else { 972 973 // Interpolate 974 a = (y2 - y1) / (x2 - x1); 975 b = y2 - a * x2; 976 } 977 } 978 979 out ->Table16[i] = _cmsQuickSaturateWord(a* y + b); 980 } 981 982 983 return out; 984 } 985 986 // Reverse a gamma table 987 cmsToneCurve* CMSEXPORT cmsReverseToneCurve(const cmsToneCurve* InGamma) 988 { 989 _cmsAssert(InGamma != NULL); 990 991 return cmsReverseToneCurveEx(4096, InGamma); 992 } 993 994 // From: Eilers, P.H.C. (1994) Smoothing and interpolation with finite 995 // differences. in: Graphic Gems IV, Heckbert, P.S. (ed.), Academic press. 996 // 997 // Smoothing and interpolation with second differences. 998 // 999 // Input: weights (w), data (y): vector from 1 to m. 1000 // Input: smoothing parameter (lambda), length (m). 1001 // Output: smoothed vector (z): vector from 1 to m. 1002 1003 static 1004 cmsBool smooth2(cmsContext ContextID, cmsFloat32Number w[], cmsFloat32Number y[], cmsFloat32Number z[], cmsFloat32Number lambda, int m) 1005 { 1006 int i, i1, i2; 1007 cmsFloat32Number *c, *d, *e; 1008 cmsBool st; 1009 1010 1011 c = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number)); 1012 d = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number)); 1013 e = (cmsFloat32Number*) _cmsCalloc(ContextID, MAX_NODES_IN_CURVE, sizeof(cmsFloat32Number)); 1014 1015 if (c != NULL && d != NULL && e != NULL) { 1016 1017 1018 d[1] = w[1] + lambda; 1019 c[1] = -2 * lambda / d[1]; 1020 e[1] = lambda /d[1]; 1021 z[1] = w[1] * y[1]; 1022 d[2] = w[2] + 5 * lambda - d[1] * c[1] * c[1]; 1023 c[2] = (-4 * lambda - d[1] * c[1] * e[1]) / d[2]; 1024 e[2] = lambda / d[2]; 1025 z[2] = w[2] * y[2] - c[1] * z[1]; 1026 1027 for (i = 3; i < m - 1; i++) { 1028 i1 = i - 1; i2 = i - 2; 1029 d[i]= w[i] + 6 * lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2]; 1030 c[i] = (-4 * lambda -d[i1] * c[i1] * e[i1])/ d[i]; 1031 e[i] = lambda / d[i]; 1032 z[i] = w[i] * y[i] - c[i1] * z[i1] - e[i2] * z[i2]; 1033 } 1034 1035 i1 = m - 2; i2 = m - 3; 1036 1037 d[m - 1] = w[m - 1] + 5 * lambda -c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2]; 1038 c[m - 1] = (-2 * lambda - d[i1] * c[i1] * e[i1]) / d[m - 1]; 1039 z[m - 1] = w[m - 1] * y[m - 1] - c[i1] * z[i1] - e[i2] * z[i2]; 1040 i1 = m - 1; i2 = m - 2; 1041 1042 d[m] = w[m] + lambda - c[i1] * c[i1] * d[i1] - e[i2] * e[i2] * d[i2]; 1043 z[m] = (w[m] * y[m] - c[i1] * z[i1] - e[i2] * z[i2]) / d[m]; 1044 z[m - 1] = z[m - 1] / d[m - 1] - c[m - 1] * z[m]; 1045 1046 for (i = m - 2; 1<= i; i--) 1047 z[i] = z[i] / d[i] - c[i] * z[i + 1] - e[i] * z[i + 2]; 1048 1049 st = TRUE; 1050 } 1051 else st = FALSE; 1052 1053 if (c != NULL) _cmsFree(ContextID, c); 1054 if (d != NULL) _cmsFree(ContextID, d); 1055 if (e != NULL) _cmsFree(ContextID, e); 1056 1057 return st; 1058 } 1059 1060 // Smooths a curve sampled at regular intervals. 1061 cmsBool CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda) 1062 { 1063 cmsFloat32Number w[MAX_NODES_IN_CURVE], y[MAX_NODES_IN_CURVE], z[MAX_NODES_IN_CURVE]; 1064 int i, nItems, Zeros, Poles; 1065 1066 if (Tab == NULL) return FALSE; 1067 1068 if (cmsIsToneCurveLinear(Tab)) return TRUE; // Nothing to do 1069 1070 nItems = Tab -> nEntries; 1071 1072 if (nItems >= MAX_NODES_IN_CURVE) { 1073 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: too many points."); 1074 return FALSE; 1075 } 1076 1077 memset(w, 0, nItems * sizeof(cmsFloat32Number)); 1078 memset(y, 0, nItems * sizeof(cmsFloat32Number)); 1079 memset(z, 0, nItems * sizeof(cmsFloat32Number)); 1080 1081 for (i=0; i < nItems; i++) 1082 { 1083 y[i+1] = (cmsFloat32Number) Tab -> Table16[i]; 1084 w[i+1] = 1.0; 1085 } 1086 1087 if (!smooth2(Tab ->InterpParams->ContextID, w, y, z, (cmsFloat32Number) lambda, nItems)) return FALSE; 1088 1089 // Do some reality - checking... 1090 Zeros = Poles = 0; 1091 for (i=nItems; i > 1; --i) { 1092 1093 if (z[i] == 0.) Zeros++; 1094 if (z[i] >= 65535.) Poles++; 1095 if (z[i] < z[i-1]) { 1096 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic."); 1097 return FALSE; 1098 } 1099 } 1100 1101 if (Zeros > (nItems / 3)) { 1102 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros."); 1103 return FALSE; 1104 } 1105 if (Poles > (nItems / 3)) { 1106 cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles."); 1107 return FALSE; 1108 } 1109 1110 // Seems ok 1111 for (i=0; i < nItems; i++) { 1112 1113 // Clamp to cmsUInt16Number 1114 Tab -> Table16[i] = _cmsQuickSaturateWord(z[i+1]); 1115 } 1116 1117 return TRUE; 1118 } 1119 1120 // Is a table linear? Do not use parametric since we cannot guarantee some weird parameters resulting 1121 // in a linear table. This way assures it is linear in 12 bits, which should be enought in most cases. 1122 cmsBool CMSEXPORT cmsIsToneCurveLinear(const cmsToneCurve* Curve) 1123 { 1124 cmsUInt32Number i; 1125 int diff; 1126 1127 _cmsAssert(Curve != NULL); 1128 1129 for (i=0; i < Curve ->nEntries; i++) { 1130 1131 diff = abs((int) Curve->Table16[i] - (int) _cmsQuantizeVal(i, Curve ->nEntries)); 1132 if (diff > 0x0f) 1133 return FALSE; 1134 } 1135 1136 return TRUE; 1137 } 1138 1139 // Same, but for monotonicity 1140 cmsBool CMSEXPORT cmsIsToneCurveMonotonic(const cmsToneCurve* t) 1141 { 1142 int n; 1143 int i, last; 1144 cmsBool lDescending; 1145 1146 _cmsAssert(t != NULL); 1147 1148 // Degenerated curves are monotonic? Ok, let's pass them 1149 n = t ->nEntries; 1150 if (n < 2) return TRUE; 1151 1152 // Curve direction 1153 lDescending = cmsIsToneCurveDescending(t); 1154 1155 if (lDescending) { 1156 1157 last = t ->Table16[0]; 1158 1159 for (i = 1; i < n; i++) { 1160 1161 if (t ->Table16[i] - last > 2) // We allow some ripple 1162 return FALSE; 1163 else 1164 last = t ->Table16[i]; 1165 1166 } 1167 } 1168 else { 1169 1170 last = t ->Table16[n-1]; 1171 1172 for (i = n-2; i >= 0; --i) { 1173 1174 if (t ->Table16[i] - last > 2) 1175 return FALSE; 1176 else 1177 last = t ->Table16[i]; 1178 1179 } 1180 } 1181 1182 return TRUE; 1183 } 1184 1185 // Same, but for descending tables 1186 cmsBool CMSEXPORT cmsIsToneCurveDescending(const cmsToneCurve* t) 1187 { 1188 _cmsAssert(t != NULL); 1189 1190 return t ->Table16[0] > t ->Table16[t ->nEntries-1]; 1191 } 1192 1193 1194 // Another info fn: is out gamma table multisegment? 1195 cmsBool CMSEXPORT cmsIsToneCurveMultisegment(const cmsToneCurve* t) 1196 { 1197 _cmsAssert(t != NULL); 1198 1199 return t -> nSegments > 1; 1200 } 1201 1202 cmsInt32Number CMSEXPORT cmsGetToneCurveParametricType(const cmsToneCurve* t) 1203 { 1204 _cmsAssert(t != NULL); 1205 1206 if (t -> nSegments != 1) return 0; 1207 return t ->Segments[0].Type; 1208 } 1209 1210 // We need accuracy this time 1211 cmsFloat32Number CMSEXPORT cmsEvalToneCurveFloat(const cmsToneCurve* Curve, cmsFloat32Number v) 1212 { 1213 _cmsAssert(Curve != NULL); 1214 1215 // Check for 16 bits table. If so, this is a limited-precision tone curve 1216 if (Curve ->nSegments == 0) { 1217 1218 cmsUInt16Number In, Out; 1219 1220 In = (cmsUInt16Number) _cmsQuickSaturateWord(v * 65535.0); 1221 Out = cmsEvalToneCurve16(Curve, In); 1222 1223 return (cmsFloat32Number) (Out / 65535.0); 1224 } 1225 1226 return (cmsFloat32Number) EvalSegmentedFn(Curve, v); 1227 } 1228 1229 // We need xput over here 1230 cmsUInt16Number CMSEXPORT cmsEvalToneCurve16(const cmsToneCurve* Curve, cmsUInt16Number v) 1231 { 1232 cmsUInt16Number out; 1233 1234 _cmsAssert(Curve != NULL); 1235 1236 Curve ->InterpParams ->Interpolation.Lerp16(&v, &out, Curve ->InterpParams); 1237 return out; 1238 } 1239 1240 1241 // Least squares fitting. 1242 // A mathematical procedure for finding the best-fitting curve to a given set of points by 1243 // minimizing the sum of the squares of the offsets ("the residuals") of the points from the curve. 1244 // The sum of the squares of the offsets is used instead of the offset absolute values because 1245 // this allows the residuals to be treated as a continuous differentiable quantity. 1246 // 1247 // y = f(x) = x ^ g 1248 // 1249 // R = (yi - (xi^g)) 1250 // R2 = (yi - (xi^g))2 1251 // SUM R2 = SUM (yi - (xi^g))2 1252 // 1253 // dR2/dg = -2 SUM x^g log(x)(y - x^g) 1254 // solving for dR2/dg = 0 1255 // 1256 // g = 1/n * SUM(log(y) / log(x)) 1257 1258 cmsFloat64Number CMSEXPORT cmsEstimateGamma(const cmsToneCurve* t, cmsFloat64Number Precision) 1259 { 1260 cmsFloat64Number gamma, sum, sum2; 1261 cmsFloat64Number n, x, y, Std; 1262 cmsUInt32Number i; 1263 1264 _cmsAssert(t != NULL); 1265 1266 sum = sum2 = n = 0; 1267 1268 // Excluding endpoints 1269 for (i=1; i < (MAX_NODES_IN_CURVE-1); i++) { 1270 1271 x = (cmsFloat64Number) i / (MAX_NODES_IN_CURVE-1); 1272 y = (cmsFloat64Number) cmsEvalToneCurveFloat(t, (cmsFloat32Number) x); 1273 1274 // Avoid 7% on lower part to prevent 1275 // artifacts due to linear ramps 1276 1277 if (y > 0. && y < 1. && x > 0.07) { 1278 1279 gamma = log(y) / log(x); 1280 sum += gamma; 1281 sum2 += gamma * gamma; 1282 n++; 1283 } 1284 } 1285 1286 // Take a look on SD to see if gamma isn't exponential at all 1287 Std = sqrt((n * sum2 - sum * sum) / (n*(n-1))); 1288 1289 if (Std > Precision) 1290 return -1.0; 1291 1292 return (sum / n); // The mean 1293 } 1294