Profile.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531
  1. /*
  2. * Copyright (c) 2022-2023, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Endian.h>
  7. #include <LibGfx/CIELAB.h>
  8. #include <LibGfx/ICC/BinaryFormat.h>
  9. #include <LibGfx/ICC/Profile.h>
  10. #include <LibGfx/ICC/Tags.h>
  11. #include <math.h>
  12. #include <time.h>
  13. // V2 spec: https://color.org/specification/ICC.1-2001-04.pdf
  14. // V4 spec: https://color.org/specification/ICC.1-2022-05.pdf
  15. namespace Gfx::ICC {
  16. namespace {
  17. ErrorOr<time_t> parse_date_time_number(DateTimeNumber const& date_time)
  18. {
  19. // ICC V4, 4.2 dateTimeNumber
  20. // "Number of the month (1 to 12)"
  21. if (date_time.month < 1 || date_time.month > 12)
  22. return Error::from_string_literal("ICC::Profile: dateTimeNumber month out of bounds");
  23. // "Number of the day of the month (1 to 31)"
  24. if (date_time.day < 1 || date_time.day > 31)
  25. return Error::from_string_literal("ICC::Profile: dateTimeNumber day out of bounds");
  26. // "Number of hours (0 to 23)"
  27. if (date_time.hours > 23)
  28. return Error::from_string_literal("ICC::Profile: dateTimeNumber hours out of bounds");
  29. // "Number of minutes (0 to 59)"
  30. if (date_time.minutes > 59)
  31. return Error::from_string_literal("ICC::Profile: dateTimeNumber minutes out of bounds");
  32. // "Number of seconds (0 to 59)"
  33. // ICC profiles apparently can't be created during leap seconds (seconds would be 60 there, but the spec doesn't allow that).
  34. if (date_time.seconds > 59)
  35. return Error::from_string_literal("ICC::Profile: dateTimeNumber seconds out of bounds");
  36. struct tm tm = {};
  37. tm.tm_year = date_time.year - 1900;
  38. tm.tm_mon = date_time.month - 1;
  39. tm.tm_mday = date_time.day;
  40. tm.tm_hour = date_time.hours;
  41. tm.tm_min = date_time.minutes;
  42. tm.tm_sec = date_time.seconds;
  43. // timegm() doesn't read tm.tm_isdst, tm.tm_wday, and tm.tm_yday, no need to fill them in.
  44. time_t timestamp = timegm(&tm);
  45. if (timestamp == -1)
  46. return Error::from_string_literal("ICC::Profile: dateTimeNumber not representable as timestamp");
  47. return timestamp;
  48. }
  49. ErrorOr<u32> parse_size(ICCHeader const& header, ReadonlyBytes icc_bytes)
  50. {
  51. // ICC v4, 7.2.2 Profile size field
  52. // "The value in the profile size field shall be the exact size obtained by combining the profile header,
  53. // the tag table, and the tagged element data, including the pad bytes for the last tag."
  54. // Valid files have enough data for profile header and tag table entry count.
  55. if (header.profile_size < sizeof(ICCHeader) + sizeof(u32))
  56. return Error::from_string_literal("ICC::Profile: Profile size too small");
  57. if (header.profile_size > icc_bytes.size())
  58. return Error::from_string_literal("ICC::Profile: Profile size larger than input data");
  59. // ICC v4, 7.1.2:
  60. // "NOTE 1 This implies that the length is required to be a multiple of four."
  61. // The ICC v2 spec doesn't have this note. It instead has:
  62. // ICC v2, 6.2.2 Offset:
  63. // "All tag data is required to start on a 4-byte boundary"
  64. // And indeed, there are files in the wild where the last tag has a size that isn't a multiple of four,
  65. // resulting in an ICC file whose size isn't a multiple of four either.
  66. if (header.profile_version_major >= 4 && header.profile_size % 4 != 0)
  67. return Error::from_string_literal("ICC::Profile: Profile size not a multiple of four");
  68. return header.profile_size;
  69. }
  70. Optional<PreferredCMMType> parse_preferred_cmm_type(ICCHeader const& header)
  71. {
  72. // ICC v4, 7.2.3 Preferred CMM type field
  73. // "This field may be used to identify the preferred CMM to be used.
  74. // If used, it shall match a CMM type signature registered in the ICC Tag Registry"
  75. // https://www.color.org/signatures2.xalter currently links to
  76. // https://www.color.org/registry/signature/TagRegistry-2021-03.pdf, which contains
  77. // some CMM signatures.
  78. // This requirement is often honored in practice, but not always. For example,
  79. // JPEGs exported in Adobe Lightroom contain profiles that set this to 'Lino',
  80. // which is not present in the "CMM Signatures" table in that PDF.
  81. // "If no preferred CMM is identified, this field shall be set to zero (00000000h)."
  82. if (header.preferred_cmm_type == PreferredCMMType { 0 })
  83. return {};
  84. return header.preferred_cmm_type;
  85. }
  86. ErrorOr<Version> parse_version(ICCHeader const& header)
  87. {
  88. // ICC v4, 7.2.4 Profile version field
  89. if (header.profile_version_zero != 0)
  90. return Error::from_string_literal("ICC::Profile: Reserved version bytes not zero");
  91. return Version(header.profile_version_major, header.profile_version_minor_bugfix);
  92. }
  93. ErrorOr<DeviceClass> parse_device_class(ICCHeader const& header)
  94. {
  95. // ICC v4, 7.2.5 Profile/device class field
  96. switch (header.profile_device_class) {
  97. case DeviceClass::InputDevice:
  98. case DeviceClass::DisplayDevice:
  99. case DeviceClass::OutputDevice:
  100. case DeviceClass::DeviceLink:
  101. case DeviceClass::ColorSpace:
  102. case DeviceClass::Abstract:
  103. case DeviceClass::NamedColor:
  104. return header.profile_device_class;
  105. }
  106. return Error::from_string_literal("ICC::Profile: Invalid device class");
  107. }
  108. ErrorOr<ColorSpace> parse_color_space(ColorSpace color_space)
  109. {
  110. // ICC v4, Table 19 — Data colour space signatures
  111. switch (color_space) {
  112. case ColorSpace::nCIEXYZ:
  113. case ColorSpace::CIELAB:
  114. case ColorSpace::CIELUV:
  115. case ColorSpace::YCbCr:
  116. case ColorSpace::CIEYxy:
  117. case ColorSpace::RGB:
  118. case ColorSpace::Gray:
  119. case ColorSpace::HSV:
  120. case ColorSpace::HLS:
  121. case ColorSpace::CMYK:
  122. case ColorSpace::CMY:
  123. case ColorSpace::TwoColor:
  124. case ColorSpace::ThreeColor:
  125. case ColorSpace::FourColor:
  126. case ColorSpace::FiveColor:
  127. case ColorSpace::SixColor:
  128. case ColorSpace::SevenColor:
  129. case ColorSpace::EightColor:
  130. case ColorSpace::NineColor:
  131. case ColorSpace::TenColor:
  132. case ColorSpace::ElevenColor:
  133. case ColorSpace::TwelveColor:
  134. case ColorSpace::ThirteenColor:
  135. case ColorSpace::FourteenColor:
  136. case ColorSpace::FifteenColor:
  137. return color_space;
  138. }
  139. return Error::from_string_literal("ICC::Profile: Invalid color space");
  140. }
  141. ErrorOr<ColorSpace> parse_data_color_space(ICCHeader const& header)
  142. {
  143. // ICC v4, 7.2.6 Data colour space field
  144. return parse_color_space(header.data_color_space);
  145. }
  146. ErrorOr<ColorSpace> parse_connection_space(ICCHeader const& header)
  147. {
  148. // ICC v4, 7.2.7 PCS field
  149. // and Annex D
  150. auto space = TRY(parse_color_space(header.profile_connection_space));
  151. if (header.profile_device_class != DeviceClass::DeviceLink && (space != ColorSpace::PCSXYZ && space != ColorSpace::PCSLAB))
  152. return Error::from_string_literal("ICC::Profile: Invalid profile connection space: Non-PCS space on non-DeviceLink profile");
  153. return space;
  154. }
  155. ErrorOr<time_t> parse_creation_date_time(ICCHeader const& header)
  156. {
  157. // ICC v4, 7.2.8 Date and time field
  158. return parse_date_time_number(header.profile_creation_time);
  159. }
  160. ErrorOr<void> parse_file_signature(ICCHeader const& header)
  161. {
  162. // ICC v4, 7.2.9 Profile file signature field
  163. if (header.profile_file_signature != ProfileFileSignature)
  164. return Error::from_string_literal("ICC::Profile: profile file signature not 'acsp'");
  165. return {};
  166. }
  167. ErrorOr<Optional<PrimaryPlatform>> parse_primary_platform(ICCHeader const& header)
  168. {
  169. // ICC v4, 7.2.10 Primary platform field
  170. // "If there is no primary platform identified, this field shall be set to zero (00000000h)."
  171. if (header.primary_platform == PrimaryPlatform { 0 })
  172. return OptionalNone {};
  173. switch (header.primary_platform) {
  174. case PrimaryPlatform::Apple:
  175. case PrimaryPlatform::Microsoft:
  176. case PrimaryPlatform::SiliconGraphics:
  177. case PrimaryPlatform::Sun:
  178. return header.primary_platform;
  179. }
  180. return Error::from_string_literal("ICC::Profile: Invalid primary platform");
  181. }
  182. Optional<DeviceManufacturer> parse_device_manufacturer(ICCHeader const& header)
  183. {
  184. // ICC v4, 7.2.12 Device manufacturer field
  185. // "This field may be used to identify a device manufacturer.
  186. // If used the signature shall match the signature contained in the appropriate section of the ICC signature registry found at www.color.org"
  187. // Device manufacturers can be looked up at https://www.color.org/signatureRegistry/index.xalter
  188. // For example: https://www.color.org/signatureRegistry/?entityEntry=APPL-4150504C
  189. // Some icc files use codes not in that registry. For example. D50_XYZ.icc from https://www.color.org/XYZprofiles.xalter
  190. // has its device manufacturer set to 'none', but https://www.color.org/signatureRegistry/?entityEntry=none-6E6F6E65 does not exist.
  191. // "If not used this field shall be set to zero (00000000h)."
  192. if (header.device_manufacturer == DeviceManufacturer { 0 })
  193. return {};
  194. return header.device_manufacturer;
  195. }
  196. Optional<DeviceModel> parse_device_model(ICCHeader const& header)
  197. {
  198. // ICC v4, 7.2.13 Device model field
  199. // "This field may be used to identify a device model.
  200. // If used the signature shall match the signature contained in the appropriate section of the ICC signature registry found at www.color.org"
  201. // Device models can be looked up at https://www.color.org/signatureRegistry/deviceRegistry/index.xalter
  202. // For example: https://www.color.org/signatureRegistry/deviceRegistry/?entityEntry=7FD8-37464438
  203. // Some icc files use codes not in that registry. For example. D50_XYZ.icc from https://www.color.org/XYZprofiles.xalter
  204. // has its device model set to 'none', but https://www.color.org/signatureRegistry/deviceRegistry?entityEntry=none-6E6F6E65 does not exist.
  205. // "If not used this field shall be set to zero (00000000h)."
  206. if (header.device_model == DeviceModel { 0 })
  207. return {};
  208. return header.device_model;
  209. }
  210. ErrorOr<DeviceAttributes> parse_device_attributes(ICCHeader const& header)
  211. {
  212. // ICC v4, 7.2.14 Device attributes field
  213. // "4 to 31": "Reserved (set to binary zero)"
  214. if (header.device_attributes & 0xffff'fff0)
  215. return Error::from_string_literal("ICC::Profile: Device attributes reserved bits not set to 0");
  216. return DeviceAttributes { header.device_attributes };
  217. }
  218. ErrorOr<RenderingIntent> parse_rendering_intent(ICCHeader const& header)
  219. {
  220. // ICC v4, 7.2.15 Rendering intent field
  221. switch (header.rendering_intent) {
  222. case RenderingIntent::Perceptual:
  223. case RenderingIntent::MediaRelativeColorimetric:
  224. case RenderingIntent::Saturation:
  225. case RenderingIntent::ICCAbsoluteColorimetric:
  226. return header.rendering_intent;
  227. }
  228. return Error::from_string_literal("ICC::Profile: Invalid rendering intent");
  229. }
  230. ErrorOr<XYZ> parse_pcs_illuminant(ICCHeader const& header)
  231. {
  232. // ICC v4, 7.2.16 PCS illuminant field
  233. XYZ xyz = (XYZ)header.pcs_illuminant;
  234. /// "The value, when rounded to four decimals, shall be X = 0,9642, Y = 1,0 and Z = 0,8249."
  235. if (round(xyz.X * 10'000) != 9'642 || round(xyz.Y * 10'000) != 10'000 || round(xyz.Z * 10'000) != 8'249)
  236. return Error::from_string_literal("ICC::Profile: Invalid pcs illuminant");
  237. return xyz;
  238. }
  239. Optional<Creator> parse_profile_creator(ICCHeader const& header)
  240. {
  241. // ICC v4, 7.2.17 Profile creator field
  242. // "This field may be used to identify the creator of the profile.
  243. // If used the signature should match the signature contained in the device manufacturer section of the ICC signature registry found at www.color.org."
  244. // This is not always true in practice.
  245. // For example, .icc files in /System/ColorSync/Profiles on macOS 12.6 set this to 'appl', which is a CMM signature, not a device signature (that one would be 'APPL').
  246. // "If not used this field shall be set to zero (00000000h)."
  247. if (header.profile_creator == Creator { 0 })
  248. return {};
  249. return header.profile_creator;
  250. }
  251. template<size_t N>
  252. bool all_bytes_are_zero(const u8 (&bytes)[N])
  253. {
  254. for (u8 byte : bytes) {
  255. if (byte != 0)
  256. return false;
  257. }
  258. return true;
  259. }
  260. ErrorOr<Optional<Crypto::Hash::MD5::DigestType>> parse_profile_id(ICCHeader const& header, ReadonlyBytes icc_bytes)
  261. {
  262. // ICC v4, 7.2.18 Profile ID field
  263. // "A profile ID field value of zero (00h) shall indicate that a profile ID has not been calculated."
  264. if (all_bytes_are_zero(header.profile_id))
  265. return OptionalNone {};
  266. Crypto::Hash::MD5::DigestType id;
  267. static_assert(sizeof(id.data) == sizeof(header.profile_id));
  268. memcpy(id.data, header.profile_id, sizeof(id.data));
  269. auto computed_id = Profile::compute_id(icc_bytes);
  270. if (id != computed_id)
  271. return Error::from_string_literal("ICC::Profile: Invalid profile id");
  272. return id;
  273. }
  274. ErrorOr<void> parse_reserved(ICCHeader const& header)
  275. {
  276. // ICC v4, 7.2.19 Reserved field
  277. // "This field of the profile header is reserved for future ICC definition and shall be set to zero."
  278. if (!all_bytes_are_zero(header.reserved))
  279. return Error::from_string_literal("ICC::Profile: Reserved header bytes are not zero");
  280. return {};
  281. }
  282. }
  283. URL device_manufacturer_url(DeviceManufacturer device_manufacturer)
  284. {
  285. return URL(DeprecatedString::formatted("https://www.color.org/signatureRegistry/?entityEntry={:c}{:c}{:c}{:c}-{:08X}",
  286. device_manufacturer.c0(), device_manufacturer.c1(), device_manufacturer.c2(), device_manufacturer.c3(), device_manufacturer.value));
  287. }
  288. URL device_model_url(DeviceModel device_model)
  289. {
  290. return URL(DeprecatedString::formatted("https://www.color.org/signatureRegistry/deviceRegistry/?entityEntry={:c}{:c}{:c}{:c}-{:08X}",
  291. device_model.c0(), device_model.c1(), device_model.c2(), device_model.c3(), device_model.value));
  292. }
  293. StringView device_class_name(DeviceClass device_class)
  294. {
  295. switch (device_class) {
  296. case DeviceClass::InputDevice:
  297. return "InputDevice"sv;
  298. case DeviceClass::DisplayDevice:
  299. return "DisplayDevice"sv;
  300. case DeviceClass::OutputDevice:
  301. return "OutputDevice"sv;
  302. case DeviceClass::DeviceLink:
  303. return "DeviceLink"sv;
  304. case DeviceClass::ColorSpace:
  305. return "ColorSpace"sv;
  306. case DeviceClass::Abstract:
  307. return "Abstract"sv;
  308. case DeviceClass::NamedColor:
  309. return "NamedColor"sv;
  310. }
  311. VERIFY_NOT_REACHED();
  312. }
  313. StringView data_color_space_name(ColorSpace color_space)
  314. {
  315. switch (color_space) {
  316. case ColorSpace::nCIEXYZ:
  317. return "nCIEXYZ"sv;
  318. case ColorSpace::CIELAB:
  319. return "CIELAB"sv;
  320. case ColorSpace::CIELUV:
  321. return "CIELUV"sv;
  322. case ColorSpace::YCbCr:
  323. return "YCbCr"sv;
  324. case ColorSpace::CIEYxy:
  325. return "CIEYxy"sv;
  326. case ColorSpace::RGB:
  327. return "RGB"sv;
  328. case ColorSpace::Gray:
  329. return "Gray"sv;
  330. case ColorSpace::HSV:
  331. return "HSV"sv;
  332. case ColorSpace::HLS:
  333. return "HLS"sv;
  334. case ColorSpace::CMYK:
  335. return "CMYK"sv;
  336. case ColorSpace::CMY:
  337. return "CMY"sv;
  338. case ColorSpace::TwoColor:
  339. return "2 color"sv;
  340. case ColorSpace::ThreeColor:
  341. return "3 color (other than XYZ, Lab, Luv, YCbCr, CIEYxy, RGB, HSV, HLS, CMY)"sv;
  342. case ColorSpace::FourColor:
  343. return "4 color (other than CMYK)"sv;
  344. case ColorSpace::FiveColor:
  345. return "5 color"sv;
  346. case ColorSpace::SixColor:
  347. return "6 color"sv;
  348. case ColorSpace::SevenColor:
  349. return "7 color"sv;
  350. case ColorSpace::EightColor:
  351. return "8 color"sv;
  352. case ColorSpace::NineColor:
  353. return "9 color"sv;
  354. case ColorSpace::TenColor:
  355. return "10 color"sv;
  356. case ColorSpace::ElevenColor:
  357. return "11 color"sv;
  358. case ColorSpace::TwelveColor:
  359. return "12 color"sv;
  360. case ColorSpace::ThirteenColor:
  361. return "13 color"sv;
  362. case ColorSpace::FourteenColor:
  363. return "14 color"sv;
  364. case ColorSpace::FifteenColor:
  365. return "15 color"sv;
  366. }
  367. VERIFY_NOT_REACHED();
  368. }
  369. StringView profile_connection_space_name(ColorSpace color_space)
  370. {
  371. switch (color_space) {
  372. case ColorSpace::PCSXYZ:
  373. return "PCSXYZ"sv;
  374. case ColorSpace::PCSLAB:
  375. return "PCSLAB"sv;
  376. default:
  377. return data_color_space_name(color_space);
  378. }
  379. }
  380. unsigned number_of_components_in_color_space(ColorSpace color_space)
  381. {
  382. switch (color_space) {
  383. case ColorSpace::Gray:
  384. return 1;
  385. case ColorSpace::TwoColor:
  386. return 2;
  387. case ColorSpace::nCIEXYZ:
  388. case ColorSpace::CIELAB:
  389. case ColorSpace::CIELUV:
  390. case ColorSpace::YCbCr:
  391. case ColorSpace::CIEYxy:
  392. case ColorSpace::RGB:
  393. case ColorSpace::HSV:
  394. case ColorSpace::HLS:
  395. case ColorSpace::CMY:
  396. case ColorSpace::ThreeColor:
  397. return 3;
  398. case ColorSpace::CMYK:
  399. case ColorSpace::FourColor:
  400. return 4;
  401. case ColorSpace::FiveColor:
  402. return 5;
  403. case ColorSpace::SixColor:
  404. return 6;
  405. case ColorSpace::SevenColor:
  406. return 7;
  407. case ColorSpace::EightColor:
  408. return 8;
  409. case ColorSpace::NineColor:
  410. return 9;
  411. case ColorSpace::TenColor:
  412. return 10;
  413. case ColorSpace::ElevenColor:
  414. return 11;
  415. case ColorSpace::TwelveColor:
  416. return 12;
  417. case ColorSpace::ThirteenColor:
  418. return 13;
  419. case ColorSpace::FourteenColor:
  420. return 14;
  421. case ColorSpace::FifteenColor:
  422. return 15;
  423. }
  424. VERIFY_NOT_REACHED();
  425. }
  426. StringView primary_platform_name(PrimaryPlatform primary_platform)
  427. {
  428. switch (primary_platform) {
  429. case PrimaryPlatform::Apple:
  430. return "Apple"sv;
  431. case PrimaryPlatform::Microsoft:
  432. return "Microsoft"sv;
  433. case PrimaryPlatform::SiliconGraphics:
  434. return "Silicon Graphics"sv;
  435. case PrimaryPlatform::Sun:
  436. return "Sun"sv;
  437. }
  438. VERIFY_NOT_REACHED();
  439. }
  440. StringView rendering_intent_name(RenderingIntent rendering_intent)
  441. {
  442. switch (rendering_intent) {
  443. case RenderingIntent::Perceptual:
  444. return "Perceptual"sv;
  445. case RenderingIntent::MediaRelativeColorimetric:
  446. return "Media-relative colorimetric"sv;
  447. case RenderingIntent::Saturation:
  448. return "Saturation"sv;
  449. case RenderingIntent::ICCAbsoluteColorimetric:
  450. return "ICC-absolute colorimetric"sv;
  451. }
  452. VERIFY_NOT_REACHED();
  453. }
  454. Flags::Flags() = default;
  455. Flags::Flags(u32 bits)
  456. : m_bits(bits)
  457. {
  458. }
  459. DeviceAttributes::DeviceAttributes() = default;
  460. DeviceAttributes::DeviceAttributes(u64 bits)
  461. : m_bits(bits)
  462. {
  463. }
  464. static ErrorOr<ProfileHeader> read_header(ReadonlyBytes bytes)
  465. {
  466. if (bytes.size() < sizeof(ICCHeader))
  467. return Error::from_string_literal("ICC::Profile: Not enough data for header");
  468. ProfileHeader header;
  469. auto raw_header = *bit_cast<ICCHeader const*>(bytes.data());
  470. TRY(parse_file_signature(raw_header));
  471. header.on_disk_size = TRY(parse_size(raw_header, bytes));
  472. header.preferred_cmm_type = parse_preferred_cmm_type(raw_header);
  473. header.version = TRY(parse_version(raw_header));
  474. header.device_class = TRY(parse_device_class(raw_header));
  475. header.data_color_space = TRY(parse_data_color_space(raw_header));
  476. header.connection_space = TRY(parse_connection_space(raw_header));
  477. header.creation_timestamp = TRY(parse_creation_date_time(raw_header));
  478. header.primary_platform = TRY(parse_primary_platform(raw_header));
  479. header.flags = Flags { raw_header.profile_flags };
  480. header.device_manufacturer = parse_device_manufacturer(raw_header);
  481. header.device_model = parse_device_model(raw_header);
  482. header.device_attributes = TRY(parse_device_attributes(raw_header));
  483. header.rendering_intent = TRY(parse_rendering_intent(raw_header));
  484. header.pcs_illuminant = TRY(parse_pcs_illuminant(raw_header));
  485. header.creator = parse_profile_creator(raw_header);
  486. header.id = TRY(parse_profile_id(raw_header, bytes));
  487. TRY(parse_reserved(raw_header));
  488. return header;
  489. }
  490. static ErrorOr<NonnullRefPtr<TagData>> read_tag(ReadonlyBytes bytes, u32 offset_to_beginning_of_tag_data_element, u32 size_of_tag_data_element)
  491. {
  492. // "All tag data elements shall start on a 4-byte boundary (relative to the start of the profile data stream)"
  493. if (offset_to_beginning_of_tag_data_element % 4 != 0)
  494. return Error::from_string_literal("ICC::Profile: Tag data not aligned");
  495. if (offset_to_beginning_of_tag_data_element + size_of_tag_data_element > bytes.size())
  496. return Error::from_string_literal("ICC::Profile: Tag data out of bounds");
  497. auto tag_bytes = bytes.slice(offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  498. // ICC v4, 9 Tag definitions
  499. // ICC v4, 9.1 General
  500. // "All tags, including private tags, have as their first four bytes a tag signature to identify to profile readers
  501. // what kind of data is contained within a tag."
  502. if (tag_bytes.size() < sizeof(u32))
  503. return Error::from_string_literal("ICC::Profile: Not enough data for tag type");
  504. auto type = tag_type(tag_bytes);
  505. switch (type) {
  506. case ChromaticityTagData::Type:
  507. return ChromaticityTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  508. case CicpTagData::Type:
  509. return CicpTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  510. case CurveTagData::Type:
  511. return CurveTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  512. case Lut16TagData::Type:
  513. return Lut16TagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  514. case Lut8TagData::Type:
  515. return Lut8TagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  516. case LutAToBTagData::Type:
  517. return LutAToBTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  518. case LutBToATagData::Type:
  519. return LutBToATagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  520. case MeasurementTagData::Type:
  521. return MeasurementTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  522. case MultiLocalizedUnicodeTagData::Type:
  523. return MultiLocalizedUnicodeTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  524. case NamedColor2TagData::Type:
  525. return NamedColor2TagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  526. case ParametricCurveTagData::Type:
  527. return ParametricCurveTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  528. case S15Fixed16ArrayTagData::Type:
  529. return S15Fixed16ArrayTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  530. case SignatureTagData::Type:
  531. return SignatureTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  532. case TextDescriptionTagData::Type:
  533. return TextDescriptionTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  534. case TextTagData::Type:
  535. return TextTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  536. case ViewingConditionsTagData::Type:
  537. return ViewingConditionsTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  538. case XYZTagData::Type:
  539. return XYZTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element);
  540. default:
  541. // FIXME: optionally ignore tags of unknown type
  542. return try_make_ref_counted<UnknownTagData>(offset_to_beginning_of_tag_data_element, size_of_tag_data_element, type);
  543. }
  544. }
  545. static ErrorOr<OrderedHashMap<TagSignature, NonnullRefPtr<TagData>>> read_tag_table(ReadonlyBytes bytes)
  546. {
  547. OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table;
  548. // ICC v4, 7.3 Tag table
  549. // ICC v4, 7.3.1 Overview
  550. // "The tag table acts as a table of contents for the tags and an index into the tag data element in the profiles. It
  551. // shall consist of a 4-byte entry that contains a count of the number of tags in the table followed by a series of 12-
  552. // byte entries with one entry for each tag. The tag table therefore contains 4+12n bytes where n is the number of
  553. // tags contained in the profile. The entries for the tags within the table are not required to be in any particular
  554. // order nor are they required to match the sequence of tag data element within the profile.
  555. // Each 12-byte tag entry following the tag count shall consist of a 4-byte tag signature, a 4-byte offset to define
  556. // the beginning of the tag data element, and a 4-byte entry identifying the length of the tag data element in bytes.
  557. // [...]
  558. // The tag table shall define a contiguous sequence of unique tag elements, with no gaps between the last byte
  559. // of any tag data element referenced from the tag table (inclusive of any necessary additional pad bytes required
  560. // to reach a four-byte boundary) and the byte offset of the following tag element, or the end of the file.
  561. // Duplicate tag signatures shall not be included in the tag table.
  562. // Tag data elements shall not partially overlap, so there shall be no part of any tag data element that falls within
  563. // the range defined for another tag in the tag table."
  564. ReadonlyBytes tag_table_bytes = bytes.slice(sizeof(ICCHeader));
  565. if (tag_table_bytes.size() < sizeof(u32))
  566. return Error::from_string_literal("ICC::Profile: Not enough data for tag count");
  567. auto tag_count = *bit_cast<BigEndian<u32> const*>(tag_table_bytes.data());
  568. tag_table_bytes = tag_table_bytes.slice(sizeof(u32));
  569. if (tag_table_bytes.size() < tag_count * sizeof(TagTableEntry))
  570. return Error::from_string_literal("ICC::Profile: Not enough data for tag table entries");
  571. auto tag_table_entries = bit_cast<TagTableEntry const*>(tag_table_bytes.data());
  572. // "The tag table may contain multiple tags signatures that all reference the same tag data element offset, allowing
  573. // efficient reuse of tag data elements."
  574. HashMap<u32, NonnullRefPtr<TagData>> offset_to_tag_data;
  575. for (u32 i = 0; i < tag_count; ++i) {
  576. // FIXME: optionally ignore tags with unknown signature
  577. // Dedupe identical offset/sizes.
  578. NonnullRefPtr<TagData> tag_data = TRY(offset_to_tag_data.try_ensure(tag_table_entries[i].offset_to_beginning_of_tag_data_element, [&]() {
  579. return read_tag(bytes, tag_table_entries[i].offset_to_beginning_of_tag_data_element, tag_table_entries[i].size_of_tag_data_element);
  580. }));
  581. // "In such cases, both the offset and size of the tag data elements in the tag table shall be the same."
  582. if (tag_data->size() != tag_table_entries[i].size_of_tag_data_element)
  583. return Error::from_string_literal("ICC::Profile: two tags have same offset but different sizes");
  584. // "Duplicate tag signatures shall not be included in the tag table."
  585. if (TRY(tag_table.try_set(tag_table_entries[i].tag_signature, move(tag_data))) != AK::HashSetResult::InsertedNewEntry)
  586. return Error::from_string_literal("ICC::Profile: duplicate tag signature");
  587. }
  588. return tag_table;
  589. }
  590. static bool is_xCLR(ColorSpace color_space)
  591. {
  592. switch (color_space) {
  593. case ColorSpace::TwoColor:
  594. case ColorSpace::ThreeColor:
  595. case ColorSpace::FourColor:
  596. case ColorSpace::FiveColor:
  597. case ColorSpace::SixColor:
  598. case ColorSpace::SevenColor:
  599. case ColorSpace::EightColor:
  600. case ColorSpace::NineColor:
  601. case ColorSpace::TenColor:
  602. case ColorSpace::ElevenColor:
  603. case ColorSpace::TwelveColor:
  604. case ColorSpace::ThirteenColor:
  605. case ColorSpace::FourteenColor:
  606. case ColorSpace::FifteenColor:
  607. return true;
  608. default:
  609. return false;
  610. }
  611. }
  612. ErrorOr<void> Profile::check_required_tags()
  613. {
  614. // ICC v4, 8 Required tags
  615. // ICC v4, 8.2 Common requirements
  616. // "With the exception of DeviceLink profiles, all profiles shall contain the following tags:
  617. // - profileDescriptionTag (see 9.2.41);
  618. // - copyrightTag (see 9.2.21);
  619. // - mediaWhitePointTag (see 9.2.34);
  620. // - chromaticAdaptationTag, when the measurement data used to calculate the profile was specified for an
  621. // adopted white with a chromaticity different from that of the PCS adopted white (see 9.2.15).
  622. // NOTE A DeviceLink profile is not required to have either a mediaWhitePointTag or a chromaticAdaptationTag."
  623. // profileDescriptionTag, copyrightTag are required for DeviceLink too (see ICC v4, 8.6 DeviceLink profile).
  624. // profileDescriptionTag, copyrightTag, mediaWhitePointTag are required in ICC v2 as well.
  625. // chromaticAdaptationTag isn't required in v2 profiles as far as I can tell.
  626. if (!m_tag_table.contains(profileDescriptionTag))
  627. return Error::from_string_literal("ICC::Profile: required profileDescriptionTag is missing");
  628. if (!m_tag_table.contains(copyrightTag))
  629. return Error::from_string_literal("ICC::Profile: required copyrightTag is missing");
  630. if (device_class() != DeviceClass::DeviceLink) {
  631. if (!m_tag_table.contains(mediaWhitePointTag))
  632. return Error::from_string_literal("ICC::Profile: required mediaWhitePointTag is missing");
  633. // FIXME: Check for chromaticAdaptationTag after figuring out when exactly it needs to be present.
  634. }
  635. auto has_tag = [&](auto& tag) { return m_tag_table.contains(tag); };
  636. auto has_all_tags = [&]<class T>(T tags) { return all_of(tags, has_tag); };
  637. switch (device_class()) {
  638. case DeviceClass::InputDevice: {
  639. // ICC v4, 8.3 Input profiles
  640. // "8.3.1 General
  641. // Input profiles are generally used with devices such as scanners and digital cameras. The types of profiles
  642. // available for use as Input profiles are N-component LUT-based, Three-component matrix-based, and
  643. // monochrome.
  644. // 8.3.2 N-component LUT-based Input profiles
  645. // In addition to the tags listed in 8.2 an N-component LUT-based Input profile shall contain the following tag:
  646. // - AToB0Tag (see 9.2.1).
  647. // 8.3.3 Three-component matrix-based Input profiles
  648. // In addition to the tags listed in 8.2, a three-component matrix-based Input profile shall contain the following tags:
  649. // - redMatrixColumnTag (see 9.2.44);
  650. // - greenMatrixColumnTag (see 9.2.30);
  651. // - blueMatrixColumnTag (see 9.2.4);
  652. // - redTRCTag (see 9.2.45);
  653. // - greenTRCTag (see 9.2.31);
  654. // - blueTRCTag (see 9.2.5).
  655. // [...] Only the PCSXYZ encoding can be used with matrix/TRC models.
  656. // 8.3.4 Monochrome Input profiles
  657. // In addition to the tags listed in 8.2, a monochrome Input profile shall contain the following tag:
  658. // - grayTRCTag (see 9.2.29)."
  659. bool has_n_component_lut_based_tags = has_tag(AToB0Tag);
  660. bool has_three_component_matrix_based_tags = has_all_tags(Array { redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag, redTRCTag, greenTRCTag, blueTRCTag });
  661. bool has_monochrome_tags = has_tag(grayTRCTag);
  662. if (!has_n_component_lut_based_tags && !has_three_component_matrix_based_tags && !has_monochrome_tags)
  663. return Error::from_string_literal("ICC::Profile: InputDevice required tags are missing");
  664. if (!has_n_component_lut_based_tags && has_three_component_matrix_based_tags && connection_space() != ColorSpace::PCSXYZ)
  665. return Error::from_string_literal("ICC::Profile: InputDevice three-component matrix-based profile must use PCSXYZ");
  666. break;
  667. }
  668. case DeviceClass::DisplayDevice: {
  669. // ICC v4, 8.4 Display profiles
  670. // "8.4.1 General
  671. // This class of profiles represents display devices such as monitors. The types of profiles available for use as
  672. // Display profiles are N-component LUT-based, Three-component matrix-based, and monochrome.
  673. // 8.4.2 N-Component LUT-based Display profiles
  674. // In addition to the tags listed in 8.2 an N-component LUT-based Input profile shall contain the following tags:
  675. // - AToB0Tag (see 9.2.1);
  676. // - BToA0Tag (see 9.2.6).
  677. // 8.4.3 Three-component matrix-based Display profiles
  678. // In addition to the tags listed in 8.2, a three-component matrix-based Display profile shall contain the following
  679. // tags:
  680. // - redMatrixColumnTag (see 9.2.44);
  681. // - greenMatrixColumnTag (see 9.2.30);
  682. // - blueMatrixColumnTag (see 9.2.4);
  683. // - redTRCTag (see 9.2.45);
  684. // - greenTRCTag (see 9.2.31);
  685. // - blueTRCTag (see 9.2.5).
  686. // [...] Only the PCSXYZ encoding can be used with matrix/TRC models.
  687. // 8.4.4 Monochrome Display profiles
  688. // In addition to the tags listed in 8.2 a monochrome Display profile shall contain the following tag:
  689. // - grayTRCTag (see 9.2.29)."
  690. bool has_n_component_lut_based_tags = has_all_tags(Array { AToB0Tag, BToA0Tag });
  691. bool has_three_component_matrix_based_tags = has_all_tags(Array { redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag, redTRCTag, greenTRCTag, blueTRCTag });
  692. bool has_monochrome_tags = has_tag(grayTRCTag);
  693. if (!has_n_component_lut_based_tags && !has_three_component_matrix_based_tags && !has_monochrome_tags)
  694. return Error::from_string_literal("ICC::Profile: DisplayDevice required tags are missing");
  695. if (!has_n_component_lut_based_tags && has_three_component_matrix_based_tags && connection_space() != ColorSpace::PCSXYZ)
  696. return Error::from_string_literal("ICC::Profile: DisplayDevice three-component matrix-based profile must use PCSXYZ");
  697. break;
  698. }
  699. case DeviceClass::OutputDevice: {
  700. // ICC v4, 8.5 Output profiles
  701. // "8.5.1 General
  702. // Output profiles are used to support devices such as printers and film recorders. The types of profiles available
  703. // for use as Output profiles are N-component LUT-based and Monochrome.
  704. // 8.5.2 N-component LUT-based Output profiles
  705. // In addition to the tags listed in 8.2 an N-component LUT-based Output profile shall contain the following tags:
  706. // - AToB0Tag (see 9.2.1);
  707. // - AToB1Tag (see 9.2.2);
  708. // - AToB2Tag (see 9.2.3);
  709. // - BToA0Tag (see 9.2.6);
  710. // - BToA1Tag (see 9.2.7);
  711. // - BToA2Tag (see 9.2.8);
  712. // - gamutTag (see 9.2.28);
  713. // - colorantTableTag (see 9.2.18), for the xCLR colour spaces (see 7.2.6)
  714. // 8.5.3 Monochrome Output profiles
  715. // In addition to the tags listed in 8.2 a monochrome Output profile shall contain the following tag:
  716. // - grayTRCTag (see 9.2.29)."
  717. // The colorantTableTag requirement is new in v4.
  718. Vector<TagSignature, 8> required_n_component_lut_based_tags = { AToB0Tag, AToB1Tag, AToB2Tag, BToA0Tag, BToA1Tag, BToA2Tag, gamutTag };
  719. if (is_v4() && is_xCLR(connection_space()))
  720. required_n_component_lut_based_tags.append(colorantTableTag);
  721. bool has_n_component_lut_based_tags = has_all_tags(required_n_component_lut_based_tags);
  722. bool has_monochrome_tags = has_tag(grayTRCTag);
  723. if (!has_n_component_lut_based_tags && !has_monochrome_tags)
  724. return Error::from_string_literal("ICC::Profile: OutputDevice required tags are missing");
  725. break;
  726. }
  727. case DeviceClass::DeviceLink: {
  728. // ICC v4, 8.6 DeviceLink profile
  729. // "A DeviceLink profile shall contain the following tags:
  730. // - profileDescriptionTag (see 9.2.41);
  731. // - copyrightTag (see 9.2.21);
  732. // - profileSequenceDescTag (see 9.2.42);
  733. // - AToB0Tag (see 9.2.1);
  734. // - colorantTableTag (see 9.2.18) which is required only if the data colour space field is xCLR, where x is
  735. // hexadecimal 2 to F (see 7.2.6);
  736. // - colorantTableOutTag (see 9.2.19), required only if the PCS field is xCLR, where x is hexadecimal 2 to F
  737. // (see 7.2.6)"
  738. // profileDescriptionTag and copyrightTag are already checked above, in the code for section 8.2.
  739. Vector<TagSignature, 4> required_tags = { profileSequenceDescTag, AToB0Tag };
  740. if (is_v4() && is_xCLR(connection_space())) { // This requirement is new in v4.
  741. required_tags.append(colorantTableTag);
  742. required_tags.append(colorantTableOutTag);
  743. }
  744. if (!has_all_tags(required_tags))
  745. return Error::from_string_literal("ICC::Profile: DeviceLink required tags are missing");
  746. // "The data colour space field (see 7.2.6) in the DeviceLink profile will be the same as the data colour space field
  747. // of the first profile in the sequence used to construct the device link. The PCS field (see 7.2.7) will be the same
  748. // as the data colour space field of the last profile in the sequence."
  749. // FIXME: Check that if profileSequenceDescType parsing is implemented.
  750. break;
  751. }
  752. case DeviceClass::ColorSpace:
  753. // ICC v4, 8.7 ColorSpace profile
  754. // "In addition to the tags listed in 8.2, a ColorSpace profile shall contain the following tags:
  755. // - BToA0Tag (see 9.2.6);
  756. // - AToB0Tag (see 9.2.1).
  757. // [...] ColorSpace profiles may be embedded in images."
  758. if (!has_all_tags(Array { AToB0Tag, BToA0Tag }))
  759. return Error::from_string_literal("ICC::Profile: ColorSpace required tags are missing");
  760. break;
  761. case DeviceClass::Abstract:
  762. // ICC v4, 8.8 Abstract profile
  763. // "In addition to the tags listed in 8.2, an Abstract profile shall contain the following tag:
  764. // - AToB0Tag (see 9.2.1).
  765. // [...] Abstract profiles cannot be embedded in images."
  766. if (!has_tag(AToB0Tag))
  767. return Error::from_string_literal("ICC::Profile: Abstract required AToB0Tag is missing");
  768. break;
  769. case DeviceClass::NamedColor:
  770. // ICC v4, 8.9 NamedColor profile
  771. // "In addition to the tags listed in 8.2, a NamedColor profile shall contain the following tag:
  772. // - namedColor2Tag (see 9.2.35)."
  773. if (!has_tag(namedColor2Tag))
  774. return Error::from_string_literal("ICC::Profile: NamedColor required namedColor2Tag is missing");
  775. break;
  776. }
  777. return {};
  778. }
  779. ErrorOr<void> Profile::check_tag_types()
  780. {
  781. // This uses m_tag_table.get() even for tags that are guaranteed to exist after check_required_tags()
  782. // so that the two functions can be called in either order.
  783. // Profile ID of /System/Library/ColorSync/Profiles/ITU-2020.icc on macOS 13.1.
  784. static constexpr Crypto::Hash::MD5::DigestType apple_itu_2020_id = { 0x57, 0x0b, 0x1b, 0x76, 0xc6, 0xa0, 0x50, 0xaa, 0x9f, 0x6c, 0x53, 0x8d, 0xbe, 0x2d, 0x3e, 0xf0 };
  785. // Profile ID of the "Display P3" profiles embedded in the images on https://webkit.org/blog-files/color-gamut/comparison.html
  786. // (The macOS 13.1 /System/Library/ColorSync/Profiles/Display\ P3.icc file no longer has this quirk.)
  787. static constexpr Crypto::Hash::MD5::DigestType apple_p3_2015_id = { 0xe5, 0xbb, 0x0e, 0x98, 0x67, 0xbd, 0x46, 0xcd, 0x4b, 0xbe, 0x44, 0x6e, 0xbd, 0x1b, 0x75, 0x98 };
  788. auto has_type = [&](auto tag, std::initializer_list<TagTypeSignature> types, std::initializer_list<TagTypeSignature> v4_types) {
  789. if (auto type = m_tag_table.get(tag); type.has_value()) {
  790. auto type_matches = [&](auto wanted_type) { return type.value()->type() == wanted_type; };
  791. return any_of(types, type_matches) || (is_v4() && any_of(v4_types, type_matches));
  792. }
  793. return true;
  794. };
  795. // ICC v4, 9.2.1 AToB0Tag
  796. // "Permitted tag types: lut8Type or lut16Type or lutAToBType"
  797. // ICC v2, 6.4.1 AToB0Tag
  798. // "Tag Type: lut8Type or lut16Type"
  799. if (!has_type(AToB0Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutAToBTagData::Type }))
  800. return Error::from_string_literal("ICC::Profile: AToB0Tag has unexpected type");
  801. // ICC v4, 9.2.2 AToB1Tag
  802. // "Permitted tag types: lut8Type or lut16Type or lutAToBType"
  803. // ICC v2, 6.4.2 AToB1Tag
  804. // "Tag Type: lut8Type or lut16Type"
  805. if (!has_type(AToB1Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutAToBTagData::Type }))
  806. return Error::from_string_literal("ICC::Profile: AToB1Tag has unexpected type");
  807. // ICC v4, 9.2.3 AToB2Tag
  808. // "Permitted tag types: lut8Type or lut16Type or lutAToBType"
  809. // ICC v2, 6.4.3 AToB2Tag
  810. // "Tag Type: lut8Type or lut16Type"
  811. if (!has_type(AToB2Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutAToBTagData::Type }))
  812. return Error::from_string_literal("ICC::Profile: AToB2Tag has unexpected type");
  813. // ICC v4, 9.2.4 blueMatrixColumnTag
  814. // "Permitted tag types: XYZType
  815. // This tag contains the third column in the matrix used in matrix/TRC transforms."
  816. // (Called blueColorantTag in the v2 spec, otherwise identical there.)
  817. if (auto type = m_tag_table.get(blueMatrixColumnTag); type.has_value()) {
  818. if (type.value()->type() != XYZTagData::Type)
  819. return Error::from_string_literal("ICC::Profile: blueMatrixColumnTag has unexpected type");
  820. if (static_cast<XYZTagData const&>(*type.value()).xyzs().size() != 1)
  821. return Error::from_string_literal("ICC::Profile: blueMatrixColumnTag has unexpected size");
  822. }
  823. // ICC v4, 9.2.5 blueTRCTag
  824. // "Permitted tag types: curveType or parametricCurveType"
  825. // ICC v2, 6.4.5 blueTRCTag
  826. // "Tag Type: curveType"
  827. if (!has_type(blueTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type }))
  828. return Error::from_string_literal("ICC::Profile: blueTRCTag has unexpected type");
  829. // ICC v4, 9.2.6 BToA0Tag
  830. // "Permitted tag types: lut8Type or lut16Type or lutBToAType"
  831. // ICC v2, 6.4.6 BToA0Tag
  832. // "Tag Type: lut8Type or lut16Type"
  833. if (!has_type(BToA0Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type }))
  834. return Error::from_string_literal("ICC::Profile: BToA0Tag has unexpected type");
  835. // ICC v4, 9.2.7 BToA1Tag
  836. // "Permitted tag types: lut8Type or lut16Type or lutBToAType"
  837. // ICC v2, 6.4.7 BToA1Tag
  838. // "Tag Type: lut8Type or lut16Type"
  839. if (!has_type(BToA1Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type }))
  840. return Error::from_string_literal("ICC::Profile: BToA1Tag has unexpected type");
  841. // ICC v4, 9.2.8 BToA2Tag
  842. // "Permitted tag types: lut8Type or lut16Type or lutBToAType"
  843. // ICC v2, 6.4.8 BToA2Tag
  844. // "Tag Type: lut8Type or lut16Type"
  845. if (!has_type(BToA2Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type }))
  846. return Error::from_string_literal("ICC::Profile: BToA2Tag has unexpected type");
  847. // ICC v4, 9.2.9 BToD0Tag
  848. // "Permitted tag types: multiProcessElementsType"
  849. // FIXME
  850. // ICC v4, 9.2.10 BToD1Tag
  851. // "Permitted tag types: multiProcessElementsType"
  852. // FIXME
  853. // ICC v4, 9.2.11 BToD2Tag
  854. // "Permitted tag types: multiProcessElementsType"
  855. // FIXME
  856. // ICC v4, 9.2.12 BToD3Tag
  857. // "Permitted tag types: multiProcessElementsType"
  858. // FIXME
  859. // ICC v4, 9.2.13 calibrationDateTimeTag
  860. // "Permitted tag types: dateTimeType"
  861. // FIXME
  862. // ICC v4, 9.2.14 charTargetTag
  863. // "Permitted tag types: textType"
  864. if (!has_type(charTargetTag, { TextTagData::Type }, {}))
  865. return Error::from_string_literal("ICC::Profile: charTargetTag has unexpected type");
  866. // ICC v4, 9.2.15 chromaticAdaptationTag
  867. // "Permitted tag types: s15Fixed16ArrayType [...]
  868. // Such a 3 x 3 chromatic adaptation matrix is organized as a 9-element array"
  869. if (auto type = m_tag_table.get(chromaticAdaptationTag); type.has_value()) {
  870. if (type.value()->type() != S15Fixed16ArrayTagData::Type)
  871. return Error::from_string_literal("ICC::Profile: chromaticAdaptationTag has unexpected type");
  872. if (static_cast<S15Fixed16ArrayTagData const&>(*type.value()).values().size() != 9)
  873. return Error::from_string_literal("ICC::Profile: chromaticAdaptationTag has unexpected size");
  874. }
  875. // ICC v4, 9.2.16 chromaticityTag
  876. // "Permitted tag types: chromaticityType"
  877. if (!has_type(chromaticityTag, { ChromaticityTagData::Type }, {}))
  878. return Error::from_string_literal("ICC::Profile: ChromaticityTagData has unexpected type");
  879. // ICC v4, 9.2.17 cicpTag
  880. // "Permitted tag types: cicpType"
  881. if (auto type = m_tag_table.get(cicpTag); type.has_value()) {
  882. if (type.value()->type() != CicpTagData::Type)
  883. return Error::from_string_literal("ICC::Profile: cicpTag has unexpected type");
  884. // "The colour encoding specified by the CICP tag content shall be equivalent to the data colour space encoding
  885. // represented by this ICC profile.
  886. // NOTE The ICC colour transform cannot match every possible rendering of a CICP colour encoding."
  887. // FIXME: Figure out what that means and check for it.
  888. // "This tag may be present when the data colour space in the profile header is RGB, YCbCr, or XYZ, and the
  889. // profile class in the profile header is Input or Display. The tag shall not be present for other data colour spaces
  890. // or profile classes indicated in the profile header."
  891. bool is_color_space_allowed = data_color_space() == ColorSpace::RGB || data_color_space() == ColorSpace::YCbCr || data_color_space() == ColorSpace::nCIEXYZ;
  892. bool is_profile_class_allowed = device_class() == DeviceClass::InputDevice || device_class() == DeviceClass::DisplayDevice;
  893. bool cicp_is_allowed = is_color_space_allowed && is_profile_class_allowed;
  894. if (!cicp_is_allowed)
  895. return Error::from_string_literal("ICC::Profile: cicpTag present but not allowed");
  896. }
  897. // ICC v4, 9.2.18 colorantOrderTag
  898. // "Permitted tag types: colorantOrderType"
  899. // FIXME
  900. // ICC v4, 9.2.19 colorantTableTag
  901. // "Permitted tag types: colorantTableType"
  902. // FIXME
  903. // ICC v4, 9.2.20 colorantTableOutTag
  904. // "Permitted tag types: colorantTableType"
  905. // FIXME
  906. // ICC v4, 9.2.21 colorimetricIntentImageStateTag
  907. // "Permitted tag types: signatureType"
  908. if (!has_type(colorimetricIntentImageStateTag, { SignatureTagData::Type }, {}))
  909. return Error::from_string_literal("ICC::Profile: colorimetricIntentImageStateTag has unexpected type");
  910. // ICC v4, 9.2.22 copyrightTag
  911. // "Permitted tag types: multiLocalizedUnicodeType"
  912. // ICC v2, 6.4.13 copyrightTag
  913. // "Tag Type: textType"
  914. if (auto type = m_tag_table.get(copyrightTag); type.has_value()) {
  915. // The v4 spec requires multiLocalizedUnicodeType for this, but I'm aware of a single file
  916. // that still uses the v2 'text' type here: /System/Library/ColorSync/Profiles/ITU-2020.icc on macOS 13.1.
  917. // https://openradar.appspot.com/radar?id=5529765549178880
  918. bool has_v2_cprt_type_in_v4_file_quirk = id() == apple_itu_2020_id || id() == apple_p3_2015_id;
  919. if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type && (!has_v2_cprt_type_in_v4_file_quirk || type.value()->type() != TextTagData::Type))
  920. return Error::from_string_literal("ICC::Profile: copyrightTag has unexpected v4 type");
  921. if (is_v2() && type.value()->type() != TextTagData::Type)
  922. return Error::from_string_literal("ICC::Profile: copyrightTag has unexpected v2 type");
  923. }
  924. // ICC v4, 9.2.23 deviceMfgDescTag
  925. // "Permitted tag types: multiLocalizedUnicodeType"
  926. // ICC v2, 6.4.15 deviceMfgDescTag
  927. // "Tag Type: textDescriptionType"
  928. if (auto type = m_tag_table.get(deviceMfgDescTag); type.has_value()) {
  929. if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type)
  930. return Error::from_string_literal("ICC::Profile: deviceMfgDescTag has unexpected v4 type");
  931. if (is_v2() && type.value()->type() != TextDescriptionTagData::Type)
  932. return Error::from_string_literal("ICC::Profile: deviceMfgDescTag has unexpected v2 type");
  933. }
  934. // ICC v4, 9.2.24 deviceModelDescTag
  935. // "Permitted tag types: multiLocalizedUnicodeType"
  936. // ICC v2, 6.4.16 deviceModelDescTag
  937. // "Tag Type: textDescriptionType"
  938. if (auto type = m_tag_table.get(deviceModelDescTag); type.has_value()) {
  939. if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type)
  940. return Error::from_string_literal("ICC::Profile: deviceModelDescTag has unexpected v4 type");
  941. if (is_v2() && type.value()->type() != TextDescriptionTagData::Type)
  942. return Error::from_string_literal("ICC::Profile: deviceModelDescTag has unexpected v2 type");
  943. }
  944. // ICC v4, 9.2.25 DToB0Tag
  945. // "Permitted tag types: multiProcessElementsType"
  946. // FIXME
  947. // ICC v4, 9.2.26 DToB1Tag
  948. // "Permitted tag types: multiProcessElementsType"
  949. // FIXME
  950. // ICC v4, 9.2.27 DToB2Tag
  951. // "Permitted tag types: multiProcessElementsType"
  952. // FIXME
  953. // ICC v4, 9.2.28 DToB3Tag
  954. // "Permitted tag types: multiProcessElementsType"
  955. // FIXME
  956. // ICC v4, 9.2.29 gamutTag
  957. // "Permitted tag types: lut8Type or lut16Type or lutBToAType"
  958. // ICC v2, 6.4.18 gamutTag
  959. // "Tag Type: lut8Type or lut16Type"
  960. if (!has_type(gamutTag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type }))
  961. return Error::from_string_literal("ICC::Profile: gamutTag has unexpected type");
  962. // ICC v4, 9.2.30 grayTRCTag
  963. // "Permitted tag types: curveType or parametricCurveType"
  964. // ICC v2, 6.4.19 grayTRCTag
  965. // "Tag Type: curveType"
  966. if (!has_type(grayTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type }))
  967. return Error::from_string_literal("ICC::Profile: grayTRCTag has unexpected type");
  968. // ICC v4, 9.2.31 greenMatrixColumnTag
  969. // "Permitted tag types: XYZType
  970. // This tag contains the second column in the matrix, which is used in matrix/TRC transforms."
  971. // (Called greenColorantTag in the v2 spec, otherwise identical there.)
  972. if (auto type = m_tag_table.get(greenMatrixColumnTag); type.has_value()) {
  973. if (type.value()->type() != XYZTagData::Type)
  974. return Error::from_string_literal("ICC::Profile: greenMatrixColumnTag has unexpected type");
  975. if (static_cast<XYZTagData const&>(*type.value()).xyzs().size() != 1)
  976. return Error::from_string_literal("ICC::Profile: greenMatrixColumnTag has unexpected size");
  977. }
  978. // ICC v4, 9.2.32 greenTRCTag
  979. // "Permitted tag types: curveType or parametricCurveType"
  980. // ICC v2, 6.4.21 greenTRCTag
  981. // "Tag Type: curveType"
  982. if (!has_type(greenTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type }))
  983. return Error::from_string_literal("ICC::Profile: greenTRCTag has unexpected type");
  984. // ICC v4, 9.2.33 luminanceTag
  985. // "Permitted tag types: XYZType"
  986. // This tag contains the absolute luminance of emissive devices in candelas per square metre as described by the
  987. // Y channel.
  988. // NOTE The X and Z values are set to zero."
  989. // ICC v2, 6.4.22 luminanceTag
  990. // "Absolute luminance of emissive devices in candelas per square meter as described by the Y channel. The
  991. // X and Z channels are ignored in all cases."
  992. if (auto type = m_tag_table.get(luminanceTag); type.has_value()) {
  993. if (type.value()->type() != XYZTagData::Type)
  994. return Error::from_string_literal("ICC::Profile: luminanceTag has unexpected type");
  995. auto& xyz_type = static_cast<XYZTagData const&>(*type.value());
  996. if (xyz_type.xyzs().size() != 1)
  997. return Error::from_string_literal("ICC::Profile: luminanceTag has unexpected size");
  998. if (is_v4() && xyz_type.xyzs()[0].X != 0)
  999. return Error::from_string_literal("ICC::Profile: luminanceTag.x unexpectedly not 0");
  1000. if (is_v4() && xyz_type.xyzs()[0].Z != 0)
  1001. return Error::from_string_literal("ICC::Profile: luminanceTag.z unexpectedly not 0");
  1002. }
  1003. // ICC v4, 9.2.34 measurementTag
  1004. // "Permitted tag types: measurementType"
  1005. if (!has_type(measurementTag, { MeasurementTagData::Type }, {}))
  1006. return Error::from_string_literal("ICC::Profile: measurementTag has unexpected type");
  1007. // ICC v4, 9.2.35 metadataTag
  1008. // "Permitted tag types: dictType"
  1009. // FIXME
  1010. // ICC v4, 9.2.36 mediaWhitePointTag
  1011. // "Permitted tag types: XYZType
  1012. // This tag, which is used for generating the ICC-absolute colorimetric intent, specifies the chromatically adapted
  1013. // nCIEXYZ tristimulus values of the media white point. When the measurement data used to create the profile
  1014. // were specified relative to an adopted white with a chromaticity different from that of the PCS adopted white, the
  1015. // media white point nCIEXYZ values shall be adapted to be relative to the PCS adopted white chromaticity using
  1016. // the chromaticAdaptationTag matrix, before recording in the tag. For capture devices, the media white point is
  1017. // the encoding maximum white for the capture encoding. For displays, the values specified shall be those of the
  1018. // PCS illuminant as defined in 7.2.16.
  1019. // See Clause 6 and Annex A for a more complete description of the use of the media white point."
  1020. // ICC v2, 6.4.25 mediaWhitePointTag
  1021. // "This tag specifies the media white point and is used for generating ICC-absolute colorimetric intent. See
  1022. // Annex A for a more complete description of its use."
  1023. if (auto type = m_tag_table.get(mediaWhitePointTag); type.has_value()) {
  1024. if (type.value()->type() != XYZTagData::Type)
  1025. return Error::from_string_literal("ICC::Profile: mediaWhitePointTag has unexpected type");
  1026. auto& xyz_type = static_cast<XYZTagData const&>(*type.value());
  1027. if (xyz_type.xyzs().size() != 1)
  1028. return Error::from_string_literal("ICC::Profile: mediaWhitePointTag has unexpected size");
  1029. // V4 requires "For displays, the values specified shall be those of the PCS illuminant".
  1030. // But in practice that's not always true. For example, on macOS 13.1, '/System/Library/ColorSync/Profiles/DCI(P3) RGB.icc'
  1031. // has these values in the header: 0000F6D6 00010000 0000D32D
  1032. // but these values in the tag: 0000F6D5 00010000 0000D32C
  1033. // These are close, but not equal.
  1034. // FIXME: File bug for these, and add id-based quirk instead.
  1035. // if (is_v4() && device_class() == DeviceClass::DisplayDevice && xyz_type.xyzs()[0] != pcs_illuminant())
  1036. // return Error::from_string_literal("ICC::Profile: mediaWhitePointTag for displays should be equal to PCS illuminant");
  1037. }
  1038. // ICC v4, 9.2.37 namedColor2Tag
  1039. // "Permitted tag types: namedColor2Type"
  1040. if (auto type = m_tag_table.get(namedColor2Tag); type.has_value()) {
  1041. if (type.value()->type() != NamedColor2TagData::Type)
  1042. return Error::from_string_literal("ICC::Profile: namedColor2Tag has unexpected type");
  1043. // ICC v4, 10.17 namedColor2Type
  1044. // "The device representation corresponds to the header’s “data colour space” field.
  1045. // This representation should be consistent with the “number of device coordinates” field in the namedColor2Type.
  1046. // If this field is 0, device coordinates are not provided."
  1047. if (auto number_of_device_coordinates = static_cast<NamedColor2TagData const&>(*type.value()).number_of_device_coordinates();
  1048. number_of_device_coordinates != 0 && number_of_device_coordinates != number_of_components_in_color_space(data_color_space())) {
  1049. return Error::from_string_literal("ICC::Profile: namedColor2Tag number of device coordinates inconsistent with data color space");
  1050. }
  1051. }
  1052. // ICC v4, 9.2.38 outputResponseTag
  1053. // "Permitted tag types: responseCurveSet16Type"
  1054. // FIXME
  1055. // ICC v4, 9.2.39 perceptualRenderingIntentGamutTag
  1056. // "Permitted tag types: signatureType"
  1057. if (!has_type(perceptualRenderingIntentGamutTag, { SignatureTagData::Type }, {}))
  1058. return Error::from_string_literal("ICC::Profile: perceptualRenderingIntentGamutTag has unexpected type");
  1059. // ICC v4, 9.2.40 preview0Tag
  1060. // "Permitted tag types: lut8Type or lut16Type or lutAToBType or lutBToAType"
  1061. // ICC v2, 6.4.29 preview0Tag
  1062. // "Tag Type: lut8Type or lut16Type"
  1063. if (!has_type(preview0Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type, LutBToATagData::Type }))
  1064. return Error::from_string_literal("ICC::Profile: preview0Tag has unexpected type");
  1065. // ICC v4, 9.2.41 preview1Tag
  1066. // "Permitted tag types: lut8Type or lut16Type or lutBToAType"
  1067. // ICC v2, 6.4.30 preview1Tag
  1068. // "Tag Type: lut8Type or lut16Type"
  1069. if (!has_type(preview1Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type }))
  1070. return Error::from_string_literal("ICC::Profile: preview1Tag has unexpected type");
  1071. // ICC v4, 9.2.42 preview2Tag
  1072. // "Permitted tag types: lut8Type or lut16Type or lutBToAType"
  1073. // ICC v2, 6.4.31 preview2Tag
  1074. // "Tag Type: lut8Type or lut16Type"
  1075. if (!has_type(preview2Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type }))
  1076. return Error::from_string_literal("ICC::Profile: preview2Tag has unexpected type");
  1077. // ICC v4, 9.2.43 profileDescriptionTag
  1078. // "Permitted tag types: multiLocalizedUnicodeType"
  1079. // ICC v2, 6.4.32 profileDescriptionTag
  1080. // "Tag Type: textDescriptionType"
  1081. if (auto type = m_tag_table.get(profileDescriptionTag); type.has_value()) {
  1082. // The v4 spec requires multiLocalizedUnicodeType for this, but I'm aware of a single file
  1083. // that still uses the v2 'desc' type here: /System/Library/ColorSync/Profiles/ITU-2020.icc on macOS 13.1.
  1084. // https://openradar.appspot.com/radar?id=5529765549178880
  1085. bool has_v2_desc_type_in_v4_file_quirk = id() == apple_itu_2020_id || id() == apple_p3_2015_id;
  1086. if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type && (!has_v2_desc_type_in_v4_file_quirk || type.value()->type() != TextDescriptionTagData::Type))
  1087. return Error::from_string_literal("ICC::Profile: profileDescriptionTag has unexpected v4 type");
  1088. if (is_v2() && type.value()->type() != TextDescriptionTagData::Type)
  1089. return Error::from_string_literal("ICC::Profile: profileDescriptionTag has unexpected v2 type");
  1090. }
  1091. // ICC v4, 9.2.44 profileSequenceDescTag
  1092. // "Permitted tag types: profileSequenceDescType"
  1093. // FIXME
  1094. // ICC v4, 9.2.45 profileSequenceIdentifierTag
  1095. // "Permitted tag types: profileSequenceIdentifierType"
  1096. // FIXME
  1097. // ICC v4, 9.2.46 redMatrixColumnTag
  1098. // "Permitted tag types: XYZType
  1099. // This tag contains the first column in the matrix, which is used in matrix/TRC transforms."
  1100. // (Called redColorantTag in the v2 spec, otherwise identical there.)
  1101. if (auto type = m_tag_table.get(redMatrixColumnTag); type.has_value()) {
  1102. if (type.value()->type() != XYZTagData::Type)
  1103. return Error::from_string_literal("ICC::Profile: redMatrixColumnTag has unexpected type");
  1104. if (static_cast<XYZTagData const&>(*type.value()).xyzs().size() != 1)
  1105. return Error::from_string_literal("ICC::Profile: redMatrixColumnTag has unexpected size");
  1106. }
  1107. // ICC v4, 9.2.47 redTRCTag
  1108. // "Permitted tag types: curveType or parametricCurveType"
  1109. // ICC v2, 6.4.41 redTRCTag
  1110. // "Tag Type: curveType"
  1111. if (!has_type(redTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type }))
  1112. return Error::from_string_literal("ICC::Profile: redTRCTag has unexpected type");
  1113. // ICC v4, 9.2.48 saturationRenderingIntentGamutTag
  1114. // "Permitted tag types: signatureType"
  1115. if (!has_type(saturationRenderingIntentGamutTag, { SignatureTagData::Type }, {}))
  1116. return Error::from_string_literal("ICC::Profile: saturationRenderingIntentGamutTag has unexpected type");
  1117. // ICC v4, 9.2.49 technologyTag
  1118. // "Permitted tag types: signatureType"
  1119. if (!has_type(technologyTag, { SignatureTagData::Type }, {}))
  1120. return Error::from_string_literal("ICC::Profile: technologyTag has unexpected type");
  1121. // ICC v4, 9.2.50 viewingCondDescTag
  1122. // "Permitted tag types: multiLocalizedUnicodeType"
  1123. // ICC v2, 6.4.46 viewingCondDescTag
  1124. // "Tag Type: textDescriptionType"
  1125. if (auto type = m_tag_table.get(viewingCondDescTag); type.has_value()) {
  1126. if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type)
  1127. return Error::from_string_literal("ICC::Profile: viewingCondDescTag has unexpected v4 type");
  1128. if (is_v2() && type.value()->type() != TextDescriptionTagData::Type)
  1129. return Error::from_string_literal("ICC::Profile: viewingCondDescTag has unexpected v2 type");
  1130. }
  1131. // ICC v4, 9.2.51 viewingConditionsTag
  1132. // "Permitted tag types: viewingConditionsType"
  1133. if (!has_type(viewingConditionsTag, { ViewingConditionsTagData::Type }, {}))
  1134. return Error::from_string_literal("ICC::Profile: viewingConditionsTag has unexpected type");
  1135. // FIXME: Add validation for v2-only tags:
  1136. // - ICC v2, 6.4.14 crdInfoTag
  1137. // "Tag Type: crdInfoType"
  1138. // - ICC v2, 6.4.17 deviceSettingsTag
  1139. // "Tag Type: deviceSettingsType"
  1140. // - ICC v2, 6.4.24 mediaBlackPointTag
  1141. // "Tag Type: XYZType"
  1142. // - ICC v2, 6.4.26 namedColorTag
  1143. // "Tag Type: namedColorType"
  1144. // - ICC v2, 6.4.34 ps2CRD0Tag
  1145. // "Tag Type: dataType"
  1146. // - ICC v2, 6.4.35 ps2CRD1Tag
  1147. // "Tag Type: dataType"
  1148. // - ICC v2, 6.4.36 ps2CRD2Tag
  1149. // "Tag Type: dataType"
  1150. // - ICC v2, 6.4.37 ps2CRD3Tag
  1151. // "Tag Type: dataType"
  1152. // - ICC v2, 6.4.38 ps2CSATag
  1153. // "Tag Type: dataType"
  1154. // - ICC v2, 6.4.39 ps2RenderingIntentTag
  1155. // "Tag Type: dataType"
  1156. // - ICC v2, 6.4.42 screeningDescTag
  1157. // "Tag Type: textDescriptionType"
  1158. // - ICC v2, 6.4.43 screeningTag
  1159. // "Tag Type: screeningType"
  1160. // - ICC v2, 6.4.45 ucrbgTag
  1161. // "Tag Type: ucrbgType"
  1162. // https://www.color.org/v2profiles.xalter says about these tags:
  1163. // "it is also recommended that optional tags in the v2 specification that have subsequently become
  1164. // obsolete are not included in future profiles made to the v2 specification."
  1165. return {};
  1166. }
  1167. ErrorOr<NonnullRefPtr<Profile>> Profile::try_load_from_externally_owned_memory(ReadonlyBytes bytes)
  1168. {
  1169. auto header = TRY(read_header(bytes));
  1170. bytes = bytes.trim(header.on_disk_size);
  1171. auto tag_table = TRY(read_tag_table(bytes));
  1172. return create(header, move(tag_table));
  1173. }
  1174. ErrorOr<NonnullRefPtr<Profile>> Profile::create(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table)
  1175. {
  1176. auto profile = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Profile(header, move(tag_table))));
  1177. TRY(profile->check_required_tags());
  1178. TRY(profile->check_tag_types());
  1179. return profile;
  1180. }
  1181. Crypto::Hash::MD5::DigestType Profile::compute_id(ReadonlyBytes bytes)
  1182. {
  1183. // ICC v4, 7.2.18 Profile ID field
  1184. // "The Profile ID shall be calculated using the MD5 fingerprinting method as defined in Internet RFC 1321.
  1185. // The entire profile, whose length is given by the size field in the header, with the
  1186. // profile flags field (bytes 44 to 47, see 7.2.11),
  1187. // rendering intent field (bytes 64 to 67, see 7.2.15),
  1188. // and profile ID field (bytes 84 to 99)
  1189. // in the profile header temporarily set to zeros (00h),
  1190. // shall be used to calculate the ID."
  1191. const u8 zero[16] = {};
  1192. Crypto::Hash::MD5 md5;
  1193. md5.update(bytes.slice(0, 44));
  1194. md5.update(ReadonlyBytes { zero, 4 }); // profile flags field
  1195. md5.update(bytes.slice(48, 64 - 48));
  1196. md5.update(ReadonlyBytes { zero, 4 }); // rendering intent field
  1197. md5.update(bytes.slice(68, 84 - 68));
  1198. md5.update(ReadonlyBytes { zero, 16 }); // profile ID field
  1199. md5.update(bytes.slice(100));
  1200. return md5.digest();
  1201. }
  1202. static TagSignature forward_transform_tag_for_rendering_intent(RenderingIntent rendering_intent)
  1203. {
  1204. // ICCv4, Table 25 — Profile type/profile tag and defined rendering intents
  1205. // This function assumes a profile class of InputDevice, DisplayDevice, OutputDevice, or ColorSpace.
  1206. switch (rendering_intent) {
  1207. case RenderingIntent::Perceptual:
  1208. return AToB0Tag;
  1209. case RenderingIntent::MediaRelativeColorimetric:
  1210. case RenderingIntent::ICCAbsoluteColorimetric:
  1211. return AToB1Tag;
  1212. case RenderingIntent::Saturation:
  1213. return AToB2Tag;
  1214. }
  1215. VERIFY_NOT_REACHED();
  1216. }
  1217. ErrorOr<FloatVector3> Profile::to_pcs(ReadonlyBytes color) const
  1218. {
  1219. if (color.size() != number_of_components_in_color_space(data_color_space()))
  1220. return Error::from_string_literal("ICC::Profile: input color doesn't match color space size");
  1221. auto has_tag = [&](auto tag) { return m_tag_table.contains(tag); };
  1222. auto has_all_tags = [&]<class T>(T tags) { return all_of(tags, has_tag); };
  1223. switch (device_class()) {
  1224. case DeviceClass::InputDevice:
  1225. case DeviceClass::DisplayDevice:
  1226. case DeviceClass::OutputDevice:
  1227. case DeviceClass::ColorSpace: {
  1228. // ICC v4, 8.10 Precedence order of tag usage
  1229. // "There are several methods of colour transformation that can function within a single CMM. If data for more than
  1230. // one method are included in the same profile, the following selection algorithm shall be used by the software
  1231. // implementation."
  1232. // ICC v4, 8.10.2 Input, display, output, or colour space profile types
  1233. // "a) Use the BToD0Tag, BToD1Tag, BToD2Tag, BToD3Tag, DToB0Tag, DToB1Tag, DToB2Tag, or
  1234. // DToB3Tag designated for the rendering intent if the tag is present, except where this tag is not needed or
  1235. // supported by the CMM (if a particular processing element within the tag is not supported the tag is not
  1236. // supported)."
  1237. // FIXME: Implement multiProcessElementsType one day.
  1238. // "b) Use the BToA0Tag, BToA1Tag, BToA2Tag, AToB0Tag, AToB1Tag, or AToB2Tag designated for the
  1239. // rendering intent if present, when the tag in a) is not used."
  1240. if (has_tag(forward_transform_tag_for_rendering_intent(rendering_intent()))) {
  1241. // FIXME
  1242. return Error::from_string_literal("ICC::Profile::to_pcs: AToB0Tag handling not yet implemented");
  1243. }
  1244. // "c) Use the BToA0Tag or AToB0Tag if present, when the tags in a) and b) are not used."
  1245. // AToB0Tag is for the conversion _to_ PCS (BToA0Tag is for conversion _from_ PCS, so not needed in this function).
  1246. if (has_tag(AToB0Tag)) {
  1247. // FIXME
  1248. return Error::from_string_literal("ICC::Profile::to_pcs: AToB0Tag handling not yet implemented");
  1249. }
  1250. // "d) Use TRCs (redTRCTag, greenTRCTag, blueTRCTag, or grayTRCTag) and colorants
  1251. // (redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag) when tags in a), b), and c) are not
  1252. // used."
  1253. if (data_color_space() == ColorSpace::Gray) {
  1254. // ICC v4, F.2 grayTRCTag
  1255. // FIXME
  1256. return Error::from_string_literal("ICC::Profile::to_pcs: Gray handling not yet implemented");
  1257. }
  1258. // FIXME: Per ICC v4, A.1 General, this should also handle HLS, HSV, YCbCr.
  1259. if (data_color_space() == ColorSpace::RGB) {
  1260. if (!has_all_tags(Array { redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag, redTRCTag, greenTRCTag, blueTRCTag }))
  1261. return Error::from_string_literal("ICC::Profile::to_pcs: RGB color space but neither LUT-based nor matrix-based tags present");
  1262. VERIFY(color.size() == 3); // True because of color.size() check further up.
  1263. // ICC v4, F.3 Three-component matrix-based profiles
  1264. // "linear_r = redTRC[device_r]
  1265. // linear_g = greenTRC[device_g]
  1266. // linear_b = blueTRC[device_b]
  1267. // [connection_X] = [redMatrixColumn_X greenMatrixColumn_X blueMatrixColumn_X] [ linear_r ]
  1268. // [connection_Y] = [redMatrixColumn_Y greenMatrixColumn_Y blueMatrixColumn_Y] * [ linear_g ]
  1269. // [connection_Z] = [redMatrixColumn_Z greenMatrixColumn_Z blueMatrixColumn_Z] [ linear_b ]"
  1270. auto evaluate_curve = [this](TagSignature curve_tag, float f) {
  1271. auto const& trc = *m_tag_table.get(curve_tag).value();
  1272. VERIFY(trc.type() == CurveTagData::Type || trc.type() == ParametricCurveTagData::Type);
  1273. if (trc.type() == CurveTagData::Type)
  1274. return static_cast<CurveTagData const&>(trc).evaluate(f);
  1275. return static_cast<ParametricCurveTagData const&>(trc).evaluate(f);
  1276. };
  1277. float linear_r = evaluate_curve(redTRCTag, color[0] / 255.f);
  1278. float linear_g = evaluate_curve(greenTRCTag, color[1] / 255.f);
  1279. float linear_b = evaluate_curve(blueTRCTag, color[2] / 255.f);
  1280. auto const& redMatrixColumn = red_matrix_column();
  1281. auto const& greenMatrixColumn = green_matrix_column();
  1282. auto const& blueMatrixColumn = blue_matrix_column();
  1283. float X = redMatrixColumn.X * linear_r + greenMatrixColumn.X * linear_g + blueMatrixColumn.X * linear_b;
  1284. float Y = redMatrixColumn.Y * linear_r + greenMatrixColumn.Y * linear_g + blueMatrixColumn.Y * linear_b;
  1285. float Z = redMatrixColumn.Z * linear_r + greenMatrixColumn.Z * linear_g + blueMatrixColumn.Z * linear_b;
  1286. return FloatVector3 { X, Y, Z };
  1287. }
  1288. return Error::from_string_literal("ICC::Profile::to_pcs: What happened?!");
  1289. }
  1290. case DeviceClass::DeviceLink:
  1291. case DeviceClass::Abstract:
  1292. // ICC v4, 8.10.3 DeviceLink or Abstract profile types
  1293. // FIXME
  1294. return Error::from_string_literal("ICC::Profile::to_pcs: conversion for DeviceLink and Abstract not implemented");
  1295. case DeviceClass::NamedColor:
  1296. return Error::from_string_literal("ICC::Profile::to_pcs: to_pcs with NamedColor profile does not make sense");
  1297. }
  1298. VERIFY_NOT_REACHED();
  1299. }
  1300. ErrorOr<CIELAB> Profile::to_lab(ReadonlyBytes color) const
  1301. {
  1302. auto pcs = TRY(to_pcs(color));
  1303. if (connection_space() == ColorSpace::PCSLAB)
  1304. return CIELAB { pcs[0], pcs[1], pcs[2] };
  1305. if (connection_space() != ColorSpace::PCSXYZ) {
  1306. VERIFY(device_class() == DeviceClass::DeviceLink);
  1307. return Error::from_string_literal("ICC::Profile::to_lab: conversion for DeviceLink not implemented");
  1308. }
  1309. // 6.3.2.2 Translation between media-relative colorimetric data and ICC-absolute colorimetric data
  1310. // 6.3.2.3 Computation of PCSLAB
  1311. // 6.3.4 Colour space encodings for the PCS
  1312. // A.3 PCS encodings
  1313. auto f = [](float x) {
  1314. if (x > powf(6.f / 29.f, 3))
  1315. return cbrtf(x);
  1316. return x / (3 * powf(6.f / 29.f, 2)) + 4.f / 29.f;
  1317. };
  1318. // "X/Xn is replaced by Xr/Xi (or Xa/Xmw)"
  1319. // 6.3.2.2 Translation between media-relative colorimetric data and ICC-absolute colorimetric data
  1320. // "The translation from ICC-absolute colorimetric data to media-relative colorimetry data is given by Equations
  1321. // Xr = (Xi/Xmw) * Xa
  1322. // where
  1323. // Xr media-relative colorimetric data (i.e. PCSXYZ);
  1324. // Xa ICC-absolute colorimetric data (i.e. nCIEXYZ);
  1325. // Xmw nCIEXYZ values of the media white point as specified in the mediaWhitePointTag;
  1326. // Xi PCSXYZ values of the PCS white point defined in 6.3.4.3."
  1327. // 6.3.4.3 PCS encodings for white and black
  1328. // "Table 14 — Encodings of PCS white point: X 0,9642 Y 1,0000 Z 0,8249"
  1329. // That's identical to the values in 7.2.16 PCS illuminant field (Bytes 68 to 79).
  1330. // 9.2.36 mediaWhitePointTag
  1331. // "For displays, the values specified shall be those of the PCS illuminant as defined in 7.2.16."
  1332. // ...so for displays, this is all equivalent I think? It's maybe different for OutputDevice profiles?
  1333. float Xn = pcs_illuminant().X;
  1334. float Yn = pcs_illuminant().Y;
  1335. float Zn = pcs_illuminant().Z;
  1336. float x = pcs[0] / Xn;
  1337. float y = pcs[1] / Yn;
  1338. float z = pcs[2] / Zn;
  1339. float L = 116 * f(y) - 16;
  1340. float a = 500 * (f(x) - f(y));
  1341. float b = 200 * (f(y) - f(z));
  1342. return CIELAB { L, a, b };
  1343. }
  1344. XYZ const& Profile::red_matrix_column() const { return xyz_data(redMatrixColumnTag); }
  1345. XYZ const& Profile::green_matrix_column() const { return xyz_data(greenMatrixColumnTag); }
  1346. XYZ const& Profile::blue_matrix_column() const { return xyz_data(blueMatrixColumnTag); }
  1347. }