Profile.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. /*
  2. * Copyright (c) 2022-2023, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Error.h>
  8. #include <AK/Format.h>
  9. #include <AK/HashMap.h>
  10. #include <AK/NonnullRefPtr.h>
  11. #include <AK/RefCounted.h>
  12. #include <AK/Span.h>
  13. #include <AK/URL.h>
  14. #include <LibCrypto/Hash/MD5.h>
  15. #include <LibGfx/Bitmap.h>
  16. #include <LibGfx/CIELAB.h>
  17. #include <LibGfx/ICC/DistinctFourCC.h>
  18. #include <LibGfx/ICC/TagTypes.h>
  19. #include <LibGfx/Matrix3x3.h>
  20. #include <LibGfx/Vector3.h>
  21. namespace Gfx::ICC {
  22. URL device_manufacturer_url(DeviceManufacturer);
  23. URL device_model_url(DeviceModel);
  24. // ICC v4, 7.2.4 Profile version field
  25. class Version {
  26. public:
  27. Version() = default;
  28. Version(u8 major, u8 minor_and_bugfix)
  29. : m_major_version(major)
  30. , m_minor_and_bugfix_version(minor_and_bugfix)
  31. {
  32. }
  33. u8 major_version() const { return m_major_version; }
  34. u8 minor_version() const { return m_minor_and_bugfix_version >> 4; }
  35. u8 bugfix_version() const { return m_minor_and_bugfix_version & 0xf; }
  36. u8 minor_and_bugfix_version() const { return m_minor_and_bugfix_version; }
  37. private:
  38. u8 m_major_version = 0;
  39. u8 m_minor_and_bugfix_version = 0;
  40. };
  41. // ICC v4, 7.2.11 Profile flags field
  42. class Flags {
  43. public:
  44. Flags();
  45. // "The profile flags field contains flags."
  46. Flags(u32);
  47. u32 bits() const { return m_bits; }
  48. // "These can indicate various hints for the CMM such as distributed processing and caching options."
  49. // "The least-significant 16 bits are reserved for the ICC."
  50. u16 color_management_module_bits() const { return bits() >> 16; }
  51. u16 icc_bits() const { return bits() & 0xffff; }
  52. // "Bit position 0: Embedded profile (0 if not embedded, 1 if embedded in file)"
  53. bool is_embedded_in_file() const { return (icc_bits() & 1) != 0; }
  54. // "Bit position 1: Profile cannot be used independently of the embedded colour data (set to 1 if true, 0 if false)"
  55. // Double negation isn't unconfusing, so this function uses the inverted, positive sense.
  56. bool can_be_used_independently_of_embedded_color_data() const { return (icc_bits() & 2) == 0; }
  57. static constexpr u32 KnownBitsMask = 3;
  58. private:
  59. u32 m_bits = 0;
  60. };
  61. // ICC v4, 7.2.14 Device attributes field
  62. class DeviceAttributes {
  63. public:
  64. DeviceAttributes();
  65. // "The device attributes field shall contain flags used to identify attributes
  66. // unique to the particular device setup for which the profile is applicable."
  67. DeviceAttributes(u64);
  68. u64 bits() const { return m_bits; }
  69. // "The least-significant 32 bits of this 64-bit value are defined by the ICC. "
  70. u32 icc_bits() const { return bits() & 0xffff'ffff; }
  71. // "Notice that bits 0, 1, 2, and 3 describe the media, not the device."
  72. // "0": "Reflective (0) or transparency (1)"
  73. enum class MediaReflectivity {
  74. Reflective,
  75. Transparent,
  76. };
  77. MediaReflectivity media_reflectivity() const { return MediaReflectivity(icc_bits() & 1); }
  78. // "1": "Glossy (0) or matte (1)"
  79. enum class MediaGlossiness {
  80. Glossy,
  81. Matte,
  82. };
  83. MediaGlossiness media_glossiness() const { return MediaGlossiness((icc_bits() >> 1) & 1); }
  84. // "2": "Media polarity, positive (0) or negative (1)"
  85. enum class MediaPolarity {
  86. Positive,
  87. Negative,
  88. };
  89. MediaPolarity media_polarity() const { return MediaPolarity((icc_bits() >> 2) & 1); }
  90. // "3": "Colour media (0), black & white media (1)"
  91. enum class MediaColor {
  92. Colored,
  93. BlackAndWhite,
  94. };
  95. MediaColor media_color() const { return MediaColor((icc_bits() >> 3) & 1); }
  96. // "4 to 31": Reserved (set to binary zero)"
  97. // "32 to 63": "Use not defined by ICC (vendor specific"
  98. u32 vendor_bits() const { return bits() >> 32; }
  99. static constexpr u64 KnownBitsMask = 0xf;
  100. private:
  101. u64 m_bits = 0;
  102. };
  103. // Time is in UTC.
  104. // Per spec, month is 1-12, day is 1-31, hours is 0-23, minutes 0-59, seconds 0-59 (i.e. no leap seconds).
  105. // But in practice, some profiles have invalid dates, like 0-0-0 0:0:0.
  106. // For valid profiles, the conversion to time_t will succeed.
  107. struct DateTime {
  108. u16 year = 1970;
  109. u16 month = 1; // One-based.
  110. u16 day = 1; // One-based.
  111. u16 hours = 0;
  112. u16 minutes = 0;
  113. u16 seconds = 0;
  114. ErrorOr<time_t> to_time_t() const;
  115. static ErrorOr<DateTime> from_time_t(time_t);
  116. };
  117. struct ProfileHeader {
  118. u32 on_disk_size { 0 };
  119. Optional<PreferredCMMType> preferred_cmm_type;
  120. Version version;
  121. DeviceClass device_class {};
  122. ColorSpace data_color_space {};
  123. ColorSpace connection_space {};
  124. DateTime creation_timestamp;
  125. Optional<PrimaryPlatform> primary_platform {};
  126. Flags flags;
  127. Optional<DeviceManufacturer> device_manufacturer;
  128. Optional<DeviceModel> device_model;
  129. DeviceAttributes device_attributes;
  130. RenderingIntent rendering_intent {};
  131. XYZ pcs_illuminant;
  132. Optional<Creator> creator;
  133. Optional<Crypto::Hash::MD5::DigestType> id;
  134. };
  135. // FIXME: This doesn't belong here.
  136. class MatrixMatrixConversion {
  137. public:
  138. MatrixMatrixConversion(LutCurveType source_red_TRC,
  139. LutCurveType source_green_TRC,
  140. LutCurveType source_blue_TRC,
  141. FloatMatrix3x3 matrix,
  142. LutCurveType destination_red_TRC,
  143. LutCurveType destination_green_TRC,
  144. LutCurveType destination_blue_TRC);
  145. Color map(FloatVector3) const;
  146. private:
  147. LutCurveType m_source_red_TRC;
  148. LutCurveType m_source_green_TRC;
  149. LutCurveType m_source_blue_TRC;
  150. FloatMatrix3x3 m_matrix;
  151. LutCurveType m_destination_red_TRC;
  152. LutCurveType m_destination_green_TRC;
  153. LutCurveType m_destination_blue_TRC;
  154. };
  155. inline Color MatrixMatrixConversion::map(FloatVector3 in_rgb) const
  156. {
  157. auto evaluate_curve = [](TagData const& trc, float f) {
  158. if (trc.type() == CurveTagData::Type)
  159. return static_cast<CurveTagData const&>(trc).evaluate(f);
  160. return static_cast<ParametricCurveTagData const&>(trc).evaluate(f);
  161. };
  162. auto evaluate_curve_inverse = [](TagData const& trc, float f) {
  163. if (trc.type() == CurveTagData::Type)
  164. return static_cast<CurveTagData const&>(trc).evaluate_inverse(f);
  165. return static_cast<ParametricCurveTagData const&>(trc).evaluate_inverse(f);
  166. };
  167. FloatVector3 linear_rgb = {
  168. evaluate_curve(m_source_red_TRC, in_rgb[0]),
  169. evaluate_curve(m_source_green_TRC, in_rgb[1]),
  170. evaluate_curve(m_source_blue_TRC, in_rgb[2]),
  171. };
  172. linear_rgb = m_matrix * linear_rgb;
  173. linear_rgb.clamp(0.f, 1.f);
  174. float device_r = evaluate_curve_inverse(m_destination_red_TRC, linear_rgb[0]);
  175. float device_g = evaluate_curve_inverse(m_destination_green_TRC, linear_rgb[1]);
  176. float device_b = evaluate_curve_inverse(m_destination_blue_TRC, linear_rgb[2]);
  177. u8 out_r = round(255 * device_r);
  178. u8 out_g = round(255 * device_g);
  179. u8 out_b = round(255 * device_b);
  180. return Color(out_r, out_g, out_b);
  181. }
  182. class Profile : public RefCounted<Profile> {
  183. public:
  184. static ErrorOr<NonnullRefPtr<Profile>> try_load_from_externally_owned_memory(ReadonlyBytes);
  185. static ErrorOr<NonnullRefPtr<Profile>> create(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table);
  186. Optional<PreferredCMMType> preferred_cmm_type() const { return m_header.preferred_cmm_type; }
  187. Version version() const { return m_header.version; }
  188. DeviceClass device_class() const { return m_header.device_class; }
  189. ColorSpace data_color_space() const { return m_header.data_color_space; }
  190. // For non-DeviceLink profiles, always PCSXYZ or PCSLAB.
  191. ColorSpace connection_space() const { return m_header.connection_space; }
  192. u32 on_disk_size() const { return m_header.on_disk_size; }
  193. DateTime creation_timestamp() const { return m_header.creation_timestamp; }
  194. Optional<PrimaryPlatform> primary_platform() const { return m_header.primary_platform; }
  195. Flags flags() const { return m_header.flags; }
  196. Optional<DeviceManufacturer> device_manufacturer() const { return m_header.device_manufacturer; }
  197. Optional<DeviceModel> device_model() const { return m_header.device_model; }
  198. DeviceAttributes device_attributes() const { return m_header.device_attributes; }
  199. RenderingIntent rendering_intent() const { return m_header.rendering_intent; }
  200. XYZ const& pcs_illuminant() const { return m_header.pcs_illuminant; }
  201. Optional<Creator> creator() const { return m_header.creator; }
  202. Optional<Crypto::Hash::MD5::DigestType> const& id() const { return m_header.id; }
  203. static Crypto::Hash::MD5::DigestType compute_id(ReadonlyBytes);
  204. template<typename Callback>
  205. void for_each_tag(Callback callback) const
  206. {
  207. for (auto const& tag : m_tag_table)
  208. callback(tag.key, tag.value);
  209. }
  210. template<FallibleFunction<TagSignature, NonnullRefPtr<TagData>> Callback>
  211. ErrorOr<void> try_for_each_tag(Callback&& callback) const
  212. {
  213. for (auto const& tag : m_tag_table)
  214. TRY(callback(tag.key, tag.value));
  215. return {};
  216. }
  217. Optional<TagData const&> tag_data(TagSignature signature) const
  218. {
  219. return m_tag_table.get(signature).map([](auto it) -> TagData const& { return *it; });
  220. }
  221. Optional<String> tag_string_data(TagSignature signature) const;
  222. size_t tag_count() const { return m_tag_table.size(); }
  223. // Only versions 2 and 4 are in use.
  224. bool is_v2() const { return version().major_version() == 2; }
  225. bool is_v4() const { return version().major_version() == 4; }
  226. // FIXME: The color conversion stuff should be in some other class.
  227. // Converts an 8-bits-per-channel color to the profile connection space.
  228. // The color's number of channels must match number_of_components_in_color_space(data_color_space()).
  229. // Do not call for DeviceLink or NamedColor profiles. (XXX others?)
  230. // Call connection_space() to find out the space the result is in.
  231. ErrorOr<FloatVector3> to_pcs(ReadonlyBytes) const;
  232. // Converts from the profile connection space to an 8-bits-per-channel color.
  233. // The notes on `to_pcs()` apply to this too.
  234. ErrorOr<void> from_pcs(Profile const& source_profile, FloatVector3, Bytes) const;
  235. ErrorOr<CIELAB> to_lab(ReadonlyBytes) const;
  236. ErrorOr<void> convert_image(Bitmap&, Profile const& source_profile) const;
  237. ErrorOr<void> convert_cmyk_image(Bitmap&, CMYKBitmap const&, Profile const& source_profile) const;
  238. // Only call these if you know that this is an RGB matrix-based profile.
  239. XYZ const& red_matrix_column() const;
  240. XYZ const& green_matrix_column() const;
  241. XYZ const& blue_matrix_column() const;
  242. Optional<MatrixMatrixConversion> matrix_matrix_conversion(Profile const& source_profile) const;
  243. private:
  244. Profile(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table)
  245. : m_header(header)
  246. , m_tag_table(move(tag_table))
  247. {
  248. }
  249. XYZ const& xyz_data(TagSignature tag) const
  250. {
  251. auto const& data = *m_tag_table.get(tag).value();
  252. VERIFY(data.type() == XYZTagData::Type);
  253. return static_cast<XYZTagData const&>(data).xyz();
  254. }
  255. ErrorOr<void> check_required_tags();
  256. ErrorOr<void> check_tag_types();
  257. ProfileHeader m_header;
  258. OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> m_tag_table;
  259. // FIXME: The color conversion stuff should be in some other class.
  260. ErrorOr<FloatVector3> to_pcs_a_to_b(TagData const& tag_data, ReadonlyBytes) const;
  261. ErrorOr<void> from_pcs_b_to_a(TagData const& tag_data, FloatVector3 const&, Bytes) const;
  262. ErrorOr<void> convert_image_matrix_matrix(Gfx::Bitmap&, MatrixMatrixConversion const&) const;
  263. // Cached values.
  264. bool m_cached_has_any_a_to_b_tag { false };
  265. bool m_cached_has_a_to_b0_tag { false };
  266. bool m_cached_has_any_b_to_a_tag { false };
  267. bool m_cached_has_b_to_a0_tag { false };
  268. bool m_cached_has_all_rgb_matrix_tags { false };
  269. // Only valid for RGB matrix-based profiles.
  270. ErrorOr<FloatMatrix3x3> xyz_to_rgb_matrix() const;
  271. FloatMatrix3x3 rgb_to_xyz_matrix() const;
  272. mutable Optional<FloatMatrix3x3> m_cached_xyz_to_rgb_matrix;
  273. struct OneElementCLUTCache {
  274. Vector<u8, 4> key;
  275. FloatVector3 value;
  276. };
  277. mutable Optional<OneElementCLUTCache> m_to_pcs_clut_cache;
  278. };
  279. }
  280. template<>
  281. struct AK::Formatter<Gfx::ICC::Version> : Formatter<FormatString> {
  282. ErrorOr<void> format(FormatBuilder& builder, Gfx::ICC::Version const& version)
  283. {
  284. return Formatter<FormatString>::format(builder, "{}.{}.{}"sv, version.major_version(), version.minor_version(), version.bugfix_version());
  285. }
  286. };