Profile.cpp 85 KB

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