3 // Little Color Management System
4 // Copyright (c) 1998-2011 Marti Maria Saguer
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:
13 // The above copyright notice and this permission notice shall be included in
14 // all copies or substantial portions of the Software.
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.
24 //---------------------------------------------------------------------------------
27 #ifndef _lcms_internal_H
29 // Include plug-in foundation
30 #ifndef _lcms_plugin_H
31 # include "lcms2_plugin.h"
34 // ctype is part of C99 as per 7.1.2
37 // assert macro is part of C99 as per 7.2
40 // Some needed constants
42 # define M_PI 3.14159265358979323846
46 # define M_LOG10E 0.434294481903251827651
49 // BorlandC 5.5, VC2003 are broken on that
50 #if defined(__BORLANDC__) || (_MSC_VER <= 1400) // 1400 == VC++ 8.0
51 #define sinf(x) (float)sin((float)x)
52 #define sqrtf(x) (float)sqrt((float)x)
56 // Alignment of ICC file format uses 4 bytes (cmsUInt32Number)
57 #define _cmsALIGNLONG(x) (((x)+(sizeof(cmsUInt32Number)-1)) & ~(sizeof(cmsUInt32Number)-1))
59 // Alignment to memory pointer
60 #define _cmsALIGNMEM(x) (((x)+(sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
62 // Maximum encodeable values in floating point
63 #define MAX_ENCODEABLE_XYZ (1.0 + 32767.0/32768.0)
64 #define MIN_ENCODEABLE_ab2 (-128.0)
65 #define MAX_ENCODEABLE_ab2 ((65535.0/256.0) - 128.0)
66 #define MIN_ENCODEABLE_ab4 (-128.0)
67 #define MAX_ENCODEABLE_ab4 (127.0)
69 // Maximum of channels for internal pipeline evaluation
70 #define MAX_STAGE_CHANNELS 128
72 // Unused parameter warning supression
73 #define cmsUNUSED_PARAMETER(x) ((void)x)
75 // The specification for "inline" is section 6.7.4 of the C99 standard (ISO/IEC 9899:1999).
76 // unfortunately VisualC++ does not conform that
77 #if defined(_MSC_VER) || defined(__BORLANDC__)
78 # define cmsINLINE __inline
80 # define cmsINLINE static inline
83 // Other replacement functions
86 # define snprintf _snprintf
89 # define vsnprintf _vsnprintf
94 // A fast way to convert from/to 16 <-> 8 bits
95 #define FROM_8_TO_16(rgb) (cmsUInt16Number) ((((cmsUInt16Number) (rgb)) << 8)|(rgb))
96 #define FROM_16_TO_8(rgb) (cmsUInt8Number) ((((rgb) * 65281 + 8388608) >> 24) & 0xFF)
98 // Code analysis is broken on asserts
100 # if (_MSC_VER >= 1500)
101 # define _cmsAssert(a) { assert((a)); __analysis_assume((a)); }
103 # define _cmsAssert(a) assert((a))
106 # define _cmsAssert(a) assert((a))
109 //---------------------------------------------------------------------------------
111 // Determinant lower than that are assumed zero (used on matrix invert)
112 #define MATRIX_DET_TOLERANCE 0.0001
114 //---------------------------------------------------------------------------------
117 #define FIXED_TO_INT(x) ((x)>>16)
118 #define FIXED_REST_TO_INT(x) ((x)&0xFFFFU)
119 #define ROUND_FIXED_TO_INT(x) (((x)+0x8000)>>16)
121 cmsINLINE cmsS15Fixed16Number _cmsToFixedDomain(int a) { return a + ((a + 0x7fff) / 0xffff); }
122 cmsINLINE int _cmsFromFixedDomain(cmsS15Fixed16Number a) { return a - ((a + 0x7fff) >> 16); }
124 // -----------------------------------------------------------------------------------------------------------
126 // Fast floor conversion logic. Thanks to Sree Kotay and Stuart Nixon
127 // note than this only works in the range ..-32767...+32767 because
128 // mantissa is interpreted as 15.16 fixed point.
129 // The union is to avoid pointer aliasing overoptimization.
130 cmsINLINE int _cmsQuickFloor(cmsFloat64Number val)
132 #ifdef CMS_DONT_USE_FAST_FLOOR
133 return (int) floor(val);
135 const cmsFloat64Number _lcms_double2fixmagic = 68719476736.0 * 1.5; // 2^36 * 1.5, (52-16=36) uses limited precision to floor
137 cmsFloat64Number val;
141 temp.val = val + _lcms_double2fixmagic;
143 #ifdef CMS_USE_BIG_ENDIAN
144 return temp.halves[1] >> 16;
146 return temp.halves[0] >> 16;
151 // Fast floor restricted to 0..65535.0
152 cmsINLINE cmsUInt16Number _cmsQuickFloorWord(cmsFloat64Number d)
154 return (cmsUInt16Number) _cmsQuickFloor(d - 32767.0) + 32767U;
157 // Floor to word, taking care of saturation
158 cmsINLINE cmsUInt16Number _cmsQuickSaturateWord(cmsFloat64Number d)
161 if (d <= 0) return 0;
162 if (d >= 65535.0) return 0xffff;
164 return _cmsQuickFloorWord(d);
167 // Plug-In registering ---------------------------------------------------------------
169 // Specialized function for plug-in memory management. No pairing free() since whole pool is freed at once.
170 void* _cmsPluginMalloc(cmsUInt32Number size);
173 cmsBool _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
176 cmsBool _cmsRegisterInterpPlugin(cmsPluginBase* Plugin);
179 cmsBool _cmsRegisterParametricCurvesPlugin(cmsPluginBase* Plugin);
181 // Formatters management
182 cmsBool _cmsRegisterFormattersPlugin(cmsPluginBase* Plugin);
184 // Tag type management
185 cmsBool _cmsRegisterTagTypePlugin(cmsPluginBase* Plugin);
188 cmsBool _cmsRegisterTagPlugin(cmsPluginBase* Plugin);
191 cmsBool _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Plugin);
193 // Multi Process elements
194 cmsBool _cmsRegisterMultiProcessElementPlugin(cmsPluginBase* Plugin);
197 cmsBool _cmsRegisterOptimizationPlugin(cmsPluginBase* Plugin);
200 // ---------------------------------------------------------------------------------------------------------
202 // Suballocators. Those are blocks of memory that is freed at the end on whole block.
203 typedef struct _cmsSubAllocator_chunk_st {
205 cmsUInt8Number* Block;
206 cmsUInt32Number BlockSize;
207 cmsUInt32Number Used;
209 struct _cmsSubAllocator_chunk_st* next;
211 } _cmsSubAllocator_chunk;
216 cmsContext ContextID;
217 _cmsSubAllocator_chunk* h;
222 _cmsSubAllocator* _cmsCreateSubAlloc(cmsContext ContextID, cmsUInt32Number Initial);
223 void _cmsSubAllocDestroy(_cmsSubAllocator* s);
224 void* _cmsSubAlloc(_cmsSubAllocator* s, cmsUInt32Number size);
226 // ----------------------------------------------------------------------------------
228 // MLU internal representation
231 cmsUInt16Number Language;
232 cmsUInt16Number Country;
234 cmsUInt32Number StrW; // Offset to current unicode string
235 cmsUInt32Number Len; // Lenght in bytes
239 struct _cms_MLU_struct {
241 cmsContext ContextID;
244 int AllocatedEntries;
246 _cmsMLUentry* Entries; // Array of pointers to strings allocated in MemPool
249 cmsUInt32Number PoolSize; // The maximum allocated size
250 cmsUInt32Number PoolUsed; // The used size
251 void* MemPool; // Pointer to begin of memory pool
254 // Named color list internal representation
257 char Name[cmsMAX_PATH];
258 cmsUInt16Number PCS[3];
259 cmsUInt16Number DeviceColorant[cmsMAXCHANNELS];
263 struct _cms_NAMEDCOLORLIST_struct {
265 cmsUInt32Number nColors;
266 cmsUInt32Number Allocated;
267 cmsUInt32Number ColorantCount;
269 char Prefix[33]; // Prefix and suffix are defined to be 32 characters at most
272 _cmsNAMEDCOLOR* List;
274 cmsContext ContextID;
278 // ----------------------------------------------------------------------------------
280 // This is the internal struct holding profile details.
282 // Maximum supported tags in a profile
283 #define MAX_TABLE_TAG 100
285 typedef struct _cms_iccprofile_struct {
288 cmsIOHANDLER* IOhandler;
291 cmsContext ContextID;
296 // Only most important items found in ICC profiles
297 cmsUInt32Number Version;
298 cmsProfileClassSignature DeviceClass;
299 cmsColorSpaceSignature ColorSpace;
300 cmsColorSpaceSignature PCS;
301 cmsUInt32Number RenderingIntent;
302 cmsUInt32Number flags;
303 cmsUInt32Number manufacturer, model;
304 cmsUInt64Number attributes;
306 cmsProfileID ProfileID;
309 cmsUInt32Number TagCount;
310 cmsTagSignature TagNames[MAX_TABLE_TAG];
311 cmsTagSignature TagLinked[MAX_TABLE_TAG]; // The tag to wich is linked (0=none)
312 cmsUInt32Number TagSizes[MAX_TABLE_TAG]; // Size on disk
313 cmsUInt32Number TagOffsets[MAX_TABLE_TAG];
314 cmsBool TagSaveAsRaw[MAX_TABLE_TAG]; // True to write uncooked
315 void * TagPtrs[MAX_TABLE_TAG];
316 cmsTagTypeHandler* TagTypeHandlers[MAX_TABLE_TAG]; // Same structure may be serialized on different types
317 // depending on profile version, so we keep track of the // type handler for each tag in the list.
323 // IO helpers for profiles
324 cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc);
325 cmsBool _cmsWriteHeader(_cmsICCPROFILE* Icc, cmsUInt32Number UsedSpace);
326 int _cmsSearchTag(_cmsICCPROFILE* Icc, cmsTagSignature sig, cmsBool lFollowLinks);
329 cmsTagTypeHandler* _cmsGetTagTypeHandler(cmsTagTypeSignature sig);
330 cmsTagTypeSignature _cmsGetTagTrueType(cmsHPROFILE hProfile, cmsTagSignature sig);
331 cmsTagDescriptor* _cmsGetTagDescriptor(cmsTagSignature sig);
333 // Error logging ---------------------------------------------------------------------------------------------------------
335 void _cmsTagSignature2String(char String[5], cmsTagSignature sig);
337 // Interpolation ---------------------------------------------------------------------------------------------------------
339 cmsInterpParams* _cmsComputeInterpParams(cmsContext ContextID, int nSamples, int InputChan, int OutputChan, const void* Table, cmsUInt32Number dwFlags);
340 cmsInterpParams* _cmsComputeInterpParamsEx(cmsContext ContextID, const cmsUInt32Number nSamples[], int InputChan, int OutputChan, const void* Table, cmsUInt32Number dwFlags);
341 void _cmsFreeInterpParams(cmsInterpParams* p);
342 cmsBool _cmsSetInterpolationRoutine(cmsInterpParams* p);
344 // Curves ----------------------------------------------------------------------------------------------------------------
346 // This struct holds information about a segment, plus a pointer to the function that implements the evaluation.
347 // In the case of table-based, Eval pointer is set to NULL
349 // The gamma function main structure
350 struct _cms_curve_struct {
352 cmsInterpParams* InterpParams; // Private optimizations for interpolation
354 cmsUInt32Number nSegments; // Number of segments in the curve. Zero for a 16-bit based tables
355 cmsCurveSegment* Segments; // The segments
356 cmsInterpParams** SegInterp; // Array of private optimizations for interpolation in table-based segments
358 cmsParametricCurveEvaluator* Evals; // Evaluators (one per segment)
360 // 16 bit Table-based representation follows
361 cmsUInt32Number nEntries; // Number of table elements
362 cmsUInt16Number* Table16; // The table itself.
366 // Pipelines & Stages ---------------------------------------------------------------------------------------------
369 struct _cmsStage_struct {
371 cmsContext ContextID;
373 cmsStageSignature Type; // Identifies the stage
374 cmsStageSignature Implements; // Identifies the *function* of the stage (for optimizations)
376 cmsUInt32Number InputChannels; // Input channels -- for optimization purposes
377 cmsUInt32Number OutputChannels; // Output channels -- for optimization purposes
379 _cmsStageEvalFn EvalPtr; // Points to fn that evaluates the stage (always in floating point)
380 _cmsStageDupElemFn DupElemPtr; // Points to a fn that duplicates the *data* of the stage
381 _cmsStageFreeElemFn FreePtr; // Points to a fn that sets the *data* of the stage free
383 // A generic pointer to whatever memory needed by the stage
386 // Maintains linked list (used internally)
387 struct _cmsStage_struct* Next;
390 // Data kept in "Element" member of cmsStage
394 cmsUInt32Number nCurves;
395 cmsToneCurve** TheCurves;
397 } _cmsStageToneCurvesData;
401 cmsFloat64Number* Double; // floating point for the matrix
402 cmsFloat64Number* Offset; // The offset
404 } _cmsStageMatrixData;
409 union { // Can have only one of both representations at same time
410 cmsUInt16Number* T; // Points to the table 16 bits table
411 cmsFloat32Number* TFloat; // Points to the cmsFloat32Number table
415 cmsInterpParams* Params;
416 cmsUInt32Number nEntries;
417 cmsBool HasFloatValues;
422 // Special Stages (cannot be saved)
423 cmsStage* _cmsStageAllocLab2XYZ(cmsContext ContextID);
424 cmsStage* _cmsStageAllocXYZ2Lab(cmsContext ContextID);
425 cmsStage* _cmsStageAllocLabPrelin(cmsContext ContextID);
426 cmsStage* _cmsStageAllocLabV2ToV4(cmsContext ContextID);
427 cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID);
428 cmsStage* _cmsStageAllocLabV4ToV2(cmsContext ContextID);
429 cmsStage* _cmsStageAllocNamedColor(cmsNAMEDCOLORLIST* NamedColorList, cmsBool UsePCS);
430 cmsStage* _cmsStageAllocIdentityCurves(cmsContext ContextID, int nChannels);
431 cmsStage* _cmsStageAllocIdentityCLut(cmsContext ContextID, int nChan);
432 cmsStage* _cmsStageNormalizeFromLabFloat(cmsContext ContextID);
433 cmsStage* _cmsStageNormalizeFromXyzFloat(cmsContext ContextID);
434 cmsStage* _cmsStageNormalizeToLabFloat(cmsContext ContextID);
435 cmsStage* _cmsStageNormalizeToXyzFloat(cmsContext ContextID);
437 // For curve set only
438 cmsToneCurve** _cmsStageGetPtrToCurveSet(const cmsStage* mpe);
441 // Pipeline Evaluator (in floating point)
442 typedef void (* _cmsPipelineEvalFloatFn)(const cmsFloat32Number In[],
443 cmsFloat32Number Out[],
446 struct _cmsPipeline_struct {
448 cmsStage* Elements; // Points to elements chain
449 cmsUInt32Number InputChannels, OutputChannels;
454 _cmsOPTeval16Fn Eval16Fn;
455 _cmsPipelineEvalFloatFn EvalFloatFn;
456 _cmsOPTfreeDataFn FreeDataFn;
457 _cmsOPTdupDataFn DupDataFn;
459 cmsContext ContextID; // Environment
461 cmsBool SaveAs8Bits; // Implementation-specific: save as 8 bits if possible
464 // LUT reading & creation -------------------------------------------------------------------------------------------
466 // Read tags using low-level function, provide necessary glue code to adapt versions, etc. All those return a brand new copy
467 // of the LUTS, since ownership of original is up to the profile. The user should free allocated resources.
469 cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent);
470 cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent);
471 cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent);
474 cmsBool _cmsReadMediaWhitePoint(cmsCIEXYZ* Dest, cmsHPROFILE hProfile);
475 cmsBool _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile);
477 // Profile linker --------------------------------------------------------------------------------------------------
479 cmsPipeline* _cmsLinkProfiles(cmsContext ContextID,
480 cmsUInt32Number nProfiles,
481 cmsUInt32Number TheIntents[],
482 cmsHPROFILE hProfiles[],
484 cmsFloat64Number AdaptationStates[],
485 cmsUInt32Number dwFlags);
487 // Sequence --------------------------------------------------------------------------------------------------------
489 cmsSEQ* _cmsReadProfileSequence(cmsHPROFILE hProfile);
490 cmsBool _cmsWriteProfileSequence(cmsHPROFILE hProfile, const cmsSEQ* seq);
491 cmsSEQ* _cmsCompileProfileSequence(cmsContext ContextID, cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[]);
494 // LUT optimization ------------------------------------------------------------------------------------------------
496 cmsUInt16Number _cmsQuantizeVal(cmsFloat64Number i, int MaxSamples);
497 int _cmsReasonableGridpointsByColorspace(cmsColorSpaceSignature Colorspace, cmsUInt32Number dwFlags);
499 cmsBool _cmsEndPointsBySpace(cmsColorSpaceSignature Space,
500 cmsUInt16Number **White,
501 cmsUInt16Number **Black,
502 cmsUInt32Number *nOutputs);
504 cmsBool _cmsOptimizePipeline(cmsPipeline** Lut,
506 cmsUInt32Number* InputFormat,
507 cmsUInt32Number* OutputFormat,
508 cmsUInt32Number* dwFlags );
511 // Hi level LUT building ----------------------------------------------------------------------------------------------
513 cmsPipeline* _cmsCreateGamutCheckPipeline(cmsContext ContextID,
514 cmsHPROFILE hProfiles[],
516 cmsUInt32Number Intents[],
517 cmsFloat64Number AdaptationStates[],
518 cmsUInt32Number nGamutPCSposition,
522 // Formatters ------------------------------------------------------------------------------------------------------------
524 #define cmsFLAGS_CAN_CHANGE_FORMATTER 0x02000000 // Allow change buffer format
526 cmsBool _cmsFormatterIsFloat(cmsUInt32Number Type);
527 cmsBool _cmsFormatterIs8bit(cmsUInt32Number Type);
529 cmsFormatter _cmsGetFormatter(cmsUInt32Number Type, // Specific type, i.e. TYPE_RGB_8
530 cmsFormatterDirection Dir,
531 cmsUInt32Number dwFlags);
534 // Transform logic ------------------------------------------------------------------------------------------------------
536 struct _cmstransform_struct;
540 // 1-pixel cache (16 bits only)
541 cmsUInt16Number CacheIn[cmsMAXCHANNELS];
542 cmsUInt16Number CacheOut[cmsMAXCHANNELS];
548 typedef void (* _cmsTransformFn)(struct _cmstransform_struct *Transform,
549 const void* InputBuffer,
551 cmsUInt32Number Size);
555 cmsUInt32Number InputFormat, OutputFormat; // Keep formats for further reference
556 cmsUInt32Number StrideIn, StrideOut; // Planar support
561 typedef struct _cmstransform_struct {
563 cmsUInt32Number InputFormat, OutputFormat; // Keep formats for further reference
565 // Points to transform code
566 _cmsTransformFn xform;
568 // Formatters, cannot be embedded into LUT because cache
569 cmsFormatter16 FromInput;
570 cmsFormatter16 ToOutput;
572 cmsFormatterFloat FromInputFloat;
573 cmsFormatterFloat ToOutputFloat;
575 // 1-pixel cache seed for zero as input (16 bits, read only)
578 // A MPE LUT holding the full (optimized) transform
581 // A MPE LUT holding the gamut check. It goes from the input space to bilevel
582 cmsPipeline* GamutCheck;
585 cmsNAMEDCOLORLIST* InputColorant; // Input Colorant table
586 cmsNAMEDCOLORLIST* OutputColorant; // Colorant table (for n chans > CMYK)
588 // Informational only
589 cmsColorSpaceSignature EntryColorSpace;
590 cmsColorSpaceSignature ExitColorSpace;
592 // Profiles used to create the transform
595 cmsUInt32Number dwOriginalFlags;
596 cmsFloat64Number AdaptationState;
598 // The intent of this transform. That is usually the last intent in the profilechain, but may differ
599 cmsUInt32Number RenderingIntent;
601 // An id that uniquely identifies the running context. May be null.
602 cmsContext ContextID;
606 // --------------------------------------------------------------------------------------------------
608 cmsHTRANSFORM _cmsChain2Lab(cmsContext ContextID,
609 cmsUInt32Number nProfiles,
610 cmsUInt32Number InputFormat,
611 cmsUInt32Number OutputFormat,
612 const cmsUInt32Number Intents[],
613 const cmsHPROFILE hProfiles[],
615 const cmsFloat64Number AdaptationStates[],
616 cmsUInt32Number dwFlags);
619 cmsToneCurve* _cmsBuildKToneCurve(cmsContext ContextID,
620 cmsUInt32Number nPoints,
621 cmsUInt32Number nProfiles,
622 const cmsUInt32Number Intents[],
623 const cmsHPROFILE hProfiles[],
625 const cmsFloat64Number AdaptationStates[],
626 cmsUInt32Number dwFlags);
628 cmsBool _cmsAdaptationMatrix(cmsMAT3* r, const cmsMAT3* ConeMatrix, const cmsCIEXYZ* FromIll, const cmsCIEXYZ* ToIll);
630 cmsBool _cmsBuildRGB2XYZtransferMatrix(cmsMAT3* r, const cmsCIExyY* WhitePoint, const cmsCIExyYTRIPLE* Primaries);
633 #define _lcms_internal_H