BinaryWriter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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()) = static_cast<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) = static_cast<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()) = static_cast<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()) = static_cast<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_measurement(MeasurementTagData const& tag_data)
  53. {
  54. // ICC v4, 10.14 measurementType
  55. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(MeasurementHeader)));
  56. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(MeasurementTagData::Type);
  57. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  58. auto& header = *bit_cast<MeasurementHeader*>(bytes.data() + 8);
  59. header.standard_observer = tag_data.standard_observer();
  60. header.tristimulus_value_for_measurement_backing = tag_data.tristimulus_value_for_measurement_backing();
  61. header.measurement_geometry = tag_data.measurement_geometry();
  62. header.measurement_flare = tag_data.measurement_flare().raw();
  63. header.standard_illuminant = tag_data.standard_illuminant();
  64. return bytes;
  65. }
  66. static ErrorOr<ByteBuffer> encode_multi_localized_unicode(MultiLocalizedUnicodeTagData const& tag_data)
  67. {
  68. // ICC v4, 10.15 multiLocalizedUnicodeType
  69. // "The Unicode strings in storage should be encoded as 16-bit big-endian, UTF-16BE,
  70. // and should not be NULL terminated."
  71. size_t number_of_records = tag_data.records().size();
  72. size_t header_and_record_size = 4 * sizeof(u32) + number_of_records * sizeof(MultiLocalizedUnicodeRawRecord);
  73. size_t number_of_codepoints = 0;
  74. Vector<Utf16Data> utf16_strings;
  75. TRY(utf16_strings.try_ensure_capacity(number_of_records));
  76. for (auto const& record : tag_data.records()) {
  77. TRY(utf16_strings.try_append(TRY(utf8_to_utf16(record.text))));
  78. number_of_codepoints += utf16_strings.last().size();
  79. }
  80. size_t string_table_size = number_of_codepoints * sizeof(u16);
  81. auto bytes = TRY(ByteBuffer::create_uninitialized(header_and_record_size + string_table_size));
  82. auto* header = bit_cast<BigEndian<u32>*>(bytes.data());
  83. header[0] = static_cast<u32>(MultiLocalizedUnicodeTagData::Type);
  84. header[1] = 0;
  85. header[2] = number_of_records;
  86. header[3] = sizeof(MultiLocalizedUnicodeRawRecord);
  87. size_t offset = header_and_record_size;
  88. auto* records = bit_cast<MultiLocalizedUnicodeRawRecord*>(bytes.data() + 16);
  89. for (size_t i = 0; i < number_of_records; ++i) {
  90. records[i].language_code = tag_data.records()[i].iso_639_1_language_code;
  91. records[i].country_code = tag_data.records()[i].iso_3166_1_country_code;
  92. records[i].string_length_in_bytes = utf16_strings[i].size() * sizeof(u16);
  93. records[i].string_offset_in_bytes = offset;
  94. offset += records[i].string_length_in_bytes;
  95. }
  96. auto* string_table = bit_cast<BigEndian<u16>*>(bytes.data() + header_and_record_size);
  97. for (auto const& utf16_string : utf16_strings) {
  98. for (size_t i = 0; i < utf16_string.size(); ++i)
  99. string_table[i] = utf16_string[i];
  100. string_table += utf16_string.size();
  101. }
  102. return bytes;
  103. }
  104. static ErrorOr<ByteBuffer> encode_parametric_curve(ParametricCurveTagData const& tag_data)
  105. {
  106. // ICC v4, 10.18 parametricCurveType
  107. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 2 * sizeof(u16) + tag_data.parameter_count() * sizeof(s15Fixed16Number)));
  108. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(ParametricCurveTagData::Type);
  109. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  110. *bit_cast<BigEndian<u16>*>(bytes.data() + 8) = static_cast<u16>(tag_data.function_type());
  111. *bit_cast<BigEndian<u16>*>(bytes.data() + 10) = 0;
  112. auto* parameters = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 12);
  113. for (size_t i = 0; i < tag_data.parameter_count(); ++i)
  114. parameters[i] = tag_data.parameter(i).raw();
  115. return bytes;
  116. }
  117. static ErrorOr<ByteBuffer> encode_s15_fixed_array(S15Fixed16ArrayTagData const& tag_data)
  118. {
  119. // ICC v4, 10.22 s15Fixed16ArrayType
  120. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.values().size() * sizeof(s15Fixed16Number)));
  121. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(S15Fixed16ArrayTagData::Type);
  122. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  123. auto* values = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 8);
  124. for (size_t i = 0; i < tag_data.values().size(); ++i)
  125. values[i] = tag_data.values()[i].raw();
  126. return bytes;
  127. }
  128. static ErrorOr<ByteBuffer> encode_signature(SignatureTagData const& tag_data)
  129. {
  130. // ICC v4, 10.23 signatureType
  131. auto bytes = TRY(ByteBuffer::create_uninitialized(3 * sizeof(u32)));
  132. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(SignatureTagData::Type);
  133. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  134. *bit_cast<BigEndian<u32>*>(bytes.data() + 8) = tag_data.signature();
  135. return bytes;
  136. }
  137. static ErrorOr<ByteBuffer> encode_text_description(TextDescriptionTagData const& tag_data)
  138. {
  139. // ICC v2, 6.5.17 textDescriptionType
  140. // All lengths include room for a trailing nul character.
  141. // See also the many comments in TextDescriptionTagData::from_bytes().
  142. u32 ascii_size = sizeof(u32) + tag_data.ascii_description().bytes().size() + 1;
  143. // FIXME: Include tag_data.unicode_description() if it's set.
  144. u32 unicode_size = 2 * sizeof(u32);
  145. // FIXME: Include tag_data.macintosh_description() if it's set.
  146. u32 macintosh_size = sizeof(u16) + sizeof(u8) + 67;
  147. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + ascii_size + unicode_size + macintosh_size));
  148. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(TextDescriptionTagData::Type);
  149. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  150. // ASCII
  151. *bit_cast<BigEndian<u32>*>(bytes.data() + 8) = tag_data.ascii_description().bytes().size() + 1;
  152. memcpy(bytes.data() + 12, tag_data.ascii_description().bytes().data(), tag_data.ascii_description().bytes().size());
  153. bytes.data()[12 + tag_data.ascii_description().bytes().size()] = '\0';
  154. // Unicode
  155. // "Because the Unicode language code and Unicode count immediately follow the ASCII description,
  156. // their alignment is not correct when the ASCII count is not a multiple of four"
  157. // So we can't use BigEndian<u32> here.
  158. u8* cursor = bytes.data() + 8 + ascii_size;
  159. u32 unicode_language_code = 0; // FIXME: Set to tag_data.unicode_language_code() once this writes unicode data.
  160. cursor[0] = unicode_language_code >> 24;
  161. cursor[1] = (unicode_language_code >> 16) & 0xff;
  162. cursor[2] = (unicode_language_code >> 8) & 0xff;
  163. cursor[3] = unicode_language_code & 0xff;
  164. cursor += 4;
  165. // FIXME: Include tag_data.unicode_description() if it's set.
  166. u32 ucs2_count = 0; // FIXME: If tag_data.unicode_description() is set, set this to its length plus room for one nul character.
  167. cursor[0] = ucs2_count >> 24;
  168. cursor[1] = (ucs2_count >> 16) & 0xff;
  169. cursor[2] = (ucs2_count >> 8) & 0xff;
  170. cursor[3] = ucs2_count & 0xff;
  171. cursor += 4;
  172. // Macintosh scriptcode
  173. u16 scriptcode_code = 0; // MacRoman
  174. cursor[0] = (scriptcode_code >> 8) & 0xff;
  175. cursor[1] = scriptcode_code & 0xff;
  176. cursor += 2;
  177. u8 macintosh_description_length = 0; // FIXME: If tag_data.macintosh_description() is set, set this to tis length plus room for one nul character.
  178. cursor[0] = macintosh_description_length;
  179. cursor += 1;
  180. memset(cursor, 0, 67);
  181. return bytes;
  182. }
  183. static ErrorOr<ByteBuffer> encode_text(TextTagData const& tag_data)
  184. {
  185. // ICC v4, 10.24 textType
  186. // "The textType is a simple text structure that contains a 7-bit ASCII text string. The length of the string is obtained
  187. // by subtracting 8 from the element size portion of the tag itself. This string shall be terminated with a 00h byte."
  188. auto text_bytes = tag_data.text().bytes();
  189. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + text_bytes.size() + 1));
  190. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(TextTagData::Type);
  191. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  192. memcpy(bytes.data() + 8, text_bytes.data(), text_bytes.size());
  193. *(bytes.data() + 8 + text_bytes.size()) = '\0';
  194. return bytes;
  195. }
  196. static ErrorOr<ByteBuffer> encode_viewing_conditions(ViewingConditionsTagData const& tag_data)
  197. {
  198. // ICC v4, 10.30 viewingConditionsType
  199. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(ViewingConditionsHeader)));
  200. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(ViewingConditionsTagData::Type);
  201. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  202. auto& header = *bit_cast<ViewingConditionsHeader*>(bytes.data() + 8);
  203. header.unnormalized_ciexyz_values_for_illuminant = tag_data.unnormalized_ciexyz_values_for_illuminant();
  204. header.unnormalized_ciexyz_values_for_surround = tag_data.unnormalized_ciexyz_values_for_surround();
  205. header.illuminant_type = tag_data.illuminant_type();
  206. return bytes;
  207. }
  208. static ErrorOr<ByteBuffer> encode_xyz(XYZTagData const& tag_data)
  209. {
  210. // ICC v4, 10.31 XYZType
  211. auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.xyzs().size() * sizeof(XYZNumber)));
  212. *bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(XYZTagData::Type);
  213. *bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
  214. auto* xyzs = bit_cast<XYZNumber*>(bytes.data() + 8);
  215. for (size_t i = 0; i < tag_data.xyzs().size(); ++i)
  216. xyzs[i] = tag_data.xyzs()[i];
  217. return bytes;
  218. }
  219. static ErrorOr<ByteBuffer> encode_tag_data(TagData const& tag_data)
  220. {
  221. switch (tag_data.type()) {
  222. case ChromaticityTagData::Type:
  223. return encode_chromaticity(static_cast<ChromaticityTagData const&>(tag_data));
  224. case CicpTagData::Type:
  225. return encode_cipc(static_cast<CicpTagData const&>(tag_data));
  226. case CurveTagData::Type:
  227. return encode_curve(static_cast<CurveTagData const&>(tag_data));
  228. case MeasurementTagData::Type:
  229. return encode_measurement(static_cast<MeasurementTagData const&>(tag_data));
  230. case MultiLocalizedUnicodeTagData::Type:
  231. return encode_multi_localized_unicode(static_cast<MultiLocalizedUnicodeTagData const&>(tag_data));
  232. case ParametricCurveTagData::Type:
  233. return encode_parametric_curve(static_cast<ParametricCurveTagData const&>(tag_data));
  234. case S15Fixed16ArrayTagData::Type:
  235. return encode_s15_fixed_array(static_cast<S15Fixed16ArrayTagData const&>(tag_data));
  236. case SignatureTagData::Type:
  237. return encode_signature(static_cast<SignatureTagData const&>(tag_data));
  238. case TextDescriptionTagData::Type:
  239. return encode_text_description(static_cast<TextDescriptionTagData const&>(tag_data));
  240. case TextTagData::Type:
  241. return encode_text(static_cast<TextTagData const&>(tag_data));
  242. case ViewingConditionsTagData::Type:
  243. return encode_viewing_conditions(static_cast<ViewingConditionsTagData const&>(tag_data));
  244. case XYZTagData::Type:
  245. return encode_xyz(static_cast<XYZTagData const&>(tag_data));
  246. }
  247. // FIXME: If this gets hit, we always write an invalid icc output file.
  248. // Make this return an Optional and don't write tags that have types we can't encode.
  249. // Not ideal, but better than writing invalid outputs.
  250. return ByteBuffer {};
  251. }
  252. static ErrorOr<Vector<ByteBuffer>> encode_tag_datas(Profile const& profile, HashMap<TagData*, size_t>& tag_data_map)
  253. {
  254. Vector<ByteBuffer> tag_data_bytes;
  255. TRY(tag_data_bytes.try_ensure_capacity(profile.tag_count()));
  256. profile.for_each_tag([&](auto, auto tag_data) {
  257. if (tag_data_map.contains(tag_data.ptr()))
  258. return;
  259. // FIXME: Come up with a way to allow TRY instead of MUST here.
  260. tag_data_bytes.append(MUST(encode_tag_data(tag_data)));
  261. MUST(tag_data_map.try_set(tag_data.ptr(), tag_data_bytes.size() - 1));
  262. });
  263. return tag_data_bytes;
  264. }
  265. static ErrorOr<void> encode_tag_table(ByteBuffer& bytes, Profile const& profile, Vector<size_t> const& offsets, Vector<ByteBuffer> const& tag_data_bytes, HashMap<TagData*, size_t> const& tag_data_map)
  266. {
  267. // ICC v4, 7.3 Tag table
  268. // ICC v4, 7.3.1 Overview
  269. VERIFY(bytes.size() >= sizeof(ICCHeader) + sizeof(u32) + profile.tag_count() * sizeof(TagTableEntry));
  270. *bit_cast<BigEndian<u32>*>(bytes.data() + sizeof(ICCHeader)) = profile.tag_count();
  271. TagTableEntry* tag_table_entries = bit_cast<TagTableEntry*>(bytes.data() + sizeof(ICCHeader) + sizeof(u32));
  272. int i = 0;
  273. profile.for_each_tag([&](auto tag_signature, auto tag_data) {
  274. tag_table_entries[i].tag_signature = tag_signature;
  275. auto index = tag_data_map.get(tag_data.ptr()).value();
  276. tag_table_entries[i].offset_to_beginning_of_tag_data_element = offsets[index];
  277. tag_table_entries[i].size_of_tag_data_element = tag_data_bytes[index].size();
  278. ++i;
  279. });
  280. return {};
  281. }
  282. static ErrorOr<void> encode_header(ByteBuffer& bytes, Profile const& profile)
  283. {
  284. VERIFY(bytes.size() >= sizeof(ICCHeader));
  285. auto& raw_header = *bit_cast<ICCHeader*>(bytes.data());
  286. raw_header.profile_size = bytes.size();
  287. raw_header.preferred_cmm_type = profile.preferred_cmm_type().value_or(PreferredCMMType { 0 });
  288. raw_header.profile_version_major = profile.version().major_version();
  289. raw_header.profile_version_minor_bugfix = profile.version().minor_and_bugfix_version();
  290. raw_header.profile_version_zero = 0;
  291. raw_header.profile_device_class = profile.device_class();
  292. raw_header.data_color_space = profile.data_color_space();
  293. raw_header.profile_connection_space = profile.connection_space();
  294. time_t profile_timestamp = profile.creation_timestamp();
  295. struct tm tm;
  296. if (!gmtime_r(&profile_timestamp, &tm))
  297. return Error::from_errno(errno);
  298. raw_header.profile_creation_time.year = tm.tm_year + 1900;
  299. raw_header.profile_creation_time.month = tm.tm_mon + 1;
  300. raw_header.profile_creation_time.day = tm.tm_mday;
  301. raw_header.profile_creation_time.hours = tm.tm_hour;
  302. raw_header.profile_creation_time.minutes = tm.tm_min;
  303. raw_header.profile_creation_time.seconds = tm.tm_sec;
  304. raw_header.profile_file_signature = ProfileFileSignature;
  305. raw_header.primary_platform = profile.primary_platform().value_or(PrimaryPlatform { 0 });
  306. raw_header.profile_flags = profile.flags().bits();
  307. raw_header.device_manufacturer = profile.device_manufacturer().value_or(DeviceManufacturer { 0 });
  308. raw_header.device_model = profile.device_model().value_or(DeviceModel { 0 });
  309. raw_header.device_attributes = profile.device_attributes().bits();
  310. raw_header.rendering_intent = profile.rendering_intent();
  311. raw_header.pcs_illuminant = profile.pcs_illuminant();
  312. raw_header.profile_creator = profile.creator().value_or(Creator { 0 });
  313. memset(raw_header.reserved, 0, sizeof(raw_header.reserved));
  314. auto id = Profile::compute_id(bytes);
  315. static_assert(sizeof(id.data) == sizeof(raw_header.profile_id));
  316. memcpy(raw_header.profile_id, id.data, sizeof(id.data));
  317. return {};
  318. }
  319. ErrorOr<ByteBuffer> encode(Profile const& profile)
  320. {
  321. // Valid profiles always have tags. Profile only represents valid profiles.
  322. VERIFY(profile.tag_count() > 0);
  323. HashMap<TagData*, size_t> tag_data_map;
  324. Vector<ByteBuffer> tag_data_bytes = TRY(encode_tag_datas(profile, tag_data_map));
  325. size_t tag_table_size = sizeof(u32) + profile.tag_count() * sizeof(TagTableEntry);
  326. size_t offset = sizeof(ICCHeader) + tag_table_size;
  327. Vector<size_t> offsets;
  328. for (auto const& bytes : tag_data_bytes) {
  329. TRY(offsets.try_append(offset));
  330. offset += align_up_to(bytes.size(), 4);
  331. }
  332. // Omit padding after last element.
  333. size_t total_size = offsets.last() + tag_data_bytes.last().size();
  334. auto bytes = TRY(ByteBuffer::create_zeroed(total_size));
  335. for (size_t i = 0; i < tag_data_bytes.size(); ++i)
  336. memcpy(bytes.data() + offsets[i], tag_data_bytes[i].data(), tag_data_bytes[i].size());
  337. TRY(encode_tag_table(bytes, profile, offsets, tag_data_bytes, tag_data_map));
  338. TRY(encode_header(bytes, profile));
  339. return bytes;
  340. }
  341. }