BinaryWriter.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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_multi_localized_unicode(MultiLocalizedUnicodeTagData const& tag_data)
  41. {
  42. // ICC v4, 10.15 multiLocalizedUnicodeType
  43. // "The Unicode strings in storage should be encoded as 16-bit big-endian, UTF-16BE,
  44. // and should not be NULL terminated."
  45. size_t number_of_records = tag_data.records().size();
  46. size_t header_and_record_size = 4 * sizeof(u32) + number_of_records * sizeof(MultiLocalizedUnicodeRawRecord);
  47. size_t number_of_codepoints = 0;
  48. Vector<Utf16Data> utf16_strings;
  49. TRY(utf16_strings.try_ensure_capacity(number_of_records));
  50. for (auto const& record : tag_data.records()) {
  51. TRY(utf16_strings.try_append(TRY(utf8_to_utf16(record.text))));
  52. number_of_codepoints += utf16_strings.last().size();
  53. }
  54. size_t string_table_size = number_of_codepoints * sizeof(u16);
  55. auto bytes = TRY(ByteBuffer::create_uninitialized(header_and_record_size + string_table_size));
  56. auto* header = bit_cast<BigEndian<u32>*>(bytes.data());
  57. header[0] = (u32)MultiLocalizedUnicodeTagData::Type;
  58. header[1] = 0;
  59. header[2] = number_of_records;
  60. header[3] = sizeof(MultiLocalizedUnicodeRawRecord);
  61. size_t offset = header_and_record_size;
  62. auto* records = bit_cast<MultiLocalizedUnicodeRawRecord*>(bytes.data() + 16);
  63. for (size_t i = 0; i < number_of_records; ++i) {
  64. records[i].language_code = tag_data.records()[i].iso_639_1_language_code;
  65. records[i].country_code = tag_data.records()[i].iso_3166_1_country_code;
  66. records[i].string_length_in_bytes = utf16_strings[i].size() * sizeof(u16);
  67. records[i].string_offset_in_bytes = offset;
  68. offset += records[i].string_offset_in_bytes;
  69. }
  70. auto* string_table = bit_cast<BigEndian<u16>*>(bytes.data() + header_and_record_size);
  71. for (auto const& utf16_string : utf16_strings) {
  72. for (size_t i = 0; i < utf16_string.size(); ++i)
  73. string_table[i] = utf16_string[i];
  74. string_table += utf16_string.size();
  75. }
  76. return bytes;
  77. }
  78. static ErrorOr<ByteBuffer> encode_parametric_curve(ParametricCurveTagData const& tag_data)
  79. {
  80. // ICC v4, 10.18 parametricCurveType
  81. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 2 * sizeof(u16) + tag_data.parameter_count() * sizeof(s15Fixed16Number)));
  82. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)ParametricCurveTagData::Type;
  83. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  84. *bit_cast<BigEndian<u16>*>(bytes.data() + 8) = (u16)tag_data.function_type();
  85. *bit_cast<BigEndian<u16>*>(bytes.data() + 10) = 0;
  86. auto* parameters = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 12);
  87. for (size_t i = 0; i < tag_data.parameter_count(); ++i)
  88. parameters[i] = tag_data.parameter(i).raw();
  89. return bytes;
  90. }
  91. static ErrorOr<ByteBuffer> encode_s15_fixed_array(S15Fixed16ArrayTagData const& tag_data)
  92. {
  93. // ICC v4, 10.22 s15Fixed16ArrayType
  94. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.values().size() * sizeof(s15Fixed16Number)));
  95. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)S15Fixed16ArrayTagData::Type;
  96. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  97. auto* values = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 8);
  98. for (size_t i = 0; i < tag_data.values().size(); ++i)
  99. values[i] = tag_data.values()[i].raw();
  100. return bytes;
  101. }
  102. static ErrorOr<ByteBuffer> encode_xyz(XYZTagData const& tag_data)
  103. {
  104. // ICC v4, 10.31 XYZType
  105. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.xyzs().size() * sizeof(XYZNumber)));
  106. *bit_cast<BigEndian<u32>*>(bytes.data()) = (u32)XYZTagData::Type;
  107. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  108. auto* xyzs = bit_cast<XYZNumber*>(bytes.data() + 8);
  109. for (size_t i = 0; i < tag_data.xyzs().size(); ++i)
  110. xyzs[i] = tag_data.xyzs()[i];
  111. return bytes;
  112. }
  113. static ErrorOr<ByteBuffer> encode_tag_data(TagData const& tag_data)
  114. {
  115. switch (tag_data.type()) {
  116. case ChromaticityTagData::Type:
  117. return encode_chromaticity(static_cast<ChromaticityTagData const&>(tag_data));
  118. case CicpTagData::Type:
  119. return encode_cipc(static_cast<CicpTagData const&>(tag_data));
  120. case MultiLocalizedUnicodeTagData::Type:
  121. return encode_multi_localized_unicode(static_cast<MultiLocalizedUnicodeTagData const&>(tag_data));
  122. case ParametricCurveTagData::Type:
  123. return encode_parametric_curve(static_cast<ParametricCurveTagData const&>(tag_data));
  124. case S15Fixed16ArrayTagData::Type:
  125. return encode_s15_fixed_array(static_cast<S15Fixed16ArrayTagData const&>(tag_data));
  126. case XYZTagData::Type:
  127. return encode_xyz(static_cast<XYZTagData const&>(tag_data));
  128. }
  129. return ByteBuffer {};
  130. }
  131. static ErrorOr<Vector<ByteBuffer>> encode_tag_datas(Profile const& profile)
  132. {
  133. Vector<ByteBuffer> tag_data_bytes;
  134. // FIXME: If two tags refer to the same TagData object, write it just once to the output.
  135. TRY(tag_data_bytes.try_resize(profile.tag_count()));
  136. size_t i = 0;
  137. profile.for_each_tag([&](auto, auto tag_data) {
  138. // FIXME: Come up with a way to allow TRY instead of MUST here.
  139. tag_data_bytes[i++] = MUST(encode_tag_data(tag_data));
  140. });
  141. return tag_data_bytes;
  142. }
  143. static ErrorOr<void> encode_tag_table(ByteBuffer& bytes, Profile const& profile, Vector<size_t> const& offsets, Vector<ByteBuffer> const& tag_data_bytes)
  144. {
  145. VERIFY(bytes.size() >= sizeof(ICCHeader) + sizeof(u32) + profile.tag_count() * sizeof(TagTableEntry));
  146. *bit_cast<BigEndian<u32>*>(bytes.data() + sizeof(ICCHeader)) = profile.tag_count();
  147. TagTableEntry* tag_table_entries = bit_cast<TagTableEntry*>(bytes.data() + sizeof(ICCHeader) + sizeof(u32));
  148. int i = 0;
  149. profile.for_each_tag([&](auto tag_signature, auto) {
  150. tag_table_entries[i].tag_signature = tag_signature;
  151. tag_table_entries[i].offset_to_beginning_of_tag_data_element = offsets[i];
  152. tag_table_entries[i].size_of_tag_data_element = tag_data_bytes[i].size();
  153. ++i;
  154. });
  155. return {};
  156. }
  157. static ErrorOr<void> encode_header(ByteBuffer& bytes, Profile const& profile)
  158. {
  159. VERIFY(bytes.size() >= sizeof(ICCHeader));
  160. auto& raw_header = *bit_cast<ICCHeader*>(bytes.data());
  161. raw_header.profile_size = bytes.size();
  162. raw_header.preferred_cmm_type = profile.preferred_cmm_type().value_or(PreferredCMMType { 0 });
  163. raw_header.profile_version_major = profile.version().major_version();
  164. raw_header.profile_version_minor_bugfix = profile.version().minor_and_bugfix_version();
  165. raw_header.profile_version_zero = 0;
  166. raw_header.profile_device_class = profile.device_class();
  167. raw_header.data_color_space = profile.data_color_space();
  168. raw_header.profile_connection_space = profile.connection_space();
  169. time_t profile_timestamp = profile.creation_timestamp();
  170. struct tm tm;
  171. if (!gmtime_r(&profile_timestamp, &tm))
  172. return Error::from_errno(errno);
  173. raw_header.profile_creation_time.year = tm.tm_year + 1900;
  174. raw_header.profile_creation_time.month = tm.tm_mon + 1;
  175. raw_header.profile_creation_time.day = tm.tm_mday;
  176. raw_header.profile_creation_time.hours = tm.tm_hour;
  177. raw_header.profile_creation_time.minutes = tm.tm_min;
  178. raw_header.profile_creation_time.seconds = tm.tm_sec;
  179. raw_header.profile_file_signature = ProfileFileSignature;
  180. raw_header.primary_platform = profile.primary_platform().value_or(PrimaryPlatform { 0 });
  181. raw_header.profile_flags = profile.flags().bits();
  182. raw_header.device_manufacturer = profile.device_manufacturer().value_or(DeviceManufacturer { 0 });
  183. raw_header.device_model = profile.device_model().value_or(DeviceModel { 0 });
  184. raw_header.device_attributes = profile.device_attributes().bits();
  185. raw_header.rendering_intent = profile.rendering_intent();
  186. raw_header.pcs_illuminant = profile.pcs_illuminant();
  187. raw_header.profile_creator = profile.creator().value_or(Creator { 0 });
  188. memset(raw_header.reserved, 0, sizeof(raw_header.reserved));
  189. auto id = Profile::compute_id(bytes);
  190. static_assert(sizeof(id.data) == sizeof(raw_header.profile_id));
  191. memcpy(raw_header.profile_id, id.data, sizeof(id.data));
  192. return {};
  193. }
  194. ErrorOr<ByteBuffer> encode(Profile const& profile)
  195. {
  196. // Valid profiles always have tags. Profile only represents valid profiles.
  197. VERIFY(profile.tag_count() > 0);
  198. Vector<ByteBuffer> tag_data_bytes = TRY(encode_tag_datas(profile));
  199. size_t tag_table_size = sizeof(u32) + profile.tag_count() * sizeof(TagTableEntry);
  200. size_t offset = sizeof(ICCHeader) + tag_table_size;
  201. Vector<size_t> offsets;
  202. for (auto const& bytes : tag_data_bytes) {
  203. TRY(offsets.try_append(offset));
  204. offset += align_up_to(bytes.size(), 4);
  205. }
  206. // Omit padding after last element.
  207. // FIXME: Is that correct?
  208. size_t total_size = offsets.last() + tag_data_bytes.last().size();
  209. // Leave enough room for the profile header and the tag table count.
  210. auto bytes = TRY(ByteBuffer::create_zeroed(total_size));
  211. for (size_t i = 0; i < tag_data_bytes.size(); ++i)
  212. memcpy(bytes.data() + offsets[i], tag_data_bytes[i].data(), tag_data_bytes[i].size());
  213. TRY(encode_tag_table(bytes, profile, offsets, tag_data_bytes));
  214. TRY(encode_header(bytes, profile));
  215. return bytes;
  216. }
  217. }