Profile.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. struct ProfileHeader {
  104. u32 on_disk_size { 0 };
  105. Optional<PreferredCMMType> preferred_cmm_type;
  106. Version version;
  107. DeviceClass device_class {};
  108. ColorSpace data_color_space {};
  109. ColorSpace connection_space {};
  110. time_t creation_timestamp { 0 };
  111. Optional<PrimaryPlatform> primary_platform {};
  112. Flags flags;
  113. Optional<DeviceManufacturer> device_manufacturer;
  114. Optional<DeviceModel> device_model;
  115. DeviceAttributes device_attributes;
  116. RenderingIntent rendering_intent {};
  117. XYZ pcs_illuminant;
  118. Optional<Creator> creator;
  119. Optional<Crypto::Hash::MD5::DigestType> id;
  120. };
  121. // FIXME: This doesn't belong here.
  122. class MatrixMatrixConversion {
  123. public:
  124. MatrixMatrixConversion(LutCurveType source_red_TRC,
  125. LutCurveType source_green_TRC,
  126. LutCurveType source_blue_TRC,
  127. FloatMatrix3x3 matrix,
  128. LutCurveType destination_red_TRC,
  129. LutCurveType destination_green_TRC,
  130. LutCurveType destination_blue_TRC);
  131. Color map(FloatVector3) const;
  132. private:
  133. LutCurveType m_source_red_TRC;
  134. LutCurveType m_source_green_TRC;
  135. LutCurveType m_source_blue_TRC;
  136. FloatMatrix3x3 m_matrix;
  137. LutCurveType m_destination_red_TRC;
  138. LutCurveType m_destination_green_TRC;
  139. LutCurveType m_destination_blue_TRC;
  140. };
  141. inline Color MatrixMatrixConversion::map(FloatVector3 in_rgb) const
  142. {
  143. auto evaluate_curve = [](TagData const& trc, float f) {
  144. if (trc.type() == CurveTagData::Type)
  145. return static_cast<CurveTagData const&>(trc).evaluate(f);
  146. return static_cast<ParametricCurveTagData const&>(trc).evaluate(f);
  147. };
  148. auto evaluate_curve_inverse = [](TagData const& trc, float f) {
  149. if (trc.type() == CurveTagData::Type)
  150. return static_cast<CurveTagData const&>(trc).evaluate_inverse(f);
  151. return static_cast<ParametricCurveTagData const&>(trc).evaluate_inverse(f);
  152. };
  153. FloatVector3 linear_rgb = {
  154. evaluate_curve(m_source_red_TRC, in_rgb[0]),
  155. evaluate_curve(m_source_green_TRC, in_rgb[1]),
  156. evaluate_curve(m_source_blue_TRC, in_rgb[2]),
  157. };
  158. linear_rgb = m_matrix * linear_rgb;
  159. linear_rgb.clamp(0.f, 1.f);
  160. float device_r = evaluate_curve_inverse(m_destination_red_TRC, linear_rgb[0]);
  161. float device_g = evaluate_curve_inverse(m_destination_green_TRC, linear_rgb[1]);
  162. float device_b = evaluate_curve_inverse(m_destination_blue_TRC, linear_rgb[2]);
  163. u8 out_r = round(255 * device_r);
  164. u8 out_g = round(255 * device_g);
  165. u8 out_b = round(255 * device_b);
  166. return Color(out_r, out_g, out_b);
  167. }
  168. class Profile : public RefCounted<Profile> {
  169. public:
  170. static ErrorOr<NonnullRefPtr<Profile>> try_load_from_externally_owned_memory(ReadonlyBytes);
  171. static ErrorOr<NonnullRefPtr<Profile>> create(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table);
  172. Optional<PreferredCMMType> preferred_cmm_type() const { return m_header.preferred_cmm_type; }
  173. Version version() const { return m_header.version; }
  174. DeviceClass device_class() const { return m_header.device_class; }
  175. ColorSpace data_color_space() const { return m_header.data_color_space; }
  176. // For non-DeviceLink profiles, always PCSXYZ or PCSLAB.
  177. ColorSpace connection_space() const { return m_header.connection_space; }
  178. u32 on_disk_size() const { return m_header.on_disk_size; }
  179. time_t creation_timestamp() const { return m_header.creation_timestamp; }
  180. Optional<PrimaryPlatform> primary_platform() const { return m_header.primary_platform; }
  181. Flags flags() const { return m_header.flags; }
  182. Optional<DeviceManufacturer> device_manufacturer() const { return m_header.device_manufacturer; }
  183. Optional<DeviceModel> device_model() const { return m_header.device_model; }
  184. DeviceAttributes device_attributes() const { return m_header.device_attributes; }
  185. RenderingIntent rendering_intent() const { return m_header.rendering_intent; }
  186. XYZ const& pcs_illuminant() const { return m_header.pcs_illuminant; }
  187. Optional<Creator> creator() const { return m_header.creator; }
  188. Optional<Crypto::Hash::MD5::DigestType> const& id() const { return m_header.id; }
  189. static Crypto::Hash::MD5::DigestType compute_id(ReadonlyBytes);
  190. template<typename Callback>
  191. void for_each_tag(Callback callback) const
  192. {
  193. for (auto const& tag : m_tag_table)
  194. callback(tag.key, tag.value);
  195. }
  196. template<FallibleFunction<TagSignature, NonnullRefPtr<TagData>> Callback>
  197. ErrorOr<void> try_for_each_tag(Callback&& callback) const
  198. {
  199. for (auto const& tag : m_tag_table)
  200. TRY(callback(tag.key, tag.value));
  201. return {};
  202. }
  203. Optional<TagData const&> tag_data(TagSignature signature) const
  204. {
  205. return m_tag_table.get(signature).map([](auto it) -> TagData const& { return *it; });
  206. }
  207. Optional<String> tag_string_data(TagSignature signature) const;
  208. size_t tag_count() const { return m_tag_table.size(); }
  209. // Only versions 2 and 4 are in use.
  210. bool is_v2() const { return version().major_version() == 2; }
  211. bool is_v4() const { return version().major_version() == 4; }
  212. // FIXME: The color conversion stuff should be in some other class.
  213. // Converts an 8-bits-per-channel color to the profile connection space.
  214. // The color's number of channels must match number_of_components_in_color_space(data_color_space()).
  215. // Do not call for DeviceLink or NamedColor profiles. (XXX others?)
  216. // Call connection_space() to find out the space the result is in.
  217. ErrorOr<FloatVector3> to_pcs(ReadonlyBytes) const;
  218. // Converts from the profile connection space to an 8-bits-per-channel color.
  219. // The notes on `to_pcs()` apply to this too.
  220. ErrorOr<void> from_pcs(Profile const& source_profile, FloatVector3, Bytes) const;
  221. ErrorOr<CIELAB> to_lab(ReadonlyBytes) const;
  222. ErrorOr<void> convert_image(Bitmap&, Profile const& source_profile) const;
  223. ErrorOr<void> convert_cmyk_image(Bitmap&, CMYKBitmap const&, Profile const& source_profile) const;
  224. // Only call these if you know that this is an RGB matrix-based profile.
  225. XYZ const& red_matrix_column() const;
  226. XYZ const& green_matrix_column() const;
  227. XYZ const& blue_matrix_column() const;
  228. Optional<MatrixMatrixConversion> matrix_matrix_conversion(Profile const& source_profile) const;
  229. private:
  230. Profile(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table)
  231. : m_header(header)
  232. , m_tag_table(move(tag_table))
  233. {
  234. }
  235. XYZ const& xyz_data(TagSignature tag) const
  236. {
  237. auto const& data = *m_tag_table.get(tag).value();
  238. VERIFY(data.type() == XYZTagData::Type);
  239. return static_cast<XYZTagData const&>(data).xyz();
  240. }
  241. ErrorOr<void> check_required_tags();
  242. ErrorOr<void> check_tag_types();
  243. ProfileHeader m_header;
  244. OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> m_tag_table;
  245. // FIXME: The color conversion stuff should be in some other class.
  246. ErrorOr<FloatVector3> to_pcs_a_to_b(TagData const& tag_data, ReadonlyBytes) const;
  247. ErrorOr<void> from_pcs_b_to_a(TagData const& tag_data, FloatVector3 const&, Bytes) const;
  248. ErrorOr<void> convert_image_matrix_matrix(Gfx::Bitmap&, MatrixMatrixConversion const&) const;
  249. // Cached values.
  250. bool m_cached_has_any_a_to_b_tag { false };
  251. bool m_cached_has_a_to_b0_tag { false };
  252. bool m_cached_has_any_b_to_a_tag { false };
  253. bool m_cached_has_b_to_a0_tag { false };
  254. bool m_cached_has_all_rgb_matrix_tags { false };
  255. // Only valid for RGB matrix-based profiles.
  256. ErrorOr<FloatMatrix3x3> xyz_to_rgb_matrix() const;
  257. FloatMatrix3x3 rgb_to_xyz_matrix() const;
  258. mutable Optional<FloatMatrix3x3> m_cached_xyz_to_rgb_matrix;
  259. };
  260. }
  261. template<>
  262. struct AK::Formatter<Gfx::ICC::Version> : Formatter<FormatString> {
  263. ErrorOr<void> format(FormatBuilder& builder, Gfx::ICC::Version const& version)
  264. {
  265. return Formatter<FormatString>::format(builder, "{}.{}.{}"sv, version.major_version(), version.minor_version(), version.bugfix_version());
  266. }
  267. };