Profile.cpp 79 KB

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