comparison mupdf-source/thirdparty/lcms2/src/cmsopt.c @ 2:b50eed0cc0ef upstream

ADD: MuPDF v1.26.7: the MuPDF source as downloaded by a default build of PyMuPDF 1.26.4. The directory name has changed: no version number in the expanded directory now.
author Franz Glasner <fzglas.hg@dom66.de>
date Mon, 15 Sep 2025 11:43:07 +0200
parents
children
comparison
equal deleted inserted replaced
1:1d09e1dec1d9 2:b50eed0cc0ef
1 //---------------------------------------------------------------------------------
2 //
3 // Little Color Management System
4 // Copyright (c) 1998-2023 Marti Maria Saguer
5 //
6 // Permission is hereby granted, free of charge, to any person obtaining
7 // a copy of this software and associated documentation files (the "Software"),
8 // to deal in the Software without restriction, including without limitation
9 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 // and/or sell copies of the Software, and to permit persons to whom the Software
11 // is furnished to do so, subject to the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
18 // THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23 //
24 //---------------------------------------------------------------------------------
25 //
26
27 #include "lcms2_internal.h"
28
29
30 //----------------------------------------------------------------------------------
31
32 // Optimization for 8 bits, Shaper-CLUT (3 inputs only)
33 typedef struct {
34
35 cmsContext ContextID;
36
37 const cmsInterpParams* p; // Tetrahedrical interpolation parameters. This is a not-owned pointer.
38
39 cmsUInt16Number rx[256], ry[256], rz[256];
40 cmsUInt32Number X0[256], Y0[256], Z0[256]; // Precomputed nodes and offsets for 8-bit input data
41
42
43 } Prelin8Data;
44
45
46 // Generic optimization for 16 bits Shaper-CLUT-Shaper (any inputs)
47 typedef struct {
48
49 cmsContext ContextID;
50
51 // Number of channels
52 cmsUInt32Number nInputs;
53 cmsUInt32Number nOutputs;
54
55 _cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS]; // The maximum number of input channels is known in advance
56 cmsInterpParams* ParamsCurveIn16[MAX_INPUT_DIMENSIONS];
57
58 _cmsInterpFn16 EvalCLUT; // The evaluator for 3D grid
59 const cmsInterpParams* CLUTparams; // (not-owned pointer)
60
61
62 _cmsInterpFn16* EvalCurveOut16; // Points to an array of curve evaluators in 16 bits (not-owned pointer)
63 cmsInterpParams** ParamsCurveOut16; // Points to an array of references to interpolation params (not-owned pointer)
64
65
66 } Prelin16Data;
67
68
69 // Optimization for matrix-shaper in 8 bits. Numbers are operated in n.14 signed, tables are stored in 1.14 fixed
70
71 typedef cmsInt32Number cmsS1Fixed14Number; // Note that this may hold more than 16 bits!
72
73 #define DOUBLE_TO_1FIXED14(x) ((cmsS1Fixed14Number) floor((x) * 16384.0 + 0.5))
74
75 typedef struct {
76
77 cmsContext ContextID;
78
79 cmsS1Fixed14Number Shaper1R[256]; // from 0..255 to 1.14 (0.0...1.0)
80 cmsS1Fixed14Number Shaper1G[256];
81 cmsS1Fixed14Number Shaper1B[256];
82
83 cmsS1Fixed14Number Mat[3][3]; // n.14 to n.14 (needs a saturation after that)
84 cmsS1Fixed14Number Off[3];
85
86 cmsUInt16Number Shaper2R[16385]; // 1.14 to 0..255
87 cmsUInt16Number Shaper2G[16385];
88 cmsUInt16Number Shaper2B[16385];
89
90 } MatShaper8Data;
91
92 // Curves, optimization is shared between 8 and 16 bits
93 typedef struct {
94 cmsUInt32Number nCurves; // Number of curves
95 cmsUInt32Number nElements; // Elements in curves
96 cmsUInt16Number** Curves; // Points to a dynamically allocated array
97
98 } Curves16Data;
99
100
101 // Simple optimizations ----------------------------------------------------------------------------------------------------------
102
103
104 // Remove an element in linked chain
105 static
106 void _RemoveElement(cmsContext ContextID, cmsStage** head)
107 {
108 cmsStage* mpe = *head;
109 cmsStage* next = mpe ->Next;
110 *head = next;
111 cmsStageFree(ContextID, mpe);
112 }
113
114 // Remove all identities in chain. Note that pt actually is a double pointer to the element that holds the pointer.
115 static
116 cmsBool _Remove1Op(cmsContext ContextID, cmsPipeline* Lut, cmsStageSignature UnaryOp)
117 {
118 cmsStage** pt = &Lut ->Elements;
119 cmsBool AnyOpt = FALSE;
120
121 while (*pt != NULL) {
122
123 if ((*pt) ->Implements == UnaryOp) {
124 _RemoveElement(ContextID, pt);
125 AnyOpt = TRUE;
126 }
127 else
128 pt = &((*pt) -> Next);
129 }
130
131 return AnyOpt;
132 }
133
134 // Same, but only if two adjacent elements are found
135 static
136 cmsBool _Remove2Op(cmsContext ContextID, cmsPipeline* Lut, cmsStageSignature Op1, cmsStageSignature Op2)
137 {
138 cmsStage** pt1;
139 cmsStage** pt2;
140 cmsBool AnyOpt = FALSE;
141
142 pt1 = &Lut ->Elements;
143 if (*pt1 == NULL) return AnyOpt;
144
145 while (*pt1 != NULL) {
146
147 pt2 = &((*pt1) -> Next);
148 if (*pt2 == NULL) return AnyOpt;
149
150 if ((*pt1) ->Implements == Op1 && (*pt2) ->Implements == Op2) {
151 _RemoveElement(ContextID, pt2);
152 _RemoveElement(ContextID, pt1);
153 AnyOpt = TRUE;
154 }
155 else
156 pt1 = &((*pt1) -> Next);
157 }
158
159 return AnyOpt;
160 }
161
162
163 static
164 cmsBool CloseEnoughFloat(cmsFloat64Number a, cmsFloat64Number b)
165 {
166 return fabs(b - a) < 0.00001f;
167 }
168
169 static
170 cmsBool isFloatMatrixIdentity(cmsContext ContextID, const cmsMAT3* a)
171 {
172 cmsMAT3 Identity;
173 int i, j;
174
175 _cmsMAT3identity(ContextID, &Identity);
176
177 for (i = 0; i < 3; i++)
178 for (j = 0; j < 3; j++)
179 if (!CloseEnoughFloat(a->v[i].n[j], Identity.v[i].n[j])) return FALSE;
180
181 return TRUE;
182 }
183
184 // if two adjacent matrices are found, multiply them.
185 static
186 cmsBool _MultiplyMatrix(cmsContext ContextID, cmsPipeline* Lut)
187 {
188 cmsStage** pt1;
189 cmsStage** pt2;
190 cmsStage* chain;
191 cmsBool AnyOpt = FALSE;
192
193 pt1 = &Lut->Elements;
194 if (*pt1 == NULL) return AnyOpt;
195
196 while (*pt1 != NULL) {
197
198 pt2 = &((*pt1)->Next);
199 if (*pt2 == NULL) return AnyOpt;
200
201 if ((*pt1)->Implements == cmsSigMatrixElemType && (*pt2)->Implements == cmsSigMatrixElemType) {
202
203 // Get both matrices
204 _cmsStageMatrixData* m1 = (_cmsStageMatrixData*) cmsStageData(ContextID, *pt1);
205 _cmsStageMatrixData* m2 = (_cmsStageMatrixData*) cmsStageData(ContextID, *pt2);
206 cmsMAT3 res;
207
208 // Input offset and output offset should be zero to use this optimization
209 if (m1->Offset != NULL || m2 ->Offset != NULL ||
210 cmsStageInputChannels(ContextID, *pt1) != 3 || cmsStageOutputChannels(ContextID, *pt1) != 3 ||
211 cmsStageInputChannels(ContextID, *pt2) != 3 || cmsStageOutputChannels(ContextID, *pt2) != 3)
212 return FALSE;
213
214 // Multiply both matrices to get the result
215 _cmsMAT3per(ContextID, &res, (cmsMAT3*)m2->Double, (cmsMAT3*)m1->Double);
216
217 // Get the next in chain after the matrices
218 chain = (*pt2)->Next;
219
220 // Remove both matrices
221 _RemoveElement(ContextID, pt2);
222 _RemoveElement(ContextID, pt1);
223
224 // Now what if the result is a plain identity?
225 if (!isFloatMatrixIdentity(ContextID, &res)) {
226
227 // We can not get rid of full matrix
228 cmsStage* Multmat = cmsStageAllocMatrix(ContextID, 3, 3, (const cmsFloat64Number*) &res, NULL);
229 if (Multmat == NULL) return FALSE; // Should never happen
230
231 // Recover the chain
232 Multmat->Next = chain;
233 *pt1 = Multmat;
234 }
235
236 AnyOpt = TRUE;
237 }
238 else
239 pt1 = &((*pt1)->Next);
240 }
241
242 return AnyOpt;
243 }
244
245
246 // Preoptimize just gets rif of no-ops coming paired. Conversion from v2 to v4 followed
247 // by a v4 to v2 and vice-versa. The elements are then discarded.
248 static
249 cmsBool PreOptimize(cmsContext ContextID, cmsPipeline* Lut)
250 {
251 cmsBool AnyOpt = FALSE, Opt;
252
253 do {
254
255 Opt = FALSE;
256
257 // Remove all identities
258 Opt |= _Remove1Op(ContextID, Lut, cmsSigIdentityElemType);
259
260 // Remove XYZ2Lab followed by Lab2XYZ
261 Opt |= _Remove2Op(ContextID, Lut, cmsSigXYZ2LabElemType, cmsSigLab2XYZElemType);
262
263 // Remove Lab2XYZ followed by XYZ2Lab
264 Opt |= _Remove2Op(ContextID, Lut, cmsSigLab2XYZElemType, cmsSigXYZ2LabElemType);
265
266 // Remove V4 to V2 followed by V2 to V4
267 Opt |= _Remove2Op(ContextID, Lut, cmsSigLabV4toV2, cmsSigLabV2toV4);
268
269 // Remove V2 to V4 followed by V4 to V2
270 Opt |= _Remove2Op(ContextID, Lut, cmsSigLabV2toV4, cmsSigLabV4toV2);
271
272 // Remove float pcs Lab conversions
273 Opt |= _Remove2Op(ContextID, Lut, cmsSigLab2FloatPCS, cmsSigFloatPCS2Lab);
274
275 // Remove float pcs Lab conversions
276 Opt |= _Remove2Op(ContextID, Lut, cmsSigXYZ2FloatPCS, cmsSigFloatPCS2XYZ);
277
278 // Simplify matrix.
279 Opt |= _MultiplyMatrix(ContextID, Lut);
280
281 if (Opt) AnyOpt = TRUE;
282
283 } while (Opt);
284
285 return AnyOpt;
286 }
287
288 static
289 void Eval16nop1D(cmsContext ContextID,
290 CMSREGISTER const cmsUInt16Number Input[],
291 CMSREGISTER cmsUInt16Number Output[],
292 CMSREGISTER const struct _cms_interp_struc* p)
293 {
294 cmsUNUSED_PARAMETER(ContextID);
295 Output[0] = Input[0];
296
297 cmsUNUSED_PARAMETER(p);
298 }
299
300 static
301 void PrelinEval16(cmsContext ContextID,
302 CMSREGISTER const cmsUInt16Number Input[],
303 CMSREGISTER cmsUInt16Number Output[],
304 CMSREGISTER const void* D)
305 {
306 Prelin16Data* p16 = (Prelin16Data*) D;
307 cmsUInt16Number StageABC[MAX_INPUT_DIMENSIONS];
308 cmsUInt16Number StageDEF[cmsMAXCHANNELS];
309 cmsUInt32Number i;
310
311 for (i=0; i < p16 ->nInputs; i++) {
312
313 p16 ->EvalCurveIn16[i](ContextID, &Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);
314 }
315
316 p16 ->EvalCLUT(ContextID, StageABC, StageDEF, p16 ->CLUTparams);
317
318 for (i=0; i < p16 ->nOutputs; i++) {
319
320 p16 ->EvalCurveOut16[i](ContextID, &StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
321 }
322 }
323
324
325 static
326 void PrelinOpt16free(cmsContext ContextID, void* ptr)
327 {
328 Prelin16Data* p16 = (Prelin16Data*) ptr;
329
330 _cmsFree(ContextID, p16 ->EvalCurveOut16);
331 _cmsFree(ContextID, p16 ->ParamsCurveOut16);
332
333 _cmsFree(ContextID, p16);
334 }
335
336 static
337 void* Prelin16dup(cmsContext ContextID, const void* ptr)
338 {
339 Prelin16Data* p16 = (Prelin16Data*) ptr;
340 Prelin16Data* Duped = (Prelin16Data*) _cmsDupMem(ContextID, p16, sizeof(Prelin16Data));
341
342 if (Duped == NULL) return NULL;
343
344 Duped->EvalCurveOut16 = (_cmsInterpFn16*) _cmsDupMem(ContextID, p16->EvalCurveOut16, p16->nOutputs * sizeof(_cmsInterpFn16));
345 Duped->ParamsCurveOut16 = (cmsInterpParams**)_cmsDupMem(ContextID, p16->ParamsCurveOut16, p16->nOutputs * sizeof(cmsInterpParams*));
346
347 return Duped;
348 }
349
350
351 static
352 Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,
353 const cmsInterpParams* ColorMap,
354 cmsUInt32Number nInputs, cmsToneCurve** In,
355 cmsUInt32Number nOutputs, cmsToneCurve** Out )
356 {
357 cmsUInt32Number i;
358 Prelin16Data* p16 = (Prelin16Data*)_cmsMallocZero(ContextID, sizeof(Prelin16Data));
359 if (p16 == NULL) return NULL;
360
361 p16 ->nInputs = nInputs;
362 p16 ->nOutputs = nOutputs;
363
364
365 for (i=0; i < nInputs; i++) {
366
367 if (In == NULL) {
368 p16 -> ParamsCurveIn16[i] = NULL;
369 p16 -> EvalCurveIn16[i] = Eval16nop1D;
370
371 }
372 else {
373 p16 -> ParamsCurveIn16[i] = In[i] ->InterpParams;
374 p16 -> EvalCurveIn16[i] = p16 ->ParamsCurveIn16[i]->Interpolation.Lerp16;
375 }
376 }
377
378 p16 ->CLUTparams = ColorMap;
379 p16 ->EvalCLUT = ColorMap ->Interpolation.Lerp16;
380
381
382 p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));
383 if (p16->EvalCurveOut16 == NULL)
384 {
385 _cmsFree(ContextID, p16);
386 return NULL;
387 }
388
389 p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));
390 if (p16->ParamsCurveOut16 == NULL)
391 {
392
393 _cmsFree(ContextID, p16->EvalCurveOut16);
394 _cmsFree(ContextID, p16);
395 return NULL;
396 }
397
398 for (i=0; i < nOutputs; i++) {
399
400 if (Out == NULL) {
401 p16 ->ParamsCurveOut16[i] = NULL;
402 p16 -> EvalCurveOut16[i] = Eval16nop1D;
403 }
404 else {
405
406 p16 ->ParamsCurveOut16[i] = Out[i] ->InterpParams;
407 p16 -> EvalCurveOut16[i] = p16 ->ParamsCurveOut16[i]->Interpolation.Lerp16;
408 }
409 }
410
411 return p16;
412 }
413
414
415
416 // Resampling ---------------------------------------------------------------------------------
417
418 #define PRELINEARIZATION_POINTS 4096
419
420 // Sampler implemented by another LUT. This is a clean way to precalculate the devicelink 3D CLUT for
421 // almost any transform. We use floating point precision and then convert from floating point to 16 bits.
422 static
423 cmsInt32Number XFormSampler16(cmsContext ContextID,
424 CMSREGISTER const cmsUInt16Number In[],
425 CMSREGISTER cmsUInt16Number Out[],
426 CMSREGISTER void* Cargo)
427 {
428 cmsPipeline* Lut = (cmsPipeline*) Cargo;
429 cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
430 cmsUInt32Number i;
431
432 _cmsAssert(Lut -> InputChannels < cmsMAXCHANNELS);
433 _cmsAssert(Lut -> OutputChannels < cmsMAXCHANNELS);
434
435 // From 16 bit to floating point
436 for (i=0; i < Lut ->InputChannels; i++)
437 InFloat[i] = (cmsFloat32Number) (In[i] / 65535.0);
438
439 // Evaluate in floating point
440 cmsPipelineEvalFloat(ContextID, InFloat, OutFloat, Lut);
441
442 // Back to 16 bits representation
443 for (i=0; i < Lut ->OutputChannels; i++)
444 Out[i] = _cmsQuickSaturateWord(OutFloat[i] * 65535.0);
445
446 // Always succeed
447 return TRUE;
448 }
449
450 // Try to see if the curves of a given MPE are linear
451 static
452 cmsBool AllCurvesAreLinear(cmsContext ContextID, cmsStage* mpe)
453 {
454 cmsToneCurve** Curves;
455 cmsUInt32Number i, n;
456
457 Curves = _cmsStageGetPtrToCurveSet(mpe);
458 if (Curves == NULL) return FALSE;
459
460 n = cmsStageOutputChannels(ContextID, mpe);
461
462 for (i=0; i < n; i++) {
463 if (!cmsIsToneCurveLinear(ContextID, Curves[i])) return FALSE;
464 }
465
466 return TRUE;
467 }
468
469 // This function replaces a specific node placed in "At" by the "Value" numbers. Its purpose
470 // is to fix scum dot on broken profiles/transforms. Works on 1, 3 and 4 channels
471 static
472 cmsBool PatchLUT(cmsContext ContextID, cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],
473 cmsUInt32Number nChannelsOut, cmsUInt32Number nChannelsIn)
474 {
475 _cmsStageCLutData* Grid = (_cmsStageCLutData*) CLUT ->Data;
476 cmsInterpParams* p16 = Grid ->Params;
477 cmsFloat64Number px, py, pz, pw;
478 int x0, y0, z0, w0;
479 int i, index;
480
481 if (CLUT -> Type != cmsSigCLutElemType) {
482 cmsSignalError(ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage");
483 return FALSE;
484 }
485
486 if (nChannelsIn == 4) {
487
488 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
489 py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
490 pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
491 pw = ((cmsFloat64Number) At[3] * (p16->Domain[3])) / 65535.0;
492
493 x0 = (int) floor(px);
494 y0 = (int) floor(py);
495 z0 = (int) floor(pz);
496 w0 = (int) floor(pw);
497
498 if (((px - x0) != 0) ||
499 ((py - y0) != 0) ||
500 ((pz - z0) != 0) ||
501 ((pw - w0) != 0)) return FALSE; // Not on exact node
502
503 index = (int) p16 -> opta[3] * x0 +
504 (int) p16 -> opta[2] * y0 +
505 (int) p16 -> opta[1] * z0 +
506 (int) p16 -> opta[0] * w0;
507 }
508 else
509 if (nChannelsIn == 3) {
510
511 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
512 py = ((cmsFloat64Number) At[1] * (p16->Domain[1])) / 65535.0;
513 pz = ((cmsFloat64Number) At[2] * (p16->Domain[2])) / 65535.0;
514
515 x0 = (int) floor(px);
516 y0 = (int) floor(py);
517 z0 = (int) floor(pz);
518
519 if (((px - x0) != 0) ||
520 ((py - y0) != 0) ||
521 ((pz - z0) != 0)) return FALSE; // Not on exact node
522
523 index = (int) p16 -> opta[2] * x0 +
524 (int) p16 -> opta[1] * y0 +
525 (int) p16 -> opta[0] * z0;
526 }
527 else
528 if (nChannelsIn == 1) {
529
530 px = ((cmsFloat64Number) At[0] * (p16->Domain[0])) / 65535.0;
531
532 x0 = (int) floor(px);
533
534 if (((px - x0) != 0)) return FALSE; // Not on exact node
535
536 index = (int) p16 -> opta[0] * x0;
537 }
538 else {
539 cmsSignalError(ContextID, cmsERROR_INTERNAL, "(internal) %d Channels are not supported on PatchLUT", nChannelsIn);
540 return FALSE;
541 }
542
543 for (i = 0; i < (int) nChannelsOut; i++)
544 Grid->Tab.T[index + i] = Value[i];
545
546 return TRUE;
547 }
548
549 // Auxiliary, to see if two values are equal or very different
550 static
551 cmsBool WhitesAreEqual(cmsUInt32Number n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
552 {
553 cmsUInt32Number i;
554
555 for (i=0; i < n; i++) {
556
557 if (abs(White1[i] - White2[i]) > 0xf000) return TRUE; // Values are so extremely different that the fixup should be avoided
558 if (White1[i] != White2[i]) return FALSE;
559 }
560 return TRUE;
561 }
562
563
564 // Locate the node for the white point and fix it to pure white in order to avoid scum dot.
565 static
566 cmsBool FixWhiteMisalignment(cmsContext ContextID, cmsPipeline* Lut, cmsColorSpaceSignature EntryColorSpace, cmsColorSpaceSignature ExitColorSpace)
567 {
568 cmsUInt16Number *WhitePointIn, *WhitePointOut;
569 cmsUInt16Number WhiteIn[cmsMAXCHANNELS], WhiteOut[cmsMAXCHANNELS], ObtainedOut[cmsMAXCHANNELS];
570 cmsUInt32Number i, nOuts, nIns;
571 cmsStage *PreLin = NULL, *CLUT = NULL, *PostLin = NULL;
572
573 if (!_cmsEndPointsBySpace(EntryColorSpace,
574 &WhitePointIn, NULL, &nIns)) return FALSE;
575
576 if (!_cmsEndPointsBySpace(ExitColorSpace,
577 &WhitePointOut, NULL, &nOuts)) return FALSE;
578
579 // It needs to be fixed?
580 if (Lut ->InputChannels != nIns) return FALSE;
581 if (Lut ->OutputChannels != nOuts) return FALSE;
582
583 cmsPipelineEval16(ContextID, WhitePointIn, ObtainedOut, Lut);
584
585 if (WhitesAreEqual(nOuts, WhitePointOut, ObtainedOut)) return TRUE; // whites already match
586
587 // Check if the LUT comes as Prelin, CLUT or Postlin. We allow all combinations
588 if (!cmsPipelineCheckAndRetreiveStages(ContextID, Lut, 3, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType, &PreLin, &CLUT, &PostLin))
589 if (!cmsPipelineCheckAndRetreiveStages(ContextID, Lut, 2, cmsSigCurveSetElemType, cmsSigCLutElemType, &PreLin, &CLUT))
590 if (!cmsPipelineCheckAndRetreiveStages(ContextID, Lut, 2, cmsSigCLutElemType, cmsSigCurveSetElemType, &CLUT, &PostLin))
591 if (!cmsPipelineCheckAndRetreiveStages(ContextID, Lut, 1, cmsSigCLutElemType, &CLUT))
592 return FALSE;
593
594 // We need to interpolate white points of both, pre and post curves
595 if (PreLin) {
596
597 cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PreLin);
598
599 for (i=0; i < nIns; i++) {
600 WhiteIn[i] = cmsEvalToneCurve16(ContextID, Curves[i], WhitePointIn[i]);
601 }
602 }
603 else {
604 for (i=0; i < nIns; i++)
605 WhiteIn[i] = WhitePointIn[i];
606 }
607
608 // If any post-linearization, we need to find how is represented white before the curve, do
609 // a reverse interpolation in this case.
610 if (PostLin) {
611
612 cmsToneCurve** Curves = _cmsStageGetPtrToCurveSet(PostLin);
613
614 for (i=0; i < nOuts; i++) {
615
616 cmsToneCurve* InversePostLin = cmsReverseToneCurve(ContextID, Curves[i]);
617 if (InversePostLin == NULL) {
618 WhiteOut[i] = WhitePointOut[i];
619
620 } else {
621
622 WhiteOut[i] = cmsEvalToneCurve16(ContextID, InversePostLin, WhitePointOut[i]);
623 cmsFreeToneCurve(ContextID, InversePostLin);
624 }
625 }
626 }
627 else {
628 for (i=0; i < nOuts; i++)
629 WhiteOut[i] = WhitePointOut[i];
630 }
631
632 // Ok, proceed with patching. May fail and we don't care if it fails
633 PatchLUT(ContextID, CLUT, WhiteIn, WhiteOut, nOuts, nIns);
634
635 return TRUE;
636 }
637
638 // -----------------------------------------------------------------------------------------------------------------------------------------------
639 // This function creates simple LUT from complex ones. The generated LUT has an optional set of
640 // prelinearization curves, a CLUT of nGridPoints and optional postlinearization tables.
641 // These curves have to exist in the original LUT in order to be used in the simplified output.
642 // Caller may also use the flags to allow this feature.
643 // LUTS with all curves will be simplified to a single curve. Parametric curves are lost.
644 // This function should be used on 16-bits LUTS only, as floating point losses precision when simplified
645 // -----------------------------------------------------------------------------------------------------------------------------------------------
646
647 static
648 cmsBool OptimizeByResampling(cmsContext ContextID, cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
649 {
650 cmsPipeline* Src = NULL;
651 cmsPipeline* Dest = NULL;
652 cmsStage* CLUT;
653 cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;
654 cmsUInt32Number nGridPoints;
655 cmsColorSpaceSignature ColorSpace, OutputColorSpace;
656 cmsStage *NewPreLin = NULL;
657 cmsStage *NewPostLin = NULL;
658 _cmsStageCLutData* DataCLUT;
659 cmsToneCurve** DataSetIn;
660 cmsToneCurve** DataSetOut;
661 Prelin16Data* p16;
662
663 // This is a lossy optimization! does not apply in floating-point cases
664 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
665
666 ColorSpace = _cmsICCcolorSpace(ContextID, (int) T_COLORSPACE(*InputFormat));
667 OutputColorSpace = _cmsICCcolorSpace(ContextID, (int) T_COLORSPACE(*OutputFormat));
668
669 // Color space must be specified
670 if (ColorSpace == (cmsColorSpaceSignature)0 ||
671 OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;
672
673 nGridPoints = _cmsReasonableGridpointsByColorspace(ContextID, ColorSpace, *dwFlags);
674
675 // For empty LUTs, 2 points are enough
676 if (cmsPipelineStageCount(ContextID, *Lut) == 0)
677 nGridPoints = 2;
678
679 Src = *Lut;
680
681 // Allocate an empty LUT
682 Dest = cmsPipelineAlloc(ContextID, Src ->InputChannels, Src ->OutputChannels);
683 if (!Dest) return FALSE;
684
685 // Prelinearization tables are kept unless indicated by flags
686 if (*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION) {
687
688 // Get a pointer to the prelinearization element
689 cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(ContextID, Src);
690
691 // Check if suitable
692 if (PreLin && PreLin ->Type == cmsSigCurveSetElemType) {
693
694 // Maybe this is a linear tram, so we can avoid the whole stuff
695 if (!AllCurvesAreLinear(ContextID, PreLin)) {
696
697 // All seems ok, proceed.
698 NewPreLin = cmsStageDup(ContextID, PreLin);
699 if(!cmsPipelineInsertStage(ContextID, Dest, cmsAT_BEGIN, NewPreLin))
700 goto Error;
701
702 // Remove prelinearization. Since we have duplicated the curve
703 // in destination LUT, the sampling should be applied after this stage.
704 cmsPipelineUnlinkStage(ContextID, Src, cmsAT_BEGIN, &KeepPreLin);
705 }
706 }
707 }
708
709 // Allocate the CLUT
710 CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, Src ->InputChannels, Src->OutputChannels, NULL);
711 if (CLUT == NULL) goto Error;
712
713 // Add the CLUT to the destination LUT
714 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_END, CLUT)) {
715 goto Error;
716 }
717
718 // Postlinearization tables are kept unless indicated by flags
719 if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {
720
721 // Get a pointer to the postlinearization if present
722 cmsStage* PostLin = cmsPipelineGetPtrToLastStage(ContextID, Src);
723
724 // Check if suitable
725 if (PostLin && cmsStageType(ContextID, PostLin) == cmsSigCurveSetElemType) {
726
727 // Maybe this is a linear tram, so we can avoid the whole stuff
728 if (!AllCurvesAreLinear(ContextID, PostLin)) {
729
730 // All seems ok, proceed.
731 NewPostLin = cmsStageDup(ContextID, PostLin);
732 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_END, NewPostLin))
733 goto Error;
734
735 // In destination LUT, the sampling should be applied after this stage.
736 cmsPipelineUnlinkStage(ContextID, Src, cmsAT_END, &KeepPostLin);
737 }
738 }
739 }
740
741 // Now its time to do the sampling. We have to ignore pre/post linearization
742 // The source LUT without pre/post curves is passed as parameter.
743 if (!cmsStageSampleCLut16bit(ContextID, CLUT, XFormSampler16, (void*) Src, 0)) {
744 Error:
745 // Ops, something went wrong, Restore stages
746 if (KeepPreLin != NULL) {
747 if (!cmsPipelineInsertStage(ContextID, Src, cmsAT_BEGIN, KeepPreLin)) {
748 _cmsAssert(0); // This never happens
749 }
750 }
751 if (KeepPostLin != NULL) {
752 if (!cmsPipelineInsertStage(ContextID, Src, cmsAT_END, KeepPostLin)) {
753 _cmsAssert(0); // This never happens
754 }
755 }
756 cmsPipelineFree(ContextID, Dest);
757 return FALSE;
758 }
759
760 // Done.
761
762 if (KeepPreLin != NULL) cmsStageFree(ContextID, KeepPreLin);
763 if (KeepPostLin != NULL) cmsStageFree(ContextID, KeepPostLin);
764 cmsPipelineFree(ContextID, Src);
765
766 DataCLUT = (_cmsStageCLutData*) CLUT ->Data;
767
768 if (NewPreLin == NULL) DataSetIn = NULL;
769 else DataSetIn = ((_cmsStageToneCurvesData*) NewPreLin ->Data) ->TheCurves;
770
771 if (NewPostLin == NULL) DataSetOut = NULL;
772 else DataSetOut = ((_cmsStageToneCurvesData*) NewPostLin ->Data) ->TheCurves;
773
774
775 if (DataSetIn == NULL && DataSetOut == NULL) {
776
777 _cmsPipelineSetOptimizationParameters(ContextID, Dest, (_cmsPipelineEval16Fn) DataCLUT->Params->Interpolation.Lerp16, DataCLUT->Params, NULL, NULL);
778 }
779 else {
780
781 p16 = PrelinOpt16alloc(ContextID,
782 DataCLUT ->Params,
783 Dest ->InputChannels,
784 DataSetIn,
785 Dest ->OutputChannels,
786 DataSetOut);
787
788 _cmsPipelineSetOptimizationParameters(ContextID, Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
789 }
790
791
792 // Don't fix white on absolute colorimetric
793 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
794 *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
795
796 if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
797
798 FixWhiteMisalignment(ContextID, Dest, ColorSpace, OutputColorSpace);
799 }
800
801 *Lut = Dest;
802 return TRUE;
803
804 cmsUNUSED_PARAMETER(Intent);
805 }
806
807
808 // -----------------------------------------------------------------------------------------------------------------------------------------------
809 // Fixes the gamma balancing of transform. This is described in my paper "Prelinearization Stages on
810 // Color-Management Application-Specific Integrated Circuits (ASICs)" presented at NIP24. It only works
811 // for RGB transforms. See the paper for more details
812 // -----------------------------------------------------------------------------------------------------------------------------------------------
813
814
815 // Normalize endpoints by slope limiting max and min. This assures endpoints as well.
816 // Descending curves are handled as well.
817 static
818 void SlopeLimiting(cmsContext ContextID, cmsToneCurve* g)
819 {
820 int BeginVal, EndVal;
821 int AtBegin = (int) floor((cmsFloat64Number) g ->nEntries * 0.02 + 0.5); // Cutoff at 2%
822 int AtEnd = (int) g ->nEntries - AtBegin - 1; // And 98%
823 cmsFloat64Number Val, Slope, beta;
824 int i;
825
826 if (cmsIsToneCurveDescending(ContextID, g)) {
827 BeginVal = 0xffff; EndVal = 0;
828 }
829 else {
830 BeginVal = 0; EndVal = 0xffff;
831 }
832
833 // Compute slope and offset for begin of curve
834 Val = g ->Table16[AtBegin];
835 Slope = (Val - BeginVal) / AtBegin;
836 beta = Val - Slope * AtBegin;
837
838 for (i=0; i < AtBegin; i++)
839 g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
840
841 // Compute slope and offset for the end
842 Val = g ->Table16[AtEnd];
843 Slope = (EndVal - Val) / AtBegin; // AtBegin holds the X interval, which is same in both cases
844 beta = Val - Slope * AtEnd;
845
846 for (i = AtEnd; i < (int) g ->nEntries; i++)
847 g ->Table16[i] = _cmsQuickSaturateWord(i * Slope + beta);
848 }
849
850
851 // Precomputes tables for 8-bit on input devicelink.
852 static
853 Prelin8Data* PrelinOpt8alloc(cmsContext ContextID, const cmsInterpParams* p, cmsToneCurve* G[3])
854 {
855 int i;
856 cmsUInt16Number Input[3];
857 cmsS15Fixed16Number v1, v2, v3;
858 Prelin8Data* p8;
859
860 p8 = (Prelin8Data*)_cmsMallocZero(ContextID, sizeof(Prelin8Data));
861 if (p8 == NULL) return NULL;
862
863 // Since this only works for 8 bit input, values comes always as x * 257,
864 // we can safely take msb byte (x << 8 + x)
865
866 for (i=0; i < 256; i++) {
867
868 if (G != NULL) {
869
870 // Get 16-bit representation
871 Input[0] = cmsEvalToneCurve16(ContextID, G[0], FROM_8_TO_16(i));
872 Input[1] = cmsEvalToneCurve16(ContextID, G[1], FROM_8_TO_16(i));
873 Input[2] = cmsEvalToneCurve16(ContextID, G[2], FROM_8_TO_16(i));
874 }
875 else {
876 Input[0] = FROM_8_TO_16(i);
877 Input[1] = FROM_8_TO_16(i);
878 Input[2] = FROM_8_TO_16(i);
879 }
880
881
882 // Move to 0..1.0 in fixed domain
883 v1 = _cmsToFixedDomain((int) (Input[0] * p -> Domain[0]));
884 v2 = _cmsToFixedDomain((int) (Input[1] * p -> Domain[1]));
885 v3 = _cmsToFixedDomain((int) (Input[2] * p -> Domain[2]));
886
887 // Store the precalculated table of nodes
888 p8 ->X0[i] = (p->opta[2] * FIXED_TO_INT(v1));
889 p8 ->Y0[i] = (p->opta[1] * FIXED_TO_INT(v2));
890 p8 ->Z0[i] = (p->opta[0] * FIXED_TO_INT(v3));
891
892 // Store the precalculated table of offsets
893 p8 ->rx[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v1);
894 p8 ->ry[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v2);
895 p8 ->rz[i] = (cmsUInt16Number) FIXED_REST_TO_INT(v3);
896 }
897
898 p8 ->ContextID = ContextID;
899 p8 ->p = p;
900
901 return p8;
902 }
903
904 static
905 void Prelin8free(cmsContext ContextID, void* ptr)
906 {
907 _cmsFree(ContextID, ptr);
908 }
909
910 static
911 void* Prelin8dup(cmsContext ContextID, const void* ptr)
912 {
913 return _cmsDupMem(ContextID, ptr, sizeof(Prelin8Data));
914 }
915
916
917
918 // A optimized interpolation for 8-bit input.
919 #define DENS(i,j,k) (LutTable[(i)+(j)+(k)+OutChan])
920 static CMS_NO_SANITIZE
921 void PrelinEval8(cmsContext ContextID,
922 CMSREGISTER const cmsUInt16Number Input[],
923 CMSREGISTER cmsUInt16Number Output[],
924 CMSREGISTER const void* D)
925 {
926 cmsUInt8Number r, g, b;
927 cmsS15Fixed16Number rx, ry, rz;
928 cmsS15Fixed16Number c0, c1, c2, c3, Rest;
929 int OutChan;
930 CMSREGISTER cmsS15Fixed16Number X0, X1, Y0, Y1, Z0, Z1;
931 Prelin8Data* p8 = (Prelin8Data*) D;
932 CMSREGISTER const cmsInterpParams* p = p8 ->p;
933 int TotalOut = (int) p -> nOutputs;
934 const cmsUInt16Number* LutTable = (const cmsUInt16Number*) p->Table;
935 cmsUNUSED_PARAMETER(ContextID);
936
937 r = (cmsUInt8Number) (Input[0] >> 8);
938 g = (cmsUInt8Number) (Input[1] >> 8);
939 b = (cmsUInt8Number) (Input[2] >> 8);
940
941 X0 = (cmsS15Fixed16Number) p8->X0[r];
942 Y0 = (cmsS15Fixed16Number) p8->Y0[g];
943 Z0 = (cmsS15Fixed16Number) p8->Z0[b];
944
945 rx = p8 ->rx[r];
946 ry = p8 ->ry[g];
947 rz = p8 ->rz[b];
948
949 X1 = X0 + (cmsS15Fixed16Number)((rx == 0) ? 0 : p ->opta[2]);
950 Y1 = Y0 + (cmsS15Fixed16Number)((ry == 0) ? 0 : p ->opta[1]);
951 Z1 = Z0 + (cmsS15Fixed16Number)((rz == 0) ? 0 : p ->opta[0]);
952
953
954 // These are the 6 Tetrahedral
955 for (OutChan=0; OutChan < TotalOut; OutChan++) {
956
957 c0 = DENS(X0, Y0, Z0);
958
959 if (rx >= ry && ry >= rz)
960 {
961 c1 = DENS(X1, Y0, Z0) - c0;
962 c2 = DENS(X1, Y1, Z0) - DENS(X1, Y0, Z0);
963 c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
964 }
965 else
966 if (rx >= rz && rz >= ry)
967 {
968 c1 = DENS(X1, Y0, Z0) - c0;
969 c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
970 c3 = DENS(X1, Y0, Z1) - DENS(X1, Y0, Z0);
971 }
972 else
973 if (rz >= rx && rx >= ry)
974 {
975 c1 = DENS(X1, Y0, Z1) - DENS(X0, Y0, Z1);
976 c2 = DENS(X1, Y1, Z1) - DENS(X1, Y0, Z1);
977 c3 = DENS(X0, Y0, Z1) - c0;
978 }
979 else
980 if (ry >= rx && rx >= rz)
981 {
982 c1 = DENS(X1, Y1, Z0) - DENS(X0, Y1, Z0);
983 c2 = DENS(X0, Y1, Z0) - c0;
984 c3 = DENS(X1, Y1, Z1) - DENS(X1, Y1, Z0);
985 }
986 else
987 if (ry >= rz && rz >= rx)
988 {
989 c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
990 c2 = DENS(X0, Y1, Z0) - c0;
991 c3 = DENS(X0, Y1, Z1) - DENS(X0, Y1, Z0);
992 }
993 else
994 if (rz >= ry && ry >= rx)
995 {
996 c1 = DENS(X1, Y1, Z1) - DENS(X0, Y1, Z1);
997 c2 = DENS(X0, Y1, Z1) - DENS(X0, Y0, Z1);
998 c3 = DENS(X0, Y0, Z1) - c0;
999 }
1000 else {
1001 c1 = c2 = c3 = 0;
1002 }
1003
1004 Rest = c1 * rx + c2 * ry + c3 * rz + 0x8001;
1005 Output[OutChan] = (cmsUInt16Number) (c0 + ((Rest + (Rest >> 16)) >> 16));
1006
1007 }
1008 }
1009
1010 #undef DENS
1011
1012
1013 // Curves that contain wide empty areas are not optimizeable
1014 static
1015 cmsBool IsDegenerated(const cmsToneCurve* g)
1016 {
1017 cmsUInt32Number i, Zeros = 0, Poles = 0;
1018 cmsUInt32Number nEntries = g ->nEntries;
1019
1020 for (i=0; i < nEntries; i++) {
1021
1022 if (g ->Table16[i] == 0x0000) Zeros++;
1023 if (g ->Table16[i] == 0xffff) Poles++;
1024 }
1025
1026 if (Zeros == 1 && Poles == 1) return FALSE; // For linear tables
1027 if (Zeros > (nEntries / 20)) return TRUE; // Degenerated, many zeros
1028 if (Poles > (nEntries / 20)) return TRUE; // Degenerated, many poles
1029
1030 return FALSE;
1031 }
1032
1033 // --------------------------------------------------------------------------------------------------------------
1034 // We need xput over here
1035
1036 static
1037 cmsBool OptimizeByComputingLinearization(cmsContext ContextID, cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1038 {
1039 cmsPipeline* OriginalLut;
1040 cmsUInt32Number nGridPoints;
1041 cmsToneCurve *Trans[cmsMAXCHANNELS], *TransReverse[cmsMAXCHANNELS];
1042 cmsUInt32Number t, i;
1043 cmsFloat32Number v, In[cmsMAXCHANNELS], Out[cmsMAXCHANNELS];
1044 cmsBool lIsSuitable, lIsLinear;
1045 cmsPipeline* OptimizedLUT = NULL, *LutPlusCurves = NULL;
1046 cmsStage* OptimizedCLUTmpe;
1047 cmsColorSpaceSignature ColorSpace, OutputColorSpace;
1048 cmsStage* OptimizedPrelinMpe;
1049 cmsToneCurve** OptimizedPrelinCurves;
1050 _cmsStageCLutData* OptimizedPrelinCLUT;
1051
1052
1053 // This is a lossy optimization! does not apply in floating-point cases
1054 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
1055
1056 // Only on chunky RGB
1057 if (T_COLORSPACE(*InputFormat) != PT_RGB) return FALSE;
1058 if (T_PLANAR(*InputFormat)) return FALSE;
1059
1060 if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
1061 if (T_PLANAR(*OutputFormat)) return FALSE;
1062
1063 // On 16 bits, user has to specify the feature
1064 if (!_cmsFormatterIs8bit(*InputFormat)) {
1065 if (!(*dwFlags & cmsFLAGS_CLUT_PRE_LINEARIZATION)) return FALSE;
1066 }
1067
1068 OriginalLut = *Lut;
1069 ColorSpace = _cmsICCcolorSpace(ContextID, (int) T_COLORSPACE(*InputFormat));
1070 OutputColorSpace = _cmsICCcolorSpace(ContextID, (int) T_COLORSPACE(*OutputFormat));
1071
1072 // Color space must be specified
1073 if (ColorSpace == (cmsColorSpaceSignature)0 ||
1074 OutputColorSpace == (cmsColorSpaceSignature)0) return FALSE;
1075
1076 nGridPoints = _cmsReasonableGridpointsByColorspace(ContextID, ColorSpace, *dwFlags);
1077
1078 // Empty gamma containers
1079 memset(Trans, 0, sizeof(Trans));
1080 memset(TransReverse, 0, sizeof(TransReverse));
1081
1082 // If the last stage of the original lut are curves, and those curves are
1083 // degenerated, it is likely the transform is squeezing and clipping
1084 // the output from previous CLUT. We cannot optimize this case
1085 {
1086 cmsStage* last = cmsPipelineGetPtrToLastStage(ContextID, OriginalLut);
1087
1088 if (last == NULL) goto Error;
1089 if (cmsStageType(ContextID, last) == cmsSigCurveSetElemType) {
1090
1091 _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*)cmsStageData(ContextID, last);
1092 for (i = 0; i < Data->nCurves; i++) {
1093 if (IsDegenerated(Data->TheCurves[i]))
1094 goto Error;
1095 }
1096 }
1097 }
1098
1099 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1100 Trans[t] = cmsBuildTabulatedToneCurve16(ContextID, PRELINEARIZATION_POINTS, NULL);
1101 if (Trans[t] == NULL) goto Error;
1102 }
1103
1104 // Populate the curves
1105 for (i=0; i < PRELINEARIZATION_POINTS; i++) {
1106
1107 v = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
1108
1109 // Feed input with a gray ramp
1110 for (t=0; t < OriginalLut ->InputChannels; t++)
1111 In[t] = v;
1112
1113 // Evaluate the gray value
1114 cmsPipelineEvalFloat(ContextID, In, Out, OriginalLut);
1115
1116 // Store result in curve
1117 for (t=0; t < OriginalLut ->InputChannels; t++)
1118 {
1119 if (Trans[t]->Table16 != NULL)
1120 Trans[t] ->Table16[i] = _cmsQuickSaturateWord(Out[t] * 65535.0);
1121 }
1122 }
1123
1124 // Slope-limit the obtained curves
1125 for (t = 0; t < OriginalLut ->InputChannels; t++)
1126 SlopeLimiting(ContextID, Trans[t]);
1127
1128 // Check for validity. lIsLinear is here for debug purposes
1129 lIsSuitable = TRUE;
1130 lIsLinear = TRUE;
1131 for (t=0; (lIsSuitable && (t < OriginalLut ->InputChannels)); t++) {
1132
1133 // Exclude if already linear
1134 if (!cmsIsToneCurveLinear(ContextID, Trans[t]))
1135 lIsLinear = FALSE;
1136
1137 // Exclude if non-monotonic
1138 if (!cmsIsToneCurveMonotonic(ContextID, Trans[t]))
1139 lIsSuitable = FALSE;
1140
1141 if (IsDegenerated(Trans[t]))
1142 lIsSuitable = FALSE;
1143 }
1144
1145 // If it is not suitable, just quit
1146 if (!lIsSuitable) goto Error;
1147
1148 // Invert curves if possible
1149 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1150 TransReverse[t] = cmsReverseToneCurveEx(ContextID, PRELINEARIZATION_POINTS, Trans[t]);
1151 if (TransReverse[t] == NULL) goto Error;
1152 }
1153
1154 // Now inset the reversed curves at the begin of transform
1155 LutPlusCurves = cmsPipelineDup(ContextID, OriginalLut);
1156 if (LutPlusCurves == NULL) goto Error;
1157
1158 if (!cmsPipelineInsertStage(ContextID, LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(ContextID, OriginalLut ->InputChannels, TransReverse)))
1159 goto Error;
1160
1161 // Create the result LUT
1162 OptimizedLUT = cmsPipelineAlloc(ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);
1163 if (OptimizedLUT == NULL) goto Error;
1164
1165 OptimizedPrelinMpe = cmsStageAllocToneCurves(ContextID, OriginalLut ->InputChannels, Trans);
1166
1167 // Create and insert the curves at the beginning
1168 if (!cmsPipelineInsertStage(ContextID, OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe))
1169 goto Error;
1170
1171 // Allocate the CLUT for result
1172 OptimizedCLUTmpe = cmsStageAllocCLut16bit(ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);
1173
1174 // Add the CLUT to the destination LUT
1175 if (!cmsPipelineInsertStage(ContextID, OptimizedLUT, cmsAT_END, OptimizedCLUTmpe))
1176 goto Error;
1177
1178 // Resample the LUT
1179 if (!cmsStageSampleCLut16bit(ContextID, OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;
1180
1181 // Free resources
1182 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1183
1184 if (Trans[t]) cmsFreeToneCurve(ContextID, Trans[t]);
1185 if (TransReverse[t]) cmsFreeToneCurve(ContextID, TransReverse[t]);
1186 }
1187
1188 cmsPipelineFree(ContextID, LutPlusCurves);
1189
1190
1191 OptimizedPrelinCurves = _cmsStageGetPtrToCurveSet(OptimizedPrelinMpe);
1192 OptimizedPrelinCLUT = (_cmsStageCLutData*) OptimizedCLUTmpe ->Data;
1193
1194 // Set the evaluator if 8-bit
1195 if (_cmsFormatterIs8bit(*InputFormat)) {
1196
1197 Prelin8Data* p8 = PrelinOpt8alloc(ContextID,
1198 OptimizedPrelinCLUT ->Params,
1199 OptimizedPrelinCurves);
1200 if (p8 == NULL) return FALSE;
1201
1202 _cmsPipelineSetOptimizationParameters(ContextID, OptimizedLUT, PrelinEval8, (void*) p8, Prelin8free, Prelin8dup);
1203
1204 }
1205 else
1206 {
1207 Prelin16Data* p16 = PrelinOpt16alloc(ContextID,
1208 OptimizedPrelinCLUT ->Params,
1209 3, OptimizedPrelinCurves, 3, NULL);
1210 if (p16 == NULL) return FALSE;
1211
1212 _cmsPipelineSetOptimizationParameters(ContextID, OptimizedLUT, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
1213
1214 }
1215
1216 // Don't fix white on absolute colorimetric
1217 if (Intent == INTENT_ABSOLUTE_COLORIMETRIC)
1218 *dwFlags |= cmsFLAGS_NOWHITEONWHITEFIXUP;
1219
1220 if (!(*dwFlags & cmsFLAGS_NOWHITEONWHITEFIXUP)) {
1221
1222 if (!FixWhiteMisalignment(ContextID, OptimizedLUT, ColorSpace, OutputColorSpace)) {
1223
1224 return FALSE;
1225 }
1226 }
1227
1228 // And return the obtained LUT
1229
1230 cmsPipelineFree(ContextID, OriginalLut);
1231 *Lut = OptimizedLUT;
1232 return TRUE;
1233
1234 Error:
1235
1236 for (t = 0; t < OriginalLut ->InputChannels; t++) {
1237
1238 if (Trans[t]) cmsFreeToneCurve(ContextID, Trans[t]);
1239 if (TransReverse[t]) cmsFreeToneCurve(ContextID, TransReverse[t]);
1240 }
1241
1242 if (LutPlusCurves != NULL) cmsPipelineFree(ContextID, LutPlusCurves);
1243 if (OptimizedLUT != NULL) cmsPipelineFree(ContextID, OptimizedLUT);
1244
1245 return FALSE;
1246
1247 cmsUNUSED_PARAMETER(Intent);
1248 cmsUNUSED_PARAMETER(lIsLinear);
1249 }
1250
1251
1252 // Curves optimizer ------------------------------------------------------------------------------------------------------------------
1253
1254 static
1255 void CurvesFree(cmsContext ContextID, void* ptr)
1256 {
1257 Curves16Data* Data = (Curves16Data*) ptr;
1258 cmsUInt32Number i;
1259
1260 for (i=0; i < Data -> nCurves; i++) {
1261
1262 _cmsFree(ContextID, Data ->Curves[i]);
1263 }
1264
1265 _cmsFree(ContextID, Data ->Curves);
1266 _cmsFree(ContextID, ptr);
1267 }
1268
1269 static
1270 void* CurvesDup(cmsContext ContextID, const void* ptr)
1271 {
1272 Curves16Data* Data = (Curves16Data*)_cmsDupMem(ContextID, ptr, sizeof(Curves16Data));
1273 cmsUInt32Number i;
1274
1275 if (Data == NULL) return NULL;
1276
1277 Data->Curves = (cmsUInt16Number**) _cmsDupMem(ContextID, Data->Curves, Data->nCurves * sizeof(cmsUInt16Number*));
1278
1279 for (i=0; i < Data -> nCurves; i++) {
1280 Data->Curves[i] = (cmsUInt16Number*) _cmsDupMem(ContextID, Data->Curves[i], Data->nElements * sizeof(cmsUInt16Number));
1281 }
1282
1283 return (void*) Data;
1284 }
1285
1286 // Precomputes tables for 8-bit on input devicelink.
1287 static
1288 Curves16Data* CurvesAlloc(cmsContext ContextID, cmsUInt32Number nCurves, cmsUInt32Number nElements, cmsToneCurve** G)
1289 {
1290 cmsUInt32Number i, j;
1291 Curves16Data* c16;
1292
1293 c16 = (Curves16Data*)_cmsMallocZero(ContextID, sizeof(Curves16Data));
1294 if (c16 == NULL) return NULL;
1295
1296 c16 ->nCurves = nCurves;
1297 c16 ->nElements = nElements;
1298
1299 c16->Curves = (cmsUInt16Number**) _cmsCalloc(ContextID, nCurves, sizeof(cmsUInt16Number*));
1300 if (c16->Curves == NULL) {
1301 _cmsFree(ContextID, c16);
1302 return NULL;
1303 }
1304
1305 for (i=0; i < nCurves; i++) {
1306
1307 c16->Curves[i] = (cmsUInt16Number*) _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
1308
1309 if (c16->Curves[i] == NULL) {
1310
1311 for (j=0; j < i; j++) {
1312 _cmsFree(ContextID, c16->Curves[j]);
1313 }
1314 _cmsFree(ContextID, c16->Curves);
1315 _cmsFree(ContextID, c16);
1316 return NULL;
1317 }
1318
1319 if (nElements == 256U) {
1320
1321 for (j=0; j < nElements; j++) {
1322
1323 c16 ->Curves[i][j] = cmsEvalToneCurve16(ContextID, G[i], FROM_8_TO_16(j));
1324 }
1325 }
1326 else {
1327
1328 for (j=0; j < nElements; j++) {
1329 c16 ->Curves[i][j] = cmsEvalToneCurve16(ContextID, G[i], (cmsUInt16Number) j);
1330 }
1331 }
1332 }
1333
1334 return c16;
1335 }
1336
1337 static
1338 void FastEvaluateCurves8(cmsContext ContextID,
1339 CMSREGISTER const cmsUInt16Number In[],
1340 CMSREGISTER cmsUInt16Number Out[],
1341 CMSREGISTER const void* D)
1342 {
1343 Curves16Data* Data = (Curves16Data*) D;
1344 int x;
1345 cmsUInt32Number i;
1346 cmsUNUSED_PARAMETER(ContextID);
1347
1348 for (i=0; i < Data ->nCurves; i++) {
1349
1350 x = (In[i] >> 8);
1351 Out[i] = Data -> Curves[i][x];
1352 }
1353 }
1354
1355
1356 static
1357 void FastEvaluateCurves16(cmsContext ContextID,
1358 CMSREGISTER const cmsUInt16Number In[],
1359 CMSREGISTER cmsUInt16Number Out[],
1360 CMSREGISTER const void* D)
1361 {
1362 Curves16Data* Data = (Curves16Data*) D;
1363 cmsUInt32Number i;
1364 cmsUNUSED_PARAMETER(ContextID);
1365
1366 for (i=0; i < Data ->nCurves; i++) {
1367 Out[i] = Data -> Curves[i][In[i]];
1368 }
1369 }
1370
1371
1372 static
1373 void FastIdentity16(cmsContext ContextID,
1374 CMSREGISTER const cmsUInt16Number In[],
1375 CMSREGISTER cmsUInt16Number Out[],
1376 CMSREGISTER const void* D)
1377 {
1378 cmsPipeline* Lut = (cmsPipeline*) D;
1379 cmsUInt32Number i;
1380 cmsUNUSED_PARAMETER(ContextID);
1381
1382 for (i=0; i < Lut ->InputChannels; i++) {
1383 Out[i] = In[i];
1384 }
1385 }
1386
1387
1388 // If the target LUT holds only curves, the optimization procedure is to join all those
1389 // curves together. That only works on curves and does not work on matrices.
1390 static
1391 cmsBool OptimizeByJoiningCurves(cmsContext ContextID, cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1392 {
1393 cmsToneCurve** GammaTables = NULL;
1394 cmsFloat32Number InFloat[cmsMAXCHANNELS], OutFloat[cmsMAXCHANNELS];
1395 cmsUInt32Number i, j;
1396 cmsPipeline* Src = *Lut;
1397 cmsPipeline* Dest = NULL;
1398 cmsStage* mpe;
1399 cmsStage* ObtainedCurves = NULL;
1400
1401
1402 // This is a lossy optimization! does not apply in floating-point cases
1403 if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
1404
1405 // Only curves in this LUT?
1406 for (mpe = cmsPipelineGetPtrToFirstStage(ContextID, Src);
1407 mpe != NULL;
1408 mpe = cmsStageNext(ContextID, mpe)) {
1409 if (cmsStageType(ContextID, mpe) != cmsSigCurveSetElemType) return FALSE;
1410 }
1411
1412 // Allocate an empty LUT
1413 Dest = cmsPipelineAlloc(ContextID, Src ->InputChannels, Src ->OutputChannels);
1414 if (Dest == NULL) return FALSE;
1415
1416 // Create target curves
1417 GammaTables = (cmsToneCurve**) _cmsCalloc(ContextID, Src ->InputChannels, sizeof(cmsToneCurve*));
1418 if (GammaTables == NULL) goto Error;
1419
1420 for (i=0; i < Src ->InputChannels; i++) {
1421 GammaTables[i] = cmsBuildTabulatedToneCurve16(ContextID, PRELINEARIZATION_POINTS, NULL);
1422 if (GammaTables[i] == NULL) goto Error;
1423 }
1424
1425 // Compute 16 bit result by using floating point
1426 for (i=0; i < PRELINEARIZATION_POINTS; i++) {
1427
1428 for (j=0; j < Src ->InputChannels; j++)
1429 InFloat[j] = (cmsFloat32Number) ((cmsFloat64Number) i / (PRELINEARIZATION_POINTS - 1));
1430
1431 cmsPipelineEvalFloat(ContextID, InFloat, OutFloat, Src);
1432
1433 for (j=0; j < Src ->InputChannels; j++)
1434 GammaTables[j] -> Table16[i] = _cmsQuickSaturateWord(OutFloat[j] * 65535.0);
1435 }
1436
1437 ObtainedCurves = cmsStageAllocToneCurves(ContextID, Src ->InputChannels, GammaTables);
1438 if (ObtainedCurves == NULL) goto Error;
1439
1440 for (i=0; i < Src ->InputChannels; i++) {
1441 cmsFreeToneCurve(ContextID, GammaTables[i]);
1442 GammaTables[i] = NULL;
1443 }
1444
1445 if (GammaTables != NULL) {
1446 _cmsFree(ContextID, GammaTables);
1447 GammaTables = NULL;
1448 }
1449
1450 // Maybe the curves are linear at the end
1451 if (!AllCurvesAreLinear(ContextID, ObtainedCurves)) {
1452 _cmsStageToneCurvesData* Data;
1453
1454 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_BEGIN, ObtainedCurves))
1455 goto Error;
1456 Data = (_cmsStageToneCurvesData*) cmsStageData(ContextID, ObtainedCurves);
1457 ObtainedCurves = NULL;
1458
1459 // If the curves are to be applied in 8 bits, we can save memory
1460 if (_cmsFormatterIs8bit(*InputFormat)) {
1461 Curves16Data* c16 = CurvesAlloc(ContextID, Data ->nCurves, 256, Data ->TheCurves);
1462
1463 if (c16 == NULL) goto Error;
1464 *dwFlags |= cmsFLAGS_NOCACHE;
1465 _cmsPipelineSetOptimizationParameters(ContextID, Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);
1466
1467 }
1468 else {
1469 Curves16Data* c16 = CurvesAlloc(ContextID, Data ->nCurves, 65536, Data ->TheCurves);
1470
1471 if (c16 == NULL) goto Error;
1472 *dwFlags |= cmsFLAGS_NOCACHE;
1473 _cmsPipelineSetOptimizationParameters(ContextID, Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);
1474 }
1475 }
1476 else {
1477
1478 // LUT optimizes to nothing. Set the identity LUT
1479 cmsStageFree(ContextID, ObtainedCurves);
1480 ObtainedCurves = NULL;
1481
1482 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_BEGIN, cmsStageAllocIdentity(ContextID, Src ->InputChannels)))
1483 goto Error;
1484
1485 *dwFlags |= cmsFLAGS_NOCACHE;
1486 _cmsPipelineSetOptimizationParameters(ContextID, Dest, FastIdentity16, (void*) Dest, NULL, NULL);
1487 }
1488
1489 // We are done.
1490 cmsPipelineFree(ContextID, Src);
1491 *Lut = Dest;
1492 return TRUE;
1493
1494 Error:
1495
1496 if (ObtainedCurves != NULL) cmsStageFree(ContextID, ObtainedCurves);
1497 if (GammaTables != NULL) {
1498 for (i=0; i < Src ->InputChannels; i++) {
1499 if (GammaTables[i] != NULL) cmsFreeToneCurve(ContextID, GammaTables[i]);
1500 }
1501
1502 _cmsFree(ContextID, GammaTables);
1503 }
1504
1505 if (Dest != NULL) cmsPipelineFree(ContextID, Dest);
1506 return FALSE;
1507
1508 cmsUNUSED_PARAMETER(Intent);
1509 cmsUNUSED_PARAMETER(InputFormat);
1510 cmsUNUSED_PARAMETER(OutputFormat);
1511 cmsUNUSED_PARAMETER(dwFlags);
1512 }
1513
1514 // -------------------------------------------------------------------------------------------------------------------------------------
1515 // LUT is Shaper - Matrix - Matrix - Shaper, which is very frequent when combining two matrix-shaper profiles
1516
1517
1518 static
1519 void FreeMatShaper(cmsContext ContextID, void* Data)
1520 {
1521 if (Data != NULL) _cmsFree(ContextID, Data);
1522 }
1523
1524 static
1525 void* DupMatShaper(cmsContext ContextID, const void* Data)
1526 {
1527 return _cmsDupMem(ContextID, Data, sizeof(MatShaper8Data));
1528 }
1529
1530
1531 // A fast matrix-shaper evaluator for 8 bits. This is a bit tricky since I'm using 1.14 signed fixed point
1532 // to accomplish some performance. Actually it takes 256x3 16 bits tables and 16385 x 3 tables of 8 bits,
1533 // in total about 50K, and the performance boost is huge!
1534 static CMS_NO_SANITIZE
1535 void MatShaperEval16(cmsContext ContextID,
1536 CMSREGISTER const cmsUInt16Number In[],
1537 CMSREGISTER cmsUInt16Number Out[],
1538 CMSREGISTER const void* D)
1539 {
1540 MatShaper8Data* p = (MatShaper8Data*) D;
1541 cmsS1Fixed14Number l1, l2, l3, r, g, b;
1542 cmsUInt32Number ri, gi, bi;
1543 cmsUNUSED_PARAMETER(ContextID);
1544
1545 // In this case (and only in this case!) we can use this simplification since
1546 // In[] is assured to come from a 8 bit number. (a << 8 | a)
1547 ri = In[0] & 0xFFU;
1548 gi = In[1] & 0xFFU;
1549 bi = In[2] & 0xFFU;
1550
1551 // Across first shaper, which also converts to 1.14 fixed point
1552 r = p->Shaper1R[ri];
1553 g = p->Shaper1G[gi];
1554 b = p->Shaper1B[bi];
1555
1556 // Evaluate the matrix in 1.14 fixed point
1557 l1 = (p->Mat[0][0] * r + p->Mat[0][1] * g + p->Mat[0][2] * b + p->Off[0] + 0x2000) >> 14;
1558 l2 = (p->Mat[1][0] * r + p->Mat[1][1] * g + p->Mat[1][2] * b + p->Off[1] + 0x2000) >> 14;
1559 l3 = (p->Mat[2][0] * r + p->Mat[2][1] * g + p->Mat[2][2] * b + p->Off[2] + 0x2000) >> 14;
1560
1561 // Now we have to clip to 0..1.0 range
1562 ri = (l1 < 0) ? 0 : ((l1 > 16384) ? 16384U : (cmsUInt32Number) l1);
1563 gi = (l2 < 0) ? 0 : ((l2 > 16384) ? 16384U : (cmsUInt32Number) l2);
1564 bi = (l3 < 0) ? 0 : ((l3 > 16384) ? 16384U : (cmsUInt32Number) l3);
1565
1566 // And across second shaper,
1567 Out[0] = p->Shaper2R[ri];
1568 Out[1] = p->Shaper2G[gi];
1569 Out[2] = p->Shaper2B[bi];
1570
1571 }
1572
1573 // This table converts from 8 bits to 1.14 after applying the curve
1574 static
1575 void FillFirstShaper(cmsContext ContextID, cmsS1Fixed14Number* Table, cmsToneCurve* Curve)
1576 {
1577 int i;
1578 cmsFloat32Number R, y;
1579
1580 for (i=0; i < 256; i++) {
1581
1582 R = (cmsFloat32Number) (i / 255.0);
1583 y = cmsEvalToneCurveFloat(ContextID, Curve, R);
1584
1585 if (y < 131072.0)
1586 Table[i] = DOUBLE_TO_1FIXED14(y);
1587 else
1588 Table[i] = 0x7fffffff;
1589 }
1590 }
1591
1592 // This table converts form 1.14 (being 0x4000 the last entry) to 8 bits after applying the curve
1593 static
1594 void FillSecondShaper(cmsContext ContextID, cmsUInt16Number* Table, cmsToneCurve* Curve, cmsBool Is8BitsOutput)
1595 {
1596 int i;
1597 cmsFloat32Number R, Val;
1598
1599 for (i=0; i < 16385; i++) {
1600
1601 R = (cmsFloat32Number) (i / 16384.0);
1602 Val = cmsEvalToneCurveFloat(ContextID, Curve, R); // Val comes 0..1.0
1603
1604 if (Val < 0)
1605 Val = 0;
1606
1607 if (Val > 1.0)
1608 Val = 1.0;
1609
1610 if (Is8BitsOutput) {
1611
1612 // If 8 bits output, we can optimize further by computing the / 257 part.
1613 // first we compute the resulting byte and then we store the byte times
1614 // 257. This quantization allows to round very quick by doing a >> 8, but
1615 // since the low byte is always equal to msb, we can do a & 0xff and this works!
1616 cmsUInt16Number w = _cmsQuickSaturateWord(Val * 65535.0);
1617 cmsUInt8Number b = FROM_16_TO_8(w);
1618
1619 Table[i] = FROM_8_TO_16(b);
1620 }
1621 else Table[i] = _cmsQuickSaturateWord(Val * 65535.0);
1622 }
1623 }
1624
1625 // Compute the matrix-shaper structure
1626 static
1627 cmsBool SetMatShaper(cmsContext ContextID, cmsPipeline* Dest, cmsToneCurve* Curve1[3], cmsMAT3* Mat, cmsVEC3* Off, cmsToneCurve* Curve2[3], cmsUInt32Number* OutputFormat)
1628 {
1629 MatShaper8Data* p;
1630 int i, j;
1631 cmsBool Is8Bits = _cmsFormatterIs8bit(*OutputFormat);
1632
1633 // Allocate a big chuck of memory to store precomputed tables
1634 p = (MatShaper8Data*) _cmsMalloc(ContextID, sizeof(MatShaper8Data));
1635 if (p == NULL) return FALSE;
1636
1637 // Precompute tables
1638 FillFirstShaper(ContextID, p ->Shaper1R, Curve1[0]);
1639 FillFirstShaper(ContextID, p ->Shaper1G, Curve1[1]);
1640 FillFirstShaper(ContextID, p ->Shaper1B, Curve1[2]);
1641
1642 FillSecondShaper(ContextID, p ->Shaper2R, Curve2[0], Is8Bits);
1643 FillSecondShaper(ContextID, p ->Shaper2G, Curve2[1], Is8Bits);
1644 FillSecondShaper(ContextID, p ->Shaper2B, Curve2[2], Is8Bits);
1645
1646 // Convert matrix to nFixed14. Note that those values may take more than 16 bits
1647 for (i=0; i < 3; i++) {
1648 for (j=0; j < 3; j++) {
1649 p ->Mat[i][j] = DOUBLE_TO_1FIXED14(Mat->v[i].n[j]);
1650 }
1651 }
1652
1653 for (i=0; i < 3; i++) {
1654
1655 if (Off == NULL) {
1656 p ->Off[i] = 0;
1657 }
1658 else {
1659 p ->Off[i] = DOUBLE_TO_1FIXED14(Off->n[i]);
1660 }
1661 }
1662
1663 // Mark as optimized for faster formatter
1664 if (Is8Bits)
1665 *OutputFormat |= OPTIMIZED_SH(1);
1666
1667 // Fill function pointers
1668 _cmsPipelineSetOptimizationParameters(ContextID, Dest, MatShaperEval16, (void*) p, FreeMatShaper, DupMatShaper);
1669 return TRUE;
1670 }
1671
1672 // 8 bits on input allows matrix-shaper boot up to 25 Mpixels per second on RGB. That's fast!
1673 static
1674 cmsBool OptimizeMatrixShaper(cmsContext ContextID, cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
1675 {
1676 cmsStage* Curve1, *Curve2;
1677 cmsStage* Matrix1, *Matrix2;
1678 cmsMAT3 res;
1679 cmsBool IdentityMat;
1680 cmsPipeline* Dest, *Src;
1681 cmsFloat64Number* Offset;
1682
1683 // Only works on RGB to RGB
1684 if (T_CHANNELS(*InputFormat) != 3 || T_CHANNELS(*OutputFormat) != 3) return FALSE;
1685
1686 // Only works on 8 bit input
1687 if (!_cmsFormatterIs8bit(*InputFormat)) return FALSE;
1688
1689 // Does not work in the presence of premultiplied alpha, as that causes the values
1690 // passed in to not actually be '8 bit' in the way that we rely on.
1691 if (*dwFlags & cmsFLAGS_PREMULT) return FALSE;
1692
1693 // Seems suitable, proceed
1694 Src = *Lut;
1695
1696 // Check for:
1697 //
1698 // shaper-matrix-matrix-shaper
1699 // shaper-matrix-shaper
1700 //
1701 // Both of those constructs are possible (first because abs. colorimetric).
1702 // additionally, In the first case, the input matrix offset should be zero.
1703
1704 IdentityMat = FALSE;
1705 if (cmsPipelineCheckAndRetreiveStages(ContextID, Src, 4,
1706 cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
1707 &Curve1, &Matrix1, &Matrix2, &Curve2)) {
1708
1709 // Get both matrices
1710 _cmsStageMatrixData* Data1 = (_cmsStageMatrixData*)cmsStageData(ContextID, Matrix1);
1711 _cmsStageMatrixData* Data2 = (_cmsStageMatrixData*)cmsStageData(ContextID, Matrix2);
1712
1713 // Only RGB to RGB
1714 if (Matrix1->InputChannels != 3 || Matrix1->OutputChannels != 3 ||
1715 Matrix2->InputChannels != 3 || Matrix2->OutputChannels != 3) return FALSE;
1716
1717 // Input offset should be zero
1718 if (Data1->Offset != NULL) return FALSE;
1719
1720 // Multiply both matrices to get the result
1721 _cmsMAT3per(ContextID, &res, (cmsMAT3*)Data2->Double, (cmsMAT3*)Data1->Double);
1722
1723 // Only 2nd matrix has offset, or it is zero
1724 Offset = Data2->Offset;
1725
1726 // Now the result is in res + Data2 -> Offset. Maybe is a plain identity?
1727 if (_cmsMAT3isIdentity(ContextID, &res) && Offset == NULL) {
1728
1729 // We can get rid of full matrix
1730 IdentityMat = TRUE;
1731 }
1732
1733 }
1734 else {
1735
1736 if (cmsPipelineCheckAndRetreiveStages(ContextID, Src, 3,
1737 cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType,
1738 &Curve1, &Matrix1, &Curve2)) {
1739
1740 _cmsStageMatrixData* Data = (_cmsStageMatrixData*)cmsStageData(ContextID, Matrix1);
1741
1742 if (Matrix1->InputChannels != 3 || Matrix1->OutputChannels != 3) return FALSE;
1743
1744 // Copy the matrix to our result
1745 memcpy(&res, Data->Double, sizeof(res));
1746
1747 // Preserve the Odffset (may be NULL as a zero offset)
1748 Offset = Data->Offset;
1749
1750 if (_cmsMAT3isIdentity(ContextID, &res) && Offset == NULL) {
1751
1752 // We can get rid of full matrix
1753 IdentityMat = TRUE;
1754 }
1755 }
1756 else
1757 return FALSE; // Not optimizeable this time
1758
1759 }
1760
1761 // Allocate an empty LUT
1762 Dest = cmsPipelineAlloc(ContextID, Src ->InputChannels, Src ->OutputChannels);
1763 if (!Dest) return FALSE;
1764
1765 // Assamble the new LUT
1766 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_BEGIN, cmsStageDup(ContextID, Curve1)))
1767 goto Error;
1768
1769 if (!IdentityMat) {
1770
1771 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (const cmsFloat64Number*)&res, Offset)))
1772 goto Error;
1773 }
1774
1775 if (!cmsPipelineInsertStage(ContextID, Dest, cmsAT_END, cmsStageDup(ContextID, Curve2)))
1776 goto Error;
1777
1778 // If identity on matrix, we can further optimize the curves, so call the join curves routine
1779 if (IdentityMat) {
1780
1781 OptimizeByJoiningCurves(ContextID, &Dest, Intent, InputFormat, OutputFormat, dwFlags);
1782 }
1783 else {
1784 _cmsStageToneCurvesData* mpeC1 = (_cmsStageToneCurvesData*) cmsStageData(ContextID, Curve1);
1785 _cmsStageToneCurvesData* mpeC2 = (_cmsStageToneCurvesData*) cmsStageData(ContextID, Curve2);
1786
1787 // In this particular optimization, cache does not help as it takes more time to deal with
1788 // the cache than with the pixel handling
1789 *dwFlags |= cmsFLAGS_NOCACHE;
1790
1791 // Setup the optimizarion routines
1792 SetMatShaper(ContextID, Dest, mpeC1 ->TheCurves, &res, (cmsVEC3*) Offset, mpeC2->TheCurves, OutputFormat);
1793 }
1794
1795 cmsPipelineFree(ContextID, Src);
1796 *Lut = Dest;
1797 return TRUE;
1798 Error:
1799 // Leave Src unchanged
1800 cmsPipelineFree(ContextID, Dest);
1801 return FALSE;
1802 }
1803
1804
1805 // -------------------------------------------------------------------------------------------------------------------------------------
1806 // Optimization plug-ins
1807
1808 // List of optimizations
1809 typedef struct _cmsOptimizationCollection_st {
1810
1811 _cmsOPToptimizeFn OptimizePtr;
1812
1813 struct _cmsOptimizationCollection_st *Next;
1814
1815 } _cmsOptimizationCollection;
1816
1817
1818 // The built-in list. We currently implement 4 types of optimizations. Joining of curves, matrix-shaper, linearization and resampling
1819 static _cmsOptimizationCollection DefaultOptimization[] = {
1820
1821 { OptimizeByJoiningCurves, &DefaultOptimization[1] },
1822 { OptimizeMatrixShaper, &DefaultOptimization[2] },
1823 { OptimizeByComputingLinearization, &DefaultOptimization[3] },
1824 { OptimizeByResampling, NULL }
1825 };
1826
1827 // The linked list head
1828 _cmsOptimizationPluginChunkType _cmsOptimizationPluginChunk = { NULL };
1829
1830
1831 // Duplicates the zone of memory used by the plug-in in the new context
1832 static
1833 void DupPluginOptimizationList(struct _cmsContext_struct* ctx,
1834 const struct _cmsContext_struct* src)
1835 {
1836 _cmsOptimizationPluginChunkType newHead = { NULL };
1837 _cmsOptimizationCollection* entry;
1838 _cmsOptimizationCollection* Anterior = NULL;
1839 _cmsOptimizationPluginChunkType* head = (_cmsOptimizationPluginChunkType*) src->chunks[OptimizationPlugin];
1840
1841 _cmsAssert(ctx != NULL);
1842 _cmsAssert(head != NULL);
1843
1844 // Walk the list copying all nodes
1845 for (entry = head->OptimizationCollection;
1846 entry != NULL;
1847 entry = entry ->Next) {
1848
1849 _cmsOptimizationCollection *newEntry = ( _cmsOptimizationCollection *) _cmsSubAllocDup(ctx ->MemPool, entry, sizeof(_cmsOptimizationCollection));
1850
1851 if (newEntry == NULL)
1852 return;
1853
1854 // We want to keep the linked list order, so this is a little bit tricky
1855 newEntry -> Next = NULL;
1856 if (Anterior)
1857 Anterior -> Next = newEntry;
1858
1859 Anterior = newEntry;
1860
1861 if (newHead.OptimizationCollection == NULL)
1862 newHead.OptimizationCollection = newEntry;
1863 }
1864
1865 ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsOptimizationPluginChunkType));
1866 }
1867
1868 void _cmsAllocOptimizationPluginChunk(struct _cmsContext_struct* ctx,
1869 const struct _cmsContext_struct* src)
1870 {
1871 if (src != NULL) {
1872
1873 // Copy all linked list
1874 DupPluginOptimizationList(ctx, src);
1875 }
1876 else {
1877 static _cmsOptimizationPluginChunkType OptimizationPluginChunkType = { NULL };
1878 ctx ->chunks[OptimizationPlugin] = _cmsSubAllocDup(ctx ->MemPool, &OptimizationPluginChunkType, sizeof(_cmsOptimizationPluginChunkType));
1879 }
1880 }
1881
1882
1883 // Register new ways to optimize
1884 cmsBool _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Data)
1885 {
1886 cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
1887 _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
1888 _cmsOptimizationCollection* fl;
1889
1890 if (Data == NULL) {
1891
1892 ctx->OptimizationCollection = NULL;
1893 return TRUE;
1894 }
1895
1896 // Optimizer callback is required
1897 if (Plugin ->OptimizePtr == NULL) return FALSE;
1898
1899 fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsOptimizationCollection));
1900 if (fl == NULL) return FALSE;
1901
1902 // Copy the parameters
1903 fl ->OptimizePtr = Plugin ->OptimizePtr;
1904
1905 // Keep linked list
1906 fl ->Next = ctx->OptimizationCollection;
1907
1908 // Set the head
1909 ctx ->OptimizationCollection = fl;
1910
1911 // All is ok
1912 return TRUE;
1913 }
1914
1915 // The entry point for LUT optimization
1916 cmsBool CMSEXPORT _cmsOptimizePipeline(cmsContext ContextID,
1917 cmsPipeline** PtrLut,
1918 cmsUInt32Number Intent,
1919 cmsUInt32Number* InputFormat,
1920 cmsUInt32Number* OutputFormat,
1921 cmsUInt32Number* dwFlags)
1922 {
1923 _cmsOptimizationPluginChunkType* ctx = ( _cmsOptimizationPluginChunkType*) _cmsContextGetClientChunk(ContextID, OptimizationPlugin);
1924 _cmsOptimizationCollection* Opts;
1925 cmsBool AnySuccess = FALSE;
1926 cmsStage* mpe;
1927
1928 // A CLUT is being asked, so force this specific optimization
1929 if (*dwFlags & cmsFLAGS_FORCE_CLUT) {
1930
1931 PreOptimize(ContextID, *PtrLut);
1932 return OptimizeByResampling(ContextID, PtrLut, Intent, InputFormat, OutputFormat, dwFlags);
1933 }
1934
1935 // Anything to optimize?
1936 if ((*PtrLut) ->Elements == NULL) {
1937 _cmsPipelineSetOptimizationParameters(ContextID, *PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1938 return TRUE;
1939 }
1940
1941 // Named color pipelines cannot be optimized
1942 for (mpe = cmsPipelineGetPtrToFirstStage(ContextID, *PtrLut);
1943 mpe != NULL;
1944 mpe = cmsStageNext(ContextID, mpe)) {
1945 if (cmsStageType(ContextID, mpe) == cmsSigNamedColorElemType) return FALSE;
1946 }
1947
1948 // Try to get rid of identities and trivial conversions.
1949 AnySuccess = PreOptimize(ContextID, *PtrLut);
1950
1951 // After removal do we end with an identity?
1952 if ((*PtrLut) ->Elements == NULL) {
1953 _cmsPipelineSetOptimizationParameters(ContextID, *PtrLut, FastIdentity16, (void*) *PtrLut, NULL, NULL);
1954 return TRUE;
1955 }
1956
1957 // Do not optimize, keep all precision
1958 if (*dwFlags & cmsFLAGS_NOOPTIMIZE)
1959 return FALSE;
1960
1961 // Try plug-in optimizations
1962 for (Opts = ctx->OptimizationCollection;
1963 Opts != NULL;
1964 Opts = Opts ->Next) {
1965
1966 // If one schema succeeded, we are done
1967 if (Opts ->OptimizePtr(ContextID, PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1968
1969 return TRUE; // Optimized!
1970 }
1971 }
1972
1973 // Try built-in optimizations
1974 for (Opts = DefaultOptimization;
1975 Opts != NULL;
1976 Opts = Opts ->Next) {
1977
1978 if (Opts ->OptimizePtr(ContextID, PtrLut, Intent, InputFormat, OutputFormat, dwFlags)) {
1979
1980 return TRUE;
1981 }
1982 }
1983
1984 // Only simple optimizations succeeded
1985 return AnySuccess;
1986 }
1987
1988 cmsBool _cmsLutIsIdentity(cmsPipeline *PtrLut)
1989 {
1990 return !PtrLut || PtrLut->Eval16Fn == FastIdentity16;
1991 }