-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathProfile.js
More file actions
1558 lines (1404 loc) · 63.4 KB
/
Copy pathProfile.js
File metadata and controls
1558 lines (1404 loc) · 63.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*************************************************************************
* @license
*
*
* Copyright © 2019, 2024 Glenn Wilton
* O2 Creative Limited
* www.o2creative.co.nz
* support@o2creative.co.nz
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
*/
'use strict';
const convert = require('./convert');
const colorEngineDef = require('./def');
const eIntent = colorEngineDef.eIntent;
const eProfileType = colorEngineDef.eProfileType;
const decode = require('./decodeICC');
/**
* ============================================================================
* Profile.js — load, decode and synthesize ICC profiles
* ============================================================================
*
* The `Profile` class is the data layer of the engine. It does not perform
* any colour conversions itself — it produces a normalized, in-memory
* description of a colour profile that `Transform.js` then consumes to
* build pipelines.
*
* Two fundamentally different ways to construct a profile:
*
* 1. ICC FILE — decode the bytes of a real `.icc` / `.icm` file via
* `decodeICC.js`. Supports ICC v2 and v4, RGB / Gray / Lab / CMYK
* (and 2CLR / 3CLR / 4CLR / CMY ) device colour spaces, with PCS
* in either Lab or XYZ. All four standard rendering intents plus
* the AtoB/BtoA LUT pairs are extracted.
*
* 2. VIRTUAL — synthesize a profile in memory from primaries + gamma.
* Supported names: sRGB, AdobeRGB, AppleRGB, ColorMatchRGB,
* ProPhotoRGB, Lab, LabD50, LabD65. No I/O, no decode, no file
* parsing — just maths. See `createVirtualProfile`.
*
* ----------------------------------------------------------------------------
* IMPORTANT: ICC vs VIRTUAL — when does loading a real profile pay off?
* ----------------------------------------------------------------------------
*
* Most RGB ICC profiles in the wild (sRGB.icc, AdobeRGB1998.icc,
* ProPhoto.icm, every monitor profile your OS ships) are MATRIX + TRC
* profiles — i.e. three primary XYZ tristimuli and three tone curves,
* no LUTs at all. The maths is exactly the same as what
* `createVirtualProfile` builds in-memory, so:
*
* `'*sRGB'` ←→ functionally identical
* `Profile().load('sRGB.icc', cb)`
*
* for any colour transform built on top. The difference is purely
* startup cost:
*
* virtual profile: ~0 ms, no I/O, no decode, deterministic numbers
* ICC matrix file: network/disk fetch + binary decode + adaptation
*
* When TO load a real ICC profile:
*
* - The profile is a CMYK or 3CLR/4CLR device profile (LUT-based; no
* virtual equivalent exists).
* - It's a printer/scanner ICC with a real measurement-derived AtoB
* LUT — the gamut mapping there is real data, not a formula.
* - It's a custom monitor profile generated by a calibrator (the
* primaries and TRC will not match a virtual sRGB).
* - You need to faithfully reproduce another CMM's interpretation of
* a specific embedded profile.
*
* When NOT to bother:
*
* - You just want "sRGB" as a working space → use `'*sRGB'`.
* - Adobe RGB, ProPhoto, Apple RGB, ColorMatch — same story.
*
* As a small optimization, when this loader decodes an RGB profile
* whose tags are matrix + TRC only (no AtoB / BtoA LUTs), it
* AUTO-PROMOTES it to the same `RGBMatrix` fast path that virtual
* profiles use (see `readICCProfile` and `createRGBMatrix` below).
* Downstream `Transform.js` cannot tell them apart — they hit the
* identical inlined matrix-and-gamma kernel.
*
* ----------------------------------------------------------------------------
* ENVIRONMENTS
* ----------------------------------------------------------------------------
*
* The loader runs in three places:
* - Browser (XHR, base64)
* - Node.js (fs, http)
* - Adobe CEP extensions (`window.cep.fs`)
*
* Each load entry-point picks the right backend automatically based on
* `isInNode()` / `isInCep()` probes at the bottom of this file.
*
* ----------------------------------------------------------------------------
* LIFECYCLE & ERROR REPORTING
* ----------------------------------------------------------------------------
*
* profile.loaded true once decoded successfully (sync or async)
* profile.loadError true if decode failed; check `profile.lastError`
* profile.lastError { err: number|string, text: string }
* profile.unsuportedTags // sic — see Pr3
*
* All the file-based loaders accept an optional `afterLoad(profile)`
* callback. Combine with `loadPromise()` for `await`-friendly use.
*
* ----------------------------------------------------------------------------
* KNOWN ISSUES (TODO)
* ----------------------------------------------------------------------------
*
* Pr3: Two property names contain typos:
* `unsuportedTags` (missing 'p')
* `virutalProfileUsesD50AdaptedPrimaries` (transposed letters)
* Both are now dual-aliased onto correctly-spelled siblings:
* `unsupportedTags`
* `virtualProfileUsesD50AdaptedPrimaries`
* Read or write either name. The typo'd versions are flagged
* `@deprecated` in JSDoc so IDE autocomplete will surface a
* warning; the corrected names are the way forward. The typos
* will not be removed (would break existing consumers).
*
* Pr4: `loadURL` is asynchronous (callback fires later); `loadFile`,
* `loadBase64`, `loadBinary`, `loadVirtualProfile` are
* SYNCHRONOUS (callback fires before the dispatch returns).
* For uniform behaviour use `loadPromise()`.
*
* Pr5: Reusing one Profile instance across multiple `load()` calls
* only resets `loaded` / `loadError`. Stale `rgb`, `A2B`, `B2A`,
* `tags`, etc. linger if the new profile lacks those tags. Best
* practice: a new `Profile()` per profile.
*
* ----------------------------------------------------------------------------
* CONSTRUCTOR
* ----------------------------------------------------------------------------
*
* @param dataOrUrl - Uint8Array
* - String: 'data:base64...' - load from base64 encoded string
* - String: 'file:filename' - load from local drive using platform File API
* - String: 'http://...' - load via XHR / http
* - String: '*name' - create a virtual profile in memory
* -'*sRGB' - sRGB
* -'*AdobeRGB' - Adobe RGB (1998)
* -'*AppleRGB' - Apple RGB
* -'*ColorMatchRGB' - ColorMatch RGB
* -'*ProPhotoRGB' - ProPhoto RGB
* -'*Lab' - Lab D50
* -'*LabD50' - Lab D50
* -'*LabD65' - Lab D65
*
* @param afterLoad - function(profile) - callback fired when the
* profile finishes loading (success or failure).
* See Pr4 — sync for in-memory paths, async for
* URL / network paths.
* @constructor
*/
class Profile {
// ========================================================================
// CONSTRUCTOR & STATE
// ========================================================================
constructor(dataOrUrl, afterLoad) {
this.loaded = false;
this.loadError = false;
this.type = 0;
this.name = '';
this.header = {};
this.intent = 0;
this.tags = [];
this.description = '';
this.tagDescription = '';
this.copyright = '';
this.technology = '';
this.viewingConditions = '';
this.characterizationTarget = '';
this.mediaWhitePoint = null;
this.PCSEncode = 2;
this.PCSDecode = 2;
this.PCS8BitScale = 0;
this.version = 0;
this.pcs = false;
this.blackPoint = null;
this.luminance = null;
this.chromaticAdaptation = null;
/**
* @deprecated Typo kept for backwards compatibility — prefer
* `virtualProfileUsesD50AdaptedPrimaries`. Both
* names are read by `createVirtualProfile` (the
* corrected one wins if both are set), so old and
* new code both work.
*/
this.virutalProfileUsesD50AdaptedPrimaries = true;
this.virtualProfileUsesD50AdaptedPrimaries = true;
/**
* @deprecated Typo kept for backwards compatibility — prefer
* `unsupportedTags`. Both names point at the same
* array (re-aliased at the end of `decodeFile`),
* so `.push()` from either is visible from both.
*/
this.unsuportedTags = [];
this.unsupportedTags = this.unsuportedTags;
this.Gray = {
kTRC: null,
inv_kTRC: null,
};
this.rgb = {
rTRC: null,
rTRCInv: null,
gTRC: null,
gTRCInv: null,
bTRC: null,
bTRCInv: null,
rXYZ: null,
gXYZ: null,
bXYZ: null
};
this.RGBMatrix = {
gamma: 0,
cRx: 0,
cRy: 0,
cGx: 0,
cGy: 0,
cBx: 0,
cBy: 0
};
this.PCSWhitepoint = convert.d50;
this.outputChannels = 0;
this.lastError = {err: 0, text: 'No Error'};
// These are floating point but more
// complicated and also additional to
// 8/16 bit tables so not implemented yet
this.B2D = [null, null, null, null];
this.D2B = [null, null, null, null];
this.A2B = [null, null, null];
this.B2A = [null, null, null];
this.absoluteAdaptationIn = {
Xa: 1,
Ya: 1,
Za: 1
};
this.absoluteAdaptationOut = {
Xa: 1,
Ya: 1,
Za: 1
};
if (dataOrUrl) {
this.load(dataOrUrl, afterLoad);
}
};
// ========================================================================
// LOADERS — dispatcher + per-source variants
// ========================================================================
/**
* Promise-flavoured wrapper around `load()`. Resolves with the
* `Profile` instance on success, rejects with an Error on failure.
* Use this when you want `await profile.loadPromise(url)` rather
* than callback wiring.
*
* @param {Uint8Array|string} dataOrUrl See `load()`.
* @returns {Promise<Profile>}
*/
loadPromise(dataOrUrl) {
return new Promise((resolve, reject) => {
this.load(dataOrUrl, (loaded) => {
if (loaded) {
resolve(loaded);
} else {
reject(new Error("Profile failed to load"));
}
});
});
}
/**
* Top-level loader. Sniffs the source type and dispatches to the
* right backend:
*
* `Uint8Array` → loadBinary (sync)
* `'*name'` → loadVirtualProfile (sync)
* `'file:...'` → loadFile (sync; Node / CEP only)
* `'data:...'` → loadBase64 (sync)
* anything else → loadURL (async; XHR or http.get)
*
* See Pr4 in the file header about the sync/async split.
*
* @param {Uint8Array|string} dataOrUrl Source identifier (see above).
* @param {function(Profile):void} [afterLoad] Completion callback.
*/
load(dataOrUrl, afterLoad) {
this.loaded = false;
this.loadError = false;
if (Object.prototype.toString.call(dataOrUrl) === '[object Uint8Array]') {
this.loadBinary(dataOrUrl, afterLoad);
} else if (dataOrUrl.substring(0, 1) === '*') {
this.loadVirtualProfile(dataOrUrl, afterLoad);
} else if (dataOrUrl.substring(0, 5).toLowerCase() === 'file:') {
this.loadFile(dataOrUrl, afterLoad);
} else if (dataOrUrl.substring(0, 5).toLowerCase() === 'data:') {
this.loadBase64(dataOrUrl, afterLoad)
} else {
this.loadURL(dataOrUrl, afterLoad);
}
};
/**
* Decode a profile already in memory as a `Uint8Array`. Synchronous.
*
* @param {Uint8Array} binary Raw profile bytes.
* @param {function(Profile):void} [afterLoad]
* @param {boolean} [searchForProfile] If true, scans the buffer
* for an embedded `'ICC_PROFILE'` marker first (e.g. when
* passing a JPEG / TIFF byte stream containing an APP2 / IPTC
* ICC payload).
*/
loadBinary(binary, afterLoad, searchForProfile) {
this.loaded = this.readICCProfile(binary, searchForProfile);
this.loadError = !this.loaded;
if(typeof afterLoad === 'function'){
afterLoad(this);
}
};
/**
* Load a profile from the local filesystem. Synchronous. Available
* in Node.js (via `fs.readFileSync`) and Adobe CEP (via
* `window.cep.fs.readFile`). Not supported in plain browsers.
*
* Accepts either a bare path or a `'file:...'`-prefixed string.
*
* @param {string} filename
* @param {function(Profile):void} [afterLoad]
*/
loadFile(filename, afterLoad) {
if(filename.substring(0, 5).toLowerCase() === 'file:'){
filename = filename.substring(5, filename.length);
}
var binaryData = this.readBinaryFile(filename);
if (binaryData !== false) {
this.loaded = this.readICCProfile(binaryData);
this.loadError = !this.loaded;
} else {
this.loadError = true;
this.loaded = false;
}
if(typeof afterLoad === 'function'){
afterLoad(this);
}
};
/**
* Load a profile from a base64-encoded string. Synchronous. Accepts
* either a bare base64 payload or a `'data:...'`-prefixed string
* (the prefix is stripped — note no MIME parsing, just the literal
* 5-char marker).
*
* @param {string} base64
* @param {function(Profile):void} [afterLoad]
*/
loadBase64(base64, afterLoad) {
if(base64.substring(0, 5).toLowerCase() === 'data:'){
base64 = base64.substring(5, base64.length);
}
var data = base64ToUint8Array(base64);
this.loaded = this.readICCProfile(data);
this.loadError = !this.loaded;
if(typeof afterLoad === 'function'){
afterLoad(this);
}
};
/**
* Load a profile over HTTP. ASYNCHRONOUS — the `afterLoad` callback
* fires after the network round-trip completes, not before this
* method returns. Uses `http.get` in Node and `XMLHttpRequest` in
* the browser.
*
* @param {string} url
* @param {function(Profile):void} [afterLoad]
*/
loadURL(url, afterLoad) {
var _this = this;
if(isInNode()){
nodeLoadFileFromURL(url, processData);
} else {
XHRLoadBinary(url, processData);
}
function processData(result, errorString) {
_this.lastError = {err: errorString === '' ? 0 : -1, text: errorString};
if(result) {
_this.loaded = _this.readICCProfile(result);
_this.loadError = !_this.loaded;
} else {
_this.loaded = false;
_this.loadError = true;
}
if(typeof afterLoad === 'function'){
afterLoad(_this);
}
}
};
/**
* Build a virtual profile by name (no file I/O). Synchronous.
*
* Accepts either a bare name (`'sRGB'`) or a `'*'`-prefixed string
* (`'*sRGB'`); the leading `*` is what the dispatcher in `load()`
* uses to pick this branch.
*
* See `createVirtualProfile` for the supported name list.
*
* @param {string} name
* @param {function(Profile):void} [afterLoad]
*/
loadVirtualProfile(name, afterLoad) {
if(name.substring(0, 1) === '*'){
name = name.substring(1, name.length);
}
this.loaded = this.createVirtualProfile(name);
this.loadError = !this.loaded;
if(typeof afterLoad === 'function'){
afterLoad(this);
}
};
/**
* Synchronous filesystem read backing `loadFile`. Returns either a
* `Uint8Array` of the file contents or `false` on failure (and
* populates `this.lastError` with a structured error object).
*
* Throws in environments other than Node and CEP.
*
* @param {string} filename
* @returns {Uint8Array|false}
*/
readBinaryFile(filename) {
let b64String;
if (isInCep()) {
if(window.cep && window.cep.fs && window.cep.fs.readFile){
//
// In adobe illustrator cep enviroment
//
let file = window.cep.fs.readFile(filename, cep.encoding.Base64);
if (file.err === 0) {
// FIX (Pr2): formerly fell through to the isInNode()
// branch (which is false in CEP) and then threw
// 'not supported in this environment' — so even
// SUCCESSFUL CEP file reads broke. Return the
// decoded payload directly here.
return base64ToUint8Array(file.data);
} else {
this.lastError = {
err: file.err,
text: file.errorString = [
'NO_ERROR', //0
'ERR_UNKNOWN', //1
'ERR_INVALID_PARAMS', //2
'ERR_NOT_FOUND', //3
'ERR_CANT_READ', // 4
'ERR_UNSUPPORTED_ENCODING', // 5
'ERR_CANT_WRITE', // 6
'ERR_OUT_OF_SPACE', // 7
'ERR_NOT_FILE', // 8
'ERR_NOT_DIRECTORY', // 9
'ERR_FILE_EXISTS', // 10
'UNABLE TO PARSE FILE', //11,
'ERR_DIRECTORY_NOT_FOUND' //12
][file.err] || 'UNKNOWN ERROR ' + file.err
};
return false;
}
}
}
if(isInNode()){
//
// In node, we can use the Buffer class
//
const fs = require("fs");
try {
b64String = fs.readFileSync(filename, {encoding: 'base64'});
} catch (e) {
this.lastError = {
err: e,
text: e.message
};
return false;
}
return base64ToUint8Array(b64String)
}
// Not supported in browser
throw new Error('readBinaryFile not supported in this environment');
}
// ========================================================================
// VIRTUAL PROFILES — synthesize a profile from primaries + gamma
// ========================================================================
/**
* Build an in-memory profile from a hard-coded primaries / gamma
* recipe. No file I/O.
*
* Recognized names (case-insensitive, spaces stripped):
*
* `lab` / `labd50` — Lab D50 abstract profile
* `labd65` — Lab D65 abstract profile
* `srgb` — sRGB working space (gamma 2.2 + sRGB special)
* `adobe` / `adobergb` /
* `adobe1998` / `adobe1998rgb` — Adobe RGB (1998), gamma 2.2
* `apple` / `applergb` — Apple RGB, gamma 2.2
* `colormatch` / `colormatchrgb` — ColorMatch RGB, gamma 1.8, D50
* `prophoto` / `prophotorgb` — ProPhoto RGB, gamma 1.8, D50
*
* For RGB names the primaries are stored EITHER pre-adapted to D50
* OR as their native chromaticities, controlled by
* `this.virutalProfileUsesD50AdaptedPrimaries` (sic — see Pr3 in
* the file header) — D50-adapted by default, matching the ICC v4
* convention so transforms with a D50 PCS need no extra step.
*
* Returns true on success, false on unsupported name (and sets
* `this.lastError`).
*
* Internally calls a `computeRGBProfile` helper that calculates
* both the legacy 3x3 matrix and the modern XYZ matrix (and their
* inverses) from the primaries.
*
* @param {string} name
* @returns {boolean}
*/
createVirtualProfile(name) {
// Honour the corrected property name as input too — if the
// caller set `virtualProfileUsesD50AdaptedPrimaries` (no typo)
// mirror it onto the legacy spelling that the read sites
// below actually consume. Lets new code use the right name
// without us having to update every read site.
if (this.virtualProfileUsesD50AdaptedPrimaries !== this.virutalProfileUsesD50AdaptedPrimaries) {
this.virutalProfileUsesD50AdaptedPrimaries = this.virtualProfileUsesD50AdaptedPrimaries;
}
// Virtual Profiles are this.version = v4 so that by default the Transform will output PCS V4 encoded date
// http://www.brucelindbloom.com/index.html?WorkingSpaceInfo.html
//
// gamma white x y Y x y Y x y Y
// Adobe RGB (1998) 2.2 D65 0.6400 0.3300 0.297361 0.2100 0.7100 0.627355 0.1500 0.0600 0.075285
// Apple RGB 1.8 D65 0.6250 0.3400 0.244634 0.2800 0.5950 0.672034 0.1550 0.0700 0.083332
// Best RGB 2.2 D50 0.7347 0.2653 0.228457 0.2150 0.7750 0.737352 0.1300 0.0350 0.034191
// Beta RGB 2.2 D50 0.6888 0.3112 0.303273 0.1986 0.7551 0.663786 0.1265 0.0352 0.032941
// Bruce RGB 2.2 D65 0.6400 0.3300 0.240995 0.2800 0.6500 0.683554 0.1500 0.0600 0.075452
// CIE RGB 2.2 E 0.7350 0.2650 0.176204 0.2740 0.7170 0.812985 0.1670 0.0090 0.010811
// ColorMatch RGB 1.8 D50 0.6300 0.3400 0.274884 0.2950 0.6050 0.658132 0.1500 0.0750 0.066985
// Don RGB 4 2.2 D50 0.6960 0.3000 0.278350 0.2150 0.7650 0.687970 0.1300 0.0350 0.033680
// ECI RGB v2 L* D50 0.6700 0.3300 0.320250 0.2100 0.7100 0.602071 0.1400 0.0800 0.077679
// Ekta Space PS5 2.2 D50 0.6950 0.3050 0.260629 0.2600 0.7000 0.734946 0.1100 0.0050 0.004425
// NTSC RGB 2.2 C 0.6700 0.3300 0.298839 0.2100 0.7100 0.586811 0.1400 0.0800 0.114350
// PAL/SECAM RGB 2.2 D65 0.6400 0.3300 0.222021 0.2900 0.6000 0.706645 0.1500 0.0600 0.071334
// ProPhoto RGB 1.8 D50 0.7347 0.2653 0.288040 0.1596 0.8404 0.711874 0.0366 0.0001 0.000086
// SMPTE-C RGB 2.2 D65 0.6300 0.3400 0.212395 0.3100 0.5950 0.701049 0.1550 0.0700 0.086556
// sRGB ≈2.2 D65 0.6400 0.3300 0.212656 0.3000 0.6000 0.715158 0.1500 0.0600 0.072186
// Wide Gamut RGB 2.2 D50 0.7350 0.2650 0.258187 0.1150 0.8260 0.724938 0.1570 0.0180 0.016875
//Working Space Primaries Adapted to D50
// x y Y x y Y x y Y
// Adobe RGB (1998) 0.648431 0.330856 0.311114 0.230154 0.701572 0.625662 0.155886 0.066044 0.063224
// Apple RGB 0.634756 0.340596 0.255166 0.301775 0.597511 0.672578 0.162897 0.079001 0.072256
// Best RGB 0.734700 0.265300 0.228457 0.215000 0.775000 0.737352 0.130000 0.035000 0.034191
// Beta RGB 0.688800 0.311200 0.303273 0.198600 0.755100 0.663786 0.126500 0.035200 0.032941
// Bruce RGB 0.648431 0.330856 0.252141 0.300115 0.640960 0.684495 0.155886 0.066044 0.063364
// CIE RGB 0.737385 0.264518 0.174658 0.266802 0.718404 0.824754 0.174329 0.000599 0.000588
// ColorMatch RGB 0.630000 0.340000 0.274884 0.295000 0.605000 0.658132 0.150000 0.075000 0.066985
// Don RGB 4 0.696000 0.300000 0.278350 0.215000 0.765000 0.687970 0.130000 0.035000 0.033680
// ECI RGB v2 0.670000 0.330000 0.320250 0.210000 0.710000 0.602071 0.140000 0.080000 0.077679
// Ekta Space PS5 0.695000 0.305000 0.260629 0.260000 0.700000 0.734946 0.110000 0.005000 0.004425
// NTSC RGB 0.671910 0.329340 0.310889 0.222591 0.710647 0.591737 0.142783 0.096145 0.097374
// PAL/SECAM RGB 0.648431 0.330856 0.232289 0.311424 0.599693 0.707805 0.155886 0.066044 0.059906
// ProPhoto RGB 0.734700 0.265300 0.288040 0.159600 0.840400 0.711874 0.036600 0.000100 0.000086
// SMPTE-C RGB 0.638852 0.340194 0.221685 0.331007 0.592082 0.703264 0.162897 0.079001 0.075052
// sRGB 0.648431 0.330856 0.222491 0.321152 0.597871 0.716888 0.155886 0.066044 0.060621
// Wide Gamut RGB 0.735000 0.265000 0.258187 0.115000 0.826000 0.724938 0.157000 0.018000 0.016875
// https://infoscience.epfl.ch/record/34089/files/SusstrunkBS99.pdf?version=3
// http://www.babelcolor.com/index_htm_files/A%20review%20of%20RGB%20color%20spaces.pdf
var redxxY, greenxyY, bluexyY, mediaWhitePoint;
// Set for RGB, Will change if we are a Lab profile
this.outputChannels = 3;
this.version = 4;
this.pcs = 'XYZ';
this.colorSpace = 'RGB';
this.header = {
profileSize: 0,
cmmType: 0,
version: 4,
pClass: 'mntr',
space: 'rgb',
pcs: 'XYZ',
date: new Date(),
signature: '',
platform: '',
flags: 0,
attributes: 0,
intent: 3,
PCSilluminant: convert.d50
};
switch (String(name).replace(' ', '').toLowerCase()) {
case 'labd50': // LabD50
case 'lab': // LabD50
this.type = eProfileType.Lab;
this.name = this.description = 'Lab D50 Profile';
this.PCSWhitepoint = convert.d50;
this.mediaWhitePoint = convert.d50;
this.pcs = 'LAB';
this.colorSpace = 'LAB';
this.header = {
profileSize: 0,
cmmType: 0,
version: 4,
pClass: 'abst',
space: 'Lab',
pcs: 'LAB',
date: new Date(),
signature: '',
platform: '',
flags: 0,
attributes: 0,
intent: 3,
PCSilluminant: convert.d50
}
return true;
case 'labd65': // LabD50
this.type = eProfileType.Lab;
this.name = this.description = 'Lab D65 Profile';
this.PCSWhitepoint = convert.d50;
this.mediaWhitePoint = convert.d65;
this.pcs = 'LAB';
this.colorSpace = 'LAB';
this.header = {
profileSize: 0,
cmmType: 0,
version: 4,
pClass: 'abst',
space: 'Lab',
pcs: 'LAB',
date: new Date(),
signature: '',
platform: '',
flags: 0,
attributes: 0,
intent: 3,
PCSilluminant: convert.d50
}
return true;
case 'srgb':
if(this.virutalProfileUsesD50AdaptedPrimaries){
redxxY = convert.xyY(0.648431, 0.330856,0.222491);
greenxyY = convert.xyY(0.321152, 0.597871,0.716888);
bluexyY = convert.xyY(0.155886, 0.066044,0.060621);
mediaWhitePoint = convert.d50;
} else {
redxxY = convert.xyY(0.64, 0.33,0.212656);
greenxyY = convert.xyY(0.30, 0.60,0.715158);
bluexyY = convert.xyY(0.15, 0.06,0.072186);
mediaWhitePoint = convert.d65;
}
this.name = 'sRGB';
this.description = "RGB is a standard RGB color space created cooperatively by HP and Microsoft in 1996 for use on monitors, printers and the Internet<br><br>Note that sRGB's small Gamut is not suitable for graphic production.<br><br>Encompasses roughly 35% of the visible colors specified by the Lab color space";
this.mediaWhitePoint = mediaWhitePoint;
computeRGBProfile(this,2.2, redxxY, greenxyY, bluexyY, true);
return true;
case 'adobe1998':
case 'adobe':
case 'adobergb':
case 'adobe1998rgb':
if(this.virutalProfileUsesD50AdaptedPrimaries){
redxxY = convert.xyY(0.648431, 0.330856,0.311114);
greenxyY = convert.xyY(0.230154, 0.701572,0.625662);
bluexyY = convert.xyY(0.155886, 0.066044,0.063224);
mediaWhitePoint = convert.d50;
} else {
redxxY = convert.xyY(0.64, 0.33,0.297361);
greenxyY = convert.xyY(0.21, 0.71,0.627355);
bluexyY = convert.xyY(0.15, 0.06,0.075285);
mediaWhitePoint = convert.d65;
}
this.name = 'Adobe RGB (1998)';
this.description = 'Developed by Adobe Systems, Inc. in 1998. It was designed to encompass most of the colors achievable on CMYK color printers, but by using RGB primary colors on a device such as a computer display. The Adobe RGB (1998) improves upon the gamut of the sRGB color space, primarily in cyan-green hues<br>Encompasses roughly 50% of the visible colors specified by the Lab color space';
this.mediaWhitePoint = mediaWhitePoint;
computeRGBProfile(this,2.2, redxxY, greenxyY, bluexyY, false);
return true;
case 'apple':
case 'applergb':
if(this.virutalProfileUsesD50AdaptedPrimaries){
redxxY = convert.xyY(0.634756, 0.340596,0.255166);
greenxyY = convert.xyY(0.301775, 0.597511,0.672578);
bluexyY = convert.xyY(0.162897, 0.079001,0.072256);
mediaWhitePoint = convert.d50;
} else {
redxxY = convert.xyY(0.6250, 0.3400,0.244634);
greenxyY = convert.xyY(0.2800, 0.5950,0.672034);
bluexyY = convert.xyY(0.1550, 0.0700,0.083332);
mediaWhitePoint = convert.d65;
}
this.name = 'Apple RGB';
this.description = 'Apple RGB is based on the classic Apple 13" RGB monitor. Because of its popularity and similar Trinitronbased monitors that followed, many key publishing applications, including Adobe Photoshop and Illustrator, used it as the default RGB space in the past.<br>Encompasses roughly 33.5% of the visible colors specified by the Lab color space';
this.mediaWhitePoint = mediaWhitePoint;
computeRGBProfile(this,2.2, redxxY, greenxyY, bluexyY, false);
return true;
case 'colormatchrgb':
case 'colormatch':
// Colormatch is D50
redxxY = convert.xyY(0.6300, 0.3400,0.274884);
greenxyY = convert.xyY(0.2950, 0.6050,0.658132);
bluexyY = convert.xyY(0.1500, 0.0750,0.066985);
this.name = 'ColorMatch RGB';
this.description = 'An RGB profile with a D50 whitepoint used for prepress<br>Encompasses roughly 35.2% of the visible colors specified by the Lab color space';
this.mediaWhitePoint = convert.d50;
computeRGBProfile(this,1.8, redxxY, greenxyY, bluexyY, false);
return true;
case 'prophoto':
case 'prophotorgb':
redxxY = convert.xyY(0.7347, 0.2653,0.288040);
greenxyY = convert.xyY(0.1596, 0.8404,0.711874);
bluexyY = convert.xyY(0.0366, 0.0001,0.000086);
this.name = 'ProPhoto RGB';
this.description = 'The ProPhoto RGB color space, also known as ROMM RGB (Reference Output Medium Metric), is an output referred RGB color space developed by Kodak. It offers an especially large gamut designed for use with photographic output in mind.<br>Encompasses roughly 91.2% of the visible colors specified by the Lab color space';
this.mediaWhitePoint = convert.d50;
computeRGBProfile(this,1.8, redxxY, greenxyY, bluexyY, false);
return true;
default:
this.lastError = {err: 100, text: 'Unsupported Virtual Profile [' + name + ']'};
return false;
}
function computeRGBProfile(profile, gamma, redxxY, greenxyY, bluexyY, isSRGB) {
profile.type = eProfileType.RGBMatrix;
profile.PCSWhitepoint = convert.d50;
profile.rgb.rXYZ = convert.xyY2XYZ(redxxY)
profile.rgb.gXYZ = convert.xyY2XYZ(greenxyY)
profile.rgb.bXYZ = convert.xyY2XYZ(bluexyY);
profile.RGBMatrix = {
gamma: gamma,
issRGB: isSRGB === true, // uses special sRGB Gamma formula
cRx: redxxY.x,
cRy: redxxY.y,
cGx: greenxyY.x,
cGy: greenxyY.y,
cBx: bluexyY.x,
cBy: bluexyY.y,
};
//
// TODO remove this code and just use XYZMatrix
//
// Note, these compute the XYZ <> RGB Matrix
// http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
//
var m = {
m00: profile.RGBMatrix.cRx / profile.RGBMatrix.cRy,
m01: profile.RGBMatrix.cGx / profile.RGBMatrix.cGy,
m02: profile.RGBMatrix.cBx / profile.RGBMatrix.cBy,
m10:1.0,
m11:1.0,
m12:1.0,
m20:(1.0 - profile.RGBMatrix.cRx - profile.RGBMatrix.cRy) / profile.RGBMatrix.cRy,
m21:(1.0 - profile.RGBMatrix.cGx - profile.RGBMatrix.cGy) / profile.RGBMatrix.cGy,
m22:(1.0 - profile.RGBMatrix.cBx - profile.RGBMatrix.cBy) / profile.RGBMatrix.cBy
};
var mi = convert.invertMatrix(m);
// Y = 1
// var sr = whitePoint.X * mi.m00 + whitePoint.Y * mi.m01 + whitePoint.Z * mi.m02;
var sR = (profile.mediaWhitePoint.X * mi.m00) + (profile.mediaWhitePoint.Y * mi.m01) + (profile.mediaWhitePoint.Z * mi.m02);
var sG = (profile.mediaWhitePoint.X * mi.m10) + (profile.mediaWhitePoint.Y * mi.m11) + (profile.mediaWhitePoint.Z * mi.m12);
var sB = (profile.mediaWhitePoint.X * mi.m20) + (profile.mediaWhitePoint.Y * mi.m21) + (profile.mediaWhitePoint.Z * mi.m22);
// Matrix from primaries - (Needed for Legacy Code)
profile.RGBMatrix.matrixV4 = {
m00 : sR * m.m00, m01 : sG * m.m01, m02 : sB * m.m02,
m10 : sR * m.m10, m11 : sG * m.m11, m12 : sB * m.m12,
m20 : sR * m.m20, m21 : sG * m.m21, m22 : sB * m.m22
};
profile.RGBMatrix.matrixInv = convert.invertMatrix(profile.RGBMatrix.matrixV4);
// Matrix from XYZ values
// Used in Transforms
profile.RGBMatrix.XYZMatrix = {
m00 : profile.rgb.rXYZ.X, m01 : profile.rgb.gXYZ.X, m02 : profile.rgb.bXYZ.X,
m10 : profile.rgb.rXYZ.Y, m11 : profile.rgb.gXYZ.Y, m12 : profile.rgb.bXYZ.Y,
m20 : profile.rgb.rXYZ.Z, m21 : profile.rgb.gXYZ.Z, m22 : profile.rgb.bXYZ.Z,
};
profile.RGBMatrix.XYZMatrixInv = convert.invertMatrix(profile.RGBMatrix.XYZMatrix);
}
};
// ========================================================================
// ICC DECODE — top-level decode + RGB-matrix auto-promotion
// ========================================================================
/**
* Top-level ICC decode. Validates the header signature (`'acsp'`),
* dispatches to `decodeFile` for tag-by-tag decode, then derives a
* couple of cached values used by `Transform.js`:
*
* - `PCSWhitepoint` from header PCS illuminant
* - `absoluteAdaptationIn/Out` ratios for absolute-colorimetric
*
* If the resulting profile is RGB with NO AtoB/BtoA LUTs but a
* complete set of primaries + TRCs, it is AUTO-PROMOTED to the
* fast `RGBMatrix` type (same internal shape as a virtual profile)
* — see the file header for why this matters.
*
* `searchForProfile` first scans the byte stream for an embedded
* `ICC_PROFILE` marker (e.g. inside a JPEG APP2 segment).
*
* @param {Uint8Array|Buffer} data
* @param {boolean} [searchForProfile]
* @returns {boolean} true on success, false on any decode failure.
*/
readICCProfile(data, searchForProfile) {
if(isInNode()){
if(data instanceof Buffer){
data = new Uint8Array(data);
}
}
var _this = this;
var start = 0;
if (searchForProfile){
//Search for text "ICC_PROFILE" in an Image
var ICC_PROFILE = [73 ,67 ,67 ,95 ,80 ,82 ,79 ,70 ,73 ,76 ,69 ];
start = scan(data,0, ICC_PROFILE);
if(start === -1){
return false;
}
}
// Search for text "acsp" in the profile header
var acsp = [97, 99, 115, 112];
var ascpPos = scan(data, start, acsp);
if (ascpPos === -1) {
return false;
}
// extract the core profile data
var result = this.decodeFile(data);
if (result === true) {
// update whitepoint
this.PCSWhitepoint = convert.getWhitePointFromIlluminant(this.header.PCSilluminant);
// this.mediaWhitePoint = convert.getWhitePointFromIlluminant(this.mediaWhitePoint);
// pre-calculate adaptation matrixV4 values
this.absoluteAdaptationIn = {
Xa: this.mediaWhitePoint.X / this.header.PCSilluminant.X,
Ya: this.mediaWhitePoint.Y / this.header.PCSilluminant.Y,
Za: this.mediaWhitePoint.Z / this.header.PCSilluminant.Z
};
this.absoluteAdaptationOut = {
Xa: this.header.PCSilluminant.X / this.mediaWhitePoint.X,
Ya: this.header.PCSilluminant.Y / this.mediaWhitePoint.Y,
Za: this.header.PCSilluminant.Z / this.mediaWhitePoint.Z
};
//TODO check for required tags for all profile types...
// determine the encoding on the A2b Tables
//this.PCSDecode = this.findA2BEncoding(this.A2B[eIntent.relative]);
if (_this.header.space === 'RGB ' &&
_this.A2B[eIntent.relative] === null &&
_this.B2A[eIntent.relative] === null &&
_this.rgb.gXYZ &&
_this.rgb.rXYZ &&
_this.rgb.bXYZ &&
_this.rgb.rTRC &&
_this.rgb.gTRC &&
_this.rgb.bTRC
) {
// Convert to an RGBMatrix type profile.
this.createRGBMatrix();
}
this.loaded = true;
return true;
}
this.loaded = false;
return false;
function scan(outerArray, start, innerArray) {
for (var i = start; i < outerArray.length - innerArray.length; i++) {
var found = true;
for (var j = 0; j < innerArray.length; j++) {
if (outerArray[i + j] !== innerArray[j]) {
found = false;
break;
}
}
if (found) {
return i;
}
}
return -1;
}
};
// ========================================================================
// RGB-MATRIX PROMOTION — make decoded RGB matrix profiles fast
// ========================================================================
/**
* Convert a freshly-decoded RGB profile (one that has primary XYZs +
* three TRC curves and no LUT) into the same internal `RGBMatrix`
* shape that virtual profiles use. After this call, downstream
* transforms hit the same inlined matrix-and-gamma kernel for both
* sources — there is no runtime cost difference between
* `'*sRGB'` and a decoded sRGB.icc.
*
* The primaries are adapted from the ICC PCS D50 reference to the
* profile's actual `mediaWhitePoint` before the matrix is computed.
*
* @return {boolean}
*/
createRGBMatrix() {
//this.PCSWhitepoint = convert.getWhitePointFromIlluminant(this.header.PCSilluminant);
this.PCSWhitepoint = this.header.PCSilluminant;
var d50 = convert.d50;
// adapt primaries from D50 as per the ICC spec to the whitepoint of the profile
//
//
var rxy = convert.XYZ2xyY(convert.adaptation(this.rgb.rXYZ, d50, this.mediaWhitePoint), this.PCSWhitepoint);
var gxy = convert.XYZ2xyY(convert.adaptation(this.rgb.gXYZ, d50, this.mediaWhitePoint), this.PCSWhitepoint);
var bxy = convert.XYZ2xyY(convert.adaptation(this.rgb.bXYZ, d50, this.mediaWhitePoint), this.PCSWhitepoint);
this.type = eProfileType.RGBMatrix;
this.RGBMatrix = {
gamma: this.rgb.rTRC.gamma,
issRGB: (this.name.substr(0, 4) === 'sRGB'),
cRx: rxy.x,
cRy: rxy.y,
cGx: gxy.x,
cGy: gxy.y,
cBx: bxy.x,