Profile.cpp 86 KB

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