BinaryWriter.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. * Copyright (c) 2023, Nico Weber <thakis@chromium.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Utf16View.h>
  7. #include <LibGfx/ICC/BinaryFormat.h>
  8. #include <LibGfx/ICC/BinaryWriter.h>
  9. #include <LibGfx/ICC/Profile.h>
  10. #include <time.h>
  11. #pragma GCC diagnostic ignored "-Warray-bounds"
  12. namespace Gfx::ICC {
  13. static ErrorOr<ByteBuffer> encode_chromaticity(ChromaticityTagData const& tag_data)
  14. {
  15. // ICC v4, 10.2 chromaticityType
  16. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 2 * sizeof(u16) + tag_data.xy_coordinates().size() * 2 * sizeof(u16Fixed16Number)));
  17. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)ChromaticityTagData::Type;
  18. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  19. *bit_cast<BigEndian<u16>*>(bytes.data() + 8) = tag_data.xy_coordinates().size();
  20. *bit_cast<BigEndian<u16>*>(bytes.data() + 10) = (u16)tag_data.phosphor_or_colorant_type();
  21. auto* coordinates = bit_cast<BigEndian<u16Fixed16Number>*>(bytes.data() + 12);
  22. for (size_t i = 0; i < tag_data.xy_coordinates().size(); ++i) {
  23. coordinates[2 * i] = tag_data.xy_coordinates()[i].x.raw();
  24. coordinates[2 * i + 1] = tag_data.xy_coordinates()[i].y.raw();
  25. }
  26. return bytes;
  27. }
  28. static ErrorOr<ByteBuffer> encode_cipc(CicpTagData const& tag_data)
  29. {
  30. // ICC v4, 10.3 cicpType
  31. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 4));
  32. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)CicpTagData::Type;
  33. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  34. bytes.data()[8] = tag_data.color_primaries();
  35. bytes.data()[9] = tag_data.transfer_characteristics();
  36. bytes.data()[10] = tag_data.matrix_coefficients();
  37. bytes.data()[11] = tag_data.video_full_range_flag();
  38. return bytes;
  39. }
  40. static ErrorOr<ByteBuffer> encode_curve(CurveTagData const& tag_data)
  41. {
  42. // ICC v4, 10.6 curveType
  43. auto bytes = TRY(ByteBuffer::create_uninitialized(3 * sizeof(u32) + tag_data.values().size() * sizeof(u16)));
  44. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)CurveTagData::Type;
  45. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  46. *bit_cast<BigEndian<u32>*>(bytes.data() + 8) = tag_data.values().size();
  47. auto* values = bit_cast<BigEndian<u16>*>(bytes.data() + 12);
  48. for (size_t i = 0; i < tag_data.values().size(); ++i)
  49. values[i] = tag_data.values()[i];
  50. return bytes;
  51. }
  52. static ErrorOr<ByteBuffer> encode_multi_localized_unicode(MultiLocalizedUnicodeTagData const& tag_data)
  53. {
  54. // ICC v4, 10.15 multiLocalizedUnicodeType
  55. // "The Unicode strings in storage should be encoded as 16-bit big-endian, UTF-16BE,
  56. // and should not be NULL terminated."
  57. size_t number_of_records = tag_data.records().size();
  58. size_t header_and_record_size = 4 * sizeof(u32) + number_of_records * sizeof(MultiLocalizedUnicodeRawRecord);
  59. size_t number_of_codepoints = 0;
  60. Vector<Utf16Data> utf16_strings;
  61. TRY(utf16_strings.try_ensure_capacity(number_of_records));
  62. for (auto const& record : tag_data.records()) {
  63. TRY(utf16_strings.try_append(TRY(utf8_to_utf16(record.text))));
  64. number_of_codepoints += utf16_strings.last().size();
  65. }
  66. size_t string_table_size = number_of_codepoints * sizeof(u16);
  67. auto bytes = TRY(ByteBuffer::create_uninitialized(header_and_record_size + string_table_size));
  68. auto* header = bit_cast<BigEndian<u32>*>(bytes.data());
  69. header[0] = (u32)MultiLocalizedUnicodeTagData::Type;
  70. header[1] = 0;
  71. header[2] = number_of_records;
  72. header[3] = sizeof(MultiLocalizedUnicodeRawRecord);
  73. size_t offset = header_and_record_size;
  74. auto* records = bit_cast<MultiLocalizedUnicodeRawRecord*>(bytes.data() + 16);
  75. for (size_t i = 0; i < number_of_records; ++i) {
  76. records[i].language_code = tag_data.records()[i].iso_639_1_language_code;
  77. records[i].country_code = tag_data.records()[i].iso_3166_1_country_code;
  78. records[i].string_length_in_bytes = utf16_strings[i].size() * sizeof(u16);
  79. records[i].string_offset_in_bytes = offset;
  80. offset += records[i].string_offset_in_bytes;
  81. }
  82. auto* string_table = bit_cast<BigEndian<u16>*>(bytes.data() + header_and_record_size);
  83. for (auto const& utf16_string : utf16_strings) {
  84. for (size_t i = 0; i < utf16_string.size(); ++i)
  85. string_table[i] = utf16_string[i];
  86. string_table += utf16_string.size();
  87. }
  88. return bytes;
  89. }
  90. static ErrorOr<ByteBuffer> encode_parametric_curve(ParametricCurveTagData const& tag_data)
  91. {
  92. // ICC v4, 10.18 parametricCurveType
  93. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 2 * sizeof(u16) + tag_data.parameter_count() * sizeof(s15Fixed16Number)));
  94. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)ParametricCurveTagData::Type;
  95. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  96. *bit_cast<BigEndian<u16>*>(bytes.data() + 8) = (u16)tag_data.function_type();
  97. *bit_cast<BigEndian<u16>*>(bytes.data() + 10) = 0;
  98. auto* parameters = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 12);
  99. for (size_t i = 0; i < tag_data.parameter_count(); ++i)
  100. parameters[i] = tag_data.parameter(i).raw();
  101. return bytes;
  102. }
  103. static ErrorOr<ByteBuffer> encode_s15_fixed_array(S15Fixed16ArrayTagData const& tag_data)
  104. {
  105. // ICC v4, 10.22 s15Fixed16ArrayType
  106. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.values().size() * sizeof(s15Fixed16Number)));
  107. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)S15Fixed16ArrayTagData::Type;
  108. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  109. auto* values = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 8);
  110. for (size_t i = 0; i < tag_data.values().size(); ++i)
  111. values[i] = tag_data.values()[i].raw();
  112. return bytes;
  113. }
  114. static ErrorOr<ByteBuffer> encode_signature(SignatureTagData const& tag_data)
  115. {
  116. // ICC v4, 10.23 signatureType
  117. auto bytes = TRY(ByteBuffer::create_uninitialized(3 * sizeof(u32)));
  118. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)SignatureTagData::Type;
  119. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  120. *bit_cast<BigEndian<u32>*>(bytes.data() + 8) = tag_data.signature();
  121. return bytes;
  122. }
  123. static ErrorOr<ByteBuffer> encode_text(TextTagData const& tag_data)
  124. {
  125. // ICC v4, 10.24 textType
  126. // "The textType is a simple text structure that contains a 7-bit ASCII text string. The length of the string is obtained
  127. // by subtracting 8 from the element size portion of the tag itself. This string shall be terminated with a 00h byte."
  128. auto text_bytes = tag_data.text().bytes();
  129. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + text_bytes.size() + 1));
  130. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)TextTagData::Type;
  131. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  132. memcpy(bytes.data() + 8, text_bytes.data(), text_bytes.size());
  133. *(bytes.data() + 8 + text_bytes.size()) = '\0';
  134. return bytes;
  135. }
  136. static ErrorOr<ByteBuffer> encode_xyz(XYZTagData const& tag_data)
  137. {
  138. // ICC v4, 10.31 XYZType
  139. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.xyzs().size() * sizeof(XYZNumber)));
  140. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)XYZTagData::Type;
  141. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  142. auto* xyzs = bit_cast<XYZNumber*>(bytes.data() + 8);
  143. for (size_t i = 0; i < tag_data.xyzs().size(); ++i)
  144. xyzs[i] = tag_data.xyzs()[i];
  145. return bytes;
  146. }
  147. static ErrorOr<ByteBuffer> encode_tag_data(TagData const& tag_data)
  148. {
  149. switch (tag_data.type()) {
  150. case ChromaticityTagData::Type:
  151. return encode_chromaticity(static_cast<ChromaticityTagData const&>(tag_data));
  152. case CicpTagData::Type:
  153. return encode_cipc(static_cast<CicpTagData const&>(tag_data));
  154. case CurveTagData::Type:
  155. return encode_curve(static_cast<CurveTagData const&>(tag_data));
  156. case MultiLocalizedUnicodeTagData::Type:
  157. return encode_multi_localized_unicode(static_cast<MultiLocalizedUnicodeTagData const&>(tag_data));
  158. case ParametricCurveTagData::Type:
  159. return encode_parametric_curve(static_cast<ParametricCurveTagData const&>(tag_data));
  160. case S15Fixed16ArrayTagData::Type:
  161. return encode_s15_fixed_array(static_cast<S15Fixed16ArrayTagData const&>(tag_data));
  162. case SignatureTagData::Type:
  163. return encode_signature(static_cast<SignatureTagData const&>(tag_data));
  164. case TextTagData::Type:
  165. return encode_text(static_cast<TextTagData const&>(tag_data));
  166. case XYZTagData::Type:
  167. return encode_xyz(static_cast<XYZTagData const&>(tag_data));
  168. }
  169. return ByteBuffer {};
  170. }
  171. static ErrorOr<Vector<ByteBuffer>> encode_tag_datas(Profile const& profile)
  172. {
  173. Vector<ByteBuffer> tag_data_bytes;
  174. // FIXME: If two tags refer to the same TagData object, write it just once to the output.
  175. TRY(tag_data_bytes.try_resize(profile.tag_count()));
  176. size_t i = 0;
  177. profile.for_each_tag([&](auto, auto tag_data) {
  178. // FIXME: Come up with a way to allow TRY instead of MUST here.
  179. tag_data_bytes[i++] = MUST(encode_tag_data(tag_data));
  180. });
  181. return tag_data_bytes;
  182. }
  183. static ErrorOr<void> encode_tag_table(ByteBuffer& bytes, Profile const& profile, Vector<size_t> const& offsets, Vector<ByteBuffer> const& tag_data_bytes)
  184. {
  185. VERIFY(bytes.size() >= sizeof(ICCHeader) + sizeof(u32) + profile.tag_count() * sizeof(TagTableEntry));
  186. *bit_cast<BigEndian<u32>*>(bytes.data() + sizeof(ICCHeader)) = profile.tag_count();
  187. TagTableEntry* tag_table_entries = bit_cast<TagTableEntry*>(bytes.data() + sizeof(ICCHeader) + sizeof(u32));
  188. int i = 0;
  189. profile.for_each_tag([&](auto tag_signature, auto) {
  190. tag_table_entries[i].tag_signature = tag_signature;
  191. tag_table_entries[i].offset_to_beginning_of_tag_data_element = offsets[i];
  192. tag_table_entries[i].size_of_tag_data_element = tag_data_bytes[i].size();
  193. ++i;
  194. });
  195. return {};
  196. }
  197. static ErrorOr<void> encode_header(ByteBuffer& bytes, Profile const& profile)
  198. {
  199. VERIFY(bytes.size() >= sizeof(ICCHeader));
  200. auto& raw_header = *bit_cast<ICCHeader*>(bytes.data());
  201. raw_header.profile_size = bytes.size();
  202. raw_header.preferred_cmm_type = profile.preferred_cmm_type().value_or(PreferredCMMType { 0 });
  203. raw_header.profile_version_major = profile.version().major_version();
  204. raw_header.profile_version_minor_bugfix = profile.version().minor_and_bugfix_version();
  205. raw_header.profile_version_zero = 0;
  206. raw_header.profile_device_class = profile.device_class();
  207. raw_header.data_color_space = profile.data_color_space();
  208. raw_header.profile_connection_space = profile.connection_space();
  209. time_t profile_timestamp = profile.creation_timestamp();
  210. struct tm tm;
  211. if (!gmtime_r(&profile_timestamp, &tm))
  212. return Error::from_errno(errno);
  213. raw_header.profile_creation_time.year = tm.tm_year + 1900;
  214. raw_header.profile_creation_time.month = tm.tm_mon + 1;
  215. raw_header.profile_creation_time.day = tm.tm_mday;
  216. raw_header.profile_creation_time.hours = tm.tm_hour;
  217. raw_header.profile_creation_time.minutes = tm.tm_min;
  218. raw_header.profile_creation_time.seconds = tm.tm_sec;
  219. raw_header.profile_file_signature = ProfileFileSignature;
  220. raw_header.primary_platform = profile.primary_platform().value_or(PrimaryPlatform { 0 });
  221. raw_header.profile_flags = profile.flags().bits();
  222. raw_header.device_manufacturer = profile.device_manufacturer().value_or(DeviceManufacturer { 0 });
  223. raw_header.device_model = profile.device_model().value_or(DeviceModel { 0 });
  224. raw_header.device_attributes = profile.device_attributes().bits();
  225. raw_header.rendering_intent = profile.rendering_intent();
  226. raw_header.pcs_illuminant = profile.pcs_illuminant();
  227. raw_header.profile_creator = profile.creator().value_or(Creator { 0 });
  228. memset(raw_header.reserved, 0, sizeof(raw_header.reserved));
  229. auto id = Profile::compute_id(bytes);
  230. static_assert(sizeof(id.data) == sizeof(raw_header.profile_id));
  231. memcpy(raw_header.profile_id, id.data, sizeof(id.data));
  232. return {};
  233. }
  234. ErrorOr<ByteBuffer> encode(Profile const& profile)
  235. {
  236. // Valid profiles always have tags. Profile only represents valid profiles.
  237. VERIFY(profile.tag_count() > 0);
  238. Vector<ByteBuffer> tag_data_bytes = TRY(encode_tag_datas(profile));
  239. size_t tag_table_size = sizeof(u32) + profile.tag_count() * sizeof(TagTableEntry);
  240. size_t offset = sizeof(ICCHeader) + tag_table_size;
  241. Vector<size_t> offsets;
  242. for (auto const& bytes : tag_data_bytes) {
  243. TRY(offsets.try_append(offset));
  244. offset += align_up_to(bytes.size(), 4);
  245. }
  246. // Omit padding after last element.
  247. // FIXME: Is that correct?
  248. size_t total_size = offsets.last() + tag_data_bytes.last().size();
  249. // Leave enough room for the profile header and the tag table count.
  250. auto bytes = TRY(ByteBuffer::create_zeroed(total_size));
  251. for (size_t i = 0; i < tag_data_bytes.size(); ++i)
  252. memcpy(bytes.data() + offsets[i], tag_data_bytes[i].data(), tag_data_bytes[i].size());
  253. TRY(encode_tag_table(bytes, profile, offsets, tag_data_bytes));
  254. TRY(encode_header(bytes, profile));
  255. return bytes;
  256. }
  257. }