diff --git a/Libraries/LibGfx/CIELAB.h b/Libraries/LibGfx/CIELAB.h deleted file mode 100644 index 6aa54f7a6761..000000000000 --- a/Libraries/LibGfx/CIELAB.h +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -namespace Gfx { - -// https://en.wikipedia.org/wiki/CIELAB_color_space -struct CIELAB { - float L; // L* - float a; // a* - float b; // b* -}; - -} diff --git a/Libraries/LibGfx/CMakeLists.txt b/Libraries/LibGfx/CMakeLists.txt index c88d0ace897f..d099b079bc7f 100644 --- a/Libraries/LibGfx/CMakeLists.txt +++ b/Libraries/LibGfx/CMakeLists.txt @@ -8,7 +8,6 @@ set(SOURCES CMYKBitmap.cpp Color.cpp ColorSpace.cpp - DeltaE.cpp FontCascadeList.cpp Font/Font.cpp Font/FontData.cpp @@ -21,12 +20,6 @@ set(SOURCES Font/WOFF/Loader.cpp Font/WOFF2/Loader.cpp GradientPainting.cpp - ICC/BinaryWriter.cpp - ICC/Enums.cpp - ICC/Profile.cpp - ICC/Tags.cpp - ICC/TagTypes.cpp - ICC/WellKnownProfiles.cpp ImageFormats/AnimationWriter.cpp ImageFormats/BMPLoader.cpp ImageFormats/BMPWriter.cpp diff --git a/Libraries/LibGfx/DeltaE.cpp b/Libraries/LibGfx/DeltaE.cpp deleted file mode 100644 index e07137215c5a..000000000000 --- a/Libraries/LibGfx/DeltaE.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include - -namespace Gfx { - -float DeltaE(CIELAB const& c1, CIELAB const& c2) -{ - // https://en.wikipedia.org/wiki/Color_difference#CIEDE2000 - // http://zschuessler.github.io/DeltaE/learn/ - // https://www.hajim.rochester.edu/ece/sites/gsharma/ciede2000/ciede2000noteCRNA.pdf - - float delta_L_prime = c2.L - c1.L; - float L_bar = (c1.L + c2.L) / 2; - - float C1 = hypotf(c1.a, c1.b); - float C2 = hypotf(c2.a, c2.b); - float C_bar = (C1 + C2) / 2; - - float G = 0.5f * (1 - sqrtf(powf(C_bar, 7) / (powf(C_bar, 7) + powf(25, 7)))); - float a1_prime = (1 + G) * c1.a; - float a2_prime = (1 + G) * c2.a; - - float C1_prime = hypotf(a1_prime, c1.b); - float C2_prime = hypotf(a2_prime, c2.b); - - float C_prime_bar = (C1_prime + C2_prime) / 2; - float delta_C_prime = C2_prime - C1_prime; - - auto h_prime = [](float b, float a_prime) { - if (b == 0 && a_prime == 0) - return 0.f; - float h_prime = atan2(b, a_prime); - if (h_prime < 0) - h_prime += 2 * static_cast(M_PI); - return AK::to_degrees(h_prime); - }; - float h1_prime = h_prime(c1.b, a1_prime); - float h2_prime = h_prime(c2.b, a2_prime); - - float delta_h_prime; - if (C1_prime == 0 || C2_prime == 0) - delta_h_prime = 0; - else if (fabsf(h1_prime - h2_prime) <= 180.f) - delta_h_prime = h2_prime - h1_prime; - else if (h2_prime <= h1_prime) - delta_h_prime = h2_prime - h1_prime + 360; - else - delta_h_prime = h2_prime - h1_prime - 360; - - auto sin_degrees = [](float x) { return sinf(AK::to_radians(x)); }; - auto cos_degrees = [](float x) { return cosf(AK::to_radians(x)); }; - - float delta_H_prime = 2 * sqrtf(C1_prime * C2_prime) * sin_degrees(delta_h_prime / 2); - - float h_prime_bar; - if (C1_prime == 0 || C2_prime == 0) - h_prime_bar = h1_prime + h2_prime; - else if (fabsf(h1_prime - h2_prime) <= 180.f) - h_prime_bar = (h1_prime + h2_prime) / 2; - else if (h1_prime + h2_prime < 360) - h_prime_bar = (h1_prime + h2_prime + 360) / 2; - else - h_prime_bar = (h1_prime + h2_prime - 360) / 2; - - float T = 1 - 0.17f * cos_degrees(h_prime_bar - 30) + 0.24f * cos_degrees(2 * h_prime_bar) + 0.32f * cos_degrees(3 * h_prime_bar + 6) - 0.2f * cos_degrees(4 * h_prime_bar - 63); - - float S_L = 1 + 0.015f * powf(L_bar - 50, 2) / sqrtf(20 + powf(L_bar - 50, 2)); - float S_C = 1 + 0.045f * C_prime_bar; - float S_H = 1 + 0.015f * C_prime_bar * T; - - float R_T = -2 * sqrtf(powf(C_prime_bar, 7) / (powf(C_prime_bar, 7) + powf(25, 7))) * sin_degrees(60 * exp(-powf((h_prime_bar - 275) / 25, 2))); - - // "kL, kC, and kH are usually unity." - float k_L = 1, k_C = 1, k_H = 1; - - float L = delta_L_prime / (k_L * S_L); - float C = delta_C_prime / (k_C * S_C); - float H = delta_H_prime / (k_H * S_H); - return sqrtf(powf(L, 2) + powf(C, 2) + powf(H, 2) + R_T * C * H); -} - -} diff --git a/Libraries/LibGfx/DeltaE.h b/Libraries/LibGfx/DeltaE.h deleted file mode 100644 index c36e9cdc49eb..000000000000 --- a/Libraries/LibGfx/DeltaE.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include - -namespace Gfx { - -// Returns a number between 0 and 100 that describes how far apart two colors are in human perception. -// A return value < 1 means that the two colors are not noticeably different. -// The larger the return value, the easier it is to tell the two colors apart. -// Works better for colors that are somewhat "close". -// -// You can use ICC::sRGB()->to_lab() to convert sRGB colors to CIELAB. -float DeltaE(CIELAB const&, CIELAB const&); - -} diff --git a/Libraries/LibGfx/ICC/BinaryFormat.h b/Libraries/LibGfx/ICC/BinaryFormat.h deleted file mode 100644 index c15486f06fbb..000000000000 --- a/Libraries/LibGfx/ICC/BinaryFormat.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace Gfx::ICC { - -// ICC V4, 4.2 dateTimeNumber -// "All the dateTimeNumber values in a profile shall be in Coordinated Universal Time [...]." -struct DateTimeNumber { - BigEndian year; - BigEndian month; - BigEndian day; - BigEndian hours; - BigEndian minutes; - BigEndian seconds; -}; - -// ICC V4, 4.6 s15Fixed16Number -using s15Fixed16Number = i32; - -// ICC V4, 4.7 u16Fixed16Number -using u16Fixed16Number = u32; - -// ICC V4, 4.14 XYZNumber -struct XYZNumber { - BigEndian X; - BigEndian Y; - BigEndian Z; - - XYZNumber() = default; - - XYZNumber(XYZ const& xyz) - : X(round(xyz.X * 0x1'0000)) - , Y(round(xyz.Y * 0x1'0000)) - , Z(round(xyz.Z * 0x1'0000)) - { - } - - operator XYZ() const - { - return XYZ { X / (float)0x1'0000, Y / (float)0x1'0000, Z / (float)0x1'0000 }; - } -}; - -// ICC V4, 7.2 Profile header -struct ICCHeader { - BigEndian profile_size; - BigEndian preferred_cmm_type; - - u8 profile_version_major; - u8 profile_version_minor_bugfix; - BigEndian profile_version_zero; - - BigEndian profile_device_class; - BigEndian data_color_space; - BigEndian profile_connection_space; // "PCS" in the spec. - - DateTimeNumber profile_creation_time; - - BigEndian profile_file_signature; - BigEndian primary_platform; - - BigEndian profile_flags; - BigEndian device_manufacturer; - BigEndian device_model; - BigEndian device_attributes; - BigEndian rendering_intent; - - XYZNumber pcs_illuminant; - - BigEndian profile_creator; - - u8 profile_id[16]; - u8 reserved[28]; -}; -static_assert(AssertSize()); - -// ICC v4, 7.2.9 Profile file signature field -// "The profile file signature field shall contain the value “acsp” (61637370h) as a profile file signature." -constexpr u32 ProfileFileSignature = 0x61637370; - -// ICC V4, 7.3 Tag table, Table 24 - Tag table structure -struct TagTableEntry { - BigEndian tag_signature; - BigEndian offset_to_beginning_of_tag_data_element; - BigEndian size_of_tag_data_element; -}; -static_assert(AssertSize()); - -// Common bits of ICC v4, Table 40 — lut16Type encoding and Table 44 — lut8Type encoding -struct LUTHeader { - u8 number_of_input_channels; - u8 number_of_output_channels; - u8 number_of_clut_grid_points; - u8 reserved_for_padding; - BigEndian e_parameters[9]; -}; -static_assert(AssertSize()); - -// Common bits of ICC v4, Table 45 — lutAToBType encoding and Table 47 — lutBToAType encoding -struct AdvancedLUTHeader { - u8 number_of_input_channels; - u8 number_of_output_channels; - BigEndian reserved_for_padding; - BigEndian offset_to_b_curves; - BigEndian offset_to_matrix; - BigEndian offset_to_m_curves; - BigEndian offset_to_clut; - BigEndian offset_to_a_curves; -}; -static_assert(AssertSize()); - -// ICC v4, Table 46 — lutAToBType CLUT encoding -// ICC v4, Table 48 — lutBToAType CLUT encoding -// (They're identical.) -struct CLUTHeader { - u8 number_of_grid_points_in_dimension[16]; - u8 precision_of_data_elements; // 1 for u8 entries, 2 for u16 entries. - u8 reserved_for_padding[3]; -}; -static_assert(AssertSize()); - -// Table 49 — measurementType structure -struct MeasurementHeader { - BigEndian standard_observer; - XYZNumber tristimulus_value_for_measurement_backing; - BigEndian measurement_geometry; - BigEndian measurement_flare; - BigEndian standard_illuminant; -}; -static_assert(AssertSize()); - -// ICC v4, 10.15 multiLocalizedUnicodeType -struct MultiLocalizedUnicodeRawRecord { - BigEndian language_code; - BigEndian country_code; - BigEndian string_length_in_bytes; - BigEndian string_offset_in_bytes; -}; -static_assert(AssertSize()); - -// Table 66 — namedColor2Type encoding -struct NamedColorHeader { - BigEndian vendor_specific_flag; - BigEndian count_of_named_colors; - BigEndian number_of_device_coordinates_of_each_named_color; - u8 prefix_for_each_color_name[32]; // null-terminated - u8 suffix_for_each_color_name[32]; // null-terminated -}; -static_assert(AssertSize()); - -// Table 84 — viewingConditionsType encoding -struct ViewingConditionsHeader { - XYZNumber unnormalized_ciexyz_values_for_illuminant; // "(in which Y is in cd/m2)" - XYZNumber unnormalized_ciexyz_values_for_surround; // "(in which Y is in cd/m2)" - BigEndian illuminant_type; -}; -static_assert(AssertSize()); - -} diff --git a/Libraries/LibGfx/ICC/BinaryWriter.cpp b/Libraries/LibGfx/ICC/BinaryWriter.cpp deleted file mode 100644 index 3912c3bc674a..000000000000 --- a/Libraries/LibGfx/ICC/BinaryWriter.cpp +++ /dev/null @@ -1,748 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include - -#pragma GCC diagnostic ignored "-Warray-bounds" - -namespace Gfx::ICC { - -static ErrorOr encode_chromaticity(ChromaticityTagData const& tag_data) -{ - // ICC v4, 10.2 chromaticityType - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 2 * sizeof(u16) + tag_data.xy_coordinates().size() * 2 * sizeof(u16Fixed16Number))); - - *bit_cast*>(bytes.data()) = static_cast(ChromaticityTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - *bit_cast*>(bytes.data() + 8) = tag_data.xy_coordinates().size(); - *bit_cast*>(bytes.data() + 10) = static_cast(tag_data.phosphor_or_colorant_type()); - - auto* coordinates = bit_cast*>(bytes.data() + 12); - for (size_t i = 0; i < tag_data.xy_coordinates().size(); ++i) { - coordinates[2 * i] = tag_data.xy_coordinates()[i].x.raw(); - coordinates[2 * i + 1] = tag_data.xy_coordinates()[i].y.raw(); - } - - return bytes; -} - -static ErrorOr encode_cipc(CicpTagData const& tag_data) -{ - // ICC v4, 10.3 cicpType - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 4)); - *bit_cast*>(bytes.data()) = static_cast(CicpTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - bytes.data()[8] = tag_data.color_primaries(); - bytes.data()[9] = tag_data.transfer_characteristics(); - bytes.data()[10] = tag_data.matrix_coefficients(); - bytes.data()[11] = tag_data.video_full_range_flag(); - return bytes; -} - -static u32 curve_encoded_size(CurveTagData const& tag_data) -{ - return 3 * sizeof(u32) + tag_data.values().size() * sizeof(u16); -} - -static void encode_curve_to(CurveTagData const& tag_data, Bytes bytes) -{ - *bit_cast*>(bytes.data()) = static_cast(CurveTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - *bit_cast*>(bytes.data() + 8) = tag_data.values().size(); - - auto* values = bit_cast*>(bytes.data() + 12); - for (size_t i = 0; i < tag_data.values().size(); ++i) - values[i] = tag_data.values()[i]; -} - -static ErrorOr encode_curve(CurveTagData const& tag_data) -{ - // ICC v4, 10.6 curveType - auto bytes = TRY(ByteBuffer::create_uninitialized(curve_encoded_size(tag_data))); - encode_curve_to(tag_data, bytes.bytes()); - return bytes; -} - -static ErrorOr encode_lut_16(Lut16TagData const& tag_data) -{ - // ICC v4, 10.10 lut16Type - u32 input_tables_size = tag_data.input_tables().size(); - u32 clut_values_size = tag_data.clut_values().size(); - u32 output_tables_size = tag_data.output_tables().size(); - - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(LUTHeader) + 2 * sizeof(u16) + sizeof(u16) * (input_tables_size + clut_values_size + output_tables_size))); - *bit_cast*>(bytes.data()) = static_cast(Lut16TagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.number_of_input_channels = tag_data.number_of_input_channels(); - header.number_of_output_channels = tag_data.number_of_output_channels(); - header.number_of_clut_grid_points = tag_data.number_of_clut_grid_points(); - header.reserved_for_padding = 0; - for (int i = 0; i < 9; ++i) - header.e_parameters[i] = tag_data.e_matrix().e[i].raw(); - - *bit_cast*>(bytes.data() + 8 + sizeof(LUTHeader)) = tag_data.number_of_input_table_entries(); - *bit_cast*>(bytes.data() + 8 + sizeof(LUTHeader) + 2) = tag_data.number_of_output_table_entries(); - - auto* values = bit_cast*>(bytes.data() + 8 + sizeof(LUTHeader) + 4); - for (u16 input_value : tag_data.input_tables()) - *values++ = input_value; - - for (u16 clut_value : tag_data.clut_values()) - *values++ = clut_value; - - for (u16 output_value : tag_data.output_tables()) - *values++ = output_value; - - return bytes; -} - -static ErrorOr encode_lut_8(Lut8TagData const& tag_data) -{ - // ICC v4, 10.11 lut8Type - u32 input_tables_size = tag_data.input_tables().size(); - u32 clut_values_size = tag_data.clut_values().size(); - u32 output_tables_size = tag_data.output_tables().size(); - - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(LUTHeader) + input_tables_size + clut_values_size + output_tables_size)); - *bit_cast*>(bytes.data()) = static_cast(Lut8TagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.number_of_input_channels = tag_data.number_of_input_channels(); - header.number_of_output_channels = tag_data.number_of_output_channels(); - header.number_of_clut_grid_points = tag_data.number_of_clut_grid_points(); - header.reserved_for_padding = 0; - for (int i = 0; i < 9; ++i) - header.e_parameters[i] = tag_data.e_matrix().e[i].raw(); - - u8* values = bytes.data() + 8 + sizeof(LUTHeader); - memcpy(values, tag_data.input_tables().data(), input_tables_size); - values += input_tables_size; - - memcpy(values, tag_data.clut_values().data(), clut_values_size); - values += clut_values_size; - - memcpy(values, tag_data.output_tables().data(), output_tables_size); - - return bytes; -} - -static u32 curve_encoded_size(CurveTagData const&); -static void encode_curve_to(CurveTagData const&, Bytes); -static u32 parametric_curve_encoded_size(ParametricCurveTagData const&); -static void encode_parametric_curve_to(ParametricCurveTagData const&, Bytes); - -static u32 byte_size_of_curve(LutCurveType const& curve) -{ - VERIFY(curve->type() == Gfx::ICC::CurveTagData::Type || curve->type() == Gfx::ICC::ParametricCurveTagData::Type); - if (curve->type() == Gfx::ICC::CurveTagData::Type) - return curve_encoded_size(static_cast(*curve)); - return parametric_curve_encoded_size(static_cast(*curve)); -} - -static u32 byte_size_of_curves(Vector const& curves) -{ - u32 size = 0; - for (auto const& curve : curves) - size += align_up_to(byte_size_of_curve(curve), 4); - return size; -} - -static void write_curve(Bytes bytes, LutCurveType const& curve) -{ - VERIFY(curve->type() == Gfx::ICC::CurveTagData::Type || curve->type() == Gfx::ICC::ParametricCurveTagData::Type); - if (curve->type() == Gfx::ICC::CurveTagData::Type) - encode_curve_to(static_cast(*curve), bytes); - if (curve->type() == Gfx::ICC::ParametricCurveTagData::Type) - encode_parametric_curve_to(static_cast(*curve), bytes); -} - -static void write_curves(Bytes bytes, Vector const& curves) -{ - u32 offset = 0; - for (auto const& curve : curves) { - u32 size = byte_size_of_curve(curve); - write_curve(bytes.slice(offset, size), curve); - offset += align_up_to(size, 4); - } -} - -static u32 byte_size_of_clut(CLUTData const& clut) -{ - u32 data_size = clut.values.visit( - [](Vector const& v) { return v.size(); }, - [](Vector const& v) { return 2 * v.size(); }); - return align_up_to(sizeof(CLUTHeader) + data_size, 4); -} - -static void write_clut(Bytes bytes, CLUTData const& clut) -{ - auto& clut_header = *bit_cast(bytes.data()); - memset(clut_header.number_of_grid_points_in_dimension, 0, sizeof(clut_header.number_of_grid_points_in_dimension)); - VERIFY(clut.number_of_grid_points_in_dimension.size() <= sizeof(clut_header.number_of_grid_points_in_dimension)); - for (size_t i = 0; i < clut.number_of_grid_points_in_dimension.size(); ++i) - clut_header.number_of_grid_points_in_dimension[i] = clut.number_of_grid_points_in_dimension[i]; - - clut_header.precision_of_data_elements = clut.values.visit( - [](Vector const&) { return 1; }, - [](Vector const&) { return 2; }); - - memset(clut_header.reserved_for_padding, 0, sizeof(clut_header.reserved_for_padding)); - - clut.values.visit( - [&bytes](Vector const& v) { - memcpy(bytes.data() + sizeof(CLUTHeader), v.data(), v.size()); - }, - [&bytes](Vector const& v) { - auto* raw_clut = bit_cast*>(bytes.data() + sizeof(CLUTHeader)); - for (size_t i = 0; i < v.size(); ++i) - raw_clut[i] = v[i]; - }); -} - -static void write_matrix(Bytes bytes, EMatrix3x4 const& e_matrix) -{ - auto* raw_e = bit_cast*>(bytes.data()); - for (int i = 0; i < 12; ++i) - raw_e[i] = e_matrix.e[i].raw(); -} - -static ErrorOr encode_lut_a_to_b(LutAToBTagData const& tag_data) -{ - // ICC v4, 10.12 lutAToBType - u32 a_curves_size = tag_data.a_curves().map(byte_size_of_curves).value_or(0); - u32 clut_size = tag_data.clut().map(byte_size_of_clut).value_or(0); - u32 m_curves_size = tag_data.m_curves().map(byte_size_of_curves).value_or(0); - u32 e_matrix_size = tag_data.e_matrix().has_value() ? 12 * sizeof(s15Fixed16Number) : 0; - u32 b_curves_size = byte_size_of_curves(tag_data.b_curves()); - - auto bytes = TRY(ByteBuffer::create_zeroed(2 * sizeof(u32) + sizeof(AdvancedLUTHeader) + a_curves_size + clut_size + m_curves_size + e_matrix_size + b_curves_size)); - *bit_cast*>(bytes.data()) = static_cast(LutAToBTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.number_of_input_channels = tag_data.number_of_input_channels(); - header.number_of_output_channels = tag_data.number_of_output_channels(); - header.reserved_for_padding = 0; - header.offset_to_b_curves = 0; - header.offset_to_matrix = 0; - header.offset_to_m_curves = 0; - header.offset_to_clut = 0; - header.offset_to_a_curves = 0; - - u32 offset = 2 * sizeof(u32) + sizeof(AdvancedLUTHeader); - auto advance = [&offset](BigEndian& header_slot, u32 size) { - header_slot = offset; - VERIFY(size % 4 == 0); - offset += size; - }; - - if (auto const& a_curves = tag_data.a_curves(); a_curves.has_value()) { - write_curves(bytes.bytes().slice(offset, a_curves_size), a_curves.value()); - advance(header.offset_to_a_curves, a_curves_size); - } - if (auto const& clut = tag_data.clut(); clut.has_value()) { - write_clut(bytes.bytes().slice(offset, clut_size), clut.value()); - advance(header.offset_to_clut, clut_size); - } - if (auto const& m_curves = tag_data.m_curves(); m_curves.has_value()) { - write_curves(bytes.bytes().slice(offset, m_curves_size), m_curves.value()); - advance(header.offset_to_m_curves, m_curves_size); - } - if (auto const& e_matrix = tag_data.e_matrix(); e_matrix.has_value()) { - write_matrix(bytes.bytes().slice(offset, e_matrix_size), e_matrix.value()); - advance(header.offset_to_matrix, e_matrix_size); - } - write_curves(bytes.bytes().slice(offset, b_curves_size), tag_data.b_curves()); - advance(header.offset_to_b_curves, b_curves_size); - - return bytes; -} - -static ErrorOr encode_lut_b_to_a(LutBToATagData const& tag_data) -{ - // ICC v4, 10.13 lutBToAType - u32 b_curves_size = byte_size_of_curves(tag_data.b_curves()); - u32 e_matrix_size = tag_data.e_matrix().has_value() ? 12 * sizeof(s15Fixed16Number) : 0; - u32 m_curves_size = tag_data.m_curves().map(byte_size_of_curves).value_or(0); - u32 clut_size = tag_data.clut().map(byte_size_of_clut).value_or(0); - u32 a_curves_size = tag_data.a_curves().map(byte_size_of_curves).value_or(0); - - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(AdvancedLUTHeader) + b_curves_size + e_matrix_size + m_curves_size + clut_size + a_curves_size)); - *bit_cast*>(bytes.data()) = static_cast(LutBToATagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.number_of_input_channels = tag_data.number_of_input_channels(); - header.number_of_output_channels = tag_data.number_of_output_channels(); - header.reserved_for_padding = 0; - header.offset_to_b_curves = 0; - header.offset_to_matrix = 0; - header.offset_to_m_curves = 0; - header.offset_to_clut = 0; - header.offset_to_a_curves = 0; - - u32 offset = 2 * sizeof(u32) + sizeof(AdvancedLUTHeader); - auto advance = [&offset](BigEndian& header_slot, u32 size) { - header_slot = offset; - VERIFY(size % 4 == 0); - offset += size; - }; - - write_curves(bytes.bytes().slice(offset, b_curves_size), tag_data.b_curves()); - advance(header.offset_to_b_curves, b_curves_size); - if (auto const& e_matrix = tag_data.e_matrix(); e_matrix.has_value()) { - write_matrix(bytes.bytes().slice(offset, e_matrix_size), e_matrix.value()); - advance(header.offset_to_matrix, e_matrix_size); - } - if (auto const& m_curves = tag_data.m_curves(); m_curves.has_value()) { - write_curves(bytes.bytes().slice(offset, m_curves_size), m_curves.value()); - advance(header.offset_to_m_curves, m_curves_size); - } - if (auto const& clut = tag_data.clut(); clut.has_value()) { - write_clut(bytes.bytes().slice(offset, clut_size), clut.value()); - advance(header.offset_to_clut, clut_size); - } - if (auto const& a_curves = tag_data.a_curves(); a_curves.has_value()) { - write_curves(bytes.bytes().slice(offset, a_curves_size), a_curves.value()); - advance(header.offset_to_a_curves, a_curves_size); - } - - return bytes; -} - -static ErrorOr encode_measurement(MeasurementTagData const& tag_data) -{ - // ICC v4, 10.14 measurementType - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(MeasurementHeader))); - *bit_cast*>(bytes.data()) = static_cast(MeasurementTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.standard_observer = tag_data.standard_observer(); - header.tristimulus_value_for_measurement_backing = tag_data.tristimulus_value_for_measurement_backing(); - header.measurement_geometry = tag_data.measurement_geometry(); - header.measurement_flare = tag_data.measurement_flare().raw(); - header.standard_illuminant = tag_data.standard_illuminant(); - - return bytes; -} - -static ErrorOr encode_multi_localized_unicode(MultiLocalizedUnicodeTagData const& tag_data) -{ - // ICC v4, 10.15 multiLocalizedUnicodeType - // "The Unicode strings in storage should be encoded as 16-bit big-endian, UTF-16BE, - // and should not be NULL terminated." - size_t number_of_records = tag_data.records().size(); - size_t header_and_record_size = 4 * sizeof(u32) + number_of_records * sizeof(MultiLocalizedUnicodeRawRecord); - - size_t number_of_codepoints = 0; - Vector utf16_strings; - TRY(utf16_strings.try_ensure_capacity(number_of_records)); - for (auto const& record : tag_data.records()) { - TRY(utf16_strings.try_append(TRY(utf8_to_utf16(record.text)))); - number_of_codepoints += utf16_strings.last().size(); - } - - size_t string_table_size = number_of_codepoints * sizeof(u16); - - auto bytes = TRY(ByteBuffer::create_uninitialized(header_and_record_size + string_table_size)); - - auto* header = bit_cast*>(bytes.data()); - header[0] = static_cast(MultiLocalizedUnicodeTagData::Type); - header[1] = 0; - header[2] = number_of_records; - header[3] = sizeof(MultiLocalizedUnicodeRawRecord); - - size_t offset = header_and_record_size; - auto* records = bit_cast(bytes.data() + 16); - for (size_t i = 0; i < number_of_records; ++i) { - records[i].language_code = tag_data.records()[i].iso_639_1_language_code; - records[i].country_code = tag_data.records()[i].iso_3166_1_country_code; - records[i].string_length_in_bytes = utf16_strings[i].size() * sizeof(u16); - records[i].string_offset_in_bytes = offset; - offset += records[i].string_length_in_bytes; - } - - auto* string_table = bit_cast*>(bytes.data() + header_and_record_size); - for (auto const& utf16_string : utf16_strings) { - for (size_t i = 0; i < utf16_string.size(); ++i) - string_table[i] = utf16_string[i]; - string_table += utf16_string.size(); - } - - return bytes; -} - -static ErrorOr encode_named_color_2(NamedColor2TagData const& tag_data) -{ - // ICC v4, 10.17 namedColor2Type - unsigned const record_byte_size = 32 + sizeof(u16) * (3 + tag_data.number_of_device_coordinates()); - - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(NamedColorHeader) + tag_data.size() * record_byte_size)); - *bit_cast*>(bytes.data()) = (u32)NamedColor2TagData::Type; - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.vendor_specific_flag = tag_data.vendor_specific_flag(); - header.count_of_named_colors = tag_data.size(); - header.number_of_device_coordinates_of_each_named_color = tag_data.number_of_device_coordinates(); - memset(header.prefix_for_each_color_name, 0, 32); - memcpy(header.prefix_for_each_color_name, tag_data.prefix().bytes().data(), tag_data.prefix().bytes().size()); - memset(header.suffix_for_each_color_name, 0, 32); - memcpy(header.suffix_for_each_color_name, tag_data.suffix().bytes().data(), tag_data.suffix().bytes().size()); - - u8* record = bytes.data() + 8 + sizeof(NamedColorHeader); - for (size_t i = 0; i < tag_data.size(); ++i) { - memset(record, 0, 32); - memcpy(record, tag_data.root_name(i).bytes().data(), tag_data.root_name(i).bytes().size()); - - auto* components = bit_cast*>(record + 32); - components[0] = tag_data.pcs_coordinates(i).xyz.x; - components[1] = tag_data.pcs_coordinates(i).xyz.y; - components[2] = tag_data.pcs_coordinates(i).xyz.z; - for (size_t j = 0; j < tag_data.number_of_device_coordinates(); ++j) - components[3 + j] = tag_data.device_coordinates(i)[j]; - - record += record_byte_size; - } - - return bytes; -} - -static u32 parametric_curve_encoded_size(ParametricCurveTagData const& tag_data) -{ - return 2 * sizeof(u32) + 2 * sizeof(u16) + tag_data.parameter_count() * sizeof(s15Fixed16Number); -} - -static void encode_parametric_curve_to(ParametricCurveTagData const& tag_data, Bytes bytes) -{ - *bit_cast*>(bytes.data()) = static_cast(ParametricCurveTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - *bit_cast*>(bytes.data() + 8) = static_cast(tag_data.function_type()); - *bit_cast*>(bytes.data() + 10) = 0; - - auto* parameters = bit_cast*>(bytes.data() + 12); - for (size_t i = 0; i < tag_data.parameter_count(); ++i) - parameters[i] = tag_data.parameter(i).raw(); -} - -static ErrorOr encode_parametric_curve(ParametricCurveTagData const& tag_data) -{ - // ICC v4, 10.18 parametricCurveType - auto bytes = TRY(ByteBuffer::create_uninitialized(parametric_curve_encoded_size(tag_data))); - encode_parametric_curve_to(tag_data, bytes.bytes()); - return bytes; -} - -static ErrorOr encode_s15_fixed_array(S15Fixed16ArrayTagData const& tag_data) -{ - // ICC v4, 10.22 s15Fixed16ArrayType - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.values().size() * sizeof(s15Fixed16Number))); - *bit_cast*>(bytes.data()) = static_cast(S15Fixed16ArrayTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto* values = bit_cast*>(bytes.data() + 8); - for (size_t i = 0; i < tag_data.values().size(); ++i) - values[i] = tag_data.values()[i].raw(); - - return bytes; -} - -static ErrorOr encode_signature(SignatureTagData const& tag_data) -{ - // ICC v4, 10.23 signatureType - auto bytes = TRY(ByteBuffer::create_uninitialized(3 * sizeof(u32))); - *bit_cast*>(bytes.data()) = static_cast(SignatureTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - *bit_cast*>(bytes.data() + 8) = tag_data.signature(); - return bytes; -} - -static ErrorOr encode_text_description(TextDescriptionTagData const& tag_data) -{ - // ICC v2, 6.5.17 textDescriptionType - // All lengths include room for a trailing nul character. - // See also the many comments in TextDescriptionTagData::from_bytes(). - u32 ascii_size = sizeof(u32) + tag_data.ascii_description().bytes().size() + 1; - - // FIXME: Include tag_data.unicode_description() if it's set. - u32 unicode_size = 2 * sizeof(u32); - - // FIXME: Include tag_data.macintosh_description() if it's set. - u32 macintosh_size = sizeof(u16) + sizeof(u8) + 67; - - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + ascii_size + unicode_size + macintosh_size)); - *bit_cast*>(bytes.data()) = static_cast(TextDescriptionTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - // ASCII - *bit_cast*>(bytes.data() + 8) = tag_data.ascii_description().bytes().size() + 1; - memcpy(bytes.data() + 12, tag_data.ascii_description().bytes().data(), tag_data.ascii_description().bytes().size()); - bytes.data()[12 + tag_data.ascii_description().bytes().size()] = '\0'; - - // Unicode - // "Because the Unicode language code and Unicode count immediately follow the ASCII description, - // their alignment is not correct when the ASCII count is not a multiple of four" - // So we can't use BigEndian here. - u8* cursor = bytes.data() + 8 + ascii_size; - u32 unicode_language_code = 0; // FIXME: Set to tag_data.unicode_language_code() once this writes unicode data. - cursor[0] = unicode_language_code >> 24; - cursor[1] = (unicode_language_code >> 16) & 0xff; - cursor[2] = (unicode_language_code >> 8) & 0xff; - cursor[3] = unicode_language_code & 0xff; - cursor += 4; - - // FIXME: Include tag_data.unicode_description() if it's set. - u32 ucs2_count = 0; // FIXME: If tag_data.unicode_description() is set, set this to its length plus room for one nul character. - cursor[0] = ucs2_count >> 24; - cursor[1] = (ucs2_count >> 16) & 0xff; - cursor[2] = (ucs2_count >> 8) & 0xff; - cursor[3] = ucs2_count & 0xff; - cursor += 4; - - // Macintosh scriptcode - u16 scriptcode_code = 0; // MacRoman - cursor[0] = (scriptcode_code >> 8) & 0xff; - cursor[1] = scriptcode_code & 0xff; - cursor += 2; - - u8 macintosh_description_length = 0; // FIXME: If tag_data.macintosh_description() is set, set this to tis length plus room for one nul character. - cursor[0] = macintosh_description_length; - cursor += 1; - memset(cursor, 0, 67); - - return bytes; -} - -static ErrorOr encode_text(TextTagData const& tag_data) -{ - // ICC v4, 10.24 textType - // "The textType is a simple text structure that contains a 7-bit ASCII text string. The length of the string is obtained - // by subtracting 8 from the element size portion of the tag itself. This string shall be terminated with a 00h byte." - auto text_bytes = tag_data.text().bytes(); - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + text_bytes.size() + 1)); - *bit_cast*>(bytes.data()) = static_cast(TextTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - memcpy(bytes.data() + 8, text_bytes.data(), text_bytes.size()); - *(bytes.data() + 8 + text_bytes.size()) = '\0'; - return bytes; -} - -static ErrorOr encode_viewing_conditions(ViewingConditionsTagData const& tag_data) -{ - // ICC v4, 10.30 viewingConditionsType - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(ViewingConditionsHeader))); - *bit_cast*>(bytes.data()) = static_cast(ViewingConditionsTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto& header = *bit_cast(bytes.data() + 8); - header.unnormalized_ciexyz_values_for_illuminant = tag_data.unnormalized_ciexyz_values_for_illuminant(); - header.unnormalized_ciexyz_values_for_surround = tag_data.unnormalized_ciexyz_values_for_surround(); - header.illuminant_type = tag_data.illuminant_type(); - - return bytes; -} - -static ErrorOr encode_xyz(XYZTagData const& tag_data) -{ - // ICC v4, 10.31 XYZType - auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + tag_data.xyzs().size() * sizeof(XYZNumber))); - *bit_cast*>(bytes.data()) = static_cast(XYZTagData::Type); - *bit_cast*>(bytes.data() + 4) = 0; - - auto* xyzs = bit_cast(bytes.data() + 8); - for (size_t i = 0; i < tag_data.xyzs().size(); ++i) - xyzs[i] = tag_data.xyzs()[i]; - - return bytes; -} - -static ErrorOr> encode_tag_data(TagData const& tag_data) -{ - switch (tag_data.type()) { - case ChromaticityTagData::Type: - return encode_chromaticity(static_cast(tag_data)); - case CicpTagData::Type: - return encode_cipc(static_cast(tag_data)); - case CurveTagData::Type: - return encode_curve(static_cast(tag_data)); - case Lut16TagData::Type: - return encode_lut_16(static_cast(tag_data)); - case Lut8TagData::Type: - return encode_lut_8(static_cast(tag_data)); - case LutAToBTagData::Type: - return encode_lut_a_to_b(static_cast(tag_data)); - case LutBToATagData::Type: - return encode_lut_b_to_a(static_cast(tag_data)); - case MeasurementTagData::Type: - return encode_measurement(static_cast(tag_data)); - case MultiLocalizedUnicodeTagData::Type: - return encode_multi_localized_unicode(static_cast(tag_data)); - case NamedColor2TagData::Type: - return encode_named_color_2(static_cast(tag_data)); - case ParametricCurveTagData::Type: - return encode_parametric_curve(static_cast(tag_data)); - case S15Fixed16ArrayTagData::Type: - return encode_s15_fixed_array(static_cast(tag_data)); - case SignatureTagData::Type: - return encode_signature(static_cast(tag_data)); - case TextDescriptionTagData::Type: - return encode_text_description(static_cast(tag_data)); - case TextTagData::Type: - return encode_text(static_cast(tag_data)); - case ViewingConditionsTagData::Type: - return encode_viewing_conditions(static_cast(tag_data)); - case XYZTagData::Type: - return encode_xyz(static_cast(tag_data)); - } - - return OptionalNone {}; -} - -static ErrorOr> encode_tag_datas(Profile const& profile, HashMap& tag_data_map) -{ - Vector tag_data_bytes; - TRY(tag_data_bytes.try_ensure_capacity(profile.tag_count())); - - TRY(profile.try_for_each_tag([&](auto, auto tag_data) -> ErrorOr { - if (tag_data_map.contains(tag_data.ptr())) - return {}; - - auto encoded_tag_data = TRY(encode_tag_data(tag_data)); - if (!encoded_tag_data.has_value()) - return {}; - - tag_data_bytes.append(encoded_tag_data.release_value()); - TRY(tag_data_map.try_set(tag_data.ptr(), tag_data_bytes.size() - 1)); - return {}; - })); - return tag_data_bytes; -} - -static ErrorOr encode_tag_table(ByteBuffer& bytes, Profile const& profile, u32 number_of_serialized_tags, Vector const& offsets, - Vector const& tag_data_bytes, HashMap const& tag_data_map) -{ - // ICC v4, 7.3 Tag table - // ICC v4, 7.3.1 Overview - VERIFY(bytes.size() >= sizeof(ICCHeader) + sizeof(u32) + number_of_serialized_tags * sizeof(TagTableEntry)); - - *bit_cast*>(bytes.data() + sizeof(ICCHeader)) = number_of_serialized_tags; - - TagTableEntry* tag_table_entries = bit_cast(bytes.data() + sizeof(ICCHeader) + sizeof(u32)); - int i = 0; - profile.for_each_tag([&](auto tag_signature, auto tag_data) { - auto index = tag_data_map.get(tag_data.ptr()); - if (!index.has_value()) - return; - - tag_table_entries[i].tag_signature = tag_signature; - - tag_table_entries[i].offset_to_beginning_of_tag_data_element = offsets[index.value()]; - tag_table_entries[i].size_of_tag_data_element = tag_data_bytes[index.value()].size(); - ++i; - }); - - return {}; -} - -static ErrorOr encode_header(ByteBuffer& bytes, Profile const& profile) -{ - VERIFY(bytes.size() >= sizeof(ICCHeader)); - auto& raw_header = *bit_cast(bytes.data()); - - raw_header.profile_size = bytes.size(); - raw_header.preferred_cmm_type = profile.preferred_cmm_type().value_or(PreferredCMMType { 0 }); - - raw_header.profile_version_major = profile.version().major_version(); - raw_header.profile_version_minor_bugfix = profile.version().minor_and_bugfix_version(); - raw_header.profile_version_zero = 0; - - raw_header.profile_device_class = profile.device_class(); - raw_header.data_color_space = profile.data_color_space(); - raw_header.profile_connection_space = profile.connection_space(); - - DateTime profile_timestamp = profile.creation_timestamp(); - raw_header.profile_creation_time.year = profile_timestamp.year; - raw_header.profile_creation_time.month = profile_timestamp.month; - raw_header.profile_creation_time.day = profile_timestamp.day; - raw_header.profile_creation_time.hours = profile_timestamp.hours; - raw_header.profile_creation_time.minutes = profile_timestamp.minutes; - raw_header.profile_creation_time.seconds = profile_timestamp.seconds; - - raw_header.profile_file_signature = ProfileFileSignature; - raw_header.primary_platform = profile.primary_platform().value_or(PrimaryPlatform { 0 }); - - raw_header.profile_flags = profile.flags().bits(); - raw_header.device_manufacturer = profile.device_manufacturer().value_or(DeviceManufacturer { 0 }); - raw_header.device_model = profile.device_model().value_or(DeviceModel { 0 }); - raw_header.device_attributes = profile.device_attributes().bits(); - raw_header.rendering_intent = profile.rendering_intent(); - - raw_header.pcs_illuminant = profile.pcs_illuminant(); - - raw_header.profile_creator = profile.creator().value_or(Creator { 0 }); - - memset(raw_header.reserved, 0, sizeof(raw_header.reserved)); - - auto id = Profile::compute_id(bytes); - static_assert(sizeof(id.data) == sizeof(raw_header.profile_id)); - memcpy(raw_header.profile_id, id.data, sizeof(id.data)); - - return {}; -} - -ErrorOr encode(Profile const& profile) -{ - // Valid profiles always have tags. Profile only represents valid profiles. - VERIFY(profile.tag_count() > 0); - - HashMap tag_data_map; - Vector tag_data_bytes = TRY(encode_tag_datas(profile, tag_data_map)); - - u32 number_of_serialized_tags = 0; - profile.for_each_tag([&](auto tag_signature, auto tag_data) { - if (!tag_data_map.contains(tag_data.ptr())) { - dbgln("ICC serialization: dropping tag {} because it has unknown type {}", tag_signature, tag_data->type()); - return; - } - number_of_serialized_tags++; - }); - - size_t tag_table_size = sizeof(u32) + number_of_serialized_tags * sizeof(TagTableEntry); - size_t offset = sizeof(ICCHeader) + tag_table_size; - Vector offsets; - for (auto const& bytes : tag_data_bytes) { - TRY(offsets.try_append(offset)); - offset += align_up_to(bytes.size(), 4); - } - - // Include padding after last element. Use create_zeroed() to fill padding bytes with null bytes. - // ICC v4, 7.1.2: - // "c) all tagged element data, including the last, shall be padded by no more than three following pad bytes to - // reach a 4-byte boundary; - // d) all pad bytes shall be NULL (as defined in ISO/IEC 646, character 0/0). - // NOTE 1 This implies that the length is required to be a multiple of four." - auto bytes = TRY(ByteBuffer::create_zeroed(offset)); - - for (size_t i = 0; i < tag_data_bytes.size(); ++i) - memcpy(bytes.data() + offsets[i], tag_data_bytes[i].data(), tag_data_bytes[i].size()); - - TRY(encode_tag_table(bytes, profile, number_of_serialized_tags, offsets, tag_data_bytes, tag_data_map)); - TRY(encode_header(bytes, profile)); - - return bytes; -} - -} diff --git a/Libraries/LibGfx/ICC/BinaryWriter.h b/Libraries/LibGfx/ICC/BinaryWriter.h deleted file mode 100644 index c7d354b9ceef..000000000000 --- a/Libraries/LibGfx/ICC/BinaryWriter.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -namespace Gfx::ICC { - -class Profile; - -// Serializes a Profile object. -// Ignores the Profile's on_disk_size() and id() and recomputes them instead. -// Also ignores and the offsets and sizes in tag data. -// But if the profile has its tag data in tag order and has a computed id, -// it's a goal that encode(Profile::try_load_from_externally_owned_memory(bytes) returns `bytes`. -// Unconditionally computes a Profile ID (which is an MD5 hash of most of the contents, see Profile::compute_id()) and writes it to the output. -ErrorOr encode(Profile const&); - -} diff --git a/Libraries/LibGfx/ICC/DistinctFourCC.h b/Libraries/LibGfx/ICC/DistinctFourCC.h deleted file mode 100644 index 34815630c634..000000000000 --- a/Libraries/LibGfx/ICC/DistinctFourCC.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include - -namespace Gfx::ICC { - -// The ICC spec uses FourCCs for many different things. -// This is used to give FourCCs for different roles distinct types, so that they can only be compared to the correct constants. -// (FourCCs that have only a small and fixed set of values should use an enum class instead, see e.g. DeviceClass and ColorSpace in Enums.h.) -enum class FourCCType { - PreferredCMMType, - DeviceManufacturer, - DeviceModel, - Creator, - TagSignature, - TagTypeSignature, -}; - -template -struct [[gnu::packed]] DistinctFourCC { - constexpr explicit DistinctFourCC(u32 value) - : value(value) - { - } - constexpr operator u32() const { return value; } - - char c0() const { return value >> 24; } - char c1() const { return (value >> 16) & 0xff; } - char c2() const { return (value >> 8) & 0xff; } - char c3() const { return value & 0xff; } - - bool operator==(DistinctFourCC b) const { return value == b.value; } - - u32 value { 0 }; -}; - -using PreferredCMMType = DistinctFourCC; // ICC v4, "7.2.3 Preferred CMM type field" -using DeviceManufacturer = DistinctFourCC; // ICC v4, "7.2.12 Device manufacturer field" -using DeviceModel = DistinctFourCC; // ICC v4, "7.2.13 Device model field" -using Creator = DistinctFourCC; // ICC v4, "7.2.17 Profile creator field" -using TagSignature = DistinctFourCC; // ICC v4, "9.2 Tag listing" -using TagTypeSignature = DistinctFourCC; // ICC v4, "10 Tag type definitions" - -} - -template -struct AK::Formatter> : StandardFormatter { - ErrorOr format(FormatBuilder& builder, Gfx::ICC::DistinctFourCC const& four_cc) - { - TRY(builder.put_padding('\'', 1)); - TRY(builder.put_padding(four_cc.c0(), 1)); - TRY(builder.put_padding(four_cc.c1(), 1)); - TRY(builder.put_padding(four_cc.c2(), 1)); - TRY(builder.put_padding(four_cc.c3(), 1)); - TRY(builder.put_padding('\'', 1)); - return {}; - } -}; - -template -struct AK::Traits> : public DefaultTraits> { - static unsigned hash(Gfx::ICC::DistinctFourCC const& key) - { - return int_hash(key.value); - } - - static bool equals(Gfx::ICC::DistinctFourCC const& a, Gfx::ICC::DistinctFourCC const& b) - { - return a == b; - } -}; diff --git a/Libraries/LibGfx/ICC/Enums.cpp b/Libraries/LibGfx/ICC/Enums.cpp deleted file mode 100644 index fbcc7c721b66..000000000000 --- a/Libraries/LibGfx/ICC/Enums.cpp +++ /dev/null @@ -1,178 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include - -namespace Gfx::ICC { - -StringView device_class_name(DeviceClass device_class) -{ - switch (device_class) { - case DeviceClass::InputDevice: - return "InputDevice"sv; - case DeviceClass::DisplayDevice: - return "DisplayDevice"sv; - case DeviceClass::OutputDevice: - return "OutputDevice"sv; - case DeviceClass::DeviceLink: - return "DeviceLink"sv; - case DeviceClass::ColorSpace: - return "ColorSpace"sv; - case DeviceClass::Abstract: - return "Abstract"sv; - case DeviceClass::NamedColor: - return "NamedColor"sv; - } - VERIFY_NOT_REACHED(); -} - -StringView data_color_space_name(ColorSpace color_space) -{ - switch (color_space) { - case ColorSpace::nCIEXYZ: - return "nCIEXYZ"sv; - case ColorSpace::CIELAB: - return "CIELAB"sv; - case ColorSpace::CIELUV: - return "CIELUV"sv; - case ColorSpace::YCbCr: - return "YCbCr"sv; - case ColorSpace::CIEYxy: - return "CIEYxy"sv; - case ColorSpace::RGB: - return "RGB"sv; - case ColorSpace::Gray: - return "Gray"sv; - case ColorSpace::HSV: - return "HSV"sv; - case ColorSpace::HLS: - return "HLS"sv; - case ColorSpace::CMYK: - return "CMYK"sv; - case ColorSpace::CMY: - return "CMY"sv; - case ColorSpace::TwoColor: - return "2 color"sv; - case ColorSpace::ThreeColor: - return "3 color (other than XYZ, Lab, Luv, YCbCr, CIEYxy, RGB, HSV, HLS, CMY)"sv; - case ColorSpace::FourColor: - return "4 color (other than CMYK)"sv; - case ColorSpace::FiveColor: - return "5 color"sv; - case ColorSpace::SixColor: - return "6 color"sv; - case ColorSpace::SevenColor: - return "7 color"sv; - case ColorSpace::EightColor: - return "8 color"sv; - case ColorSpace::NineColor: - return "9 color"sv; - case ColorSpace::TenColor: - return "10 color"sv; - case ColorSpace::ElevenColor: - return "11 color"sv; - case ColorSpace::TwelveColor: - return "12 color"sv; - case ColorSpace::ThirteenColor: - return "13 color"sv; - case ColorSpace::FourteenColor: - return "14 color"sv; - case ColorSpace::FifteenColor: - return "15 color"sv; - } - VERIFY_NOT_REACHED(); -} - -StringView profile_connection_space_name(ColorSpace color_space) -{ - switch (color_space) { - case ColorSpace::PCSXYZ: - return "PCSXYZ"sv; - case ColorSpace::PCSLAB: - return "PCSLAB"sv; - default: - return data_color_space_name(color_space); - } -} - -unsigned number_of_components_in_color_space(ColorSpace color_space) -{ - switch (color_space) { - case ColorSpace::Gray: - return 1; - case ColorSpace::TwoColor: - return 2; - case ColorSpace::nCIEXYZ: - case ColorSpace::CIELAB: - case ColorSpace::CIELUV: - case ColorSpace::YCbCr: - case ColorSpace::CIEYxy: - case ColorSpace::RGB: - case ColorSpace::HSV: - case ColorSpace::HLS: - case ColorSpace::CMY: - case ColorSpace::ThreeColor: - return 3; - case ColorSpace::CMYK: - case ColorSpace::FourColor: - return 4; - case ColorSpace::FiveColor: - return 5; - case ColorSpace::SixColor: - return 6; - case ColorSpace::SevenColor: - return 7; - case ColorSpace::EightColor: - return 8; - case ColorSpace::NineColor: - return 9; - case ColorSpace::TenColor: - return 10; - case ColorSpace::ElevenColor: - return 11; - case ColorSpace::TwelveColor: - return 12; - case ColorSpace::ThirteenColor: - return 13; - case ColorSpace::FourteenColor: - return 14; - case ColorSpace::FifteenColor: - return 15; - } - VERIFY_NOT_REACHED(); -} - -StringView primary_platform_name(PrimaryPlatform primary_platform) -{ - switch (primary_platform) { - case PrimaryPlatform::Apple: - return "Apple"sv; - case PrimaryPlatform::Microsoft: - return "Microsoft"sv; - case PrimaryPlatform::SiliconGraphics: - return "Silicon Graphics"sv; - case PrimaryPlatform::Sun: - return "Sun"sv; - } - VERIFY_NOT_REACHED(); -} - -StringView rendering_intent_name(RenderingIntent rendering_intent) -{ - switch (rendering_intent) { - case RenderingIntent::Perceptual: - return "Perceptual"sv; - case RenderingIntent::MediaRelativeColorimetric: - return "Media-relative colorimetric"sv; - case RenderingIntent::Saturation: - return "Saturation"sv; - case RenderingIntent::ICCAbsoluteColorimetric: - return "ICC-absolute colorimetric"sv; - } - VERIFY_NOT_REACHED(); -} - -} diff --git a/Libraries/LibGfx/ICC/Enums.h b/Libraries/LibGfx/ICC/Enums.h deleted file mode 100644 index 1c298dbe9a2a..000000000000 --- a/Libraries/LibGfx/ICC/Enums.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include - -namespace Gfx::ICC { - -// ICC v4, 7.2.5 Profile/device class field -enum class DeviceClass : u32 { - InputDevice = 0x73636E72, // 'scnr' - DisplayDevice = 0x6D6E7472, // 'mntr' - OutputDevice = 0x70727472, // 'prtr' - DeviceLink = 0x6C696E6B, // 'link' - ColorSpace = 0x73706163, // 'spac' - Abstract = 0x61627374, // 'abst' - NamedColor = 0x6E6D636C, // 'nmcl' -}; -StringView device_class_name(DeviceClass); - -// ICC v4, 7.2.6 Data colour space field, Table 19 — Data colour space signatures -enum class ColorSpace : u32 { - nCIEXYZ = 0x58595A20, // 'XYZ ', used in data color spaces. - PCSXYZ = nCIEXYZ, // Used in profile connection space instead. - CIELAB = 0x4C616220, // 'Lab ', used in data color spaces. - PCSLAB = CIELAB, // Used in profile connection space instead. - CIELUV = 0x4C757620, // 'Luv ' - YCbCr = 0x59436272, // 'YCbr' - CIEYxy = 0x59787920, // 'Yxy ' - RGB = 0x52474220, // 'RGB ' - Gray = 0x47524159, // 'GRAY' - HSV = 0x48535620, // 'HSV ' - HLS = 0x484C5320, // 'HLS ' - CMYK = 0x434D594B, // 'CMYK' - CMY = 0x434D5920, // 'CMY ' - TwoColor = 0x32434C52, // '2CLR' - ThreeColor = 0x33434C52, // '3CLR' - FourColor = 0x34434C52, // '4CLR' - FiveColor = 0x35434C52, // '5CLR' - SixColor = 0x36434C52, // '6CLR' - SevenColor = 0x37434C52, // '7CLR' - EightColor = 0x38434C52, // '8CLR' - NineColor = 0x39434C52, // '9CLR' - TenColor = 0x41434C52, // 'ACLR' - ElevenColor = 0x42434C52, // 'BCLR' - TwelveColor = 0x43434C52, // 'CCLR' - ThirteenColor = 0x44434C52, // 'DCLR' - FourteenColor = 0x45434C52, // 'ECLR' - FifteenColor = 0x46434C52, // 'FCLR' -}; -StringView data_color_space_name(ColorSpace); -StringView profile_connection_space_name(ColorSpace); -unsigned number_of_components_in_color_space(ColorSpace); - -// ICC v4, 7.2.10 Primary platform field, Table 20 — Primary platforms -enum class PrimaryPlatform : u32 { - Apple = 0x4150504C, // 'APPL' - Microsoft = 0x4D534654, // 'MSFT' - SiliconGraphics = 0x53474920, // 'SGI ' - Sun = 0x53554E57, // 'SUNW' -}; -StringView primary_platform_name(PrimaryPlatform); - -// ICC v4, 7.2.15 Rendering intent field -enum class RenderingIntent { - Perceptual, - MediaRelativeColorimetric, - Saturation, - ICCAbsoluteColorimetric, -}; -StringView rendering_intent_name(RenderingIntent); - -} diff --git a/Libraries/LibGfx/ICC/Profile.cpp b/Libraries/LibGfx/ICC/Profile.cpp deleted file mode 100644 index b4d66b635784..000000000000 --- a/Libraries/LibGfx/ICC/Profile.cpp +++ /dev/null @@ -1,1812 +0,0 @@ -/* - * Copyright (c) 2022-2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// V2 spec: https://color.org/specification/ICC.1-2001-04.pdf -// V4 spec: https://color.org/specification/ICC.1-2022-05.pdf - -namespace Gfx::ICC { - -namespace { - -ErrorOr parse_date_time_number(DateTimeNumber const& date_time) -{ - return DateTime { - .year = date_time.year, - .month = date_time.month, - .day = date_time.day, - .hours = date_time.hours, - .minutes = date_time.minutes, - .seconds = date_time.seconds, - }; -} - -ErrorOr parse_size(ICCHeader const& header, ReadonlyBytes icc_bytes) -{ - // ICC v4, 7.2.2 Profile size field - // "The value in the profile size field shall be the exact size obtained by combining the profile header, - // the tag table, and the tagged element data, including the pad bytes for the last tag." - - // Valid files have enough data for profile header and tag table entry count. - if (header.profile_size < sizeof(ICCHeader) + sizeof(u32)) - return Error::from_string_literal("ICC::Profile: Profile size too small"); - - if (header.profile_size > icc_bytes.size()) - return Error::from_string_literal("ICC::Profile: Profile size larger than input data"); - - // ICC v4, 7.1.2: - // "NOTE 1 This implies that the length is required to be a multiple of four." - // The ICC v2 spec doesn't have this note. It instead has: - // ICC v2, 6.2.2 Offset: - // "All tag data is required to start on a 4-byte boundary" - // And indeed, there are files in the wild where the last tag has a size that isn't a multiple of four, - // resulting in an ICC file whose size isn't a multiple of four either. - if (header.profile_version_major >= 4 && header.profile_size % 4 != 0) - return Error::from_string_literal("ICC::Profile: Profile size not a multiple of four"); - - return header.profile_size; -} - -Optional parse_preferred_cmm_type(ICCHeader const& header) -{ - // ICC v4, 7.2.3 Preferred CMM type field - - // "This field may be used to identify the preferred CMM to be used. - // If used, it shall match a CMM type signature registered in the ICC Tag Registry" - // https://www.color.org/signatures2.xalter currently links to - // https://www.color.org/registry/signature/TagRegistry-2021-03.pdf, which contains - // some CMM signatures. - // This requirement is often honored in practice, but not always. For example, - // JPEGs exported in Adobe Lightroom contain profiles that set this to 'Lino', - // which is not present in the "CMM Signatures" table in that PDF. - - // "If no preferred CMM is identified, this field shall be set to zero (00000000h)." - if (header.preferred_cmm_type == PreferredCMMType { 0 }) - return {}; - return header.preferred_cmm_type; -} - -ErrorOr parse_version(ICCHeader const& header) -{ - // ICC v4, 7.2.4 Profile version field - if (header.profile_version_zero != 0) - return Error::from_string_literal("ICC::Profile: Reserved version bytes not zero"); - return Version(header.profile_version_major, header.profile_version_minor_bugfix); -} - -ErrorOr parse_device_class(ICCHeader const& header) -{ - // ICC v4, 7.2.5 Profile/device class field - switch (header.profile_device_class) { - case DeviceClass::InputDevice: - case DeviceClass::DisplayDevice: - case DeviceClass::OutputDevice: - case DeviceClass::DeviceLink: - case DeviceClass::ColorSpace: - case DeviceClass::Abstract: - case DeviceClass::NamedColor: - return header.profile_device_class; - } - return Error::from_string_literal("ICC::Profile: Invalid device class"); -} - -ErrorOr parse_color_space(ColorSpace color_space) -{ - // ICC v4, Table 19 — Data colour space signatures - switch (color_space) { - case ColorSpace::nCIEXYZ: - case ColorSpace::CIELAB: - case ColorSpace::CIELUV: - case ColorSpace::YCbCr: - case ColorSpace::CIEYxy: - case ColorSpace::RGB: - case ColorSpace::Gray: - case ColorSpace::HSV: - case ColorSpace::HLS: - case ColorSpace::CMYK: - case ColorSpace::CMY: - case ColorSpace::TwoColor: - case ColorSpace::ThreeColor: - case ColorSpace::FourColor: - case ColorSpace::FiveColor: - case ColorSpace::SixColor: - case ColorSpace::SevenColor: - case ColorSpace::EightColor: - case ColorSpace::NineColor: - case ColorSpace::TenColor: - case ColorSpace::ElevenColor: - case ColorSpace::TwelveColor: - case ColorSpace::ThirteenColor: - case ColorSpace::FourteenColor: - case ColorSpace::FifteenColor: - return color_space; - } - return Error::from_string_literal("ICC::Profile: Invalid color space"); -} - -ErrorOr parse_data_color_space(ICCHeader const& header) -{ - // ICC v4, 7.2.6 Data colour space field - return parse_color_space(header.data_color_space); -} - -ErrorOr parse_connection_space(ICCHeader const& header) -{ - // ICC v4, 7.2.7 PCS field - // and Annex D - auto space = TRY(parse_color_space(header.profile_connection_space)); - - if (header.profile_device_class != DeviceClass::DeviceLink && (space != ColorSpace::PCSXYZ && space != ColorSpace::PCSLAB)) - return Error::from_string_literal("ICC::Profile: Invalid profile connection space: Non-PCS space on non-DeviceLink profile"); - - return space; -} - -ErrorOr parse_creation_date_time(ICCHeader const& header) -{ - // ICC v4, 7.2.8 Date and time field - return parse_date_time_number(header.profile_creation_time); -} - -ErrorOr parse_file_signature(ICCHeader const& header) -{ - // ICC v4, 7.2.9 Profile file signature field - if (header.profile_file_signature != ProfileFileSignature) - return Error::from_string_literal("ICC::Profile: profile file signature not 'acsp'"); - return {}; -} - -ErrorOr> parse_primary_platform(ICCHeader const& header) -{ - // ICC v4, 7.2.10 Primary platform field - // "If there is no primary platform identified, this field shall be set to zero (00000000h)." - if (header.primary_platform == PrimaryPlatform { 0 }) - return OptionalNone {}; - - switch (header.primary_platform) { - case PrimaryPlatform::Apple: - case PrimaryPlatform::Microsoft: - case PrimaryPlatform::SiliconGraphics: - case PrimaryPlatform::Sun: - return header.primary_platform; - } - return Error::from_string_literal("ICC::Profile: Invalid primary platform"); -} - -Optional parse_device_manufacturer(ICCHeader const& header) -{ - // ICC v4, 7.2.12 Device manufacturer field - // "This field may be used to identify a device manufacturer. - // If used the signature shall match the signature contained in the appropriate section of the ICC signature registry found at www.color.org" - // Device manufacturers can be looked up at https://www.color.org/signatureRegistry/index.xalter - // For example: https://www.color.org/signatureRegistry/?entityEntry=APPL-4150504C - // Some icc files use codes not in that registry. For example. D50_XYZ.icc from https://www.color.org/XYZprofiles.xalter - // has its device manufacturer set to 'none', but https://www.color.org/signatureRegistry/?entityEntry=none-6E6F6E65 does not exist. - - // "If not used this field shall be set to zero (00000000h)." - if (header.device_manufacturer == DeviceManufacturer { 0 }) - return {}; - return header.device_manufacturer; -} - -Optional parse_device_model(ICCHeader const& header) -{ - // ICC v4, 7.2.13 Device model field - // "This field may be used to identify a device model. - // If used the signature shall match the signature contained in the appropriate section of the ICC signature registry found at www.color.org" - // Device models can be looked up at https://www.color.org/signatureRegistry/deviceRegistry/index.xalter - // For example: https://www.color.org/signatureRegistry/deviceRegistry/?entityEntry=7FD8-37464438 - // Some icc files use codes not in that registry. For example. D50_XYZ.icc from https://www.color.org/XYZprofiles.xalter - // has its device model set to 'none', but https://www.color.org/signatureRegistry/deviceRegistry?entityEntry=none-6E6F6E65 does not exist. - - // "If not used this field shall be set to zero (00000000h)." - if (header.device_model == DeviceModel { 0 }) - return {}; - return header.device_model; -} - -ErrorOr parse_device_attributes(ICCHeader const& header) -{ - // ICC v4, 7.2.14 Device attributes field - - // "4 to 31": "Reserved (set to binary zero)" - if (header.device_attributes & 0xffff'fff0) - return Error::from_string_literal("ICC::Profile: Device attributes reserved bits not set to 0"); - - return DeviceAttributes { header.device_attributes }; -} - -ErrorOr parse_rendering_intent(ICCHeader const& header) -{ - // ICC v4, 7.2.15 Rendering intent field - switch (header.rendering_intent) { - case RenderingIntent::Perceptual: - case RenderingIntent::MediaRelativeColorimetric: - case RenderingIntent::Saturation: - case RenderingIntent::ICCAbsoluteColorimetric: - return header.rendering_intent; - } - return Error::from_string_literal("ICC::Profile: Invalid rendering intent"); -} - -ErrorOr parse_pcs_illuminant(ICCHeader const& header) -{ - // ICC v4, 7.2.16 PCS illuminant field - XYZ xyz = (XYZ)header.pcs_illuminant; - - /// "The value, when rounded to four decimals, shall be X = 0,9642, Y = 1,0 and Z = 0,8249." - if (round(xyz.X * 10'000) != 9'642 || round(xyz.Y * 10'000) != 10'000 || round(xyz.Z * 10'000) != 8'249) - return Error::from_string_literal("ICC::Profile: Invalid pcs illuminant"); - - return xyz; -} - -Optional parse_profile_creator(ICCHeader const& header) -{ - // ICC v4, 7.2.17 Profile creator field - // "This field may be used to identify the creator of the profile. - // If used the signature should match the signature contained in the device manufacturer section of the ICC signature registry found at www.color.org." - // This is not always true in practice. - // For example, .icc files in /System/ColorSync/Profiles on macOS 12.6 set this to 'appl', which is a CMM signature, not a device signature (that one would be 'APPL'). - - // "If not used this field shall be set to zero (00000000h)." - if (header.profile_creator == Creator { 0 }) - return {}; - return header.profile_creator; -} - -template -bool all_bytes_are_zero(u8 const (&bytes)[N]) -{ - for (u8 byte : bytes) { - if (byte != 0) - return false; - } - return true; -} - -ErrorOr> parse_profile_id(ICCHeader const& header, ReadonlyBytes icc_bytes) -{ - // ICC v4, 7.2.18 Profile ID field - // "A profile ID field value of zero (00h) shall indicate that a profile ID has not been calculated." - if (all_bytes_are_zero(header.profile_id)) - return OptionalNone {}; - - Crypto::Hash::MD5::DigestType id; - static_assert(sizeof(id.data) == sizeof(header.profile_id)); - memcpy(id.data, header.profile_id, sizeof(id.data)); - - auto computed_id = Profile::compute_id(icc_bytes); - if (id != computed_id) - return Error::from_string_literal("ICC::Profile: Invalid profile id"); - - return id; -} - -ErrorOr parse_reserved(ICCHeader const& header) -{ - // ICC v4, 7.2.19 Reserved field - // "This field of the profile header is reserved for future ICC definition and shall be set to zero." - if (!all_bytes_are_zero(header.reserved)) - return Error::from_string_literal("ICC::Profile: Reserved header bytes are not zero"); - return {}; -} -} - -URL::URL device_manufacturer_url(DeviceManufacturer device_manufacturer) -{ - return URL::URL(ByteString::formatted("https://www.color.org/signatureRegistry/?entityEntry={:c}{:c}{:c}{:c}-{:08X}", - device_manufacturer.c0(), device_manufacturer.c1(), device_manufacturer.c2(), device_manufacturer.c3(), device_manufacturer.value)); -} - -URL::URL device_model_url(DeviceModel device_model) -{ - return URL::URL(ByteString::formatted("https://www.color.org/signatureRegistry/deviceRegistry/?entityEntry={:c}{:c}{:c}{:c}-{:08X}", - device_model.c0(), device_model.c1(), device_model.c2(), device_model.c3(), device_model.value)); -} - -Flags::Flags() = default; -Flags::Flags(u32 bits) - : m_bits(bits) -{ -} - -DeviceAttributes::DeviceAttributes() = default; -DeviceAttributes::DeviceAttributes(u64 bits) - : m_bits(bits) -{ -} - -static ErrorOr validate_date_time(DateTime const& date_time) -{ - // Returns if a DateTime is valid per ICC V4, 4.2 dateTimeNumber. - // In practice, some profiles contain invalid dates, but we should enforce this for data we write at least. - - // "Number of the month (1 to 12)" - if (date_time.month < 1 || date_time.month > 12) - return Error::from_string_literal("ICC::Profile: dateTimeNumber month out of bounds"); - - // "Number of the day of the month (1 to 31)" - if (date_time.day < 1 || date_time.day > 31) - return Error::from_string_literal("ICC::Profile: dateTimeNumber day out of bounds"); - - // "Number of hours (0 to 23)" - if (date_time.hours > 23) - return Error::from_string_literal("ICC::Profile: dateTimeNumber hours out of bounds"); - - // "Number of minutes (0 to 59)" - if (date_time.minutes > 59) - return Error::from_string_literal("ICC::Profile: dateTimeNumber minutes out of bounds"); - - // "Number of seconds (0 to 59)" - // ICC profiles apparently can't be created during leap seconds (seconds would be 60 there, but the spec doesn't allow that). - if (date_time.seconds > 59) - return Error::from_string_literal("ICC::Profile: dateTimeNumber seconds out of bounds"); - - return {}; -} - -ErrorOr DateTime::to_time_t() const -{ - TRY(validate_date_time(*this)); - - struct tm tm = {}; - tm.tm_year = year - 1900; - tm.tm_mon = month - 1; - tm.tm_mday = day; - tm.tm_hour = hours; - tm.tm_min = minutes; - tm.tm_sec = seconds; - // timegm() doesn't read tm.tm_isdst, tm.tm_wday, and tm.tm_yday, no need to fill them in. - - time_t timestamp = timegm(&tm); - if (timestamp == -1) - return Error::from_string_literal("ICC::Profile: dateTimeNumber not representable as timestamp"); - - return timestamp; -} - -ErrorOr DateTime::from_time_t(time_t timestamp) -{ - struct tm gmt_tm; - if (gmtime_r(×tamp, &gmt_tm) == NULL) - return Error::from_string_literal("ICC::Profile: timestamp not representable as DateTimeNumber"); - - // FIXME: Range-check, using something like `TRY(Checked(x).try_value())`? - DateTime result { - .year = static_cast(gmt_tm.tm_year + 1900), - .month = static_cast(gmt_tm.tm_mon + 1), - .day = static_cast(gmt_tm.tm_mday), - .hours = static_cast(gmt_tm.tm_hour), - .minutes = static_cast(gmt_tm.tm_min), - .seconds = static_cast(gmt_tm.tm_sec), - }; - TRY(validate_date_time(result)); - return result; -} - -static ErrorOr read_header(ReadonlyBytes bytes) -{ - if (bytes.size() < sizeof(ICCHeader)) - return Error::from_string_literal("ICC::Profile: Not enough data for header"); - - ProfileHeader header; - auto raw_header = *bit_cast(bytes.data()); - - TRY(parse_file_signature(raw_header)); - header.on_disk_size = TRY(parse_size(raw_header, bytes)); - header.preferred_cmm_type = parse_preferred_cmm_type(raw_header); - header.version = TRY(parse_version(raw_header)); - header.device_class = TRY(parse_device_class(raw_header)); - header.data_color_space = TRY(parse_data_color_space(raw_header)); - header.connection_space = TRY(parse_connection_space(raw_header)); - header.creation_timestamp = TRY(parse_creation_date_time(raw_header)); - header.primary_platform = TRY(parse_primary_platform(raw_header)); - header.flags = Flags { raw_header.profile_flags }; - header.device_manufacturer = parse_device_manufacturer(raw_header); - header.device_model = parse_device_model(raw_header); - header.device_attributes = TRY(parse_device_attributes(raw_header)); - header.rendering_intent = TRY(parse_rendering_intent(raw_header)); - header.pcs_illuminant = TRY(parse_pcs_illuminant(raw_header)); - header.creator = parse_profile_creator(raw_header); - header.id = TRY(parse_profile_id(raw_header, bytes)); - TRY(parse_reserved(raw_header)); - - return header; -} - -static ErrorOr> read_tag(ReadonlyBytes bytes, u32 offset_to_beginning_of_tag_data_element, u32 size_of_tag_data_element) -{ - // "All tag data elements shall start on a 4-byte boundary (relative to the start of the profile data stream)" - if (offset_to_beginning_of_tag_data_element % 4 != 0) - return Error::from_string_literal("ICC::Profile: Tag data not aligned"); - - if (static_cast(offset_to_beginning_of_tag_data_element) + size_of_tag_data_element > bytes.size()) - return Error::from_string_literal("ICC::Profile: Tag data out of bounds"); - - auto tag_bytes = bytes.slice(offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - - // ICC v4, 9 Tag definitions - // ICC v4, 9.1 General - // "All tags, including private tags, have as their first four bytes a tag signature to identify to profile readers - // what kind of data is contained within a tag." - if (tag_bytes.size() < sizeof(u32)) - return Error::from_string_literal("ICC::Profile: Not enough data for tag type"); - - auto type = tag_type(tag_bytes); - switch (type) { - case ChromaticityTagData::Type: - return ChromaticityTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case CicpTagData::Type: - return CicpTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case CurveTagData::Type: - return CurveTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case Lut16TagData::Type: - return Lut16TagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case Lut8TagData::Type: - return Lut8TagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case LutAToBTagData::Type: - return LutAToBTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case LutBToATagData::Type: - return LutBToATagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case MeasurementTagData::Type: - return MeasurementTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case MultiLocalizedUnicodeTagData::Type: - return MultiLocalizedUnicodeTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case NamedColor2TagData::Type: - return NamedColor2TagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case ParametricCurveTagData::Type: - return ParametricCurveTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case S15Fixed16ArrayTagData::Type: - return S15Fixed16ArrayTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case SignatureTagData::Type: - return SignatureTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case TextDescriptionTagData::Type: - return TextDescriptionTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case TextTagData::Type: - return TextTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case ViewingConditionsTagData::Type: - return ViewingConditionsTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - case XYZTagData::Type: - return XYZTagData::from_bytes(tag_bytes, offset_to_beginning_of_tag_data_element, size_of_tag_data_element); - default: - // FIXME: optionally ignore tags of unknown type - return try_make_ref_counted(offset_to_beginning_of_tag_data_element, size_of_tag_data_element, type); - } -} - -static ErrorOr>> read_tag_table(ReadonlyBytes bytes) -{ - OrderedHashMap> tag_table; - - // ICC v4, 7.3 Tag table - // ICC v4, 7.3.1 Overview - // "The tag table acts as a table of contents for the tags and an index into the tag data element in the profiles. It - // shall consist of a 4-byte entry that contains a count of the number of tags in the table followed by a series of 12- - // byte entries with one entry for each tag. The tag table therefore contains 4+12n bytes where n is the number of - // tags contained in the profile. The entries for the tags within the table are not required to be in any particular - // order nor are they required to match the sequence of tag data element within the profile. - // Each 12-byte tag entry following the tag count shall consist of a 4-byte tag signature, a 4-byte offset to define - // the beginning of the tag data element, and a 4-byte entry identifying the length of the tag data element in bytes. - // [...] - // The tag table shall define a contiguous sequence of unique tag elements, with no gaps between the last byte - // of any tag data element referenced from the tag table (inclusive of any necessary additional pad bytes required - // to reach a four-byte boundary) and the byte offset of the following tag element, or the end of the file. - // Duplicate tag signatures shall not be included in the tag table. - // Tag data elements shall not partially overlap, so there shall be no part of any tag data element that falls within - // the range defined for another tag in the tag table." - - ReadonlyBytes tag_table_bytes = bytes.slice(sizeof(ICCHeader)); - - if (tag_table_bytes.size() < sizeof(u32)) - return Error::from_string_literal("ICC::Profile: Not enough data for tag count"); - auto tag_count = *bit_cast const*>(tag_table_bytes.data()); - - tag_table_bytes = tag_table_bytes.slice(sizeof(u32)); - if (tag_table_bytes.size() < tag_count * sizeof(TagTableEntry)) - return Error::from_string_literal("ICC::Profile: Not enough data for tag table entries"); - auto tag_table_entries = bit_cast(tag_table_bytes.data()); - - // "The tag table may contain multiple tags signatures that all reference the same tag data element offset, allowing - // efficient reuse of tag data elements." - HashMap> offset_to_tag_data; - - for (u32 i = 0; i < tag_count; ++i) { - // FIXME: optionally ignore tags with unknown signature - - // Dedupe identical offset/sizes. - NonnullRefPtr tag_data = TRY(offset_to_tag_data.try_ensure(tag_table_entries[i].offset_to_beginning_of_tag_data_element, [&]() { - return read_tag(bytes, tag_table_entries[i].offset_to_beginning_of_tag_data_element, tag_table_entries[i].size_of_tag_data_element); - })); - - // "In such cases, both the offset and size of the tag data elements in the tag table shall be the same." - if (tag_data->size() != tag_table_entries[i].size_of_tag_data_element) - return Error::from_string_literal("ICC::Profile: two tags have same offset but different sizes"); - - // "Duplicate tag signatures shall not be included in the tag table." - if (TRY(tag_table.try_set(tag_table_entries[i].tag_signature, move(tag_data))) != AK::HashSetResult::InsertedNewEntry) - return Error::from_string_literal("ICC::Profile: duplicate tag signature"); - } - - return tag_table; -} - -static bool is_xCLR(ColorSpace color_space) -{ - switch (color_space) { - case ColorSpace::TwoColor: - case ColorSpace::ThreeColor: - case ColorSpace::FourColor: - case ColorSpace::FiveColor: - case ColorSpace::SixColor: - case ColorSpace::SevenColor: - case ColorSpace::EightColor: - case ColorSpace::NineColor: - case ColorSpace::TenColor: - case ColorSpace::ElevenColor: - case ColorSpace::TwelveColor: - case ColorSpace::ThirteenColor: - case ColorSpace::FourteenColor: - case ColorSpace::FifteenColor: - return true; - default: - return false; - } -} - -ErrorOr Profile::check_required_tags() -{ - // ICC v4, 8 Required tags - - // ICC v4, 8.2 Common requirements - // "With the exception of DeviceLink profiles, all profiles shall contain the following tags: - // - profileDescriptionTag (see 9.2.41); - // - copyrightTag (see 9.2.21); - // - mediaWhitePointTag (see 9.2.34); - // - chromaticAdaptationTag, when the measurement data used to calculate the profile was specified for an - // adopted white with a chromaticity different from that of the PCS adopted white (see 9.2.15). - // NOTE A DeviceLink profile is not required to have either a mediaWhitePointTag or a chromaticAdaptationTag." - // profileDescriptionTag, copyrightTag are required for DeviceLink too (see ICC v4, 8.6 DeviceLink profile). - // profileDescriptionTag, copyrightTag, mediaWhitePointTag are required in ICC v2 as well. - // chromaticAdaptationTag isn't required in v2 profiles as far as I can tell. - - if (!m_tag_table.contains(profileDescriptionTag)) - return Error::from_string_literal("ICC::Profile: required profileDescriptionTag is missing"); - - if (!m_tag_table.contains(copyrightTag)) - return Error::from_string_literal("ICC::Profile: required copyrightTag is missing"); - - if (device_class() != DeviceClass::DeviceLink) { - if (!m_tag_table.contains(mediaWhitePointTag)) - return Error::from_string_literal("ICC::Profile: required mediaWhitePointTag is missing"); - - // FIXME: Check for chromaticAdaptationTag after figuring out when exactly it needs to be present. - } - - auto has_tag = [&](auto& tag) { return m_tag_table.contains(tag); }; - auto has_all_tags = [&](T tags) { return all_of(tags, has_tag); }; - - switch (device_class()) { - case DeviceClass::InputDevice: { - // ICC v4, 8.3 Input profiles - // "8.3.1 General - // Input profiles are generally used with devices such as scanners and digital cameras. The types of profiles - // available for use as Input profiles are N-component LUT-based, Three-component matrix-based, and - // monochrome. - // 8.3.2 N-component LUT-based Input profiles - // In addition to the tags listed in 8.2 an N-component LUT-based Input profile shall contain the following tag: - // - AToB0Tag (see 9.2.1). - // 8.3.3 Three-component matrix-based Input profiles - // In addition to the tags listed in 8.2, a three-component matrix-based Input profile shall contain the following tags: - // - redMatrixColumnTag (see 9.2.44); - // - greenMatrixColumnTag (see 9.2.30); - // - blueMatrixColumnTag (see 9.2.4); - // - redTRCTag (see 9.2.45); - // - greenTRCTag (see 9.2.31); - // - blueTRCTag (see 9.2.5). - // [...] Only the PCSXYZ encoding can be used with matrix/TRC models. - // 8.3.4 Monochrome Input profiles - // In addition to the tags listed in 8.2, a monochrome Input profile shall contain the following tag: - // - grayTRCTag (see 9.2.29)." - bool has_n_component_lut_based_tags = has_tag(AToB0Tag); - bool has_three_component_matrix_based_tags = has_all_tags(Array { redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag, redTRCTag, greenTRCTag, blueTRCTag }); - bool has_monochrome_tags = has_tag(grayTRCTag); - if (!has_n_component_lut_based_tags && !has_three_component_matrix_based_tags && !has_monochrome_tags) - return Error::from_string_literal("ICC::Profile: InputDevice required tags are missing"); - if (!has_n_component_lut_based_tags && has_three_component_matrix_based_tags && connection_space() != ColorSpace::PCSXYZ) - return Error::from_string_literal("ICC::Profile: InputDevice three-component matrix-based profile must use PCSXYZ"); - break; - } - case DeviceClass::DisplayDevice: { - // ICC v4, 8.4 Display profiles - // "8.4.1 General - // This class of profiles represents display devices such as monitors. The types of profiles available for use as - // Display profiles are N-component LUT-based, Three-component matrix-based, and monochrome. - // 8.4.2 N-Component LUT-based Display profiles - // In addition to the tags listed in 8.2 an N-component LUT-based Input profile shall contain the following tags: - // - AToB0Tag (see 9.2.1); - // - BToA0Tag (see 9.2.6). - // 8.4.3 Three-component matrix-based Display profiles - // In addition to the tags listed in 8.2, a three-component matrix-based Display profile shall contain the following - // tags: - // - redMatrixColumnTag (see 9.2.44); - // - greenMatrixColumnTag (see 9.2.30); - // - blueMatrixColumnTag (see 9.2.4); - // - redTRCTag (see 9.2.45); - // - greenTRCTag (see 9.2.31); - // - blueTRCTag (see 9.2.5). - // [...] Only the PCSXYZ encoding can be used with matrix/TRC models. - // 8.4.4 Monochrome Display profiles - // In addition to the tags listed in 8.2 a monochrome Display profile shall contain the following tag: - // - grayTRCTag (see 9.2.29)." - bool has_n_component_lut_based_tags = has_all_tags(Array { AToB0Tag, BToA0Tag }); - bool has_three_component_matrix_based_tags = has_all_tags(Array { redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag, redTRCTag, greenTRCTag, blueTRCTag }); - bool has_monochrome_tags = has_tag(grayTRCTag); - if (!has_n_component_lut_based_tags && !has_three_component_matrix_based_tags && !has_monochrome_tags) - return Error::from_string_literal("ICC::Profile: DisplayDevice required tags are missing"); - if (!has_n_component_lut_based_tags && has_three_component_matrix_based_tags && connection_space() != ColorSpace::PCSXYZ) - return Error::from_string_literal("ICC::Profile: DisplayDevice three-component matrix-based profile must use PCSXYZ"); - break; - } - case DeviceClass::OutputDevice: { - // ICC v4, 8.5 Output profiles - // "8.5.1 General - // Output profiles are used to support devices such as printers and film recorders. The types of profiles available - // for use as Output profiles are N-component LUT-based and Monochrome. - // 8.5.2 N-component LUT-based Output profiles - // In addition to the tags listed in 8.2 an N-component LUT-based Output profile shall contain the following tags: - // - AToB0Tag (see 9.2.1); - // - AToB1Tag (see 9.2.2); - // - AToB2Tag (see 9.2.3); - // - BToA0Tag (see 9.2.6); - // - BToA1Tag (see 9.2.7); - // - BToA2Tag (see 9.2.8); - // - gamutTag (see 9.2.28); - // - colorantTableTag (see 9.2.18), for the xCLR colour spaces (see 7.2.6) - // 8.5.3 Monochrome Output profiles - // In addition to the tags listed in 8.2 a monochrome Output profile shall contain the following tag: - // - grayTRCTag (see 9.2.29)." - // The colorantTableTag requirement is new in v4. - Vector required_n_component_lut_based_tags = { AToB0Tag, AToB1Tag, AToB2Tag, BToA0Tag, BToA1Tag, BToA2Tag, gamutTag }; - if (is_v4() && is_xCLR(connection_space())) - required_n_component_lut_based_tags.append(colorantTableTag); - bool has_n_component_lut_based_tags = has_all_tags(required_n_component_lut_based_tags); - bool has_monochrome_tags = has_tag(grayTRCTag); - if (!has_n_component_lut_based_tags && !has_monochrome_tags) - return Error::from_string_literal("ICC::Profile: OutputDevice required tags are missing"); - break; - } - case DeviceClass::DeviceLink: { - // ICC v4, 8.6 DeviceLink profile - // "A DeviceLink profile shall contain the following tags: - // - profileDescriptionTag (see 9.2.41); - // - copyrightTag (see 9.2.21); - // - profileSequenceDescTag (see 9.2.42); - // - AToB0Tag (see 9.2.1); - // - colorantTableTag (see 9.2.18) which is required only if the data colour space field is xCLR, where x is - // hexadecimal 2 to F (see 7.2.6); - // - colorantTableOutTag (see 9.2.19), required only if the PCS field is xCLR, where x is hexadecimal 2 to F - // (see 7.2.6)" - // profileDescriptionTag and copyrightTag are already checked above, in the code for section 8.2. - Vector required_tags = { profileSequenceDescTag, AToB0Tag }; - if (is_v4() && is_xCLR(connection_space())) { // This requirement is new in v4. - required_tags.append(colorantTableTag); - required_tags.append(colorantTableOutTag); - } - if (!has_all_tags(required_tags)) - return Error::from_string_literal("ICC::Profile: DeviceLink required tags are missing"); - // "The data colour space field (see 7.2.6) in the DeviceLink profile will be the same as the data colour space field - // of the first profile in the sequence used to construct the device link. The PCS field (see 7.2.7) will be the same - // as the data colour space field of the last profile in the sequence." - // FIXME: Check that if profileSequenceDescType parsing is implemented. - break; - } - case DeviceClass::ColorSpace: - // ICC v4, 8.7 ColorSpace profile - // "In addition to the tags listed in 8.2, a ColorSpace profile shall contain the following tags: - // - BToA0Tag (see 9.2.6); - // - AToB0Tag (see 9.2.1). - // [...] ColorSpace profiles may be embedded in images." - if (!has_all_tags(Array { AToB0Tag, BToA0Tag })) - return Error::from_string_literal("ICC::Profile: ColorSpace required tags are missing"); - break; - case DeviceClass::Abstract: - // ICC v4, 8.8 Abstract profile - // "In addition to the tags listed in 8.2, an Abstract profile shall contain the following tag: - // - AToB0Tag (see 9.2.1). - // [...] Abstract profiles cannot be embedded in images." - if (!has_tag(AToB0Tag)) - return Error::from_string_literal("ICC::Profile: Abstract required AToB0Tag is missing"); - break; - case DeviceClass::NamedColor: - // ICC v4, 8.9 NamedColor profile - // "In addition to the tags listed in 8.2, a NamedColor profile shall contain the following tag: - // - namedColor2Tag (see 9.2.35)." - if (!has_tag(namedColor2Tag)) - return Error::from_string_literal("ICC::Profile: NamedColor required namedColor2Tag is missing"); - break; - } - - m_cached_has_any_a_to_b_tag = has_tag(AToB0Tag) || has_tag(AToB1Tag) || has_tag(AToB2Tag); - m_cached_has_a_to_b0_tag = has_tag(AToB0Tag); - m_cached_has_any_b_to_a_tag = has_tag(BToA0Tag) || has_tag(BToA1Tag) || has_tag(BToA2Tag); - m_cached_has_b_to_a0_tag = has_tag(BToA0Tag); - m_cached_has_all_rgb_matrix_tags = has_all_tags(Array { redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag, redTRCTag, greenTRCTag, blueTRCTag }); - - return {}; -} - -ErrorOr Profile::check_tag_types() -{ - // This uses m_tag_table.get() even for tags that are guaranteed to exist after check_required_tags() - // so that the two functions can be called in either order. - - // Profile ID of /System/Library/ColorSync/Profiles/ITU-2020.icc on macOS 13.1. - static constexpr Crypto::Hash::MD5::DigestType apple_itu_2020_id = { 0x57, 0x0b, 0x1b, 0x76, 0xc6, 0xa0, 0x50, 0xaa, 0x9f, 0x6c, 0x53, 0x8d, 0xbe, 0x2d, 0x3e, 0xf0 }; - - // Profile ID of the "Display P3" profiles embedded in the images on https://webkit.org/blog-files/color-gamut/comparison.html - // (The macOS 13.1 /System/Library/ColorSync/Profiles/Display\ P3.icc file no longer has this quirk.) - static constexpr Crypto::Hash::MD5::DigestType apple_p3_2015_id = { 0xe5, 0xbb, 0x0e, 0x98, 0x67, 0xbd, 0x46, 0xcd, 0x4b, 0xbe, 0x44, 0x6e, 0xbd, 0x1b, 0x75, 0x98 }; - - // Profile ID of the "Display P3" profile in object 881 in https://fredrikbk.com/publications/copy-and-patch.pdf - // (The macOS 13.1 /System/Library/ColorSync/Profiles/Display\ P3.icc file no longer has this quirk.) - static constexpr Crypto::Hash::MD5::DigestType apple_p3_2017_id = { 0xca, 0x1a, 0x95, 0x82, 0x25, 0x7f, 0x10, 0x4d, 0x38, 0x99, 0x13, 0xd5, 0xd1, 0xea, 0x15, 0x82 }; - - auto has_type = [&](auto tag, std::initializer_list types, std::initializer_list v4_types) { - if (auto type = m_tag_table.get(tag); type.has_value()) { - auto type_matches = [&](auto wanted_type) { return type.value()->type() == wanted_type; }; - return any_of(types, type_matches) || (is_v4() && any_of(v4_types, type_matches)); - } - return true; - }; - - // ICC v4, 9.2.1 AToB0Tag - // "Permitted tag types: lut8Type or lut16Type or lutAToBType" - // ICC v2, 6.4.1 AToB0Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(AToB0Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutAToBTagData::Type })) - return Error::from_string_literal("ICC::Profile: AToB0Tag has unexpected type"); - - // ICC v4, 9.2.2 AToB1Tag - // "Permitted tag types: lut8Type or lut16Type or lutAToBType" - // ICC v2, 6.4.2 AToB1Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(AToB1Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutAToBTagData::Type })) - return Error::from_string_literal("ICC::Profile: AToB1Tag has unexpected type"); - - // ICC v4, 9.2.3 AToB2Tag - // "Permitted tag types: lut8Type or lut16Type or lutAToBType" - // ICC v2, 6.4.3 AToB2Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(AToB2Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutAToBTagData::Type })) - return Error::from_string_literal("ICC::Profile: AToB2Tag has unexpected type"); - - // ICC v4, 9.2.4 blueMatrixColumnTag - // "Permitted tag types: XYZType - // This tag contains the third column in the matrix used in matrix/TRC transforms." - // (Called blueColorantTag in the v2 spec, otherwise identical there.) - if (auto type = m_tag_table.get(blueMatrixColumnTag); type.has_value()) { - if (type.value()->type() != XYZTagData::Type) - return Error::from_string_literal("ICC::Profile: blueMatrixColumnTag has unexpected type"); - if (static_cast(*type.value()).xyzs().size() != 1) - return Error::from_string_literal("ICC::Profile: blueMatrixColumnTag has unexpected size"); - } - - // ICC v4, 9.2.5 blueTRCTag - // "Permitted tag types: curveType or parametricCurveType" - // ICC v2, 6.4.5 blueTRCTag - // "Tag Type: curveType" - if (!has_type(blueTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type })) - return Error::from_string_literal("ICC::Profile: blueTRCTag has unexpected type"); - - // ICC v4, 9.2.6 BToA0Tag - // "Permitted tag types: lut8Type or lut16Type or lutBToAType" - // ICC v2, 6.4.6 BToA0Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(BToA0Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: BToA0Tag has unexpected type"); - - // ICC v4, 9.2.7 BToA1Tag - // "Permitted tag types: lut8Type or lut16Type or lutBToAType" - // ICC v2, 6.4.7 BToA1Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(BToA1Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: BToA1Tag has unexpected type"); - - // ICC v4, 9.2.8 BToA2Tag - // "Permitted tag types: lut8Type or lut16Type or lutBToAType" - // ICC v2, 6.4.8 BToA2Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(BToA2Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: BToA2Tag has unexpected type"); - - // ICC v4, 9.2.9 BToD0Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.10 BToD1Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.11 BToD2Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.12 BToD3Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.13 calibrationDateTimeTag - // "Permitted tag types: dateTimeType" - // FIXME - - // ICC v4, 9.2.14 charTargetTag - // "Permitted tag types: textType" - if (!has_type(charTargetTag, { TextTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: charTargetTag has unexpected type"); - - // ICC v4, 9.2.15 chromaticAdaptationTag - // "Permitted tag types: s15Fixed16ArrayType [...] - // Such a 3 x 3 chromatic adaptation matrix is organized as a 9-element array" - if (auto type = m_tag_table.get(chromaticAdaptationTag); type.has_value()) { - if (type.value()->type() != S15Fixed16ArrayTagData::Type) - return Error::from_string_literal("ICC::Profile: chromaticAdaptationTag has unexpected type"); - if (static_cast(*type.value()).values().size() != 9) - return Error::from_string_literal("ICC::Profile: chromaticAdaptationTag has unexpected size"); - } - - // ICC v4, 9.2.16 chromaticityTag - // "Permitted tag types: chromaticityType" - if (!has_type(chromaticityTag, { ChromaticityTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: ChromaticityTagData has unexpected type"); - - // ICC v4, 9.2.17 cicpTag - // "Permitted tag types: cicpType" - if (auto type = m_tag_table.get(cicpTag); type.has_value()) { - if (type.value()->type() != CicpTagData::Type) - return Error::from_string_literal("ICC::Profile: cicpTag has unexpected type"); - - // "The colour encoding specified by the CICP tag content shall be equivalent to the data colour space encoding - // represented by this ICC profile. - // NOTE The ICC colour transform cannot match every possible rendering of a CICP colour encoding." - // FIXME: Figure out what that means and check for it. - - // "This tag may be present when the data colour space in the profile header is RGB, YCbCr, or XYZ, and the - // profile class in the profile header is Input or Display. The tag shall not be present for other data colour spaces - // or profile classes indicated in the profile header." - bool is_color_space_allowed = data_color_space() == ColorSpace::RGB || data_color_space() == ColorSpace::YCbCr || data_color_space() == ColorSpace::nCIEXYZ; - bool is_profile_class_allowed = device_class() == DeviceClass::InputDevice || device_class() == DeviceClass::DisplayDevice; - bool cicp_is_allowed = is_color_space_allowed && is_profile_class_allowed; - if (!cicp_is_allowed) - return Error::from_string_literal("ICC::Profile: cicpTag present but not allowed"); - } - - // ICC v4, 9.2.18 colorantOrderTag - // "Permitted tag types: colorantOrderType" - // FIXME - - // ICC v4, 9.2.19 colorantTableTag - // "Permitted tag types: colorantTableType" - // FIXME - - // ICC v4, 9.2.20 colorantTableOutTag - // "Permitted tag types: colorantTableType" - // FIXME - - // ICC v4, 9.2.21 colorimetricIntentImageStateTag - // "Permitted tag types: signatureType" - if (!has_type(colorimetricIntentImageStateTag, { SignatureTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: colorimetricIntentImageStateTag has unexpected type"); - - // ICC v4, 9.2.22 copyrightTag - // "Permitted tag types: multiLocalizedUnicodeType" - // ICC v2, 6.4.13 copyrightTag - // "Tag Type: textType" - if (auto type = m_tag_table.get(copyrightTag); type.has_value()) { - // The v4 spec requires multiLocalizedUnicodeType for this, but I'm aware of a single file - // that still uses the v2 'text' type here: /System/Library/ColorSync/Profiles/ITU-2020.icc on macOS 13.1. - // https://openradar.appspot.com/radar?id=5529765549178880 - bool has_v2_cprt_type_in_v4_file_quirk = id() == apple_itu_2020_id || id() == apple_p3_2015_id || id() == apple_p3_2017_id; - if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type && (!has_v2_cprt_type_in_v4_file_quirk || type.value()->type() != TextTagData::Type)) - return Error::from_string_literal("ICC::Profile: copyrightTag has unexpected v4 type"); - if (is_v2() && type.value()->type() != TextTagData::Type) - return Error::from_string_literal("ICC::Profile: copyrightTag has unexpected v2 type"); - } - - // ICC v4, 9.2.23 deviceMfgDescTag - // "Permitted tag types: multiLocalizedUnicodeType" - // ICC v2, 6.4.15 deviceMfgDescTag - // "Tag Type: textDescriptionType" - if (auto type = m_tag_table.get(deviceMfgDescTag); type.has_value()) { - if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type) - return Error::from_string_literal("ICC::Profile: deviceMfgDescTag has unexpected v4 type"); - if (is_v2() && type.value()->type() != TextDescriptionTagData::Type) - return Error::from_string_literal("ICC::Profile: deviceMfgDescTag has unexpected v2 type"); - } - - // ICC v4, 9.2.24 deviceModelDescTag - // "Permitted tag types: multiLocalizedUnicodeType" - // ICC v2, 6.4.16 deviceModelDescTag - // "Tag Type: textDescriptionType" - if (auto type = m_tag_table.get(deviceModelDescTag); type.has_value()) { - if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type) - return Error::from_string_literal("ICC::Profile: deviceModelDescTag has unexpected v4 type"); - if (is_v2() && type.value()->type() != TextDescriptionTagData::Type) - return Error::from_string_literal("ICC::Profile: deviceModelDescTag has unexpected v2 type"); - } - - // ICC v4, 9.2.25 DToB0Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.26 DToB1Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.27 DToB2Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.28 DToB3Tag - // "Permitted tag types: multiProcessElementsType" - // FIXME - - // ICC v4, 9.2.29 gamutTag - // "Permitted tag types: lut8Type or lut16Type or lutBToAType" - // ICC v2, 6.4.18 gamutTag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(gamutTag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: gamutTag has unexpected type"); - - // ICC v4, 9.2.30 grayTRCTag - // "Permitted tag types: curveType or parametricCurveType" - // ICC v2, 6.4.19 grayTRCTag - // "Tag Type: curveType" - if (!has_type(grayTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type })) - return Error::from_string_literal("ICC::Profile: grayTRCTag has unexpected type"); - - // ICC v4, 9.2.31 greenMatrixColumnTag - // "Permitted tag types: XYZType - // This tag contains the second column in the matrix, which is used in matrix/TRC transforms." - // (Called greenColorantTag in the v2 spec, otherwise identical there.) - if (auto type = m_tag_table.get(greenMatrixColumnTag); type.has_value()) { - if (type.value()->type() != XYZTagData::Type) - return Error::from_string_literal("ICC::Profile: greenMatrixColumnTag has unexpected type"); - if (static_cast(*type.value()).xyzs().size() != 1) - return Error::from_string_literal("ICC::Profile: greenMatrixColumnTag has unexpected size"); - } - - // ICC v4, 9.2.32 greenTRCTag - // "Permitted tag types: curveType or parametricCurveType" - // ICC v2, 6.4.21 greenTRCTag - // "Tag Type: curveType" - if (!has_type(greenTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type })) - return Error::from_string_literal("ICC::Profile: greenTRCTag has unexpected type"); - - // ICC v4, 9.2.33 luminanceTag - // "Permitted tag types: XYZType" - // This tag contains the absolute luminance of emissive devices in candelas per square metre as described by the - // Y channel. - // NOTE The X and Z values are set to zero." - // ICC v2, 6.4.22 luminanceTag - // "Absolute luminance of emissive devices in candelas per square meter as described by the Y channel. The - // X and Z channels are ignored in all cases." - if (auto type = m_tag_table.get(luminanceTag); type.has_value()) { - if (type.value()->type() != XYZTagData::Type) - return Error::from_string_literal("ICC::Profile: luminanceTag has unexpected type"); - auto& xyz_type = static_cast(*type.value()); - if (xyz_type.xyzs().size() != 1) - return Error::from_string_literal("ICC::Profile: luminanceTag has unexpected size"); - if (is_v4() && xyz_type.xyzs()[0].X != 0) - return Error::from_string_literal("ICC::Profile: luminanceTag.x unexpectedly not 0"); - if (is_v4() && xyz_type.xyzs()[0].Z != 0) - return Error::from_string_literal("ICC::Profile: luminanceTag.z unexpectedly not 0"); - } - - // ICC v4, 9.2.34 measurementTag - // "Permitted tag types: measurementType" - if (!has_type(measurementTag, { MeasurementTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: measurementTag has unexpected type"); - - // ICC v4, 9.2.35 metadataTag - // "Permitted tag types: dictType" - // FIXME - - // ICC v4, 9.2.36 mediaWhitePointTag - // "Permitted tag types: XYZType - // This tag, which is used for generating the ICC-absolute colorimetric intent, specifies the chromatically adapted - // nCIEXYZ tristimulus values of the media white point. When the measurement data used to create the profile - // were specified relative to an adopted white with a chromaticity different from that of the PCS adopted white, the - // media white point nCIEXYZ values shall be adapted to be relative to the PCS adopted white chromaticity using - // the chromaticAdaptationTag matrix, before recording in the tag. For capture devices, the media white point is - // the encoding maximum white for the capture encoding. For displays, the values specified shall be those of the - // PCS illuminant as defined in 7.2.16. - // See Clause 6 and Annex A for a more complete description of the use of the media white point." - // ICC v2, 6.4.25 mediaWhitePointTag - // "This tag specifies the media white point and is used for generating ICC-absolute colorimetric intent. See - // Annex A for a more complete description of its use." - if (auto type = m_tag_table.get(mediaWhitePointTag); type.has_value()) { - if (type.value()->type() != XYZTagData::Type) - return Error::from_string_literal("ICC::Profile: mediaWhitePointTag has unexpected type"); - auto& xyz_type = static_cast(*type.value()); - if (xyz_type.xyzs().size() != 1) - return Error::from_string_literal("ICC::Profile: mediaWhitePointTag has unexpected size"); - - // V4 requires "For displays, the values specified shall be those of the PCS illuminant". - // But in practice that's not always true. For example, on macOS 13.1, '/System/Library/ColorSync/Profiles/DCI(P3) RGB.icc' - // has these values in the header: 0000F6D6 00010000 0000D32D - // but these values in the tag: 0000F6D5 00010000 0000D32C - // These are close, but not equal. - // FIXME: File bug for these, and add id-based quirk instead. - // if (is_v4() && device_class() == DeviceClass::DisplayDevice && xyz_type.xyzs()[0] != pcs_illuminant()) - // return Error::from_string_literal("ICC::Profile: mediaWhitePointTag for displays should be equal to PCS illuminant"); - } - - // ICC v4, 9.2.37 namedColor2Tag - // "Permitted tag types: namedColor2Type" - if (auto type = m_tag_table.get(namedColor2Tag); type.has_value()) { - if (type.value()->type() != NamedColor2TagData::Type) - return Error::from_string_literal("ICC::Profile: namedColor2Tag has unexpected type"); - // ICC v4, 10.17 namedColor2Type - // "The device representation corresponds to the header’s “data colour space” field. - // This representation should be consistent with the “number of device coordinates” field in the namedColor2Type. - // If this field is 0, device coordinates are not provided." - if (auto number_of_device_coordinates = static_cast(*type.value()).number_of_device_coordinates(); - number_of_device_coordinates != 0 && number_of_device_coordinates != number_of_components_in_color_space(data_color_space())) { - return Error::from_string_literal("ICC::Profile: namedColor2Tag number of device coordinates inconsistent with data color space"); - } - } - - // ICC v4, 9.2.38 outputResponseTag - // "Permitted tag types: responseCurveSet16Type" - // FIXME - - // ICC v4, 9.2.39 perceptualRenderingIntentGamutTag - // "Permitted tag types: signatureType" - if (!has_type(perceptualRenderingIntentGamutTag, { SignatureTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: perceptualRenderingIntentGamutTag has unexpected type"); - - // ICC v4, 9.2.40 preview0Tag - // "Permitted tag types: lut8Type or lut16Type or lutAToBType or lutBToAType" - // ICC v2, 6.4.29 preview0Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(preview0Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type, LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: preview0Tag has unexpected type"); - - // ICC v4, 9.2.41 preview1Tag - // "Permitted tag types: lut8Type or lut16Type or lutBToAType" - // ICC v2, 6.4.30 preview1Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(preview1Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: preview1Tag has unexpected type"); - - // ICC v4, 9.2.42 preview2Tag - // "Permitted tag types: lut8Type or lut16Type or lutBToAType" - // ICC v2, 6.4.31 preview2Tag - // "Tag Type: lut8Type or lut16Type" - if (!has_type(preview2Tag, { Lut8TagData::Type, Lut16TagData::Type }, { LutBToATagData::Type })) - return Error::from_string_literal("ICC::Profile: preview2Tag has unexpected type"); - - // ICC v4, 9.2.43 profileDescriptionTag - // "Permitted tag types: multiLocalizedUnicodeType" - // ICC v2, 6.4.32 profileDescriptionTag - // "Tag Type: textDescriptionType" - if (auto type = m_tag_table.get(profileDescriptionTag); type.has_value()) { - // The v4 spec requires multiLocalizedUnicodeType for this, but I'm aware of a single file - // that still uses the v2 'desc' type here: /System/Library/ColorSync/Profiles/ITU-2020.icc on macOS 13.1. - // https://openradar.appspot.com/radar?id=5529765549178880 - bool has_v2_desc_type_in_v4_file_quirk = id() == apple_itu_2020_id || id() == apple_p3_2015_id || id() == apple_p3_2017_id; - if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type && (!has_v2_desc_type_in_v4_file_quirk || type.value()->type() != TextDescriptionTagData::Type)) - return Error::from_string_literal("ICC::Profile: profileDescriptionTag has unexpected v4 type"); - if (is_v2() && type.value()->type() != TextDescriptionTagData::Type) - return Error::from_string_literal("ICC::Profile: profileDescriptionTag has unexpected v2 type"); - } - - // ICC v4, 9.2.44 profileSequenceDescTag - // "Permitted tag types: profileSequenceDescType" - // FIXME - - // ICC v4, 9.2.45 profileSequenceIdentifierTag - // "Permitted tag types: profileSequenceIdentifierType" - // FIXME - - // ICC v4, 9.2.46 redMatrixColumnTag - // "Permitted tag types: XYZType - // This tag contains the first column in the matrix, which is used in matrix/TRC transforms." - // (Called redColorantTag in the v2 spec, otherwise identical there.) - if (auto type = m_tag_table.get(redMatrixColumnTag); type.has_value()) { - if (type.value()->type() != XYZTagData::Type) - return Error::from_string_literal("ICC::Profile: redMatrixColumnTag has unexpected type"); - if (static_cast(*type.value()).xyzs().size() != 1) - return Error::from_string_literal("ICC::Profile: redMatrixColumnTag has unexpected size"); - } - - // ICC v4, 9.2.47 redTRCTag - // "Permitted tag types: curveType or parametricCurveType" - // ICC v2, 6.4.41 redTRCTag - // "Tag Type: curveType" - if (!has_type(redTRCTag, { CurveTagData::Type }, { ParametricCurveTagData::Type })) - return Error::from_string_literal("ICC::Profile: redTRCTag has unexpected type"); - - // ICC v4, 9.2.48 saturationRenderingIntentGamutTag - // "Permitted tag types: signatureType" - if (!has_type(saturationRenderingIntentGamutTag, { SignatureTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: saturationRenderingIntentGamutTag has unexpected type"); - - // ICC v4, 9.2.49 technologyTag - // "Permitted tag types: signatureType" - if (!has_type(technologyTag, { SignatureTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: technologyTag has unexpected type"); - - // ICC v4, 9.2.50 viewingCondDescTag - // "Permitted tag types: multiLocalizedUnicodeType" - // ICC v2, 6.4.46 viewingCondDescTag - // "Tag Type: textDescriptionType" - if (auto type = m_tag_table.get(viewingCondDescTag); type.has_value()) { - if (is_v4() && type.value()->type() != MultiLocalizedUnicodeTagData::Type) - return Error::from_string_literal("ICC::Profile: viewingCondDescTag has unexpected v4 type"); - if (is_v2() && type.value()->type() != TextDescriptionTagData::Type) - return Error::from_string_literal("ICC::Profile: viewingCondDescTag has unexpected v2 type"); - } - - // ICC v4, 9.2.51 viewingConditionsTag - // "Permitted tag types: viewingConditionsType" - if (!has_type(viewingConditionsTag, { ViewingConditionsTagData::Type }, {})) - return Error::from_string_literal("ICC::Profile: viewingConditionsTag has unexpected type"); - - // FIXME: Add validation for v2-only tags: - // - ICC v2, 6.4.14 crdInfoTag - // "Tag Type: crdInfoType" - // - ICC v2, 6.4.17 deviceSettingsTag - // "Tag Type: deviceSettingsType" - // - ICC v2, 6.4.24 mediaBlackPointTag - // "Tag Type: XYZType" - // - ICC v2, 6.4.26 namedColorTag - // "Tag Type: namedColorType" - // - ICC v2, 6.4.34 ps2CRD0Tag - // "Tag Type: dataType" - // - ICC v2, 6.4.35 ps2CRD1Tag - // "Tag Type: dataType" - // - ICC v2, 6.4.36 ps2CRD2Tag - // "Tag Type: dataType" - // - ICC v2, 6.4.37 ps2CRD3Tag - // "Tag Type: dataType" - // - ICC v2, 6.4.38 ps2CSATag - // "Tag Type: dataType" - // - ICC v2, 6.4.39 ps2RenderingIntentTag - // "Tag Type: dataType" - // - ICC v2, 6.4.42 screeningDescTag - // "Tag Type: textDescriptionType" - // - ICC v2, 6.4.43 screeningTag - // "Tag Type: screeningType" - // - ICC v2, 6.4.45 ucrbgTag - // "Tag Type: ucrbgType" - // https://www.color.org/v2profiles.xalter says about these tags: - // "it is also recommended that optional tags in the v2 specification that have subsequently become - // obsolete are not included in future profiles made to the v2 specification." - - return {}; -} - -ErrorOr> Profile::try_load_from_externally_owned_memory(ReadonlyBytes bytes) -{ - auto header = TRY(read_header(bytes)); - bytes = bytes.trim(header.on_disk_size); - auto tag_table = TRY(read_tag_table(bytes)); - - return create(header, move(tag_table)); -} - -ErrorOr> Profile::create(ProfileHeader const& header, OrderedHashMap> tag_table) -{ - auto profile = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) Profile(header, move(tag_table)))); - - TRY(profile->check_required_tags()); - TRY(profile->check_tag_types()); - - return profile; -} - -Crypto::Hash::MD5::DigestType Profile::compute_id(ReadonlyBytes bytes) -{ - // ICC v4, 7.2.18 Profile ID field - // "The Profile ID shall be calculated using the MD5 fingerprinting method as defined in Internet RFC 1321. - // The entire profile, whose length is given by the size field in the header, with the - // profile flags field (bytes 44 to 47, see 7.2.11), - // rendering intent field (bytes 64 to 67, see 7.2.15), - // and profile ID field (bytes 84 to 99) - // in the profile header temporarily set to zeros (00h), - // shall be used to calculate the ID." - u8 const zero[16] = {}; - Crypto::Hash::MD5 md5; - md5.update(bytes.slice(0, 44)); - md5.update(ReadonlyBytes { zero, 4 }); // profile flags field - md5.update(bytes.slice(48, 64 - 48)); - md5.update(ReadonlyBytes { zero, 4 }); // rendering intent field - md5.update(bytes.slice(68, 84 - 68)); - md5.update(ReadonlyBytes { zero, 16 }); // profile ID field - md5.update(bytes.slice(100)); - return md5.digest(); -} - -static TagSignature forward_transform_tag_for_rendering_intent(RenderingIntent rendering_intent) -{ - // ICCv4, Table 25 — Profile type/profile tag and defined rendering intents - // This function assumes a profile class of InputDevice, DisplayDevice, OutputDevice, or ColorSpace. - switch (rendering_intent) { - case RenderingIntent::Perceptual: - return AToB0Tag; - case RenderingIntent::MediaRelativeColorimetric: - case RenderingIntent::ICCAbsoluteColorimetric: - return AToB1Tag; - case RenderingIntent::Saturation: - return AToB2Tag; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr Profile::to_pcs_a_to_b(TagData const& tag_data, ReadonlyBytes color) const -{ - // Assumes a "normal" device_class() (i.e. not DeviceLink). - VERIFY(number_of_components_in_color_space(connection_space()) == 3); - - if (m_to_pcs_clut_cache.has_value() && m_to_pcs_clut_cache->key == color) - return m_to_pcs_clut_cache->value; - - FloatVector3 result; - - switch (tag_data.type()) { - case Lut16TagData::Type: { - auto const& a_to_b = static_cast(tag_data); - result = TRY(a_to_b.evaluate(data_color_space(), connection_space(), color)); - break; - } - case Lut8TagData::Type: { - auto const& a_to_b = static_cast(tag_data); - result = TRY(a_to_b.evaluate(data_color_space(), connection_space(), color)); - break; - } - case LutAToBTagData::Type: { - auto const& a_to_b = static_cast(tag_data); - if (a_to_b.number_of_input_channels() != number_of_components_in_color_space(data_color_space())) - return Error::from_string_literal("ICC::Profile::to_pcs_a_to_b: mAB input channel count does not match color space size"); - - if (a_to_b.number_of_output_channels() != number_of_components_in_color_space(connection_space())) - return Error::from_string_literal("ICC::Profile::to_pcs_a_to_b: mAB output channel count does not match profile connection space size"); - - result = TRY(a_to_b.evaluate(connection_space(), color)); - break; - } - default: - VERIFY_NOT_REACHED(); - } - - if (!m_to_pcs_clut_cache.has_value()) - m_to_pcs_clut_cache = OneElementCLUTCache {}; - m_to_pcs_clut_cache->key = Vector(color); - m_to_pcs_clut_cache->value = result; - - return result; -} - -ErrorOr Profile::to_pcs(ReadonlyBytes color) const -{ - if (color.size() != number_of_components_in_color_space(data_color_space())) - return Error::from_string_literal("ICC::Profile: input color doesn't match color space size"); - - auto get_tag = [&](auto tag) { return m_tag_table.get(tag); }; - - switch (device_class()) { - case DeviceClass::InputDevice: - case DeviceClass::DisplayDevice: - case DeviceClass::OutputDevice: - case DeviceClass::ColorSpace: { - // ICC v4, 8.10 Precedence order of tag usage - // "There are several methods of colour transformation that can function within a single CMM. If data for more than - // one method are included in the same profile, the following selection algorithm shall be used by the software - // implementation." - // ICC v4, 8.10.2 Input, display, output, or colour space profile types - // "a) Use the BToD0Tag, BToD1Tag, BToD2Tag, BToD3Tag, DToB0Tag, DToB1Tag, DToB2Tag, or - // DToB3Tag designated for the rendering intent if the tag is present, except where this tag is not needed or - // supported by the CMM (if a particular processing element within the tag is not supported the tag is not - // supported)." - // FIXME: Implement multiProcessElementsType one day. - - // "b) Use the BToA0Tag, BToA1Tag, BToA2Tag, AToB0Tag, AToB1Tag, or AToB2Tag designated for the - // rendering intent if present, when the tag in a) is not used." - if (m_cached_has_any_a_to_b_tag) - if (auto tag = get_tag(forward_transform_tag_for_rendering_intent(rendering_intent())); tag.has_value()) - return to_pcs_a_to_b(*tag.value(), color); - - // "c) Use the BToA0Tag or AToB0Tag if present, when the tags in a) and b) are not used." - // AToB0Tag is for the conversion _to_ PCS (BToA0Tag is for conversion _from_ PCS, so not needed in this function). - if (m_cached_has_a_to_b0_tag) - if (auto tag = get_tag(AToB0Tag); tag.has_value()) - return to_pcs_a_to_b(*tag.value(), color); - - // "d) Use TRCs (redTRCTag, greenTRCTag, blueTRCTag, or grayTRCTag) and colorants - // (redMatrixColumnTag, greenMatrixColumnTag, blueMatrixColumnTag) when tags in a), b), and c) are not - // used." - auto evaluate_curve = [this](TagSignature curve_tag, float f) { - auto const& trc = *m_tag_table.get(curve_tag).value(); - VERIFY(trc.type() == CurveTagData::Type || trc.type() == ParametricCurveTagData::Type); - if (trc.type() == CurveTagData::Type) - return static_cast(trc).evaluate(f); - return static_cast(trc).evaluate(f); - }; - - if (data_color_space() == ColorSpace::Gray) { - VERIFY(color.size() == 1); // True because of color.size() check further up. - - // ICC v4, F.2 grayTRCTag - // "connection = grayTRC[device]" - float gray = evaluate_curve(grayTRCTag, color[0] / 255.f); - FloatVector3 white { pcs_illuminant().X, pcs_illuminant().Y, pcs_illuminant().Z }; - return white * gray; - } - - // FIXME: Per ICC v4, A.1 General, this should also handle HLS, HSV, YCbCr. - if (data_color_space() == ColorSpace::RGB) { - if (!m_cached_has_all_rgb_matrix_tags) - return Error::from_string_literal("ICC::Profile::to_pcs: RGB color space but neither LUT-based nor matrix-based tags present"); - VERIFY(color.size() == 3); // True because of color.size() check further up. - - // ICC v4, F.3 Three-component matrix-based profiles - // "linear_r = redTRC[device_r] - // linear_g = greenTRC[device_g] - // linear_b = blueTRC[device_b] - // [connection_X] = [redMatrixColumn_X greenMatrixColumn_X blueMatrixColumn_X] [ linear_r ] - // [connection_Y] = [redMatrixColumn_Y greenMatrixColumn_Y blueMatrixColumn_Y] * [ linear_g ] - // [connection_Z] = [redMatrixColumn_Z greenMatrixColumn_Z blueMatrixColumn_Z] [ linear_b ]" - FloatVector3 linear_rgb { - evaluate_curve(redTRCTag, color[0] / 255.f), - evaluate_curve(greenTRCTag, color[1] / 255.f), - evaluate_curve(blueTRCTag, color[2] / 255.f), - }; - - return rgb_to_xyz_matrix() * linear_rgb; - } - - return Error::from_string_literal("ICC::Profile::to_pcs: What happened?!"); - } - - case DeviceClass::DeviceLink: - case DeviceClass::Abstract: - // ICC v4, 8.10.3 DeviceLink or Abstract profile types - // FIXME - return Error::from_string_literal("ICC::Profile::to_pcs: conversion for DeviceLink and Abstract not implemented"); - - case DeviceClass::NamedColor: - return Error::from_string_literal("ICC::Profile::to_pcs: to_pcs with NamedColor profile does not make sense"); - } - VERIFY_NOT_REACHED(); -} - -static FloatVector3 lab_from_xyz(FloatVector3 xyz, XYZ white_point) -{ - // 6.3.2.2 Translation between media-relative colorimetric data and ICC-absolute colorimetric data - // 6.3.2.3 Computation of PCSLAB - // 6.3.4 Colour space encodings for the PCS - // A.3 PCS encodings - - auto f = [](float x) { - if (x > powf(6.f / 29.f, 3)) - return cbrtf(x); - return x / (3 * powf(6.f / 29.f, 2)) + 4.f / 29.f; - }; - - // "X/Xn is replaced by Xr/Xi (or Xa/Xmw)" - - // 6.3.2.2 Translation between media-relative colorimetric data and ICC-absolute colorimetric data - // "The translation from ICC-absolute colorimetric data to media-relative colorimetry data is given by Equations - // Xr = (Xi/Xmw) * Xa - // where - // Xr media-relative colorimetric data (i.e. PCSXYZ); - // Xa ICC-absolute colorimetric data (i.e. nCIEXYZ); - // Xmw nCIEXYZ values of the media white point as specified in the mediaWhitePointTag; - // Xi PCSXYZ values of the PCS white point defined in 6.3.4.3." - // 6.3.4.3 PCS encodings for white and black - // "Table 14 — Encodings of PCS white point: X 0,9642 Y 1,0000 Z 0,8249" - // That's identical to the values in 7.2.16 PCS illuminant field (Bytes 68 to 79). - // 9.2.36 mediaWhitePointTag - // "For displays, the values specified shall be those of the PCS illuminant as defined in 7.2.16." - // ...so for displays, this is all equivalent I think? It's maybe different for OutputDevice profiles? - - float Xn = white_point.X; - float Yn = white_point.Y; - float Zn = white_point.Z; - - float x = xyz[0] / Xn; - float y = xyz[1] / Yn; - float z = xyz[2] / Zn; - - float L = 116 * f(y) - 16; - float a = 500 * (f(x) - f(y)); - float b = 200 * (f(y) - f(z)); - - return { L, a, b }; -} - -static FloatVector3 xyz_from_lab(FloatVector3 lab, XYZ white_point) -{ - // Inverse of lab_from_xyz(). - auto L_star = lab[0]; - auto a_star = lab[1]; - auto b_star = lab[2]; - - auto L = (L_star + 16) / 116 + a_star / 500; // f(x) - auto M = (L_star + 16) / 116; // f(y) - auto N = (L_star + 16) / 116 - b_star / 200; // f(z) - - // Inverse of f in lab_from_xyz(). - auto g = [](float x) { - if (x >= 6.0f / 29.0f) - return powf(x, 3); - return (x - 4.0f / 29.0f) * (3 * powf(6.f / 29.f, 2)); - }; - - return { white_point.X * g(L), white_point.Y * g(M), white_point.Z * g(N) }; -} - -static TagSignature backward_transform_tag_for_rendering_intent(RenderingIntent rendering_intent) -{ - // ICCv4, Table 25 — Profile type/profile tag and defined rendering intents - // This function assumes a profile class of InputDevice, DisplayDevice, OutputDevice, or ColorSpace. - switch (rendering_intent) { - case RenderingIntent::Perceptual: - return BToA0Tag; - case RenderingIntent::MediaRelativeColorimetric: - case RenderingIntent::ICCAbsoluteColorimetric: - return BToA1Tag; - case RenderingIntent::Saturation: - return BToA2Tag; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr Profile::from_pcs_b_to_a(TagData const& tag_data, FloatVector3 const& pcs, Bytes out_bytes) const -{ - switch (tag_data.type()) { - case Lut16TagData::Type: - // FIXME - return Error::from_string_literal("ICC::Profile::to_pcs: BToA*Tag handling for mft2 tags not yet implemented"); - case Lut8TagData::Type: - // FIXME - return Error::from_string_literal("ICC::Profile::to_pcs: BToA*Tag handling for mft1 tags not yet implemented"); - case LutBToATagData::Type: { - auto const& b_to_a = static_cast(tag_data); - if (b_to_a.number_of_input_channels() != number_of_components_in_color_space(connection_space())) - return Error::from_string_literal("ICC::Profile::from_pcs_b_to_a: mBA input channel count does not match color space size"); - - if (b_to_a.number_of_output_channels() != number_of_components_in_color_space(data_color_space())) - return Error::from_string_literal("ICC::Profile::from_pcs_b_to_a: mBA output channel count does not match profile connection space size"); - - return b_to_a.evaluate(connection_space(), pcs, out_bytes); - } - } - VERIFY_NOT_REACHED(); -} - -ErrorOr Profile::from_pcs(Profile const& source_profile, FloatVector3 pcs, Bytes color) const -{ - if (source_profile.connection_space() != connection_space()) { - if (source_profile.connection_space() == ColorSpace::PCSLAB) { - VERIFY(connection_space() == ColorSpace::PCSXYZ); - pcs = xyz_from_lab(pcs, source_profile.pcs_illuminant()); - } else { - VERIFY(source_profile.connection_space() == ColorSpace::PCSXYZ); - VERIFY(connection_space() == ColorSpace::PCSLAB); - pcs = lab_from_xyz(pcs, pcs_illuminant()); - } - } - - // See `to_pcs()` for spec links. - // This function is very similar, but uses BToAn instead of AToBn for LUT profiles, - // and an inverse transform for matrix profiles. - if (color.size() != number_of_components_in_color_space(data_color_space())) - return Error::from_string_literal("ICC::Profile: output color doesn't match color space size"); - - auto get_tag = [&](auto tag) { return m_tag_table.get(tag); }; - - switch (device_class()) { - case DeviceClass::InputDevice: - case DeviceClass::DisplayDevice: - case DeviceClass::OutputDevice: - case DeviceClass::ColorSpace: { - // FIXME: Implement multiProcessElementsType one day. - - if (m_cached_has_any_b_to_a_tag) - if (auto tag = get_tag(backward_transform_tag_for_rendering_intent(rendering_intent())); tag.has_value()) - return from_pcs_b_to_a(*tag.value(), pcs, color); - - if (m_cached_has_b_to_a0_tag) - if (auto tag = get_tag(BToA0Tag); tag.has_value()) - return from_pcs_b_to_a(*tag.value(), pcs, color); - - if (data_color_space() == ColorSpace::Gray) { - // FIXME - return Error::from_string_literal("ICC::Profile::from_pcs: Gray handling not yet implemented"); - } - - // FIXME: Per ICC v4, A.1 General, this should also handle HLS, HSV, YCbCr. - if (data_color_space() == ColorSpace::RGB) { - if (!m_cached_has_all_rgb_matrix_tags) - return Error::from_string_literal("ICC::Profile::from_pcs: RGB color space but neither LUT-based nor matrix-based tags present"); - VERIFY(color.size() == 3); // True because of color.size() check further up. - - // ICC v4, F.3 Three-component matrix-based profiles - // "The inverse model is given by the following equations: - // [linear_r] = [redMatrixColumn_X greenMatrixColumn_X blueMatrixColumn_X]^-1 [ connection_X ] - // [linear_g] = [redMatrixColumn_Y greenMatrixColumn_Y blueMatrixColumn_Y] * [ connection_Y ] - // [linear_b] = [redMatrixColumn_Z greenMatrixColumn_Z blueMatrixColumn_Z] [ connection_Z ] - // - // for linear_r < 0, device_r = redTRC^-1[0] (F.8) - // for 0 ≤ linear_r ≤ 1, device_r = redTRC^-1[linear_r] (F.9) - // for linear_r > 1, device_r = redTRC^-1[1] (F.10) - // - // for linear_g < 0, device_g = greenTRC^-1[0] (F.11) - // for 0 ≤ linear_g ≤ 1, device_g = greenTRC^-1[linear_g] (F.12) - // for linear_g > 1, device_g = greenTRC^-1[1] (F.13) - // - // for linear_b < 0, device_b = blueTRC^-1[0] (F.14) - // for 0 ≤ linear_b ≤ 1, device_b = blueTRC^-1[linear_b] (F.15) - // for linear_b > 1, device_b = blueTRC^-1[1] (F.16) - // - // where redTRC^-1, greenTRC^-1, and blueTRC^-1 indicate the inverse functions of the redTRC greenTRC and - // blueTRC functions respectively. - // If the redTRC, greenTRC, or blueTRC function is not invertible the behaviour of the corresponding redTRC^-1, - // greenTRC^-1, and blueTRC^-1 function is undefined. If a one-dimensional curve is constant, the curve cannot be - // inverted." - - // Convert from XYZ to linear rgb. - // FIXME: Inverting curves on every call to this function is very inefficient. - FloatVector3 linear_rgb = TRY(xyz_to_rgb_matrix()) * pcs; - - auto evaluate_curve_inverse = [this](TagSignature curve_tag, float f) { - auto const& trc = *m_tag_table.get(curve_tag).value(); - VERIFY(trc.type() == CurveTagData::Type || trc.type() == ParametricCurveTagData::Type); - if (trc.type() == CurveTagData::Type) - return static_cast(trc).evaluate_inverse(f); - return static_cast(trc).evaluate_inverse(f); - }; - - // Convert from linear rgb to device rgb. - // See equations (F.8) - (F.16) above. - // FIXME: The spec says to do this, but it loses information. Color.js returns unclamped - // values instead (...but how do those make it through the TRC?) and has a separate - // clipping step. Maybe that's better? - // Also, maybe doing actual gamut mapping would look better? - // (For LUT profiles, I think the gamut mapping is baked into the BToA* data in the profile (?). - // But for matrix profiles, it'd have to be done in code.) - linear_rgb.clamp(0.f, 1.f); - float device_r = evaluate_curve_inverse(redTRCTag, linear_rgb[0]); - float device_g = evaluate_curve_inverse(greenTRCTag, linear_rgb[1]); - float device_b = evaluate_curve_inverse(blueTRCTag, linear_rgb[2]); - - color[0] = round(255 * device_r); - color[1] = round(255 * device_g); - color[2] = round(255 * device_b); - return {}; - } - - return Error::from_string_literal("ICC::Profile::from_pcs: What happened?!"); - } - - case DeviceClass::DeviceLink: - case DeviceClass::Abstract: - // ICC v4, 8.10.3 DeviceLink or Abstract profile types - // FIXME - return Error::from_string_literal("ICC::Profile::from_pcs: conversion for DeviceLink and Abstract not implemented"); - - case DeviceClass::NamedColor: - return Error::from_string_literal("ICC::Profile::from_pcs: from_pcs with NamedColor profile does not make sense"); - } - VERIFY_NOT_REACHED(); -} - -ErrorOr Profile::to_lab(ReadonlyBytes color) const -{ - auto pcs = TRY(to_pcs(color)); - if (connection_space() == ColorSpace::PCSLAB) - return CIELAB { pcs[0], pcs[1], pcs[2] }; - - if (connection_space() != ColorSpace::PCSXYZ) { - VERIFY(device_class() == DeviceClass::DeviceLink); - return Error::from_string_literal("ICC::Profile::to_lab: conversion for DeviceLink not implemented"); - } - - FloatVector3 lab = lab_from_xyz(pcs, pcs_illuminant()); - return CIELAB { lab[0], lab[1], lab[2] }; -} - -MatrixMatrixConversion::MatrixMatrixConversion(LutCurveType source_red_TRC, - LutCurveType source_green_TRC, - LutCurveType source_blue_TRC, - FloatMatrix3x3 matrix, - LutCurveType destination_red_TRC, - LutCurveType destination_green_TRC, - LutCurveType destination_blue_TRC) - : m_source_red_TRC(move(source_red_TRC)) - , m_source_green_TRC(move(source_green_TRC)) - , m_source_blue_TRC(move(source_blue_TRC)) - , m_matrix(matrix) - , m_destination_red_TRC(move(destination_red_TRC)) - , m_destination_green_TRC(move(destination_green_TRC)) - , m_destination_blue_TRC(move(destination_blue_TRC)) -{ - auto check = [](auto const& trc) { - VERIFY(trc->type() == CurveTagData::Type || trc->type() == ParametricCurveTagData::Type); - }; - check(m_source_red_TRC); - check(m_source_green_TRC); - check(m_source_blue_TRC); - check(m_destination_red_TRC); - check(m_destination_green_TRC); - check(m_destination_blue_TRC); -} - -Optional Profile::matrix_matrix_conversion(Profile const& source_profile) const -{ - auto has_normal_device_class = [](DeviceClass device) { - return device == DeviceClass::InputDevice - || device == DeviceClass::DisplayDevice - || device == DeviceClass::OutputDevice - || device == DeviceClass::ColorSpace; - }; - - bool is_matrix_matrix_conversion = has_normal_device_class(device_class()) - && has_normal_device_class(source_profile.device_class()) - && connection_space() == ColorSpace::PCSXYZ - && source_profile.connection_space() == ColorSpace::PCSXYZ - && data_color_space() == ColorSpace::RGB - && source_profile.data_color_space() == ColorSpace::RGB - && !m_cached_has_any_a_to_b_tag - && !source_profile.m_cached_has_any_a_to_b_tag - && m_cached_has_all_rgb_matrix_tags - && source_profile.m_cached_has_all_rgb_matrix_tags - && rgb_to_xyz_matrix().is_invertible(); - - if (!is_matrix_matrix_conversion) - return OptionalNone {}; - - LutCurveType sourceRedTRC = *source_profile.m_tag_table.get(redTRCTag).value(); - LutCurveType sourceGreenTRC = *source_profile.m_tag_table.get(greenTRCTag).value(); - LutCurveType sourceBlueTRC = *source_profile.m_tag_table.get(blueTRCTag).value(); - - FloatMatrix3x3 matrix = MUST(xyz_to_rgb_matrix()) * source_profile.rgb_to_xyz_matrix(); - - LutCurveType destinationRedTRC = *m_tag_table.get(redTRCTag).value(); - LutCurveType destinationGreenTRC = *m_tag_table.get(greenTRCTag).value(); - LutCurveType destinationBlueTRC = *m_tag_table.get(blueTRCTag).value(); - - return MatrixMatrixConversion(sourceRedTRC, sourceGreenTRC, sourceBlueTRC, matrix, destinationRedTRC, destinationGreenTRC, destinationBlueTRC); -} - -ErrorOr Profile::convert_image_matrix_matrix(Gfx::Bitmap& bitmap, MatrixMatrixConversion const& map) const -{ - for (auto& pixel : bitmap) { - FloatVector3 rgb { (float)Color::from_argb(pixel).red(), (float)Color::from_argb(pixel).green(), (float)Color::from_argb(pixel).blue() }; - auto out = map.map(rgb / 255.0f); - out.set_alpha(Color::from_argb(pixel).alpha()); - pixel = out.value(); - } - return {}; -} - -ErrorOr Profile::convert_image(Gfx::Bitmap& bitmap, Profile const& source_profile) const -{ - if (auto map = matrix_matrix_conversion(source_profile); map.has_value()) - return convert_image_matrix_matrix(bitmap, map.value()); - - for (auto& pixel : bitmap) { - u8 rgb[] = { Color::from_argb(pixel).red(), Color::from_argb(pixel).green(), Color::from_argb(pixel).blue() }; - auto pcs = TRY(source_profile.to_pcs(rgb)); - TRY(from_pcs(source_profile, pcs, rgb)); - pixel = Color(rgb[0], rgb[1], rgb[2], Color::from_argb(pixel).alpha()).value(); - } - - return {}; -} - -ErrorOr Profile::convert_cmyk_image(Bitmap& out, CMYKBitmap const& in, Profile const& source_profile) const -{ - if (out.size() != in.size()) - return Error::from_string_literal("ICC::Profile::convert_cmyk_image: out and in must have the same dimensions"); - - // Might fail if `out` has a scale_factor() != 1. - if (out.data_size() != in.data_size()) - return Error::from_string_literal("ICC::Profile::convert_cmyk_image: out and in must have the same buffer size"); - - static_assert(sizeof(ARGB32) == sizeof(CMYK)); - ARGB32* out_data = out.begin(); - CMYK const* in_data = const_cast(in).begin(); - - for (size_t i = 0; i < in.data_size() / sizeof(CMYK); ++i) { - u8 cmyk[] = { in_data[i].c, in_data[i].m, in_data[i].y, in_data[i].k }; - auto pcs = TRY(source_profile.to_pcs(cmyk)); - - u8 rgb[3]; - TRY(from_pcs(source_profile, pcs, rgb)); - out_data[i] = Color(rgb[0], rgb[1], rgb[2]).value(); - } - - return {}; -} - -XYZ const& Profile::red_matrix_column() const { return xyz_data(redMatrixColumnTag); } -XYZ const& Profile::green_matrix_column() const { return xyz_data(greenMatrixColumnTag); } -XYZ const& Profile::blue_matrix_column() const { return xyz_data(blueMatrixColumnTag); } - -Optional Profile::tag_string_data(TagSignature signature) const -{ - auto maybe_tag_data = tag_data(signature); - if (!maybe_tag_data.has_value()) - return {}; - auto& tag_data = maybe_tag_data.release_value(); - if (tag_data.type() == Gfx::ICC::MultiLocalizedUnicodeTagData::Type) { - auto& multi_localized_unicode = static_cast(tag_data); - // Try to find 'en-US', otherwise any 'en' language, otherwise the first record. - Optional en_string; - constexpr u16 language_en = ('e' << 8) + 'n'; - constexpr u16 country_us = ('U' << 8) + 'S'; - for (auto const& record : multi_localized_unicode.records()) { - if (record.iso_639_1_language_code == language_en) { - if (record.iso_3166_1_country_code == country_us) - return record.text; - en_string = record.text; - } - } - if (en_string.has_value()) - return en_string.value(); - if (!multi_localized_unicode.records().is_empty()) - return multi_localized_unicode.records().first().text; - return {}; - } - if (tag_data.type() == Gfx::ICC::TextDescriptionTagData::Type) { - auto& text_description = static_cast(tag_data); - return text_description.ascii_description(); - } - if (tag_data.type() == Gfx::ICC::TextTagData::Type) { - auto& text = static_cast(tag_data); - return text.text(); - } - return {}; -} - -ErrorOr Profile::xyz_to_rgb_matrix() const -{ - if (!m_cached_xyz_to_rgb_matrix.has_value()) { - FloatMatrix3x3 forward_matrix = rgb_to_xyz_matrix(); - if (!forward_matrix.is_invertible()) - return Error::from_string_literal("ICC::Profile::from_pcs: matrix not invertible"); - m_cached_xyz_to_rgb_matrix = forward_matrix.inverse(); - } - return m_cached_xyz_to_rgb_matrix.value(); -} - -FloatMatrix3x3 Profile::rgb_to_xyz_matrix() const -{ - auto const& red_matrix_column = this->red_matrix_column(); - auto const& green_matrix_column = this->green_matrix_column(); - auto const& blue_matrix_column = this->blue_matrix_column(); - - return FloatMatrix3x3 { - red_matrix_column.X, green_matrix_column.X, blue_matrix_column.X, - red_matrix_column.Y, green_matrix_column.Y, blue_matrix_column.Y, - red_matrix_column.Z, green_matrix_column.Z, blue_matrix_column.Z - }; -} - -} diff --git a/Libraries/LibGfx/ICC/Profile.h b/Libraries/LibGfx/ICC/Profile.h deleted file mode 100644 index a96981741ab7..000000000000 --- a/Libraries/LibGfx/ICC/Profile.h +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright (c) 2022-2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Gfx::ICC { - -URL::URL device_manufacturer_url(DeviceManufacturer); -URL::URL device_model_url(DeviceModel); - -// ICC v4, 7.2.4 Profile version field -class Version { -public: - Version() = default; - Version(u8 major, u8 minor_and_bugfix) - : m_major_version(major) - , m_minor_and_bugfix_version(minor_and_bugfix) - { - } - - u8 major_version() const { return m_major_version; } - u8 minor_version() const { return m_minor_and_bugfix_version >> 4; } - u8 bugfix_version() const { return m_minor_and_bugfix_version & 0xf; } - - u8 minor_and_bugfix_version() const { return m_minor_and_bugfix_version; } - -private: - u8 m_major_version = 0; - u8 m_minor_and_bugfix_version = 0; -}; - -// ICC v4, 7.2.11 Profile flags field -class Flags { -public: - Flags(); - - // "The profile flags field contains flags." - Flags(u32); - - u32 bits() const { return m_bits; } - - // "These can indicate various hints for the CMM such as distributed processing and caching options." - // "The least-significant 16 bits are reserved for the ICC." - u16 color_management_module_bits() const { return bits() >> 16; } - u16 icc_bits() const { return bits() & 0xffff; } - - // "Bit position 0: Embedded profile (0 if not embedded, 1 if embedded in file)" - bool is_embedded_in_file() const { return (icc_bits() & 1) != 0; } - - // "Bit position 1: Profile cannot be used independently of the embedded colour data (set to 1 if true, 0 if false)" - // Double negation isn't unconfusing, so this function uses the inverted, positive sense. - bool can_be_used_independently_of_embedded_color_data() const { return (icc_bits() & 2) == 0; } - - static constexpr u32 KnownBitsMask = 3; - -private: - u32 m_bits = 0; -}; - -// ICC v4, 7.2.14 Device attributes field -class DeviceAttributes { -public: - DeviceAttributes(); - - // "The device attributes field shall contain flags used to identify attributes - // unique to the particular device setup for which the profile is applicable." - DeviceAttributes(u64); - - u64 bits() const { return m_bits; } - - // "The least-significant 32 bits of this 64-bit value are defined by the ICC. " - u32 icc_bits() const { return bits() & 0xffff'ffff; } - - // "Notice that bits 0, 1, 2, and 3 describe the media, not the device." - - // "0": "Reflective (0) or transparency (1)" - enum class MediaReflectivity { - Reflective, - Transparent, - }; - MediaReflectivity media_reflectivity() const { return MediaReflectivity(icc_bits() & 1); } - - // "1": "Glossy (0) or matte (1)" - enum class MediaGlossiness { - Glossy, - Matte, - }; - MediaGlossiness media_glossiness() const { return MediaGlossiness((icc_bits() >> 1) & 1); } - - // "2": "Media polarity, positive (0) or negative (1)" - enum class MediaPolarity { - Positive, - Negative, - }; - MediaPolarity media_polarity() const { return MediaPolarity((icc_bits() >> 2) & 1); } - - // "3": "Colour media (0), black & white media (1)" - enum class MediaColor { - Colored, - BlackAndWhite, - }; - MediaColor media_color() const { return MediaColor((icc_bits() >> 3) & 1); } - - // "4 to 31": Reserved (set to binary zero)" - - // "32 to 63": "Use not defined by ICC (vendor specific" - u32 vendor_bits() const { return bits() >> 32; } - - static constexpr u64 KnownBitsMask = 0xf; - -private: - u64 m_bits = 0; -}; - -// Time is in UTC. -// 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). -// But in practice, some profiles have invalid dates, like 0-0-0 0:0:0. -// For valid profiles, the conversion to time_t will succeed. -struct DateTime { - u16 year = 1970; - u16 month = 1; // One-based. - u16 day = 1; // One-based. - u16 hours = 0; - u16 minutes = 0; - u16 seconds = 0; - - ErrorOr to_time_t() const; - static ErrorOr from_time_t(time_t); -}; - -struct ProfileHeader { - u32 on_disk_size { 0 }; - Optional preferred_cmm_type; - Version version; - DeviceClass device_class {}; - ColorSpace data_color_space {}; - ColorSpace connection_space {}; - DateTime creation_timestamp; - Optional primary_platform {}; - Flags flags; - Optional device_manufacturer; - Optional device_model; - DeviceAttributes device_attributes; - RenderingIntent rendering_intent {}; - XYZ pcs_illuminant; - Optional creator; - Optional id; -}; - -// FIXME: This doesn't belong here. -class MatrixMatrixConversion { -public: - MatrixMatrixConversion(LutCurveType source_red_TRC, - LutCurveType source_green_TRC, - LutCurveType source_blue_TRC, - FloatMatrix3x3 matrix, - LutCurveType destination_red_TRC, - LutCurveType destination_green_TRC, - LutCurveType destination_blue_TRC); - - Color map(FloatVector3) const; - -private: - LutCurveType m_source_red_TRC; - LutCurveType m_source_green_TRC; - LutCurveType m_source_blue_TRC; - FloatMatrix3x3 m_matrix; - LutCurveType m_destination_red_TRC; - LutCurveType m_destination_green_TRC; - LutCurveType m_destination_blue_TRC; -}; - -inline Color MatrixMatrixConversion::map(FloatVector3 in_rgb) const -{ - auto evaluate_curve = [](TagData const& trc, float f) { - if (trc.type() == CurveTagData::Type) - return static_cast(trc).evaluate(f); - return static_cast(trc).evaluate(f); - }; - - auto evaluate_curve_inverse = [](TagData const& trc, float f) { - if (trc.type() == CurveTagData::Type) - return static_cast(trc).evaluate_inverse(f); - return static_cast(trc).evaluate_inverse(f); - }; - - FloatVector3 linear_rgb = { - evaluate_curve(m_source_red_TRC, in_rgb[0]), - evaluate_curve(m_source_green_TRC, in_rgb[1]), - evaluate_curve(m_source_blue_TRC, in_rgb[2]), - }; - linear_rgb = m_matrix * linear_rgb; - - linear_rgb.clamp(0.f, 1.f); - float device_r = evaluate_curve_inverse(m_destination_red_TRC, linear_rgb[0]); - float device_g = evaluate_curve_inverse(m_destination_green_TRC, linear_rgb[1]); - float device_b = evaluate_curve_inverse(m_destination_blue_TRC, linear_rgb[2]); - - u8 out_r = round(255 * device_r); - u8 out_g = round(255 * device_g); - u8 out_b = round(255 * device_b); - - return Color(out_r, out_g, out_b); -} - -class Profile : public RefCounted { -public: - static ErrorOr> try_load_from_externally_owned_memory(ReadonlyBytes); - static ErrorOr> create(ProfileHeader const& header, OrderedHashMap> tag_table); - - Optional preferred_cmm_type() const { return m_header.preferred_cmm_type; } - Version version() const { return m_header.version; } - DeviceClass device_class() const { return m_header.device_class; } - ColorSpace data_color_space() const { return m_header.data_color_space; } - - // For non-DeviceLink profiles, always PCSXYZ or PCSLAB. - ColorSpace connection_space() const { return m_header.connection_space; } - - u32 on_disk_size() const { return m_header.on_disk_size; } - DateTime creation_timestamp() const { return m_header.creation_timestamp; } - Optional primary_platform() const { return m_header.primary_platform; } - Flags flags() const { return m_header.flags; } - Optional device_manufacturer() const { return m_header.device_manufacturer; } - Optional device_model() const { return m_header.device_model; } - DeviceAttributes device_attributes() const { return m_header.device_attributes; } - RenderingIntent rendering_intent() const { return m_header.rendering_intent; } - XYZ const& pcs_illuminant() const { return m_header.pcs_illuminant; } - Optional creator() const { return m_header.creator; } - Optional const& id() const { return m_header.id; } - - static Crypto::Hash::MD5::DigestType compute_id(ReadonlyBytes); - - template - void for_each_tag(Callback callback) const - { - for (auto const& tag : m_tag_table) - callback(tag.key, tag.value); - } - - template> Callback> - ErrorOr try_for_each_tag(Callback&& callback) const - { - for (auto const& tag : m_tag_table) - TRY(callback(tag.key, tag.value)); - return {}; - } - - Optional tag_data(TagSignature signature) const - { - return m_tag_table.get(signature).map([](auto it) -> TagData const& { return *it; }); - } - - Optional tag_string_data(TagSignature signature) const; - - size_t tag_count() const { return m_tag_table.size(); } - - // Only versions 2 and 4 are in use. - bool is_v2() const { return version().major_version() == 2; } - bool is_v4() const { return version().major_version() == 4; } - - // FIXME: The color conversion stuff should be in some other class. - - // Converts an 8-bits-per-channel color to the profile connection space. - // The color's number of channels must match number_of_components_in_color_space(data_color_space()). - // Do not call for DeviceLink or NamedColor profiles. (XXX others?) - // Call connection_space() to find out the space the result is in. - ErrorOr to_pcs(ReadonlyBytes) const; - - // Converts from the profile connection space to an 8-bits-per-channel color. - // The notes on `to_pcs()` apply to this too. - ErrorOr from_pcs(Profile const& source_profile, FloatVector3, Bytes) const; - - ErrorOr to_lab(ReadonlyBytes) const; - - ErrorOr convert_image(Bitmap&, Profile const& source_profile) const; - ErrorOr convert_cmyk_image(Bitmap&, CMYKBitmap const&, Profile const& source_profile) const; - - // Only call these if you know that this is an RGB matrix-based profile. - XYZ const& red_matrix_column() const; - XYZ const& green_matrix_column() const; - XYZ const& blue_matrix_column() const; - - Optional matrix_matrix_conversion(Profile const& source_profile) const; - -private: - Profile(ProfileHeader const& header, OrderedHashMap> tag_table) - : m_header(header) - , m_tag_table(move(tag_table)) - { - } - - XYZ const& xyz_data(TagSignature tag) const - { - auto const& data = *m_tag_table.get(tag).value(); - VERIFY(data.type() == XYZTagData::Type); - return static_cast(data).xyz(); - } - - ErrorOr check_required_tags(); - ErrorOr check_tag_types(); - - ProfileHeader m_header; - OrderedHashMap> m_tag_table; - - // FIXME: The color conversion stuff should be in some other class. - ErrorOr to_pcs_a_to_b(TagData const& tag_data, ReadonlyBytes) const; - ErrorOr from_pcs_b_to_a(TagData const& tag_data, FloatVector3 const&, Bytes) const; - ErrorOr convert_image_matrix_matrix(Gfx::Bitmap&, MatrixMatrixConversion const&) const; - - // Cached values. - bool m_cached_has_any_a_to_b_tag { false }; - bool m_cached_has_a_to_b0_tag { false }; - bool m_cached_has_any_b_to_a_tag { false }; - bool m_cached_has_b_to_a0_tag { false }; - bool m_cached_has_all_rgb_matrix_tags { false }; - - // Only valid for RGB matrix-based profiles. - ErrorOr xyz_to_rgb_matrix() const; - FloatMatrix3x3 rgb_to_xyz_matrix() const; - - mutable Optional m_cached_xyz_to_rgb_matrix; - - struct OneElementCLUTCache { - Vector key; - FloatVector3 value; - }; - mutable Optional m_to_pcs_clut_cache; -}; - -} - -template<> -struct AK::Formatter : Formatter { - ErrorOr format(FormatBuilder& builder, Gfx::ICC::Version const& version) - { - return Formatter::format(builder, "{}.{}.{}"sv, version.major_version(), version.minor_version(), version.bugfix_version()); - } -}; diff --git a/Libraries/LibGfx/ICC/TagTypes.cpp b/Libraries/LibGfx/ICC/TagTypes.cpp deleted file mode 100644 index f68c5eee1cb3..000000000000 --- a/Libraries/LibGfx/ICC/TagTypes.cpp +++ /dev/null @@ -1,1245 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include - -namespace Gfx::ICC { - -namespace { - -ErrorOr check_reserved(ReadonlyBytes tag_bytes) -{ - if (tag_bytes.size() < 2 * sizeof(u32)) - return Error::from_string_literal("ICC::Profile: Not enough data for tag reserved field"); - - if (*bit_cast const*>(tag_bytes.data() + sizeof(u32)) != 0) - return Error::from_string_literal("ICC::Profile: tag reserved field not 0"); - - return {}; -} - -} - -TagTypeSignature tag_type(ReadonlyBytes tag_bytes) -{ - VERIFY(tag_bytes.size() >= sizeof(u32)); - return *bit_cast const*>(tag_bytes.data()); -} - -StringView ChromaticityTagData::phosphor_or_colorant_type_name(PhosphorOrColorantType phosphor_or_colorant_type) -{ - switch (phosphor_or_colorant_type) { - case PhosphorOrColorantType::Unknown: - return "Unknown"sv; - case PhosphorOrColorantType::ITU_R_BT_709_2: - return "ITU-R BT.709-2"sv; - case PhosphorOrColorantType::SMPTE_RP145: - return "SMPTE RP145"sv; - case PhosphorOrColorantType::EBU_Tech_3213_E: - return "EBU Tech. 3213-E"sv; - case PhosphorOrColorantType::P22: - return "P22"sv; - case PhosphorOrColorantType::P3: - return "P3"sv; - case PhosphorOrColorantType::ITU_R_BT_2020: - return "ITU-R BT.2020"sv; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr> ChromaticityTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.2 chromaticityType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + 2 * sizeof(u16)) - return Error::from_string_literal("ICC::Profile: chromaticityType has not enough data"); - - u16 number_of_device_channels = *bit_cast const*>(bytes.data() + 8); - PhosphorOrColorantType phosphor_or_colorant_type = *bit_cast const*>(bytes.data() + 10); - - switch (phosphor_or_colorant_type) { - case PhosphorOrColorantType::Unknown: - case PhosphorOrColorantType::ITU_R_BT_709_2: - case PhosphorOrColorantType::SMPTE_RP145: - case PhosphorOrColorantType::EBU_Tech_3213_E: - case PhosphorOrColorantType::P22: - case PhosphorOrColorantType::P3: - case PhosphorOrColorantType::ITU_R_BT_2020: - break; - default: - return Error::from_string_literal("ICC::Profile: chromaticityType invalid phosphor_or_colorant_type"); - } - - // "If the value is 0001h to 0004h, the number of channels shall be three..." - if (phosphor_or_colorant_type != PhosphorOrColorantType::Unknown && number_of_device_channels != 3) - return Error::from_string_literal("ICC::Profile: chromaticityType unexpected number of channels for phosphor_or_colorant_type"); - - if (bytes.size() < 2 * sizeof(u32) + 2 * sizeof(u16) + number_of_device_channels * 2 * sizeof(u16Fixed16Number)) - return Error::from_string_literal("ICC::Profile: chromaticityType has not enough data for xy coordinates"); - - auto* raw_xy_coordinates = bit_cast const*>(bytes.data() + 12); - Vector xy_coordinates; - TRY(xy_coordinates.try_resize(number_of_device_channels)); - for (size_t i = 0; i < number_of_device_channels; ++i) { - xy_coordinates[i].x = U16Fixed16::create_raw(raw_xy_coordinates[2 * i]); - xy_coordinates[i].y = U16Fixed16::create_raw(raw_xy_coordinates[2 * i + 1]); - } - - // FIXME: Once I find files that have phosphor_or_colorant_type != Unknown, check that the values match the values in Table 31. - - return try_make_ref_counted(offset, size, phosphor_or_colorant_type, move(xy_coordinates)); -} - -ErrorOr> CicpTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.3 cicpType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + 4 * sizeof(u8)) - return Error::from_string_literal("ICC::Profile: cicpType has not enough data"); - - u8 color_primaries = bytes[8]; - u8 transfer_characteristics = bytes[9]; - u8 matrix_coefficients = bytes[10]; - u8 video_full_range_flag = bytes[11]; - - return try_make_ref_counted(offset, size, color_primaries, transfer_characteristics, matrix_coefficients, video_full_range_flag); -} - -namespace { - -struct CurveData { - u32 computed_size; - Vector values; -}; - -ErrorOr curve_data_from_bytes(ReadonlyBytes bytes) -{ - // ICC v4, 10.6 curveType - VERIFY(tag_type(bytes) == CurveTagData::Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 3 * sizeof(u32)) - return Error::from_string_literal("ICC::Profile: curveType has not enough data for count"); - u32 count = *bit_cast const*>(bytes.data() + 8); - - u32 computed_size = 3 * sizeof(u32) + count * sizeof(u16); - if (bytes.size() < computed_size) - return Error::from_string_literal("ICC::Profile: curveType has not enough data for curve points"); - - auto* raw_values = bit_cast const*>(bytes.data() + 12); - Vector values; - TRY(values.try_resize(count)); - - for (u32 i = 0; i < count; ++i) - values[i] = raw_values[i]; - - return CurveData { computed_size, move(values) }; -} - -} - -ErrorOr> CurveTagData::from_bytes(ReadonlyBytes bytes, u32 offset) -{ - auto curve_data = TRY(curve_data_from_bytes(bytes)); - return try_make_ref_counted(offset, curve_data.computed_size, move(curve_data.values)); -} - -ErrorOr> CurveTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - auto curve_data = TRY(curve_data_from_bytes(bytes)); - return try_make_ref_counted(offset, size, move(curve_data.values)); -} - -ErrorOr> Lut16TagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.10 lut16Type - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + sizeof(LUTHeader) + 2 + sizeof(u16)) - return Error::from_string_literal("ICC::Profile: lut16Type has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - if (header.reserved_for_padding != 0) - return Error::from_string_literal("ICC::Profile: lut16Type reserved_for_padding not 0"); - - u16 number_of_input_table_entries = *bit_cast const*>(bytes.data() + 8 + sizeof(LUTHeader)); - u16 number_of_output_table_entries = *bit_cast const*>(bytes.data() + 8 + sizeof(LUTHeader) + 2); - ReadonlyBytes table_bytes = bytes.slice(8 + sizeof(LUTHeader) + 4); - - // "Each input table consists of a minimum of two and a maximum of 4096 uInt16Number integers. - if (number_of_input_table_entries < 2 || number_of_input_table_entries > 4096) - return Error::from_string_literal("ICC::Profile: lut16Type bad number of input table entries"); - - // "Each output table consists of a minimum of two and a maximum of 4096 uInt16Number integers." - if (number_of_output_table_entries < 2 || number_of_output_table_entries > 4096) - return Error::from_string_literal("ICC::Profile: lut16Type bad number of output table entries"); - - EMatrix3x3 e; - for (int i = 0; i < 9; ++i) - e.e[i] = S15Fixed16::create_raw(header.e_parameters[i]); - - u32 input_tables_size = number_of_input_table_entries * header.number_of_input_channels; - u32 output_tables_size = number_of_output_table_entries * header.number_of_output_channels; - u32 clut_values_size = header.number_of_output_channels; - for (int i = 0; i < header.number_of_input_channels; ++i) - clut_values_size *= header.number_of_clut_grid_points; - - if (table_bytes.size() < (input_tables_size + clut_values_size + output_tables_size) * sizeof(u16)) - return Error::from_string_literal("ICC::Profile: lut16Type has not enough data for tables"); - - auto* raw_table_data = bit_cast const*>(table_bytes.data()); - - Vector input_tables; - input_tables.resize(input_tables_size); - for (u32 i = 0; i < input_tables_size; ++i) - input_tables[i] = raw_table_data[i]; - - Vector clut_values; - clut_values.resize(clut_values_size); - for (u32 i = 0; i < clut_values_size; ++i) - clut_values[i] = raw_table_data[input_tables_size + i]; - - Vector output_tables; - output_tables.resize(output_tables_size); - for (u32 i = 0; i < output_tables_size; ++i) - output_tables[i] = raw_table_data[input_tables_size + clut_values_size + i]; - - return try_make_ref_counted(offset, size, e, - header.number_of_input_channels, header.number_of_output_channels, header.number_of_clut_grid_points, - number_of_input_table_entries, number_of_output_table_entries, - move(input_tables), move(clut_values), move(output_tables)); -} - -ErrorOr> Lut8TagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.11 lut8Type - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 8 + sizeof(LUTHeader)) - return Error::from_string_literal("ICC::Profile: lut8Type has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - if (header.reserved_for_padding != 0) - return Error::from_string_literal("ICC::Profile: lut16Type reserved_for_padding not 0"); - - u16 number_of_input_table_entries = 256; - u16 number_of_output_table_entries = 256; - ReadonlyBytes table_bytes = bytes.slice(8 + sizeof(LUTHeader)); - - EMatrix3x3 e; - for (int i = 0; i < 9; ++i) - e.e[i] = S15Fixed16::create_raw(header.e_parameters[i]); - - u32 input_tables_size = number_of_input_table_entries * header.number_of_input_channels; - u32 output_tables_size = number_of_output_table_entries * header.number_of_output_channels; - u32 clut_values_size = header.number_of_output_channels; - for (int i = 0; i < header.number_of_input_channels; ++i) - clut_values_size *= header.number_of_clut_grid_points; - - if (table_bytes.size() < input_tables_size + clut_values_size + output_tables_size) - return Error::from_string_literal("ICC::Profile: lut8Type has not enough data for tables"); - - Vector input_tables; - input_tables.resize(input_tables_size); - memcpy(input_tables.data(), table_bytes.data(), input_tables_size); - - Vector clut_values; - clut_values.resize(clut_values_size); - memcpy(clut_values.data(), table_bytes.data() + input_tables_size, clut_values_size); - - Vector output_tables; - output_tables.resize(output_tables_size); - memcpy(output_tables.data(), table_bytes.data() + input_tables_size + clut_values_size, output_tables_size); - - return try_make_ref_counted(offset, size, e, - header.number_of_input_channels, header.number_of_output_channels, header.number_of_clut_grid_points, - number_of_input_table_entries, number_of_output_table_entries, - move(input_tables), move(clut_values), move(output_tables)); -} - -static ErrorOr read_clut_data(ReadonlyBytes bytes, AdvancedLUTHeader const& header) -{ - // Reads a CLUT as described in ICC v4, 10.12.3 CLUT and 10.13.5 CLUT (the two sections are virtually identical). - if (header.offset_to_clut + sizeof(CLUTHeader) > bytes.size()) - return Error::from_string_literal("ICC::Profile: clut out of bounds"); - - if (header.number_of_input_channels >= sizeof(CLUTHeader::number_of_grid_points_in_dimension)) - return Error::from_string_literal("ICC::Profile: clut has too many input channels"); - - auto& clut_header = *bit_cast(bytes.data() + header.offset_to_clut); - - // "Number of grid points in each dimension. Only the first i entries are used, where i is the number of input channels." - Vector number_of_grid_points_in_dimension; - TRY(number_of_grid_points_in_dimension.try_resize(header.number_of_input_channels)); - for (size_t i = 0; i < header.number_of_input_channels; ++i) - number_of_grid_points_in_dimension[i] = clut_header.number_of_grid_points_in_dimension[i]; - - // "Unused entries shall be set to 00h." - for (size_t i = header.number_of_input_channels; i < sizeof(CLUTHeader::number_of_grid_points_in_dimension); ++i) { - if (clut_header.number_of_grid_points_in_dimension[i] != 0) - return Error::from_string_literal("ICC::Profile: unused clut grid point not 0"); - } - - // "Precision of data elements in bytes. Shall be either 01h or 02h." - if (clut_header.precision_of_data_elements != 1 && clut_header.precision_of_data_elements != 2) - return Error::from_string_literal("ICC::Profile: clut invalid data element precision"); - - // "Reserved for padding, shall be set to 0" - for (size_t i = 0; i < sizeof(CLUTHeader::reserved_for_padding); ++i) { - if (clut_header.reserved_for_padding[i] != 0) - return Error::from_string_literal("ICC::Profile: clut reserved for padding not 0"); - } - - // "The size of the CLUT in bytes is (nGrid1 x nGrid2 x…x nGridN) x number of output channels (o) x size of (channel component)." - u32 clut_size = header.number_of_output_channels; - for (u8 grid_size_in_dimension : number_of_grid_points_in_dimension) - clut_size *= grid_size_in_dimension; - - if (header.offset_to_clut + sizeof(CLUTHeader) + clut_size * clut_header.precision_of_data_elements > bytes.size()) - return Error::from_string_literal("ICC::Profile: clut data out of bounds"); - - if (clut_header.precision_of_data_elements == 1) { - auto* raw_values = bytes.data() + header.offset_to_clut + sizeof(CLUTHeader); - Vector values; - TRY(values.try_resize(clut_size)); - for (u32 i = 0; i < clut_size; ++i) - values[i] = raw_values[i]; - return CLUTData { move(number_of_grid_points_in_dimension), move(values) }; - } - - VERIFY(clut_header.precision_of_data_elements == 2); - auto* raw_values = bit_cast const*>(bytes.data() + header.offset_to_clut + sizeof(CLUTHeader)); - Vector values; - TRY(values.try_resize(clut_size)); - for (u32 i = 0; i < clut_size; ++i) - values[i] = raw_values[i]; - return CLUTData { move(number_of_grid_points_in_dimension), move(values) }; -} - -static ErrorOr read_curve(ReadonlyBytes bytes, u32 offset) -{ - // "All tag data elements shall start on a 4-byte boundary (relative to the start of the profile data stream)" - if (offset % 4 != 0) - return Error::from_string_literal("ICC::Profile: lut curve data not aligned"); - - // See read_curves() below. - if (offset + sizeof(u32) > bytes.size()) - return Error::from_string_literal("ICC::Profile: not enough data for lut curve type"); - - ReadonlyBytes tag_bytes = bytes.slice(offset); - auto type = tag_type(tag_bytes); - - if (type == CurveTagData::Type) - return CurveTagData::from_bytes(tag_bytes, offset); - - if (type == ParametricCurveTagData::Type) - return ParametricCurveTagData::from_bytes(tag_bytes, offset); - - return Error::from_string_literal("ICC::Profile: invalid tag type for lut curve"); -} - -static ErrorOr> read_curves(ReadonlyBytes bytes, u32 offset, u32 count) -{ - // Reads "A", "M", or "B" curves from lutAToBType or lutBToAType. They all have the same - // description (ICC v4 10.12.2, 10.12.4, 10.12.6, 10.13.2, 10.13.4, 10.13.6): - // "The curves are stored sequentially, with 00h bytes used for padding between them if needed. - // Each [type] curve is stored as an embedded curveType or a parametricCurveType (see 10.5 or 10.16). The length - // is as indicated by the convention of the respective curve type. Note that the entire tag type, including the tag - // type signature and reserved bytes, is included for each curve." - - // Both types also say: - // "Curve data elements may be shared. For example, the offsets for A, B and M curves can be identical." - // FIXME: Implement sharing curve objects when that happens. (I haven't seen it happen in practice yet.) - // Probably just pass in an offset->curve hashmap and look there first. - - Vector curves; - - for (u32 i = 0; i < count; ++i) { - // This can't call Profile::read_tag() because that requires tag size to be known in advance. - // Some tag types (e.g. textType) depend on this externally stored size. - // curveType and parametricCurveType don't. - // - // Commentary on the ICC spec: It still seems a bit awkward that the way curve tag types are stored here is - // different from how tag types are stored in the main container. Maybe that's so that the A, M, B curves - // can share data better? - // It's also weird that the A curves can't share data for their various curves -- in the main profile, - // redTRCTag, greenTRCTag, and blueTRCTag usually share the same curve, but here this isn't possible. - // Maybe it wouldn't usually happen for profiles that need lutAToBType or lutBToAType tags? - // I would've probably embedded a tag table in this tag and then have the A, M, B offsets store indices - // into that local table. Maybe there's a good reason why that wasn't done, and anyways, the spec is what it is. - auto curve = TRY(read_curve(bytes, offset)); - offset += align_up_to(curve->size(), 4); - TRY(curves.try_append(move(curve))); - } - - return curves; -} - -static bool is_valid_curve(LutCurveType const& curve) -{ - return curve->type() == CurveTagData::Type || curve->type() == ParametricCurveTagData::Type; -} - -bool are_valid_curves(Optional> const& curves) -{ - if (!curves.has_value()) - return true; - - for (auto const& curve : curves.value()) { - if (!is_valid_curve(curve)) - return false; - } - return true; -} - -ErrorOr> LutAToBTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.12 lutAToBType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + sizeof(AdvancedLUTHeader)) - return Error::from_string_literal("ICC::Profile: lutAToBType has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - if (header.reserved_for_padding != 0) - return Error::from_string_literal("ICC::Profile: lutAToBType reserved_for_padding not 0"); - - // 10.12.2 “A” curves - // "There are the same number of “A” curves as there are input channels. The “A” curves may only be used when - // the CLUT is used. The curves are stored sequentially, with 00h bytes used for padding between them if needed. - // Each “A” curve is stored as an embedded curveType or a parametricCurveType (see 10.5 or 10.16). The length - // is as indicated by the convention of the respective curve type. Note that the entire tag type, including the tag - // type signature and reserved bytes, is included for each curve." - Optional> a_curves; - if (header.offset_to_a_curves) - a_curves = TRY(read_curves(bytes, header.offset_to_a_curves, header.number_of_input_channels)); - - // 10.12.3 CLUT - Optional clut_data; - if (header.offset_to_clut) { - clut_data = TRY(read_clut_data(bytes, header)); - } else if (header.number_of_input_channels != header.number_of_output_channels) { - // "If the number of input channels does not equal the number of output channels, the CLUT shall be present." - return Error::from_string_literal("ICC::Profile: lutAToBType no CLUT despite different number of input and output channels"); - } - - // Follows from the "Only the following combinations are permitted" list in 10.12.1. - if (a_curves.has_value() != clut_data.has_value()) - return Error::from_string_literal("ICC::Profile: lutAToBType must have 'A' curves exactly if it has a CLUT"); - - // 10.12.4 “M” curves - // "There are the same number of “M” curves as there are output channels. The curves are stored sequentially, - // with 00h bytes used for padding between them if needed. Each “M” curve is stored as an embedded curveType - // or a parametricCurveType (see 10.5 or 10.16). The length is as indicated by the convention of the respective - // curve type. Note that the entire tag type, including the tag type signature and reserved bytes, is included for - // each curve. The “M” curves may only be used when the matrix is used." - Optional> m_curves; - if (header.offset_to_m_curves) - m_curves = TRY(read_curves(bytes, header.offset_to_m_curves, header.number_of_output_channels)); - - // 10.12.5 Matrix - // "The matrix is organized as a 3 x 4 array. The elements appear in order from e1-e12. The matrix elements are - // each s15Fixed16Numbers." - Optional e; - if (header.offset_to_matrix) { - if (header.offset_to_matrix + 12 * sizeof(s15Fixed16Number) > bytes.size()) - return Error::from_string_literal("ICC::Profile: lutAToBType matrix out of bounds"); - - e = EMatrix3x4 {}; - auto* raw_e = bit_cast const*>(bytes.data() + header.offset_to_matrix); - for (int i = 0; i < 12; ++i) - e->e[i] = S15Fixed16::create_raw(raw_e[i]); - } - - // Follows from the "Only the following combinations are permitted" list in 10.12.1. - if (m_curves.has_value() != e.has_value()) - return Error::from_string_literal("ICC::Profile: lutAToBType must have 'M' curves exactly if it has a matrix"); - - // 10.12.6 “B” curves - // "There are the same number of “B” curves as there are output channels. The curves are stored sequentially, with - // 00h bytes used for padding between them if needed. Each “B” curve is stored as an embedded curveType or a - // parametricCurveType (see 10.5 or 10.16). The length is as indicated by the convention of the respective curve - // type. Note that the entire tag type, including the tag type signature and reserved bytes, are included for each - // curve." - if (!header.offset_to_b_curves) - return Error::from_string_literal("ICC::Profile: lutAToBType without B curves"); - Vector b_curves = TRY(read_curves(bytes, header.offset_to_b_curves, header.number_of_output_channels)); - - return try_make_ref_counted(offset, size, header.number_of_input_channels, header.number_of_output_channels, - move(a_curves), move(clut_data), move(m_curves), e, move(b_curves)); -} - -ErrorOr> LutBToATagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.13 lutBToAType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + sizeof(AdvancedLUTHeader)) - return Error::from_string_literal("ICC::Profile: lutBToAType has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - if (header.reserved_for_padding != 0) - return Error::from_string_literal("ICC::Profile: lutBToAType reserved_for_padding not 0"); - - // 10.13.2 “B” curves - // "There are the same number of “B” curves as there are input channels. The curves are stored sequentially, with - // 00h bytes used for padding between them if needed. Each “B” curve is stored as an embedded curveType tag - // or a parametricCurveType (see 10.5 or 10.16). The length is as indicated by the convention of the proper curve - // type. Note that the entire tag type, including the tag type signature and reserved bytes, is included for each - // curve." - if (!header.offset_to_b_curves) - return Error::from_string_literal("ICC::Profile: lutBToAType without B curves"); - Vector b_curves = TRY(read_curves(bytes, header.offset_to_b_curves, header.number_of_input_channels)); - - // 10.13.3 Matrix - // "The matrix is organized as a 3 x 4 array. The elements of the matrix appear in the type in order from e1 to e12. - // The matrix elements are each s15Fixed16Numbers" - Optional e; - if (header.offset_to_matrix) { - if (header.offset_to_matrix + 12 * sizeof(s15Fixed16Number) > bytes.size()) - return Error::from_string_literal("ICC::Profile: lutBToAType matrix out of bounds"); - - e = EMatrix3x4 {}; - auto* raw_e = bit_cast const*>(bytes.data() + header.offset_to_matrix); - for (int i = 0; i < 12; ++i) - e->e[i] = S15Fixed16::create_raw(raw_e[i]); - } - - // 10.13.4 “M” curves - // "There are the same number of “M” curves as there are input channels. The curves are stored sequentially, with - // 00h bytes used for padding between them if needed. Each “M” curve is stored as an embedded curveType or - // a parametricCurveType (see 10.5 or 10.16). The length is as indicated by the convention of the proper curve - // type. Note that the entire tag type, including the tag type signature and reserved bytes, are included for each - // curve. The “M” curves may only be used when the matrix is used." - Optional> m_curves; - if (header.offset_to_m_curves) - m_curves = TRY(read_curves(bytes, header.offset_to_m_curves, header.number_of_input_channels)); - - // Follows from the "Only the following combinations are permitted" list in 10.13.1. - if (e.has_value() != m_curves.has_value()) - return Error::from_string_literal("ICC::Profile: lutBToAType must have matrix exactly if it has 'M' curves"); - - // 10.13.5 CLUT - Optional clut_data; - if (header.offset_to_clut) { - clut_data = TRY(read_clut_data(bytes, header)); - } else if (header.number_of_input_channels != header.number_of_output_channels) { - // "If the number of input channels does not equal the number of output channels, the CLUT shall be present." - return Error::from_string_literal("ICC::Profile: lutAToBType no CLUT despite different number of input and output channels"); - } - - // 10.13.6 “A” curves - // "There are the same number of “A” curves as there are output channels. The “A” curves may only be used when - // the CLUT is used. The curves are stored sequentially, with 00h bytes used for padding between them if needed. - // Each “A” curve is stored as an embedded curveType or a parametricCurveType (see 10.5 or 10.16). The length - // is as indicated by the convention of the proper curve type. Note that the entire tag type, including the tag type - // signature and reserved bytes, is included for each curve." - Optional> a_curves; - if (header.offset_to_a_curves) - a_curves = TRY(read_curves(bytes, header.offset_to_a_curves, header.number_of_output_channels)); - - // Follows from the "Only the following combinations are permitted" list in 10.13.1. - if (clut_data.has_value() != a_curves.has_value()) - return Error::from_string_literal("ICC::Profile: lutBToAType must have A clut exactly if it has 'A' curves"); - - return try_make_ref_counted(offset, size, header.number_of_input_channels, header.number_of_output_channels, - move(b_curves), e, move(m_curves), move(clut_data), move(a_curves)); -} - -ErrorOr> MeasurementTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.14 measurementType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + sizeof(MeasurementHeader)) - return Error::from_string_literal("ICC::Profile: measurementTag has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - - TRY(validate_standard_observer(header.standard_observer)); - TRY(validate_measurement_geometry(header.measurement_geometry)); - TRY(validate_standard_illuminant(header.standard_illuminant)); - - return try_make_ref_counted(offset, size, header.standard_observer, header.tristimulus_value_for_measurement_backing, - header.measurement_geometry, U16Fixed16::create_raw(header.measurement_flare), header.standard_illuminant); -} - -ErrorOr MeasurementTagData::validate_standard_observer(StandardObserver standard_observer) -{ - switch (standard_observer) { - case StandardObserver::Unknown: - case StandardObserver::CIE_1931_standard_colorimetric_observer: - case StandardObserver::CIE_1964_standard_colorimetric_observer: - return {}; - } - return Error::from_string_literal("ICC::Profile: unknown standard_observer"); -} - -StringView MeasurementTagData::standard_observer_name(StandardObserver standard_observer) -{ - switch (standard_observer) { - case StandardObserver::Unknown: - return "Unknown"sv; - case StandardObserver::CIE_1931_standard_colorimetric_observer: - return "CIE 1931 standard colorimetric observer"sv; - case StandardObserver::CIE_1964_standard_colorimetric_observer: - return "CIE 1964 standard colorimetric observer"sv; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr MeasurementTagData::validate_measurement_geometry(MeasurementGeometry measurement_geometry) -{ - switch (measurement_geometry) { - case MeasurementGeometry::Unknown: - case MeasurementGeometry::Degrees_0_45_or_45_0: - case MeasurementGeometry::Degrees_0_d_or_d_0: - return {}; - } - return Error::from_string_literal("ICC::Profile: unknown measurement_geometry"); -} - -StringView MeasurementTagData::measurement_geometry_name(MeasurementGeometry measurement_geometry) -{ - switch (measurement_geometry) { - case MeasurementGeometry::Unknown: - return "Unknown"sv; - case MeasurementGeometry::Degrees_0_45_or_45_0: - return "0°:45° or 45°:0°"sv; - case MeasurementGeometry::Degrees_0_d_or_d_0: - return "0°:d or d:0°"sv; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr MeasurementTagData::validate_standard_illuminant(StandardIlluminant standard_illuminant) -{ - switch (standard_illuminant) { - case StandardIlluminant::Unknown: - case StandardIlluminant::D50: - case StandardIlluminant::D65: - case StandardIlluminant::D93: - case StandardIlluminant::F2: - case StandardIlluminant::D55: - case StandardIlluminant::A: - case StandardIlluminant::Equi_Power_E: - case StandardIlluminant::F8: - return {}; - } - return Error::from_string_literal("ICC::Profile: unknown standard_illuminant"); -} - -StringView MeasurementTagData::standard_illuminant_name(StandardIlluminant standard_illuminant) -{ - switch (standard_illuminant) { - case StandardIlluminant::Unknown: - return "Unknown"sv; - case StandardIlluminant::D50: - return "D50"sv; - case StandardIlluminant::D65: - return "D65"sv; - case StandardIlluminant::D93: - return "D93"sv; - case StandardIlluminant::F2: - return "F2"sv; - case StandardIlluminant::D55: - return "D55"sv; - case StandardIlluminant::A: - return "A"sv; - case StandardIlluminant::Equi_Power_E: - return "Equi-Power (E)"sv; - case StandardIlluminant::F8: - return "F8"sv; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr> MultiLocalizedUnicodeTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.15 multiLocalizedUnicodeType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - // "Multiple strings within this tag may share storage locations. For example, en/US and en/UK can refer to the - // same string data." - // This implementation makes redundant string copies in that case. - // Most of the time, this costs just a few bytes, so that seems ok. - - if (bytes.size() < 4 * sizeof(u32)) - return Error::from_string_literal("ICC::Profile: multiLocalizedUnicodeType has not enough data"); - - // Table 54 — multiLocalizedUnicodeType - u32 number_of_records = *bit_cast const*>(bytes.data() + 8); - u32 record_size = *bit_cast const*>(bytes.data() + 12); - - // "The fourth field of this tag, the record size, should contain the value 12, which corresponds to the size in bytes - // of each record. Any code that needs to access the nth record should determine the record’s offset by multiplying - // n by the contents of this size field and adding 16. This minor extra effort allows for future expansion of the record - // encoding, should the need arise, without having to define a new tag type." - if (record_size < sizeof(MultiLocalizedUnicodeRawRecord)) - return Error::from_string_literal("ICC::Profile: multiLocalizedUnicodeType record size too small"); - - Checked records_size_in_bytes = number_of_records; - records_size_in_bytes *= record_size; - records_size_in_bytes += 16; - if (records_size_in_bytes.has_overflow() || bytes.size() < records_size_in_bytes.value()) - return Error::from_string_literal("ICC::Profile: multiLocalizedUnicodeType not enough data for records"); - - Vector records; - TRY(records.try_resize(number_of_records)); - - // "For the definition of language codes and country codes, see respectively - // ISO 639-1 and ISO 3166-1. The Unicode strings in storage should be encoded as 16-bit big-endian, UTF-16BE, - // and should not be NULL terminated." - auto& utf_16be_decoder = *TextCodec::decoder_for("utf-16be"sv); - - for (u32 i = 0; i < number_of_records; ++i) { - size_t offset = 16 + i * record_size; - auto record = *bit_cast(bytes.data() + offset); - - records[i].iso_639_1_language_code = record.language_code; - records[i].iso_3166_1_country_code = record.country_code; - - if (record.string_length_in_bytes % 2 != 0) - return Error::from_string_literal("ICC::Profile: multiLocalizedUnicodeType odd UTF-16 byte length"); - - if (static_cast(record.string_offset_in_bytes) + record.string_length_in_bytes > bytes.size()) - return Error::from_string_literal("ICC::Profile: multiLocalizedUnicodeType string offset out of bounds"); - - StringView utf_16be_data { bytes.data() + record.string_offset_in_bytes, record.string_length_in_bytes }; - - // Despite the "should not be NULL terminated" in the spec, some files in the wild have trailing NULLs. - // Fix up this case here, so that application code doesn't have to worry about it. - // (If this wasn't hit in practice, we'd return an Error instead.) - while (utf_16be_data.length() >= 2 && utf_16be_data.ends_with(StringView("\0", 2))) - utf_16be_data = utf_16be_data.substring_view(0, utf_16be_data.length() - 2); - - records[i].text = TRY(utf_16be_decoder.to_utf8(utf_16be_data)); - } - - return try_make_ref_counted(offset, size, move(records)); -} - -unsigned ParametricCurveTagData::parameter_count(FunctionType function_type) -{ - switch (function_type) { - case FunctionType::Type0: - return 1; - case FunctionType::Type1: - return 3; - case FunctionType::Type2: - return 4; - case FunctionType::Type3: - return 5; - case FunctionType::Type4: - return 7; - } - VERIFY_NOT_REACHED(); -} - -ErrorOr> NamedColor2TagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.17 namedColor2Type - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + sizeof(NamedColorHeader)) - return Error::from_string_literal("ICC::Profile: namedColor2Type has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - - Checked record_byte_size = 3; - record_byte_size += header.number_of_device_coordinates_of_each_named_color; - record_byte_size *= sizeof(u16); - record_byte_size += 32; - - Checked end_of_record = record_byte_size; - end_of_record *= header.count_of_named_colors; - end_of_record += 2 * sizeof(u32) + sizeof(NamedColorHeader); - if (end_of_record.has_overflow() || bytes.size() < end_of_record.value()) - return Error::from_string_literal("ICC::Profile: namedColor2Type has not enough color data"); - - auto buffer_to_string = [](u8 const* buffer) -> ErrorOr { - size_t length = strnlen((char const*)buffer, 32); - if (length == 32) - return Error::from_string_literal("ICC::Profile: namedColor2Type string not \\0-terminated"); - for (size_t i = 0; i < length; ++i) - if (buffer[i] >= 128) - return Error::from_string_literal("ICC::Profile: namedColor2Type not 7-bit ASCII"); - return String::from_utf8({ buffer, length }); - }; - - String prefix = TRY(buffer_to_string(header.prefix_for_each_color_name)); - String suffix = TRY(buffer_to_string(header.suffix_for_each_color_name)); - - Vector root_names; - Vector pcs_coordinates; - Vector device_coordinates; - - TRY(root_names.try_resize(header.count_of_named_colors)); - TRY(pcs_coordinates.try_resize(header.count_of_named_colors)); - TRY(device_coordinates.try_resize(header.count_of_named_colors * header.number_of_device_coordinates_of_each_named_color)); - - for (size_t i = 0; i < header.count_of_named_colors; ++i) { - u8 const* root_name = bytes.data() + 8 + sizeof(NamedColorHeader) + i * record_byte_size.value(); - auto* components = bit_cast const*>(root_name + 32); - - root_names[i] = TRY(buffer_to_string(root_name)); - pcs_coordinates[i] = { { { components[0], components[1], components[2] } } }; - for (size_t j = 0; j < header.number_of_device_coordinates_of_each_named_color; ++j) - device_coordinates[i * header.number_of_device_coordinates_of_each_named_color + j] = components[3 + j]; - } - - return try_make_ref_counted(offset, size, header.vendor_specific_flag, header.number_of_device_coordinates_of_each_named_color, - move(prefix), move(suffix), move(root_names), move(pcs_coordinates), move(device_coordinates)); -} - -ErrorOr NamedColor2TagData::color_name(u32 index) const -{ - StringBuilder builder; - builder.append(prefix()); - builder.append(root_name(index)); - builder.append(suffix()); - return builder.to_string(); -} - -namespace { - -struct ParametricCurveData { - u32 computed_size; - ParametricCurveTagData::FunctionType function_type; - Array parameters; -}; - -ErrorOr parametric_curve_data_from_bytes(ReadonlyBytes bytes) -{ - // ICC v4, 10.18 parametricCurveType - VERIFY(tag_type(bytes) == ParametricCurveTagData::Type); - TRY(check_reserved(bytes)); - - // "The parametricCurveType describes a one-dimensional curve by specifying one of a predefined set of functions - // using the parameters." - - if (bytes.size() < 2 * sizeof(u32) + 2 * sizeof(u16)) - return Error::from_string_literal("ICC::Profile: parametricCurveType has not enough data"); - - u16 raw_function_type = *bit_cast const*>(bytes.data() + 8); - u16 reserved = *bit_cast const*>(bytes.data() + 10); - if (reserved != 0) - return Error::from_string_literal("ICC::Profile: parametricCurveType reserved u16 after function type not 0"); - - if (raw_function_type > 4) - return Error::from_string_literal("ICC::Profile: parametricCurveType unknown function type"); - - auto function_type = (ParametricCurveTagData::FunctionType)raw_function_type; - unsigned count = ParametricCurveTagData::parameter_count(function_type); - - u32 computed_size = 2 * sizeof(u32) + 2 * sizeof(u16) + count * sizeof(s15Fixed16Number); - if (bytes.size() < computed_size) - return Error::from_string_literal("ICC::Profile: parametricCurveType has not enough data for parameters"); - - auto* raw_parameters = bit_cast const*>(bytes.data() + 12); - Array parameters; - parameters.fill(0); - for (size_t i = 0; i < count; ++i) - parameters[i] = S15Fixed16::create_raw(raw_parameters[i]); - - return ParametricCurveData { computed_size, function_type, move(parameters) }; -} - -} - -ErrorOr> ParametricCurveTagData::from_bytes(ReadonlyBytes bytes, u32 offset) -{ - auto curve_data = TRY(parametric_curve_data_from_bytes(bytes)); - return try_make_ref_counted(offset, curve_data.computed_size, curve_data.function_type, move(curve_data.parameters)); -} - -ErrorOr> ParametricCurveTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - auto curve_data = TRY(parametric_curve_data_from_bytes(bytes)); - return try_make_ref_counted(offset, size, curve_data.function_type, move(curve_data.parameters)); -} - -ErrorOr> S15Fixed16ArrayTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.22 s15Fixed16ArrayType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - // "This type represents an array of generic 4-byte (32-bit) fixed point quantity. The number of values is determined - // from the size of the tag." - size_t byte_size = bytes.size() - 8; - if (byte_size % sizeof(s15Fixed16Number) != 0) - return Error::from_string_literal("ICC::Profile: s15Fixed16ArrayType has wrong size"); - - size_t count = byte_size / sizeof(s15Fixed16Number); - auto* raw_values = bit_cast const*>(bytes.data() + 8); - Vector values; - TRY(values.try_resize(count)); - for (size_t i = 0; i < count; ++i) - values[i] = S15Fixed16::create_raw(raw_values[i]); - - return try_make_ref_counted(offset, size, move(values)); -} - -ErrorOr> SignatureTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.23 signatureType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 3 * sizeof(u32)) - return Error::from_string_literal("ICC::Profile: signatureType has not enough data"); - - u32 signature = *bit_cast const*>(bytes.data() + 8); - - return try_make_ref_counted(offset, size, signature); -} - -Optional SignatureTagData::colorimetric_intent_image_state_signature_name(u32 colorimetric_intent_image_state) -{ - // Table 26 — colorimetricIntentImageStateTag signatures - switch (colorimetric_intent_image_state) { - case 0x73636F65: // 'scoe' - return "Scene colorimetry estimates"sv; - case 0x73617065: // 'sape' - return "Scene appearance estimates"sv; - case 0x66706365: // 'fpce' - return "Focal plane colorimetry estimates"sv; - case 0x72686F63: // 'rhoc' - return "Reflection hardcopy original colorimetry"sv; - case 0x72706F63: // 'rpoc' - return "Reflection print output colorimetry"sv; - } - // "Other image state specifications are reserved for future ICC use." - return {}; -} - -Optional SignatureTagData::perceptual_rendering_intent_gamut_signature_name(u32 perceptual_rendering_intent_gamut) -{ - // Table 27 — Perceptual rendering intent gamut - switch (perceptual_rendering_intent_gamut) { - case 0x70726D67: // 'prmg' - return "Perceptual reference medium gamut"sv; - } - // "It is possible that the ICC will define other signature values in the future." - return {}; -} - -Optional SignatureTagData::saturation_rendering_intent_gamut_signature_name(u32 saturation_rendering_intent_gamut) -{ - // Table 28 — Saturation rendering intent gamut - switch (saturation_rendering_intent_gamut) { - case 0x70726D67: // 'prmg' - return "Perceptual reference medium gamut"sv; - } - // "It is possible that the ICC will define other signature values in the future." - return {}; -} - -Optional SignatureTagData::technology_signature_name(u32 technology) -{ - // Table 29 — Technology signatures - switch (technology) { - case 0x6673636E: // 'fscn' - return "Film scanner"sv; - case 0x6463616D: // 'dcam' - return "Digital camera"sv; - case 0x7273636E: // 'rscn' - return "Reflective scanner"sv; - case 0x696A6574: // 'ijet' - return "Ink jet printer"sv; - case 0x74776178: // 'twax' - return "Thermal wax printer"sv; - case 0x6570686F: // 'epho' - return "Electrophotographic printer"sv; - case 0x65737461: // 'esta' - return "Electrostatic printer"sv; - case 0x64737562: // 'dsub' - return "Dye sublimation printer"sv; - case 0x7270686F: // 'rpho' - return "Photographic paper printer"sv; - case 0x6670726E: // 'fprn' - return "Film writer"sv; - case 0x7669646D: // 'vidm' - return "Video monitor"sv; - case 0x76696463: // 'vidc' - return "Video camera"sv; - case 0x706A7476: // 'pjtv' - return "Projection television"sv; - case 0x43525420: // 'CRT ' - return "Cathode ray tube display"sv; - case 0x504D4420: // 'PMD ' - return "Passive matrix display"sv; - case 0x414D4420: // 'AMD ' - return "Active matrix display"sv; - case 0x4C434420: // 'LCD ' - return "Liquid crystal display"sv; - case 0x4F4C4544: // 'OLED' - return "Organic LED display"sv; - case 0x4B504344: // 'KPCD' - return "Photo CD"sv; - case 0x696D6773: // 'imgs' - return "Photographic image setter"sv; - case 0x67726176: // 'grav' - return "Gravure"sv; - case 0x6F666673: // 'offs' - return "Offset lithography"sv; - case 0x73696C6B: // 'silk' - return "Silkscreen"sv; - case 0x666C6578: // 'flex' - return "Flexography"sv; - case 0x6D706673: // 'mpfs' - return "Motion picture film scanner"sv; - case 0x6D706672: // 'mpfr' - return "Motion picture film recorder"sv; - case 0x646D7063: // 'dmpc' - return "Digital motion picture camera"sv; - case 0x64636A70: // 'dcpj' - return "Digital cinema projector"sv; - } - // The spec does *not* say that other values are reserved for future use, but it says that for - // all other tags using signatureType. So return a {} here too instead of VERIFY_NOT_REACHED(). - return {}; -} - -Optional SignatureTagData::name_for_tag(TagSignature tag) -{ - if (tag == colorimetricIntentImageStateTag) - return colorimetric_intent_image_state_signature_name(signature()); - if (tag == perceptualRenderingIntentGamutTag) - return perceptual_rendering_intent_gamut_signature_name(signature()); - if (tag == saturationRenderingIntentGamutTag) - return saturation_rendering_intent_gamut_signature_name(signature()); - if (tag == technologyTag) - return technology_signature_name(signature()); - return {}; -} - -ErrorOr> TextDescriptionTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v2, 6.5.17 textDescriptionType - // textDescriptionType is no longer in the V4 spec. - // In both the V2 and V4 specs, 'desc' is a required tag. In V4, it has type multiLocalizedUnicodeType, - // but in V2 it has type textDescriptionType. Since 'desc' is required, this type is present in every - // V2 icc file, and there are still many V2 files in use. So textDescriptionType is here to stay for now. - // It's a very 90s type, preceding universal adoption of Unicode. - - // "The textDescriptionType is a complex structure that contains three types of text description structures: - // 7-bit ASCII, Unicode and ScriptCode. Since no single standard method for specifying localizable character - // sets exists across the major platform vendors, including all three provides access for the major operating - // systems. The 7-bit ASCII description is to be an invariant, nonlocalizable name for consistent reference. - // It is preferred that both the Unicode and ScriptCode structures be properly localized." - - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - // 7-bit ASCII - - // "ASCII: The count is the length of the string in bytes including the null terminator." - if (bytes.size() < 3 * sizeof(u32)) - return Error::from_string_literal("ICC::Profile: textDescriptionType has not enough data for ASCII size"); - u32 ascii_description_length = *bit_cast const*>(bytes.data() + 8); - - Checked ascii_description_end = 3 * sizeof(u32); - ascii_description_end += ascii_description_length; - if (ascii_description_end.has_overflow() || bytes.size() < ascii_description_end.value()) - return Error::from_string_literal("ICC::Profile: textDescriptionType has not enough data for ASCII description"); - - u8 const* ascii_description_data = bytes.data() + 3 * sizeof(u32); - for (u32 i = 0; i < ascii_description_length; ++i) { - if (ascii_description_data[i] >= 128) - return Error::from_string_literal("ICC::Profile: textDescriptionType ASCII description not 7-bit ASCII"); - } - - if (ascii_description_length == 0) - return Error::from_string_literal("ICC::Profile: textDescriptionType ASCII description length does not include trailing \\0"); - - if (ascii_description_data[ascii_description_length - 1] != '\0') - return Error::from_string_literal("ICC::Profile: textDescriptionType ASCII description not \\0-terminated"); - - StringView ascii_description { ascii_description_data, ascii_description_length - 1 }; - - // Unicode - - Checked unicode_metadata_end = ascii_description_end; - unicode_metadata_end += 2 * sizeof(u32); - if (unicode_metadata_end.has_overflow() || bytes.size() < unicode_metadata_end.value()) - return Error::from_string_literal("ICC::Profile: textDescriptionType has not enough data for Unicode metadata"); - - // "Because the Unicode language code and Unicode count immediately follow the ASCII description, - // their alignment is not correct when the ASCII count is not a multiple of four" - // So we can't use BigEndian here. - u8 const* cursor = ascii_description_data + ascii_description_length; - u32 unicode_language_code = (u32)(cursor[0] << 24) | (u32)(cursor[1] << 16) | (u32)(cursor[2] << 8) | (u32)cursor[3]; - cursor += 4; - - // "Unicode: The count is the number of characters including a Unicode null where a character is always two bytes." - // This implies UCS-2. - u32 unicode_description_length = (u32)(cursor[0] << 24) | (u32)(cursor[1] << 16) | (u32)(cursor[2] << 8) | (u32)cursor[3]; - cursor += 4; - - Checked unicode_desciption_end = unicode_description_length; - unicode_desciption_end *= 2; - unicode_desciption_end += unicode_metadata_end; - if (unicode_desciption_end.has_overflow() || bytes.size() < unicode_desciption_end.value()) - return Error::from_string_literal("ICC::Profile: textDescriptionType has not enough data for Unicode description"); - - u8 const* unicode_description_data = cursor; - cursor += 2 * unicode_description_length; - for (u32 i = 0; i < unicode_description_length; ++i) { - u16 code_point = (u16)(unicode_description_data[2 * i] << 8) | (u16)unicode_description_data[2 * i + 1]; - if (is_unicode_surrogate(code_point)) - return Error::from_string_literal("ICC::Profile: textDescriptionType Unicode description is not valid UCS-2"); - } - - // If Unicode is not native on the platform, then the Unicode language code and Unicode count should be - // filled in as 0, with no data placed in the Unicode localizable profile description area. - Optional unicode_description; - if (unicode_description_length > 0) { - u32 byte_size_without_nul = 2 * (unicode_description_length - 1); - u16 last_code_point = (u16)(unicode_description_data[byte_size_without_nul] << 8) | (u16)unicode_description_data[byte_size_without_nul + 1]; - if (last_code_point != 0) - return Error::from_string_literal("ICC::Profile: textDescriptionType Unicode description not \\0-terminated"); - - StringView utf_16be_data { unicode_description_data, byte_size_without_nul }; - unicode_description = TRY(TextCodec::decoder_for("utf-16be"sv)->to_utf8(utf_16be_data)); - } - - // ScriptCode - - // What is a script code? It's an old, obsolete mac thing. It looks like it's documented in - // https://developer.apple.com/library/archive/documentation/mac/pdf/Text.pdf - // "Script Codes, Language Codes, and Region Codes 1", PDF page 82. - // I haven't found a complete explanation though. PDF page 84 suggests that: - // - There are 16 script codes - // - 0 is Roman, 1 is Japanese, 2 is Chinese, 3 is Korean, 9 is Devanagari - // Roman uses https://en.wikipedia.org/wiki/Mac_OS_Roman as encoding (also on page 89), - // and "All non-Roman script systems include Roman as a subscript" (page 87). - - // Aha, "Script Codes 6" on page 676 has the complete list! There are 32 of them. - // The document mentions that each script code possibly has its own encoding, but I haven't found - // details on the encodings for script codes other than 0 (which uses Mac OS Roman). - // http://www.kreativekorp.com/charset/encoding/ has an unofficial list of old Mac OS encodings, - // but it's not clear to me which script codes map to which encoding. - - // From here on, quotes are from the ICC spec on textDescriptionType again. - - // "The ScriptCode code is misaligned when the ASCII count is odd." - // So don't use BigEndian here. - u16 scriptcode_code = (u16)(cursor[0] << 8) | (u32)cursor[1]; - cursor += 2; - - // "ScriptCode: The count is the length of the string in bytes including the terminating null." - u8 macintosh_description_length = *cursor; - cursor += 1; - - Checked macintosh_description_end = unicode_desciption_end; - macintosh_description_end += 3; - macintosh_description_end += macintosh_description_length; - if (macintosh_description_length > 67 || macintosh_description_end.has_overflow() || macintosh_description_end.value() > bytes.size()) - return Error::from_string_literal("ICC::Profile: textDescriptionType ScriptCode description too long"); - - u8 const* macintosh_description_data = cursor; - - // "If Scriptcode is not native on the platform, then the ScriptCode code and ScriptCode count should be filled - // in as 0. The 67-byte localizable Macintosh profile description should be filled with 0’s." - Optional macintosh_description; - if (macintosh_description_length > 0) { - // ScriptCode is old-timey and a complicated to fully support. Lightroom Classic does write the ScriptCode section of textDescriptionType. - // But supporting only ASCII MacRoman is good enough for those files, and easy to implement, so let's do only that for now. - if (scriptcode_code == 0) { // MacRoman - if (macintosh_description_data[macintosh_description_length - 1] != '\0') - return Error::from_string_literal("ICC::Profile: textDescriptionType ScriptCode not \\0-terminated"); - - macintosh_description = TRY(TextCodec::decoder_for("x-mac-roman"sv)->to_utf8({ macintosh_description_data, (size_t)macintosh_description_length - 1 })); - } else { - dbgln("TODO: ICCProfile textDescriptionType ScriptCode {}, length {}", scriptcode_code, macintosh_description_length); - } - } - - return try_make_ref_counted(offset, size, TRY(String::from_utf8(ascii_description)), unicode_language_code, move(unicode_description), move(macintosh_description)); -} - -ErrorOr> TextTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.24 textType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - // "The textType is a simple text structure that contains a 7-bit ASCII text string. The length of the string is obtained - // by subtracting 8 from the element size portion of the tag itself. This string shall be terminated with a 00h byte." - u32 length = bytes.size() - 8; - - u8 const* text_data = bytes.data() + 8; - for (u32 i = 0; i < length; ++i) { - if (text_data[i] >= 128) - return Error::from_string_literal("ICC::Profile: textType data not 7-bit ASCII"); - } - - if (length == 0) - return Error::from_string_literal("ICC::Profile: textType too short for \\0 byte"); - - if (text_data[length - 1] != '\0') - return Error::from_string_literal("ICC::Profile: textType data not \\0-terminated"); - - return try_make_ref_counted(offset, size, TRY(String::from_utf8(StringView(text_data, length - 1)))); -} - -ErrorOr> ViewingConditionsTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.30 viewingConditionsType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - if (bytes.size() < 2 * sizeof(u32) + sizeof(ViewingConditionsHeader)) - return Error::from_string_literal("ICC::Profile: viewingConditionsType has not enough data"); - - auto& header = *bit_cast(bytes.data() + 8); - - TRY(MeasurementTagData::validate_standard_illuminant(header.illuminant_type)); - - return try_make_ref_counted(offset, size, header.unnormalized_ciexyz_values_for_illuminant, - header.unnormalized_ciexyz_values_for_surround, header.illuminant_type); -} - -ErrorOr> XYZTagData::from_bytes(ReadonlyBytes bytes, u32 offset, u32 size) -{ - // ICC v4, 10.31 XYZType - VERIFY(tag_type(bytes) == Type); - TRY(check_reserved(bytes)); - - // "The XYZType contains an array of three encoded values for PCSXYZ, CIEXYZ, or nCIEXYZ values. The - // number of sets of values is determined from the size of the tag." - size_t byte_size = bytes.size() - 8; - if (byte_size % sizeof(XYZNumber) != 0) - return Error::from_string_literal("ICC::Profile: XYZType has wrong size"); - - size_t xyz_count = byte_size / sizeof(XYZNumber); - auto* raw_xyzs = bit_cast(bytes.data() + 8); - Vector xyzs; - TRY(xyzs.try_resize(xyz_count)); - for (size_t i = 0; i < xyz_count; ++i) - xyzs[i] = (XYZ)raw_xyzs[i]; - - return try_make_ref_counted(offset, size, move(xyzs)); -} - -} diff --git a/Libraries/LibGfx/ICC/TagTypes.h b/Libraries/LibGfx/ICC/TagTypes.h deleted file mode 100644 index f62b1d3eff07..000000000000 --- a/Libraries/LibGfx/ICC/TagTypes.h +++ /dev/null @@ -1,1381 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace Gfx::ICC { - -// Does one-dimensional linear interpolation over a lookup table. -// Takes a span of values an x in [0.0, 1.0]. -// Finds the two values in the span closest to x (where x = 0.0 is the span's first element and x = 1.0 the span's last element), -// and linearly interpolates between those two values, assumes all values are the same amount apart. -template -float lerp_1d(ReadonlySpan values, float x) -{ - size_t n = values.size() - 1; - size_t i = min(static_cast(x * n), n - 1); - return mix(static_cast(values[i]), static_cast(values[i + 1]), x * n - i); -} - -// Does multi-dimensional linear interpolation over a lookup table. -// `size(i)` should returns the number of samples in the i'th dimension. -// `sample()` gets a vector where 0 <= i'th coordinate < size(i) and should return the value of the look-up table at that position. -inline FloatVector3 lerp_nd(Function size, Function const&)> sample, ReadonlySpan x) -{ - unsigned left_index[x.size()]; - float factor[x.size()]; - for (size_t i = 0; i < x.size(); ++i) { - unsigned n = size(i) - 1; - float ec = x[i] * n; - left_index[i] = min(static_cast(ec), n - 1); - factor[i] = ec - left_index[i]; - } - - FloatVector3 sample_output {}; - // The i'th bit of mask indicates if the i'th coordinate is rounded up or down. - unsigned coordinates[x.size()]; - ReadonlySpan coordinates_span { coordinates, x.size() }; - for (size_t mask = 0; mask < (1u << x.size()); ++mask) { - float sample_weight = 1.0f; - for (size_t i = 0; i < x.size(); ++i) { - coordinates[i] = left_index[i] + ((mask >> i) & 1u); - sample_weight *= ((mask >> i) & 1u) ? factor[i] : 1.0f - factor[i]; - } - sample_output += sample(coordinates_span) * sample_weight; - } - - return sample_output; -} - -using S15Fixed16 = AK::FixedPoint<16, i32>; -using U16Fixed16 = AK::FixedPoint<16, u32>; - -struct XYZ { - float X { 0 }; - float Y { 0 }; - float Z { 0 }; - - bool operator==(const XYZ&) const = default; -}; - -TagTypeSignature tag_type(ReadonlyBytes tag_bytes); - -class TagData : public RefCounted { -public: - u32 offset() const { return m_offset; } - u32 size() const { return m_size; } - TagTypeSignature type() const { return m_type; } - - virtual ~TagData() = default; - -protected: - TagData(u32 offset, u32 size, TagTypeSignature type) - : m_offset(offset) - , m_size(size) - , m_type(type) - { - } - -private: - u32 m_offset; - u32 m_size; - TagTypeSignature m_type; -}; - -class UnknownTagData : public TagData { -public: - UnknownTagData(u32 offset, u32 size, TagTypeSignature type) - : TagData(offset, size, type) - { - } -}; - -// ICC v4, 10.2 chromaticityType -class ChromaticityTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6368726D }; // 'chrm' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - // ICC v4, Table 31 — Colorant and phosphor encoding - enum class PhosphorOrColorantType : u16 { - Unknown = 0, - ITU_R_BT_709_2 = 1, - SMPTE_RP145 = 2, - EBU_Tech_3213_E = 3, - P22 = 4, - P3 = 5, - ITU_R_BT_2020 = 6, - }; - - static StringView phosphor_or_colorant_type_name(PhosphorOrColorantType); - - struct xyCoordinate { - U16Fixed16 x; - U16Fixed16 y; - }; - - ChromaticityTagData(u32 offset, u32 size, PhosphorOrColorantType phosphor_or_colorant_type, Vector xy_coordinates) - : TagData(offset, size, Type) - , m_phosphor_or_colorant_type(phosphor_or_colorant_type) - , m_xy_coordinates(move(xy_coordinates)) - { - } - - PhosphorOrColorantType phosphor_or_colorant_type() const { return m_phosphor_or_colorant_type; } - Vector xy_coordinates() const { return m_xy_coordinates; } - -private: - PhosphorOrColorantType m_phosphor_or_colorant_type; - Vector m_xy_coordinates; -}; - -// ICC v4, 10.3 cicpType -// "The cicpType specifies Coding-independent code points for video signal type identification." -// See presentations at https://www.color.org/events/HDR_experts.xalter for background. -class CicpTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x63696370 }; // 'cicp' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - CicpTagData(u32 offset, u32 size, u8 color_primaries, u8 transfer_characteristics, u8 matrix_coefficients, u8 video_full_range_flag) - : TagData(offset, size, Type) - , m_color_primaries(color_primaries) - , m_transfer_characteristics(transfer_characteristics) - , m_matrix_coefficients(matrix_coefficients) - , m_video_full_range_flag(video_full_range_flag) - { - } - - // "The fields ColourPrimaries, TransferCharacteristics, MatrixCoefficients, and VideoFullRangeFlag shall be - // encoded as specified in Recommendation ITU-T H.273. Recommendation ITU-T H.273 (ISO/IEC 23091-2) - // provides detailed descriptions of the code values and their interpretation." - u8 color_primaries() const { return m_color_primaries; } - u8 transfer_characteristics() const { return m_transfer_characteristics; } - u8 matrix_coefficients() const { return m_matrix_coefficients; } - u8 video_full_range_flag() const { return m_video_full_range_flag; } - -private: - u8 m_color_primaries; - u8 m_transfer_characteristics; - u8 m_matrix_coefficients; - u8 m_video_full_range_flag; -}; - -// ICC v4, 10.6 curveType -class CurveTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x63757276 }; // 'curv' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset); - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - CurveTagData(u32 offset, u32 size, Vector values) - : TagData(offset, size, Type) - , m_values(move(values)) - { - } - - // "The curveType embodies a one-dimensional function which maps an input value in the domain of the function - // to an output value in the range of the function. The domain and range values are in the range of 0,0 to 1,0. - // - When n is equal to 0, an identity response is assumed. - // - When n is equal to 1, then the curve value shall be interpreted as a gamma value, encoded as a - // u8Fixed8Number. Gamma shall be interpreted as the exponent in the equation y = pow(x,γ) and not as an inverse. - // - When n is greater than 1, the curve values (which embody a sampled one-dimensional function) shall be - // defined as follows: - // - The first entry represents the input value 0,0, the last entry represents the input value 1,0, and intermediate - // entries are uniformly spaced using an increment of 1,0/(n-1). These entries are encoded as uInt16Numbers - // (i.e. the values represented by the entries, which are in the range 0,0 to 1,0 are encoded in the range 0 to - // 65 535). Function values between the entries shall be obtained through linear interpolation." - Vector const& values() const { return m_values; } - - // x must be in [0..1]. - float evaluate(float x) const - { - VERIFY(0.f <= x && x <= 1.f); - - if (values().is_empty()) - return x; - - if (values().size() == 1) - return powf(x, values()[0] / (float)0x100); - - return lerp_1d(values().span(), x) / 65535.0f; - } - - // y must be in [0..1]. - float evaluate_inverse(float y) const - { - VERIFY(0.f <= y && y <= 1.f); - - if (values().is_empty()) - return y; - - if (values().size() == 1) - return powf(y, 1.f / (values()[0] / (float)0x100)); - - // FIXME: Verify somewhere that: - // * values() is non-decreasing - // * values()[0] is 0, values()[values().size() - 1] is 65535 - - // FIXME: Use binary search. - size_t n = values().size() - 1; - size_t i = 0; - for (; i < n; ++i) { - if (values()[i] / 65535.f <= y && y <= values()[i + 1] / 65535.f) - break; - } - - float x1 = i / (float)n; - float y1 = values()[i] / 65535.f; - float x2 = (i + 1) / (float)n; - float y2 = values()[i + 1] / 65535.f; - - // Flat line segment? - if (y1 == y2) - return (x1 + x2) / 2; - - return (y - y1) / (y2 - y1) * (x2 - x1) + x1; // Same as `((y - y1) / (y2 - y1) + i) / (float)n` - } - -private: - Vector m_values; -}; - -struct EMatrix3x3 { - // A row-major 3x3 matrix: - // [ e[0] e[1] e[2] ] - // [ e[3] e[4] e[5] ] * v - // ] e[6] e[7] e[8] ] - S15Fixed16 e[9]; - - S15Fixed16 const& operator[](unsigned i) const - { - VERIFY(i < array_size(e)); - return e[i]; - } -}; - -// ICC v4, 10.10 lut16Type -class Lut16TagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6D667432 }; // 'mft2' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - Lut16TagData(u32 offset, u32 size, EMatrix3x3 e, - u8 number_of_input_channels, u8 number_of_output_channels, u8 number_of_clut_grid_points, - u16 number_of_input_table_entries, u16 number_of_output_table_entries, - Vector input_tables, Vector clut_values, Vector output_tables) - : TagData(offset, size, Type) - , m_e(e) - , m_number_of_input_channels(number_of_input_channels) - , m_number_of_output_channels(number_of_output_channels) - , m_number_of_clut_grid_points(number_of_clut_grid_points) - , m_number_of_input_table_entries(number_of_input_table_entries) - , m_number_of_output_table_entries(number_of_output_table_entries) - , m_input_tables(move(input_tables)) - , m_clut_values(move(clut_values)) - , m_output_tables(move(output_tables)) - { - VERIFY(m_input_tables.size() == number_of_input_channels * number_of_input_table_entries); - VERIFY(m_output_tables.size() == number_of_output_channels * number_of_output_table_entries); - - VERIFY(number_of_input_table_entries >= 2); - VERIFY(number_of_input_table_entries <= 4096); - VERIFY(number_of_output_table_entries >= 2); - VERIFY(number_of_output_table_entries <= 4096); - } - - EMatrix3x3 const& e_matrix() const { return m_e; } - - u8 number_of_input_channels() const { return m_number_of_input_channels; } - u8 number_of_output_channels() const { return m_number_of_output_channels; } - u8 number_of_clut_grid_points() const { return m_number_of_clut_grid_points; } - - u16 number_of_input_table_entries() const { return m_number_of_input_table_entries; } - u16 number_of_output_table_entries() const { return m_number_of_output_table_entries; } - - Vector const& input_tables() const { return m_input_tables; } - Vector const& clut_values() const { return m_clut_values; } - Vector const& output_tables() const { return m_output_tables; } - - ErrorOr evaluate(ColorSpace input_space, ColorSpace connection_space, ReadonlyBytes) const; - -private: - EMatrix3x3 m_e; - - u8 m_number_of_input_channels; - u8 m_number_of_output_channels; - u8 m_number_of_clut_grid_points; - - u16 m_number_of_input_table_entries; - u16 m_number_of_output_table_entries; - - Vector m_input_tables; - Vector m_clut_values; - Vector m_output_tables; -}; - -// ICC v4, 10.11 lut8Type -class Lut8TagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6D667431 }; // 'mft1' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - Lut8TagData(u32 offset, u32 size, EMatrix3x3 e, - u8 number_of_input_channels, u8 number_of_output_channels, u8 number_of_clut_grid_points, - u16 number_of_input_table_entries, u16 number_of_output_table_entries, - Vector input_tables, Vector clut_values, Vector output_tables) - : TagData(offset, size, Type) - , m_e(e) - , m_number_of_input_channels(number_of_input_channels) - , m_number_of_output_channels(number_of_output_channels) - , m_number_of_clut_grid_points(number_of_clut_grid_points) - , m_number_of_input_table_entries(number_of_input_table_entries) - , m_number_of_output_table_entries(number_of_output_table_entries) - , m_input_tables(move(input_tables)) - , m_clut_values(move(clut_values)) - , m_output_tables(move(output_tables)) - { - VERIFY(m_input_tables.size() == number_of_input_channels * number_of_input_table_entries); - VERIFY(m_output_tables.size() == number_of_output_channels * number_of_output_table_entries); - - VERIFY(number_of_input_table_entries == 256); - VERIFY(number_of_output_table_entries == 256); - } - - EMatrix3x3 const& e_matrix() const { return m_e; } - - u8 number_of_input_channels() const { return m_number_of_input_channels; } - u8 number_of_output_channels() const { return m_number_of_output_channels; } - u8 number_of_clut_grid_points() const { return m_number_of_clut_grid_points; } - - u16 number_of_input_table_entries() const { return m_number_of_input_table_entries; } - u16 number_of_output_table_entries() const { return m_number_of_output_table_entries; } - - Vector const& input_tables() const { return m_input_tables; } - Vector const& clut_values() const { return m_clut_values; } - Vector const& output_tables() const { return m_output_tables; } - - ErrorOr evaluate(ColorSpace input_space, ColorSpace connection_space, ReadonlyBytes) const; - -private: - EMatrix3x3 m_e; - - u8 m_number_of_input_channels; - u8 m_number_of_output_channels; - u8 m_number_of_clut_grid_points; - - u16 m_number_of_input_table_entries; - u16 m_number_of_output_table_entries; - - Vector m_input_tables; - Vector m_clut_values; - Vector m_output_tables; -}; - -struct EMatrix3x4 { - // A row-major 3x3 matrix followed by a translation vector: - // [ e[0] e[1] e[2] ] [ e[9] ] - // [ e[3] e[4] e[5] ] * v + [ e[10] ] - // [ e[6] e[7] e[8] ] [ e[11] ] - S15Fixed16 e[12]; - - S15Fixed16 const& operator[](unsigned i) const - { - VERIFY(i < array_size(e)); - return e[i]; - } -}; - -struct CLUTData { - Vector number_of_grid_points_in_dimension; - Variant, Vector> values; -}; - -using LutCurveType = NonnullRefPtr; // FIXME: Variant instead? - -bool are_valid_curves(Optional> const& curves); - -// ICC v4, 10.12 lutAToBType -class LutAToBTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6D414220 }; // 'mAB ' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - LutAToBTagData(u32 offset, u32 size, u8 number_of_input_channels, u8 number_of_output_channels, - Optional> a_curves, Optional clut, Optional> m_curves, Optional e, Vector b_curves) - : TagData(offset, size, Type) - , m_number_of_input_channels(number_of_input_channels) - , m_number_of_output_channels(number_of_output_channels) - , m_a_curves(move(a_curves)) - , m_clut(move(clut)) - , m_m_curves(move(m_curves)) - , m_e(e) - , m_b_curves(move(b_curves)) - { - VERIFY(!m_a_curves.has_value() || m_a_curves->size() == m_number_of_input_channels); - VERIFY(!m_m_curves.has_value() || m_m_curves->size() == m_number_of_output_channels); - VERIFY(m_b_curves.size() == m_number_of_output_channels); - - VERIFY(number_of_input_channels == number_of_output_channels || m_clut.has_value()); - VERIFY(m_a_curves.has_value() == m_clut.has_value()); - VERIFY(m_m_curves.has_value() == m_e.has_value()); - - VERIFY(are_valid_curves(m_a_curves)); - VERIFY(are_valid_curves(m_m_curves)); - VERIFY(are_valid_curves(m_b_curves)); - } - - u8 number_of_input_channels() const { return m_number_of_input_channels; } - u8 number_of_output_channels() const { return m_number_of_output_channels; } - - Optional> const& a_curves() const { return m_a_curves; } - Optional const& clut() const { return m_clut; } - Optional> const& m_curves() const { return m_m_curves; } - Optional const& e_matrix() const { return m_e; } - Vector const& b_curves() const { return m_b_curves; } - - // Returns the result of the LUT pipeline for u8 inputs. - ErrorOr evaluate(ColorSpace connection_space, ReadonlyBytes) const; - -private: - u8 m_number_of_input_channels; - u8 m_number_of_output_channels; - - // "It is possible to use any or all of these processing elements. At least one processing element shall be included. - // Only the following combinations are permitted: - // - B; - // - M, Matrix, B; - // - A, CLUT, B; - // - A, CLUT, M, Matrix, B." - // This seems to imply that the B curve is not in fact optional. - Optional> m_a_curves; - Optional m_clut; - Optional> m_m_curves; - Optional m_e; - Vector m_b_curves; -}; - -// ICC v4, 10.13 lutBToAType -class LutBToATagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6D424120 }; // 'mBA ' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - LutBToATagData(u32 offset, u32 size, u8 number_of_input_channels, u8 number_of_output_channels, - Vector b_curves, Optional e, Optional> m_curves, Optional clut, Optional> a_curves) - : TagData(offset, size, Type) - , m_number_of_input_channels(number_of_input_channels) - , m_number_of_output_channels(number_of_output_channels) - , m_b_curves(move(b_curves)) - , m_e(e) - , m_m_curves(move(m_curves)) - , m_clut(move(clut)) - , m_a_curves(move(a_curves)) - { - VERIFY(m_b_curves.size() == m_number_of_input_channels); - VERIFY(!m_m_curves.has_value() || m_m_curves->size() == m_number_of_input_channels); - VERIFY(!m_a_curves.has_value() || m_a_curves->size() == m_number_of_output_channels); - - VERIFY(m_e.has_value() == m_m_curves.has_value()); - VERIFY(m_clut.has_value() == m_a_curves.has_value()); - VERIFY(number_of_input_channels == number_of_output_channels || m_clut.has_value()); - - VERIFY(are_valid_curves(m_b_curves)); - VERIFY(are_valid_curves(m_m_curves)); - VERIFY(are_valid_curves(m_a_curves)); - } - - u8 number_of_input_channels() const { return m_number_of_input_channels; } - u8 number_of_output_channels() const { return m_number_of_output_channels; } - - Vector const& b_curves() const { return m_b_curves; } - Optional const& e_matrix() const { return m_e; } - Optional> const& m_curves() const { return m_m_curves; } - Optional const& clut() const { return m_clut; } - Optional> const& a_curves() const { return m_a_curves; } - - // Returns the result of the LUT pipeline for u8 outputs. - ErrorOr evaluate(ColorSpace connection_space, FloatVector3 const&, Bytes) const; - -private: - u8 m_number_of_input_channels; - u8 m_number_of_output_channels; - - // "It is possible to use any or all of these processing elements. At least one processing element shall be included. - // Only the following combinations are permitted: - // - B; - // - B, Matrix, M; - // - B, CLUT, A; - // - B, Matrix, M, CLUT, A." - // This seems to imply that the B curve is not in fact optional. - Vector m_b_curves; - Optional m_e; - Optional> m_m_curves; - Optional m_clut; - Optional> m_a_curves; -}; - -// ICC v4, 10.14 measurementType -class MeasurementTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6D656173 }; // 'meas' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - // Table 50 — Standard observer encodings - enum class StandardObserver { - Unknown = 0, - CIE_1931_standard_colorimetric_observer = 1, - CIE_1964_standard_colorimetric_observer = 2, - }; - static ErrorOr validate_standard_observer(StandardObserver); - static StringView standard_observer_name(StandardObserver); - - // Table 51 — Measurement geometry encodings - enum class MeasurementGeometry { - Unknown = 0, - Degrees_0_45_or_45_0 = 1, - Degrees_0_d_or_d_0 = 2, - }; - static ErrorOr validate_measurement_geometry(MeasurementGeometry); - static StringView measurement_geometry_name(MeasurementGeometry); - - // Table 53 — Standard illuminant encodings - enum class StandardIlluminant { - Unknown = 0, - D50 = 1, - D65 = 2, - D93 = 3, - F2 = 4, - D55 = 5, - A = 6, - Equi_Power_E = 7, - F8 = 8, - }; - static ErrorOr validate_standard_illuminant(StandardIlluminant); - static StringView standard_illuminant_name(StandardIlluminant); - - MeasurementTagData(u32 offset, u32 size, StandardObserver standard_observer, XYZ tristimulus_value_for_measurement_backing, - MeasurementGeometry measurement_geometry, U16Fixed16 measurement_flare, StandardIlluminant standard_illuminant) - : TagData(offset, size, Type) - , m_standard_observer(standard_observer) - , m_tristimulus_value_for_measurement_backing(tristimulus_value_for_measurement_backing) - , m_measurement_geometry(measurement_geometry) - , m_measurement_flare(measurement_flare) - , m_standard_illuminant(standard_illuminant) - { - } - - StandardObserver standard_observer() const { return m_standard_observer; } - XYZ const& tristimulus_value_for_measurement_backing() const { return m_tristimulus_value_for_measurement_backing; } - MeasurementGeometry measurement_geometry() const { return m_measurement_geometry; } - U16Fixed16 measurement_flare() const { return m_measurement_flare; } - StandardIlluminant standard_illuminant() const { return m_standard_illuminant; } - -private: - StandardObserver m_standard_observer; - XYZ m_tristimulus_value_for_measurement_backing; - MeasurementGeometry m_measurement_geometry; - U16Fixed16 m_measurement_flare; - StandardIlluminant m_standard_illuminant; -}; - -// ICC v4, 10.15 multiLocalizedUnicodeType -class MultiLocalizedUnicodeTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6D6C7563 }; // 'mluc' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - struct Record { - u16 iso_639_1_language_code; - u16 iso_3166_1_country_code; - String text; - }; - - MultiLocalizedUnicodeTagData(u32 offset, u32 size, Vector records) - : TagData(offset, size, Type) - , m_records(move(records)) - { - } - - Vector const& records() const { return m_records; } - -private: - Vector m_records; -}; - -// ICC v4, 10.17 namedColor2Type -class NamedColor2TagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x6E636C32 }; // 'ncl2' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - // "The encoding is the same as the encodings for the PCS colour spaces - // as described in 6.3.4.2 and 10.8. Only PCSXYZ and - // legacy 16-bit PCSLAB encodings are permitted. PCS - // values shall be relative colorimetric." - // (Which I suppose implies this type must not be used in DeviceLink profiles unless - // the device's PCS happens to be PCSXYZ or PCSLAB.) - struct XYZOrLAB { - union { - struct { - u16 x, y, z; - } xyz; - struct { - u16 L, a, b; - } lab; - }; - }; - - NamedColor2TagData(u32 offset, u32 size, u32 vendor_specific_flag, u32 number_of_device_coordinates, String prefix, String suffix, - Vector root_names, Vector pcs_coordinates, Vector device_coordinates) - : TagData(offset, size, Type) - , m_vendor_specific_flag(vendor_specific_flag) - , m_number_of_device_coordinates(number_of_device_coordinates) - , m_prefix(move(prefix)) - , m_suffix(move(suffix)) - , m_root_names(move(root_names)) - , m_pcs_coordinates(move(pcs_coordinates)) - , m_device_coordinates(move(device_coordinates)) - { - VERIFY(root_names.size() == pcs_coordinates.size()); - VERIFY(root_names.size() * number_of_device_coordinates == device_coordinates.size()); - - for (u8 byte : m_prefix.bytes()) - VERIFY(byte < 128); - VERIFY(m_prefix.bytes().size() < 32); - - for (u8 byte : m_suffix.bytes()) - VERIFY(byte < 128); - VERIFY(m_suffix.bytes().size() < 32); - - for (auto const& root_name : m_root_names) { - for (u8 byte : root_name.bytes()) - VERIFY(byte < 128); - VERIFY(root_name.bytes().size() < 32); - } - } - - // "(least-significant 16 bits reserved for ICC use)" - u32 vendor_specific_flag() const { return m_vendor_specific_flag; } - - // "If this field is 0, device coordinates are not provided." - u32 number_of_device_coordinates() const { return m_number_of_device_coordinates; } - - u32 size() const { return m_root_names.size(); } - - // "In order to maintain maximum portability, it is strongly recommended that - // special characters of the 7-bit ASCII set not be used." - String const& prefix() const { return m_prefix; } // "7-bit ASCII" - String const& suffix() const { return m_suffix; } // "7-bit ASCII" - String const& root_name(u32 index) const { return m_root_names[index]; } // "7-bit ASCII" - - // Returns 7-bit ASCII. - ErrorOr color_name(u32 index) const; - - // "The PCS representation corresponds to the header’s PCS field." - XYZOrLAB const& pcs_coordinates(u32 index) const { return m_pcs_coordinates[index]; } - - // "The device representation corresponds to the header’s “data colour space” field." - u16 const* device_coordinates(u32 index) const - { - VERIFY((index + 1) * m_number_of_device_coordinates <= m_device_coordinates.size()); - return m_device_coordinates.data() + index * m_number_of_device_coordinates; - } - -private: - u32 m_vendor_specific_flag; - u32 m_number_of_device_coordinates; - String m_prefix; - String m_suffix; - Vector m_root_names; - Vector m_pcs_coordinates; - Vector m_device_coordinates; -}; - -// ICC v4, 10.18 parametricCurveType -class ParametricCurveTagData : public TagData { -public: - // Table 68 — parametricCurveType function type encoding - enum class FunctionType { - // Y = X**g - Type0, - - // Y = (a*X + b)**g if X >= -b/a - // = 0 else - Type1, - CIE_122_1966 = Type1, - - // Y = (a*X + b)**g + c if X >= -b/a - // = c else - Type2, - IEC_61966_1 = Type2, - - // Y = (a*X + b)**g if X >= d - // = c*X else - Type3, - IEC_61966_2_1 = Type3, - sRGB = Type3, - - // Y = (a*X + b)**g + e if X >= d - // = c*X + f else - Type4, - }; - - // "The domain and range of each function shall be [0,0 1,0]. Any function value outside the range shall be clipped - // to the range of the function." - // "NOTE 1 The parameters selected for a parametric curve can result in complex or undefined values for the input range - // used. This can occur, for example, if d < -b/a. In such cases the behaviour of the curve is undefined." - - static constexpr TagTypeSignature Type { 0x70617261 }; // 'para' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset); - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - ParametricCurveTagData(u32 offset, u32 size, FunctionType function_type, Array parameters) - : TagData(offset, size, Type) - , m_function_type(function_type) - , m_parameters(move(parameters)) - { - } - - FunctionType function_type() const { return m_function_type; } - - static unsigned parameter_count(FunctionType); - - unsigned parameter_count() const { return parameter_count(function_type()); } - S15Fixed16 parameter(size_t i) const - { - VERIFY(i < parameter_count()); - return m_parameters[i]; - } - - S15Fixed16 g() const { return m_parameters[0]; } - S15Fixed16 a() const - { - VERIFY(function_type() >= FunctionType::Type1); - return m_parameters[1]; - } - S15Fixed16 b() const - { - VERIFY(function_type() >= FunctionType::Type1); - return m_parameters[2]; - } - S15Fixed16 c() const - { - VERIFY(function_type() >= FunctionType::Type2); - return m_parameters[3]; - } - S15Fixed16 d() const - { - VERIFY(function_type() >= FunctionType::Type3); - return m_parameters[4]; - } - S15Fixed16 e() const - { - VERIFY(function_type() >= FunctionType::Type4); - return m_parameters[5]; - } - S15Fixed16 f() const - { - VERIFY(function_type() >= FunctionType::Type4); - return m_parameters[6]; - } - - // x must be in [0..1]. - float evaluate(float x) const - { - VERIFY(0.f <= x && x <= 1.f); - - switch (function_type()) { - case FunctionType::Type0: - return powf(x, (float)g()); - case FunctionType::Type1: - if (x >= -(float)b() / (float)a()) - return powf((float)a() * x + (float)b(), (float)g()); - return 0; - case FunctionType::Type2: - if (x >= -(float)b() / (float)a()) - return powf((float)a() * x + (float)b(), (float)g()) + (float)c(); - return (float)c(); - case FunctionType::Type3: - if (x >= (float)d()) - return powf((float)a() * x + (float)b(), (float)g()); - return (float)c() * x; - case FunctionType::Type4: - if (x >= (float)d()) - return powf((float)a() * x + (float)b(), (float)g()) + (float)e(); - return (float)c() * x + (float)f(); - } - VERIFY_NOT_REACHED(); - } - - // y must be in [0..1]. - float evaluate_inverse(float y) const - { - VERIFY(0.f <= y && y <= 1.f); - - // See "Recommendations" section in https://www.color.org/whitepapers/ICC_White_Paper35-Use_of_the_parametricCurveType.pdf - // Requirements for the curve to be non-decreasing: - // * γ > 0 - // * a > 0 for types 1-4 - // * c ≥ 0 for types 3 and 4 - // - // Types 3 and 4 additionally require: - // To prevent negative discontinuities: - // * cd ≤ (ad + b) for type 3 - // * cd + f ≤ (ad + b)^γ + e for type 4 - // To prevent complex numbers: - // * ad + b ≥ 0 - // FIXME: Check these requirements somewhere. - - switch (function_type()) { - case FunctionType::Type0: - return powf(y, 1.f / (float)g()); - case FunctionType::Type1: - return (powf(y, 1.f / (float)g()) - (float)b()) / (float)a(); - case FunctionType::Type2: - // Only defined for Y >= c, so I suppose this requires c <= 0 in practice (?). - return (powf(y - (float)c(), 1.f / (float)g()) - (float)b()) / (float)a(); - case FunctionType::Type3: - if (y >= (float)c() * (float)d()) - return (powf(y, 1.f / (float)g()) - (float)b()) / (float)a(); - return y / (float)c(); - case FunctionType::Type4: - if (y >= (float)c() * (float)d()) - return (powf(y - (float)e(), 1.f / (float)g()) - (float)b()) / (float)a(); - return (y - (float)f()) / (float)c(); - } - VERIFY_NOT_REACHED(); - } - -private: - FunctionType m_function_type; - - // Contains, in this order, g a b c d e f. - // Not all FunctionTypes use all parameters. - Array m_parameters; -}; - -// ICC v4, 10.22 s15Fixed16ArrayType -class S15Fixed16ArrayTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x73663332 }; // 'sf32' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - S15Fixed16ArrayTagData(u32 offset, u32 size, Vector values) - : TagData(offset, size, Type) - , m_values(move(values)) - { - } - - Vector const& values() const { return m_values; } - -private: - Vector m_values; -}; - -// ICC v4, 10.23 signatureType -class SignatureTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x73696720 }; // 'sig ' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - SignatureTagData(u32 offset, u32 size, u32 signature) - : TagData(offset, size, Type) - , m_signature(signature) - { - } - - u32 signature() const { return m_signature; } - - static Optional colorimetric_intent_image_state_signature_name(u32); - static Optional perceptual_rendering_intent_gamut_signature_name(u32); - static Optional saturation_rendering_intent_gamut_signature_name(u32); - static Optional technology_signature_name(u32); - - Optional name_for_tag(TagSignature); - -private: - u32 m_signature; -}; - -// ICC v2, 6.5.17 textDescriptionType -class TextDescriptionTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x64657363 }; // 'desc' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - TextDescriptionTagData(u32 offset, u32 size, String ascii_description, u32 unicode_language_code, Optional unicode_description, Optional macintosh_description) - : TagData(offset, size, Type) - , m_ascii_description(move(ascii_description)) - , m_unicode_language_code(unicode_language_code) - , m_unicode_description(move(unicode_description)) - , m_macintosh_description(move(macintosh_description)) - { - for (u8 byte : m_ascii_description.bytes()) - VERIFY(byte < 128); - } - - // Guaranteed to be 7-bit ASCII. - String const& ascii_description() const { return m_ascii_description; } - - u32 unicode_language_code() const { return m_unicode_language_code; } - Optional const& unicode_description() const { return m_unicode_description; } - - Optional const& macintosh_description() const { return m_macintosh_description; } - -private: - String m_ascii_description; - - u32 m_unicode_language_code { 0 }; - Optional m_unicode_description; - - Optional m_macintosh_description; -}; - -// ICC v4, 10.24 textType -class TextTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x74657874 }; // 'text' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - TextTagData(u32 offset, u32 size, String text) - : TagData(offset, size, Type) - , m_text(move(text)) - { - for (u8 byte : m_text.bytes()) - VERIFY(byte < 128); - } - - // Guaranteed to be 7-bit ASCII. - String const& text() const { return m_text; } - -private: - String m_text; -}; - -// ICC v4, 10.30 viewingConditionsType -class ViewingConditionsTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x76696577 }; // 'view' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - ViewingConditionsTagData(u32 offset, u32 size, XYZ const& unnormalized_ciexyz_values_for_illuminant, - XYZ const& unnormalized_ciexyz_values_for_surround, MeasurementTagData::StandardIlluminant illuminant_type) - : TagData(offset, size, Type) - , m_unnormalized_ciexyz_values_for_illuminant(unnormalized_ciexyz_values_for_illuminant) - , m_unnormalized_ciexyz_values_for_surround(unnormalized_ciexyz_values_for_surround) - , m_illuminant_type(illuminant_type) - { - } - - XYZ const& unnormalized_ciexyz_values_for_illuminant() const { return m_unnormalized_ciexyz_values_for_illuminant; } - XYZ const& unnormalized_ciexyz_values_for_surround() const { return m_unnormalized_ciexyz_values_for_surround; } - MeasurementTagData::StandardIlluminant illuminant_type() const { return m_illuminant_type; } - -private: - XYZ m_unnormalized_ciexyz_values_for_illuminant; // "(in which Y is in cd/m2)" - XYZ m_unnormalized_ciexyz_values_for_surround; // "(in which Y is in cd/m2)" - MeasurementTagData::StandardIlluminant m_illuminant_type; -}; - -// ICC v4, 10.31 XYZType -class XYZTagData : public TagData { -public: - static constexpr TagTypeSignature Type { 0x58595A20 }; // 'XYZ ' - - static ErrorOr> from_bytes(ReadonlyBytes, u32 offset, u32 size); - - XYZTagData(u32 offset, u32 size, Vector xyzs) - : TagData(offset, size, Type) - , m_xyzs(move(xyzs)) - { - } - - Vector const& xyzs() const { return m_xyzs; } - - XYZ const& xyz() const - { - VERIFY(m_xyzs.size() == 1); - return m_xyzs[0]; - } - -private: - Vector m_xyzs; -}; - -inline ErrorOr Lut16TagData::evaluate(ColorSpace input_space, ColorSpace connection_space, ReadonlyBytes color_u8) const -{ - // See comment at start of LutAToBTagData::evaluate() for the clipping flow. - VERIFY(connection_space == ColorSpace::PCSXYZ || connection_space == ColorSpace::PCSLAB); - VERIFY(number_of_input_channels() == color_u8.size()); - - // FIXME: This will be wrong once Profile::from_pcs_b_to_a() calls this function too. - VERIFY(number_of_output_channels() == 3); - - // ICC v4, 10.11 lut8Type - // "Data is processed using these elements via the following sequence: - // (matrix) ⇨ (1d input tables) ⇨ (multi-dimensional lookup table, CLUT) ⇨ (1d output tables)" - - Vector color; - for (u8 c : color_u8) - color.append(c / 255.0f); - - // "3 x 3 matrix (which shall be the identity matrix unless the input colour space is PCSXYZ)" - // In practice, it's usually RGB or CMYK. - if (input_space == ColorSpace::PCSXYZ) { - EMatrix3x3 const& e = m_e; - color = Vector { - (float)e[0] * color[0] + (float)e[1] * color[1] + (float)e[2] * color[2], - (float)e[3] * color[0] + (float)e[4] * color[1] + (float)e[5] * color[2], - (float)e[6] * color[0] + (float)e[7] * color[1] + (float)e[8] * color[2], - }; - } - - // "The input tables are arrays of 16-bit unsigned values. Each input table consists of a minimum of two and a maximum of 4096 uInt16Number integers. - // Each input table entry is appropriately normalized to the range 0 to 65535. - // The inputTable is of size (InputChannels x inputTableEntries x 2) bytes. - // When stored in this tag, the one-dimensional lookup tables are packed one after another" - for (size_t c = 0; c < color.size(); ++c) - color[c] = lerp_1d(m_input_tables.span().slice(c * m_number_of_input_table_entries, m_number_of_input_table_entries), color[c]) / 65535.0f; - - // "The CLUT is organized as an i-dimensional array with a given number of grid points in each dimension, - // where i is the number of input channels (input tables) in the transform. - // The dimension corresponding to the first input channel varies least rapidly and - // the dimension corresponding to the last input channel varies most rapidly. - // Each grid point value is an o-byte array, where o is the number of output channels. - // The first sequential byte of the entry contains the function value for the first output function, - // the second sequential byte of the entry contains the function value for the second output function, - // and so on until all the output functions have been supplied." - auto sample = [this](ReadonlySpan const& coordinates) { - size_t stride = 3; - size_t offset = 0; - for (int i = coordinates.size() - 1; i >= 0; --i) { - offset += coordinates[i] * stride; - stride *= m_number_of_clut_grid_points; - } - return FloatVector3 { (float)m_clut_values[offset], (float)m_clut_values[offset + 1], (float)m_clut_values[offset + 2] }; - }; - auto size = [this](size_t) { return m_number_of_clut_grid_points; }; - FloatVector3 output_color = lerp_nd(move(size), move(sample), color) / 65535.0f; - - // "The output tables are arrays of 16-bit unsigned values. Each output table consists of a minimum of two and a maximum of 4096 uInt16Number integers. - // Each output table entry is appropriately normalized to the range 0 to 65535. - // The outputTable is of size (OutputChannels x outputTableEntries x 2) bytes. - // When stored in this tag, the one-dimensional lookup tables are packed one after another" - for (u8 c = 0; c < 3; ++c) - output_color[c] = lerp_1d(m_output_tables.span().slice(c * m_number_of_output_table_entries, m_number_of_output_table_entries), output_color[c]) / 65535.0f; - - if (connection_space == ColorSpace::PCSXYZ) { - // Table 11 - PCSXYZ X, Y or Z encoding - output_color *= 65535 / 32768.0f; - } else { - VERIFY(connection_space == ColorSpace::PCSLAB); - - // ICC v4, 10.10 lut16Type - // Note: lut16Type does _not_ use the encoding in 6.3.4.2 General PCS encoding! - - // "To convert colour values from this tag's legacy 16-bit PCSLAB encoding to the 16-bit PCSLAB encoding defined in 6.3.4.2 (Tables 12 and 13), - // multiply all values with 65 535/65 280 (i.e. FFFFh/FF00h). - // Any colour values that are in the value range of legacy 16-bit PCSLAB encoding, but not in the more recent 16-bit PCSLAB encoding, - // shall be clipped on a per-component basis." - output_color *= 65535.0f / 65280.0f; - - // Table 42 — Legacy PCSLAB L* encoding - output_color[0] = clamp(output_color[0] * 100.0f, 0.0f, 100.0f); - - // Table 43 — Legacy PCSLAB a* or PCSLAB b* encoding - output_color[1] = clamp(output_color[1] * 255.0f - 128.0f, -128.0f, 127.0f); - output_color[2] = clamp(output_color[2] * 255.0f - 128.0f, -128.0f, 127.0f); - } - - return output_color; -} - -inline ErrorOr Lut8TagData::evaluate(ColorSpace input_space, ColorSpace connection_space, ReadonlyBytes color_u8) const -{ - // See comment at start of LutAToBTagData::evaluate() for the clipping flow. - VERIFY(connection_space == ColorSpace::PCSXYZ || connection_space == ColorSpace::PCSLAB); - VERIFY(number_of_input_channels() == color_u8.size()); - - // FIXME: This will be wrong once Profile::from_pcs_b_to_a() calls this function too. - VERIFY(number_of_output_channels() == 3); - - // ICC v4, 10.11 lut8Type - // "Data is processed using these elements via the following sequence: - // (matrix) ⇨ (1d input tables) ⇨ (multi-dimensional lookup table, CLUT) ⇨ (1d output tables)" - - Vector color; - for (u8 c : color_u8) - color.append(c / 255.0f); - - // "3 x 3 matrix (which shall be the identity matrix unless the input colour space is PCSXYZ)" - // In practice, it's usually RGB or CMYK. - if (input_space == ColorSpace::PCSXYZ) { - EMatrix3x3 const& e = m_e; - color = Vector { - (float)e[0] * color[0] + (float)e[1] * color[1] + (float)e[2] * color[2], - (float)e[3] * color[0] + (float)e[4] * color[1] + (float)e[5] * color[2], - (float)e[6] * color[0] + (float)e[7] * color[1] + (float)e[8] * color[2], - }; - } - - // "The input tables are arrays of uInt8Number values. Each input table consists of 256 uInt8Number integers. - // Each input table entry is appropriately normalized to the range 0 to 255. - // The inputTable is of size (InputChannels x 256) bytes. - // When stored in this tag, the one-dimensional lookup tables are packed one after another" - for (size_t c = 0; c < color.size(); ++c) - color[c] = lerp_1d(m_input_tables.span().slice(c * 256, 256), color[c]) / 255.0f; - - // "The CLUT is organized as an i-dimensional array with a given number of grid points in each dimension, - // where i is the number of input channels (input tables) in the transform. - // The dimension corresponding to the first input channel varies least rapidly and - // the dimension corresponding to the last input channel varies most rapidly. - // Each grid point value is an o-byte array, where o is the number of output channels. - // The first sequential byte of the entry contains the function value for the first output function, - // the second sequential byte of the entry contains the function value for the second output function, - // and so on until all the output functions have been supplied." - auto sample = [this](ReadonlySpan const& coordinates) { - size_t stride = 3; - size_t offset = 0; - for (int i = coordinates.size() - 1; i >= 0; --i) { - offset += coordinates[i] * stride; - stride *= m_number_of_clut_grid_points; - } - return FloatVector3 { (float)m_clut_values[offset], (float)m_clut_values[offset + 1], (float)m_clut_values[offset + 2] }; - }; - auto size = [this](size_t) { return m_number_of_clut_grid_points; }; - FloatVector3 output_color = lerp_nd(move(size), move(sample), color) / 255.0f; - - // "The output tables are arrays of uInt8Number values. Each output table consists of 256 uInt8Number integers. - // Each output table entry is appropriately normalized to the range 0 to 255. - // The outputTable is of size (OutputChannels x 256) bytes. - // When stored in this tag, the one-dimensional lookup tables are packed one after another" - for (u8 c = 0; c < 3; ++c) - output_color[c] = lerp_1d(m_output_tables.span().slice(c * 256, 256), output_color[c]) / 255.0f; - - if (connection_space == ColorSpace::PCSXYZ) { - // "An 8-bit PCSXYZ encoding has not been defined, so the interpretation of a lut8Type in a profile that uses PCSXYZ is implementation specific." - } else { - VERIFY(connection_space == ColorSpace::PCSLAB); - - // ICC v4, 6.3.4.2 General PCS encoding - // Table 12 — PCSLAB L* encoding - output_color[0] *= 100.0f; - - // Table 13 — PCSLAB a* or PCSLAB b* encoding - output_color[1] = output_color[1] * 255.0f - 128.0f; - output_color[2] = output_color[2] * 255.0f - 128.0f; - } - - return output_color; -} - -inline ErrorOr LutAToBTagData::evaluate(ColorSpace connection_space, ReadonlyBytes color_u8) const -{ - VERIFY(connection_space == ColorSpace::PCSXYZ || connection_space == ColorSpace::PCSLAB); - VERIFY(number_of_input_channels() == color_u8.size()); - VERIFY(number_of_output_channels() == 3); - - // ICC v4, 10.12 lutAToBType - // "Data are processed using these elements via the following sequence: - // (“A” curves) ⇨ (multi-dimensional lookup table, CLUT) ⇨ (“M” curves) ⇨ (matrix) ⇨ (“B” curves). - - // "The domain and range of the A and B curves and CLUT are defined to consist of all real numbers between 0,0 and 1,0 inclusive. - // The first entry is located at 0,0, the last entry at 1,0, and intermediate entries are uniformly spaced using an increment of 1,0/(m-1). - // For the A and B curves, m is the number of entries in the table. For the CLUT, m is the number of grid points along each dimension. - // Since the domain and range of the tables are 0,0 to 1,0 it is necessary to convert all device values and PCSLAB values to this numeric range. - // It shall be assumed that the maximum value in each case is set to 1,0 and the minimum value to 0,0 and all intermediate values are - // linearly scaled accordingly." - // Scaling from the full range to 0..1 before a curve and then back after the curve only to scale to 0..1 again before the next curve is a no-op, - // so we only scale back to the full range at the very end of this function. - - auto evaluate_curve = [](LutCurveType const& curve, float f) { - VERIFY(curve->type() == CurveTagData::Type || curve->type() == ParametricCurveTagData::Type); - if (curve->type() == CurveTagData::Type) - return static_cast(*curve).evaluate(f); - return static_cast(*curve).evaluate(f); - }; - - FloatVector3 color; - - VERIFY(m_a_curves.has_value() == m_clut.has_value()); - if (m_a_curves.has_value()) { - Vector in_color; - - auto const& a_curves = m_a_curves.value(); - for (u8 c = 0; c < color_u8.size(); ++c) - in_color.append(evaluate_curve(a_curves[c], color_u8[c] / 255.0f)); - - auto const& clut = m_clut.value(); - auto sample1 = [&clut](Vector const& data, ReadonlySpan const& coordinates) { - size_t stride = 3; - size_t offset = 0; - for (int i = coordinates.size() - 1; i >= 0; --i) { - offset += coordinates[i] * stride; - stride *= clut.number_of_grid_points_in_dimension[i]; - } - return FloatVector3 { (float)data[offset], (float)data[offset + 1], (float)data[offset + 2] }; - }; - auto sample = [&clut, &sample1](ReadonlySpan const& coordinates) { - return clut.values.visit( - [&](Vector const& v) { return sample1(v, coordinates) / 255.0f; }, - [&](Vector const& v) { return sample1(v, coordinates) / 65535.0f; }); - }; - auto size = [&clut](size_t i) { return clut.number_of_grid_points_in_dimension[i]; }; - color = lerp_nd(move(size), move(sample), in_color); - } else { - color = FloatVector3 { color_u8[0] / 255.f, color_u8[1] / 255.f, color_u8[2] / 255.f }; - } - - VERIFY(m_m_curves.has_value() == m_e.has_value()); - if (m_m_curves.has_value()) { - auto const& m_curves = m_m_curves.value(); - color = FloatVector3 { - evaluate_curve(m_curves[0], color[0]), - evaluate_curve(m_curves[1], color[1]), - evaluate_curve(m_curves[2], color[2]) - }; - - // ICC v4, 10.12.5 Matrix - // "The resultant values Y1, Y2 and Y3 shall be clipped to the range 0,0 to 1,0 and used as inputs to the “B” curves." - EMatrix3x4 const& e = m_e.value(); - FloatVector3 new_color = { - (float)e[0] * color[0] + (float)e[1] * color[1] + (float)e[2] * color[2] + (float)e[9], - (float)e[3] * color[0] + (float)e[4] * color[1] + (float)e[5] * color[2] + (float)e[10], - (float)e[6] * color[0] + (float)e[7] * color[1] + (float)e[8] * color[2] + (float)e[11], - }; - color = new_color.clamped(0.f, 1.f); - } - - FloatVector3 output_color { - evaluate_curve(m_b_curves[0], color[0]), - evaluate_curve(m_b_curves[1], color[1]), - evaluate_curve(m_b_curves[2], color[2]) - }; - - // ICC v4, 6.3.4.2 General PCS encoding - if (connection_space == ColorSpace::PCSXYZ) { - // Table 11 - PCSXYZ X, Y or Z encoding - output_color *= 65535 / 32768.0f; - } else { - VERIFY(connection_space == ColorSpace::PCSLAB); - // Table 12 — PCSLAB L* encoding - output_color[0] *= 100.0f; - - // Table 13 — PCSLAB a* or PCSLAB b* encoding - output_color[1] = output_color[1] * 255.0f - 128.0f; - output_color[2] = output_color[2] * 255.0f - 128.0f; - } - return output_color; -} - -inline ErrorOr LutBToATagData::evaluate(ColorSpace connection_space, FloatVector3 const& in_color, Bytes out_bytes) const -{ - VERIFY(connection_space == ColorSpace::PCSXYZ || connection_space == ColorSpace::PCSLAB); - VERIFY(number_of_input_channels() == 3); - VERIFY(number_of_output_channels() == out_bytes.size()); - - // ICC v4, 10.13 lutBToAType - // "Data are processed using these elements via the following sequence: - // (“B” curves) ⇨ (matrix) ⇨ (“M” curves) ⇨ (multi-dimensional lookup table, CLUT) ⇨ (“A” curves)." - - // See comment at start of LutAToBTagData::evaluate() for the clipping flow. - // This function generally is the same as LutAToBTagData::evaluate() upside down. - - auto evaluate_curve = [](LutCurveType const& curve, float f) { - VERIFY(curve->type() == CurveTagData::Type || curve->type() == ParametricCurveTagData::Type); - if (curve->type() == CurveTagData::Type) - return static_cast(*curve).evaluate(f); - return static_cast(*curve).evaluate(f); - }; - - FloatVector3 color; - if (connection_space == ColorSpace::PCSXYZ) { - color = in_color * 32768 / 65535.0f; - } else { - VERIFY(connection_space == ColorSpace::PCSLAB); - color[0] = in_color[0] / 100.0f; - color[1] = (in_color[1] + 128.0f) / 255.0f; - color[2] = (in_color[2] + 128.0f) / 255.0f; - } - - color = FloatVector3 { - evaluate_curve(m_b_curves[0], color[0]), - evaluate_curve(m_b_curves[1], color[1]), - evaluate_curve(m_b_curves[2], color[2]) - }; - - VERIFY(m_e.has_value() == m_m_curves.has_value()); - if (m_e.has_value()) { - // ICC v4, 10.13.3 Matrix - // "The resultant values Y1, Y2 and Y3 shall be clipped to the range 0,0 to 1,0 and used as inputs to the “M” curves." - EMatrix3x4 const& e = m_e.value(); - FloatVector3 new_color = { - (float)e[0] * color[0] + (float)e[1] * color[1] + (float)e[2] * color[2] + (float)e[9], - (float)e[3] * color[0] + (float)e[4] * color[1] + (float)e[5] * color[2] + (float)e[10], - (float)e[6] * color[0] + (float)e[7] * color[1] + (float)e[8] * color[2] + (float)e[11], - }; - color = new_color.clamped(0.f, 1.f); - - auto const& m_curves = m_m_curves.value(); - color = FloatVector3 { - evaluate_curve(m_curves[0], color[0]), - evaluate_curve(m_curves[1], color[1]), - evaluate_curve(m_curves[2], color[2]) - }; - } - - VERIFY(m_clut.has_value() == m_a_curves.has_value()); - if (m_clut.has_value()) { - // FIXME - return Error::from_string_literal("LutBToATagData::evaluate: Not yet implemented when CLUT present"); - } else { - VERIFY(number_of_output_channels() == 3); - out_bytes[0] = round_to(color[0] * 255.0f); - out_bytes[1] = round_to(color[1] * 255.0f); - out_bytes[2] = round_to(color[2] * 255.0f); - } - - return {}; -} - -} - -template<> -struct AK::Formatter : Formatter { - ErrorOr format(FormatBuilder& builder, Gfx::ICC::XYZ const& xyz) - { - return Formatter::format(builder, "X = {}, Y = {}, Z = {}"sv, xyz.X, xyz.Y, xyz.Z); - } -}; diff --git a/Libraries/LibGfx/ICC/Tags.cpp b/Libraries/LibGfx/ICC/Tags.cpp deleted file mode 100644 index 7d8a75f296ee..000000000000 --- a/Libraries/LibGfx/ICC/Tags.cpp +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include - -namespace Gfx::ICC { - -Optional tag_signature_spec_name(TagSignature tag_signature) -{ - switch (tag_signature) { -#define TAG(name, id) \ - case name: \ - return #name##sv; - ENUMERATE_TAG_SIGNATURES(TAG) -#undef TAG - } - return {}; -} - -} diff --git a/Libraries/LibGfx/ICC/Tags.h b/Libraries/LibGfx/ICC/Tags.h deleted file mode 100644 index abefb64f0a03..000000000000 --- a/Libraries/LibGfx/ICC/Tags.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include -#include - -namespace Gfx::ICC { - -// ICC v4, 9.2 Tag listing -#define ENUMERATE_TAG_SIGNATURES(TAG) \ - TAG(AToB0Tag, 0x41324230 /* 'A2B0' */) \ - TAG(AToB1Tag, 0x41324231 /* 'A2B1' */) \ - TAG(AToB2Tag, 0x41324232 /* 'A2B2' */) \ - TAG(blueMatrixColumnTag, 0x6258595A /* 'bXYZ' */) \ - TAG(blueTRCTag, 0x62545243 /* 'bTRC' */) \ - TAG(BToA0Tag, 0x42324130 /* 'B2A0' */) \ - TAG(BToA1Tag, 0x42324131 /* 'B2A1' */) \ - TAG(BToA2Tag, 0x42324132 /* 'B2A2' */) \ - TAG(BToD0Tag, 0x42324430 /* 'B2D0' */) \ - TAG(BToD1Tag, 0x42324431 /* 'B2D1' */) \ - TAG(BToD2Tag, 0x42324432 /* 'B2D2' */) \ - TAG(BToD3Tag, 0x42324433 /* 'B2D3' */) \ - TAG(calibrationDateTimeTag, 0x63616C74 /* 'calt' */) \ - TAG(charTargetTag, 0x74617267 /* 'targ' */) \ - TAG(chromaticAdaptationTag, 0x63686164 /* 'chad' */) \ - TAG(chromaticityTag, 0x6368726D /* 'chrm' */) \ - TAG(cicpTag, 0x63696370 /* 'cicp' */) \ - TAG(colorantOrderTag, 0x636C726F /* 'clro' */) \ - TAG(colorantTableTag, 0x636C7274 /* 'clrt' */) \ - TAG(colorantTableOutTag, 0x636C6F74 /* 'clot' */) \ - TAG(colorimetricIntentImageStateTag, 0x63696973 /* 'ciis' */) \ - TAG(copyrightTag, 0x63707274 /* 'cprt' */) \ - TAG(deviceMfgDescTag, 0x646D6E64 /* 'dmnd' */) \ - TAG(deviceModelDescTag, 0x646D6464 /* 'dmdd' */) \ - TAG(DToB0Tag, 0x44324230 /* 'D2B0' */) \ - TAG(DToB1Tag, 0x44324231 /* 'D2B1' */) \ - TAG(DToB2Tag, 0x44324232 /* 'D2B2' */) \ - TAG(DToB3Tag, 0x44324233 /* 'D2B3' */) \ - TAG(gamutTag, 0x67616D74 /* 'gamt' */) \ - TAG(grayTRCTag, 0x6B545243 /* 'kTRC' */) \ - TAG(greenMatrixColumnTag, 0x6758595A /* 'gXYZ' */) \ - TAG(greenTRCTag, 0x67545243 /* 'gTRC' */) \ - TAG(luminanceTag, 0x6C756D69 /* 'lumi' */) \ - TAG(measurementTag, 0x6D656173 /* 'meas' */) \ - TAG(metadataTag, 0x6D657461 /* 'meta' */) \ - TAG(mediaWhitePointTag, 0x77747074 /* 'wtpt' */) \ - TAG(namedColor2Tag, 0x6E636C32 /* 'ncl2' */) \ - TAG(outputResponseTag, 0x72657370 /* 'resp' */) \ - TAG(perceptualRenderingIntentGamutTag, 0x72696730 /* 'rig0' */) \ - TAG(preview0Tag, 0x70726530 /* 'pre0' */) \ - TAG(preview1Tag, 0x70726531 /* 'pre1' */) \ - TAG(preview2Tag, 0x70726532 /* 'pre2' */) \ - TAG(profileDescriptionTag, 0x64657363 /* 'desc' */) \ - TAG(profileSequenceDescTag, 0x70736571 /* 'pseq' */) \ - TAG(profileSequenceIdentifierTag, 0x70736964 /* 'psid' */) \ - TAG(redMatrixColumnTag, 0x7258595A /* 'rXYZ' */) \ - TAG(redTRCTag, 0x72545243 /* 'rTRC' */) \ - TAG(saturationRenderingIntentGamutTag, 0x72696732 /* 'rig2' */) \ - TAG(technologyTag, 0x74656368 /* 'tech' */) \ - TAG(viewingCondDescTag, 0x76756564 /* 'vued' */) \ - TAG(viewingConditionsTag, 0x76696577 /* 'view' */) \ - /* The following tags are v2-only */ \ - TAG(crdInfoTag, 0x63726469 /* 'crdi' */) \ - TAG(deviceSettingsTag, 0x64657673 /* 'devs' */) \ - TAG(mediaBlackPointTag, 0x626B7074 /* 'bkpt' */) \ - TAG(namedColorTag, 0x6E636F6C /* 'ncol' */) \ - TAG(ps2CRD0Tag, 0x70736430 /* 'psd0' */) \ - TAG(ps2CRD1Tag, 0x70736431 /* 'psd1' */) \ - TAG(ps2CRD2Tag, 0x70736432 /* 'psd2' */) \ - TAG(ps2CRD3Tag, 0x70736433 /* 'psd3' */) \ - TAG(ps2CSATag, 0x70733273 /* 'ps2s' */) \ - TAG(ps2RenderingIntentTag, 0x70733269 /* 'ps2i' */) \ - TAG(screeningDescTag, 0x73637264 /* 'scrd' */) \ - TAG(screeningTag, 0x7363726E /* 'scrn' */) \ - TAG(ucrbgTag, 0x62666420 /* 'bfd ' */) - -#define TAG(name, id) constexpr inline TagSignature name { id }; -ENUMERATE_TAG_SIGNATURES(TAG) -#undef TAG - -Optional tag_signature_spec_name(TagSignature); - -} diff --git a/Libraries/LibGfx/ICC/WellKnownProfiles.cpp b/Libraries/LibGfx/ICC/WellKnownProfiles.cpp deleted file mode 100644 index c923ccce7d14..000000000000 --- a/Libraries/LibGfx/ICC/WellKnownProfiles.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include - -namespace Gfx::ICC { - -static ProfileHeader rgb_header() -{ - ProfileHeader header; - header.version = Version(4, 0x40); - header.device_class = DeviceClass::DisplayDevice; - header.data_color_space = ColorSpace::RGB; - header.connection_space = ColorSpace::PCSXYZ; - header.creation_timestamp = MUST(DateTime::from_time_t(0)); - header.rendering_intent = RenderingIntent::Perceptual; - header.pcs_illuminant = XYZ { 0.9642, 1.0, 0.8249 }; - return header; -} - -static ErrorOr> en_US(StringView text) -{ - Vector records; - TRY(records.try_append({ ('e' << 8) | 'n', ('U' << 8) | 'S', TRY(String::from_utf8(text)) })); - return try_make_ref_counted(0, 0, records); -} - -static ErrorOr> XYZ_data(XYZ xyz) -{ - Vector xyzs; - TRY(xyzs.try_append(xyz)); - return try_make_ref_counted(0, 0, move(xyzs)); -} - -ErrorOr> sRGB_curve() -{ - // Numbers from https://en.wikipedia.org/wiki/SRGB#From_sRGB_to_CIE_XYZ - Array curve_parameters = { 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045 }; - return try_make_ref_counted(0, 0, ParametricCurveTagData::FunctionType::sRGB, curve_parameters); -} - -ErrorOr> sRGB() -{ - // Returns an sRGB profile. - // https://en.wikipedia.org/wiki/SRGB - - // FIXME: There are many different sRGB ICC profiles in the wild. - // Explain why, and why this picks the numbers it does. - // In the meantime, https://github.com/SerenityOS/serenity/pull/17714 has a few notes. - - auto header = rgb_header(); - - OrderedHashMap> tag_table; - - TRY(tag_table.try_set(profileDescriptionTag, TRY(en_US("SerenityOS sRGB"sv)))); - TRY(tag_table.try_set(copyrightTag, TRY(en_US("Public Domain"sv)))); - - // Transfer function. - auto curve = TRY(sRGB_curve()); - TRY(tag_table.try_set(redTRCTag, curve)); - TRY(tag_table.try_set(greenTRCTag, curve)); - TRY(tag_table.try_set(blueTRCTag, curve)); - - // White point. - // ICC v4, 9.2.36 mediaWhitePointTag: "For displays, the values specified shall be those of the PCS illuminant as defined in 7.2.16." - TRY(tag_table.try_set(mediaWhitePointTag, TRY(XYZ_data(header.pcs_illuminant)))); - - // The chromatic_adaptation_matrix values are from https://www.color.org/chadtag.xalter - // That leads to exactly the S15Fixed16 values in the sRGB profiles in GIMP, Android, RawTherapee (but not in Compact-ICC-Profiles's v4 sRGB profile). - Vector chromatic_adaptation_matrix = { 1.047882, 0.022918, -0.050217, 0.029586, 0.990478, -0.017075, -0.009247, 0.015075, 0.751678 }; - TRY(tag_table.try_set(chromaticAdaptationTag, TRY(try_make_ref_counted(0, 0, move(chromatic_adaptation_matrix))))); - - // The chromaticity values are from https://www.color.org/srgb.pdf - // The chromatic adaptation matrix in that document is slightly different from the one on https://www.color.org/chadtag.xalter, - // so the values in our sRGB profile are currently not fully self-consistent. - // FIXME: Make values self-consistent (probably by using slightly different chromaticities). - TRY(tag_table.try_set(redMatrixColumnTag, TRY(XYZ_data(XYZ { 0.436030342570117, 0.222438466210245, 0.013897440074263 })))); - TRY(tag_table.try_set(greenMatrixColumnTag, TRY(XYZ_data(XYZ { 0.385101860087134, 0.716942745571917, 0.097076381494207 })))); - TRY(tag_table.try_set(blueMatrixColumnTag, TRY(XYZ_data(XYZ { 0.143067806654203, 0.060618777416563, 0.713926257896652 })))); - - return Profile::create(header, move(tag_table)); -} - -} diff --git a/Libraries/LibGfx/ICC/WellKnownProfiles.h b/Libraries/LibGfx/ICC/WellKnownProfiles.h deleted file mode 100644 index 17e2a0a5dcd4..000000000000 --- a/Libraries/LibGfx/ICC/WellKnownProfiles.h +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#pragma once - -#include -#include - -namespace Gfx::ICC { - -class Profile; -class TagData; - -ErrorOr> sRGB(); - -ErrorOr> sRGB_curve(); - -} diff --git a/Meta/CMake/common_options.cmake b/Meta/CMake/common_options.cmake index 52d2fd3a4fd8..72f71003ba65 100644 --- a/Meta/CMake/common_options.cmake +++ b/Meta/CMake/common_options.cmake @@ -19,7 +19,6 @@ serenity_option(UNDEFINED_BEHAVIOR_IS_FATAL OFF CACHE BOOL "Make undefined behav serenity_option(ENABLE_ALL_THE_DEBUG_MACROS OFF CACHE BOOL "Enable all debug macros to validate they still compile") serenity_option(ENABLE_ALL_DEBUG_FACILITIES OFF CACHE BOOL "Enable all noisy debug symbols and options. Not recommended for normal developer use") -serenity_option(ENABLE_ADOBE_ICC_PROFILES_DOWNLOAD ON CACHE BOOL "Enable download of Adobe's ICC profiles") serenity_option(ENABLE_COMPILETIME_HEADER_CHECK OFF CACHE BOOL "Enable compiletime check that each library header compiles stand-alone") serenity_option(ENABLE_PUBLIC_SUFFIX_DOWNLOAD ON CACHE BOOL "Enable download of the Public Suffix List at build time") diff --git a/Meta/CMake/download_icc_profiles.cmake b/Meta/CMake/download_icc_profiles.cmake deleted file mode 100644 index 39c2182a5a3e..000000000000 --- a/Meta/CMake/download_icc_profiles.cmake +++ /dev/null @@ -1,25 +0,0 @@ -include(${CMAKE_CURRENT_LIST_DIR}/utils.cmake) - -if (ENABLE_ADOBE_ICC_PROFILES_DOWNLOAD) - set(ADOBE_ICC_PROFILES_PATH "${SERENITY_CACHE_DIR}/AdobeICCProfiles" CACHE PATH "Download location for Adobe ICC profiles") - set(ADOBE_ICC_PROFILES_DATA_URL "https://download.adobe.com/pub/adobe/iccprofiles/win/AdobeICCProfilesCS4Win_end-user.zip") - set(ADOBE_ICC_PROFILES_ZIP_PATH "${ADOBE_ICC_PROFILES_PATH}/adobe-icc-profiles.zip") - if (ENABLE_NETWORK_DOWNLOADS) - download_file("${ADOBE_ICC_PROFILES_DATA_URL}" "${ADOBE_ICC_PROFILES_ZIP_PATH}") - else() - message(STATUS "Skipping download of ${ADOBE_ICC_PROFILES_DATA_URL}, expecting the archive to have been donwloaded to ${ADOBE_ICC_PROFILES_ZIP_PATH}") - endif() - - function(extract_adobe_icc_profiles source path) - if(EXISTS "${ADOBE_ICC_PROFILES_ZIP_PATH}" AND NOT EXISTS "${path}") - file(ARCHIVE_EXTRACT INPUT "${ADOBE_ICC_PROFILES_ZIP_PATH}" DESTINATION "${ADOBE_ICC_PROFILES_PATH}" PATTERNS "${source}") - endif() - endfunction() - - set(ADOBE_ICC_CMYK_SWOP "CMYK/USWebCoatedSWOP.icc") - set(ADOBE_ICC_CMYK_SWOP_PATH "${ADOBE_ICC_PROFILES_PATH}/Adobe ICC Profiles (end-user)/${ADOBE_ICC_CMYK_SWOP}") - extract_adobe_icc_profiles("Adobe ICC Profiles (end-user)/${ADOBE_ICC_CMYK_SWOP}" "${ADOBE_ICC_CMYK_SWOP_PATH}") - - set(ADOBE_ICC_CMYK_SWOP_INSTALL_PATH "${CMAKE_BINARY_DIR}/Root/res/icc/Adobe/${ADOBE_ICC_CMYK_SWOP}") - configure_file("${ADOBE_ICC_CMYK_SWOP_PATH}" "${ADOBE_ICC_CMYK_SWOP_INSTALL_PATH}" COPYONLY) -endif() diff --git a/Meta/Lagom/CMakeLists.txt b/Meta/Lagom/CMakeLists.txt index 91022d1f0730..a156a3e07fac 100644 --- a/Meta/Lagom/CMakeLists.txt +++ b/Meta/Lagom/CMakeLists.txt @@ -452,7 +452,6 @@ lagom_utility(dns SOURCES ../../Utilities/dns.cpp LIBS LibDNS LibMain LibTLS Lib if (ENABLE_GUI_TARGETS) lagom_utility(animation SOURCES ../../Utilities/animation.cpp LIBS LibGfx LibMain) - lagom_utility(icc SOURCES ../../Utilities/icc.cpp LIBS LibGfx LibMain LibURL) lagom_utility(image SOURCES ../../Utilities/image.cpp LIBS LibGfx LibMain) endif() diff --git a/Meta/Lagom/Fuzzers/FuzzICCProfile.cpp b/Meta/Lagom/Fuzzers/FuzzICCProfile.cpp deleted file mode 100644 index 4aa67688b2f0..000000000000 --- a/Meta/Lagom/Fuzzers/FuzzICCProfile.cpp +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include - -extern "C" int LLVMFuzzerTestOneInput(uint8_t const* data, size_t size) -{ - AK::set_debug_enabled(false); - (void)Gfx::ICC::Profile::try_load_from_externally_owned_memory({ data, size }); - return 0; -} diff --git a/Meta/Lagom/Fuzzers/fuzzers.cmake b/Meta/Lagom/Fuzzers/fuzzers.cmake index 03a24b9eea4a..c461e6ba8a64 100644 --- a/Meta/Lagom/Fuzzers/fuzzers.cmake +++ b/Meta/Lagom/Fuzzers/fuzzers.cmake @@ -9,7 +9,6 @@ set(FUZZER_TARGETS GIFLoader GzipDecompression GzipRoundtrip - ICCProfile ICOLoader JPEGLoader Js @@ -56,7 +55,6 @@ set(FUZZER_DEPENDENCIES_ELF LibELF) set(FUZZER_DEPENDENCIES_GIFLoader LibGfx) set(FUZZER_DEPENDENCIES_GzipDecompression LibCompress) set(FUZZER_DEPENDENCIES_GzipRoundtrip LibCompress) -set(FUZZER_DEPENDENCIES_ICCProfile LibGfx) set(FUZZER_DEPENDENCIES_ICOLoader LibGfx) set(FUZZER_DEPENDENCIES_JPEGLoader LibGfx) set(FUZZER_DEPENDENCIES_Js LibJS LibGC) diff --git a/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn b/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn index 90d0928965c6..657a7237bef7 100644 --- a/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn +++ b/Meta/gn/secondary/Userland/Libraries/LibGfx/BUILD.gn @@ -29,7 +29,6 @@ shared_library("LibGfx") { "BitmapSequence.cpp", "CMYKBitmap.cpp", "Color.cpp", - "DeltaE.cpp", "Font/Font.cpp", "Font/FontData.cpp", "Font/FontDatabase.cpp", @@ -41,12 +40,6 @@ shared_library("LibGfx") { "Font/WOFF2/Loader.cpp", "FontCascadeList.cpp", "GradientPainting.cpp", - "ICC/BinaryWriter.cpp", - "ICC/Enums.cpp", - "ICC/Profile.cpp", - "ICC/TagTypes.cpp", - "ICC/Tags.cpp", - "ICC/WellKnownProfiles.cpp", "ImageFormats/AVIFLoader.cpp", "ImageFormats/AnimationWriter.cpp", "ImageFormats/BMPLoader.cpp", diff --git a/Tests/LibGfx/CMakeLists.txt b/Tests/LibGfx/CMakeLists.txt index 2666d735d968..a096845e49c2 100644 --- a/Tests/LibGfx/CMakeLists.txt +++ b/Tests/LibGfx/CMakeLists.txt @@ -1,8 +1,6 @@ set(TEST_SOURCES BenchmarkJPEGLoader.cpp TestColor.cpp - TestDeltaE.cpp - TestICCProfile.cpp TestImageDecoder.cpp TestImageWriter.cpp TestQuad.cpp diff --git a/Tests/LibGfx/TestDeltaE.cpp b/Tests/LibGfx/TestDeltaE.cpp deleted file mode 100644 index fdce878b4d0f..000000000000 --- a/Tests/LibGfx/TestDeltaE.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include - -TEST_CASE(delta_e) -{ - // Test data is from https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/dataNprograms/ciede2000testdata.txt, - // linked to from https://hajim.rochester.edu/ece/sites/gsharma/ciede2000/, which is source [5] in - // https://www.hajim.rochester.edu/ece/sites/gsharma/ciede2000/ciede2000noteCRNA.pdf - struct { - Gfx::CIELAB a; - Gfx::CIELAB b; - float expected_delta; - } test_cases[] = { - { { 50.0000, 2.6772, -79.7751 }, { 50.0000, 0.0000, -82.7485 }, 2.0425 }, - { { 50.0000, 3.1571, -77.2803 }, { 50.0000, 0.0000, -82.7485 }, 2.8615 }, - { { 50.0000, 2.8361, -74.0200 }, { 50.0000, 0.0000, -82.7485 }, 3.4412 }, - { { 50.0000, -1.3802, -84.2814 }, { 50.0000, 0.0000, -82.7485 }, 1.0000 }, - { { 50.0000, -1.1848, -84.8006 }, { 50.0000, 0.0000, -82.7485 }, 1.0000 }, - { { 50.0000, -0.9009, -85.5211 }, { 50.0000, 0.0000, -82.7485 }, 1.0000 }, - { { 50.0000, 0.0000, 0.0000 }, { 50.0000, -1.0000, 2.0000 }, 2.3669 }, - { { 50.0000, -1.0000, 2.0000 }, { 50.0000, 0.0000, 0.0000 }, 2.3669 }, - { { 50.0000, 2.4900, -0.0010 }, { 50.0000, -2.4900, 0.0009 }, 7.1792 }, - { { 50.0000, 2.4900, -0.0010 }, { 50.0000, -2.4900, 0.0010 }, 7.1792 }, - { { 50.0000, 2.4900, -0.0010 }, { 50.0000, -2.4900, 0.0011 }, 7.2195 }, - { { 50.0000, 2.4900, -0.0010 }, { 50.0000, -2.4900, 0.0012 }, 7.2195 }, - { { 50.0000, -0.0010, 2.4900 }, { 50.0000, 0.0009, -2.4900 }, 4.8045 }, - { { 50.0000, -0.0010, 2.4900 }, { 50.0000, 0.0010, -2.4900 }, 4.8045 }, - { { 50.0000, -0.0010, 2.4900 }, { 50.0000, 0.0011, -2.4900 }, 4.7461 }, - { { 50.0000, 2.5000, 0.0000 }, { 50.0000, 0.0000, -2.5000 }, 4.3065 }, - { { 50.0000, 2.5000, 0.0000 }, { 73.0000, 25.0000, -18.0000 }, 27.1492 }, - { { 50.0000, 2.5000, 0.0000 }, { 61.0000, -5.0000, 29.0000 }, 22.8977 }, - { { 50.0000, 2.5000, 0.0000 }, { 56.0000, -27.0000, -3.0000 }, 31.9030 }, - { { 50.0000, 2.5000, 0.0000 }, { 58.0000, 24.0000, 15.0000 }, 19.4535 }, - { { 50.0000, 2.5000, 0.0000 }, { 50.0000, 3.1736, 0.5854 }, 1.0000 }, - { { 50.0000, 2.5000, 0.0000 }, { 50.0000, 3.2972, 0.0000 }, 1.0000 }, - { { 50.0000, 2.5000, 0.0000 }, { 50.0000, 1.8634, 0.5757 }, 1.0000 }, - { { 50.0000, 2.5000, 0.0000 }, { 50.0000, 3.2592, 0.3350 }, 1.0000 }, - { { 60.2574, -34.0099, 36.2677 }, { 60.4626, -34.1751, 39.4387 }, 1.2644 }, - { { 63.0109, -31.0961, -5.8663 }, { 62.8187, -29.7946, -4.0864 }, 1.2630 }, - { { 61.2901, 3.7196, -5.3901 }, { 61.4292, 2.2480, -4.9620 }, 1.8731 }, - { { 35.0831, -44.1164, 3.7933 }, { 35.0232, -40.0716, 1.5901 }, 1.8645 }, - { { 22.7233, 20.0904, -46.6940 }, { 23.0331, 14.9730, -42.5619 }, 2.0373 }, - { { 36.4612, 47.8580, 18.3852 }, { 36.2715, 50.5065, 21.2231 }, 1.4146 }, - { { 90.8027, -2.0831, 1.4410 }, { 91.1528, -1.6435, 0.0447 }, 1.4441 }, - { { 90.9257, -0.5406, -0.9208 }, { 88.6381, -0.8985, -0.7239 }, 1.5381 }, - { { 6.7747, -0.2908, -2.4247 }, { 5.8714, -0.0985, -2.2286 }, 0.6377 }, - { { 2.0776, 0.0795, -1.1350 }, { 0.9033, -0.0636, -0.5514 }, 0.9082 }, - }; - - for (auto const& test_case : test_cases) { - // The inputs are given with 4 decimal digits, so we can be up to 0.00005 away just to rounding to 4 decimal digits. - EXPECT_APPROXIMATE_WITH_ERROR(Gfx::DeltaE(test_case.a, test_case.b), test_case.expected_delta, 0.00005); - EXPECT_APPROXIMATE_WITH_ERROR(Gfx::DeltaE(test_case.b, test_case.a), test_case.expected_delta, 0.00005); - } -} diff --git a/Tests/LibGfx/TestICCProfile.cpp b/Tests/LibGfx/TestICCProfile.cpp deleted file mode 100644 index 37f8c3c03db6..000000000000 --- a/Tests/LibGfx/TestICCProfile.cpp +++ /dev/null @@ -1,286 +0,0 @@ -/* - * Copyright (c) 2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define TEST_INPUT(x) ("test-inputs/" x) - -TEST_CASE(png) -{ - auto file = MUST(Core::MappedFile::map(TEST_INPUT("icc/icc-v2.png"sv))); - auto png = MUST(Gfx::PNGImageDecoderPlugin::create(file->bytes())); - auto icc_bytes = MUST(png->icc_data()); - EXPECT(icc_bytes.has_value()); - - auto icc_profile = MUST(Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_bytes.value())); - EXPECT(icc_profile->is_v2()); -} - -TEST_CASE(jpg) -{ - auto file = MUST(Core::MappedFile::map(TEST_INPUT("icc/icc-v4.jpg"sv))); - auto jpg = MUST(Gfx::JPEGImageDecoderPlugin::create(file->bytes())); - auto icc_bytes = MUST(jpg->icc_data()); - EXPECT(icc_bytes.has_value()); - - auto icc_profile = MUST(Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_bytes.value())); - EXPECT(icc_profile->is_v4()); - - icc_profile->for_each_tag([](auto tag_signature, auto tag_data) { - if (tag_signature == Gfx::ICC::profileDescriptionTag) { - // Required per v4 spec, but in practice even v4 files sometimes have TextDescriptionTagData descriptions. Not icc-v4.jpg, though. - EXPECT_EQ(tag_data->type(), Gfx::ICC::MultiLocalizedUnicodeTagData::Type); - auto& multi_localized_unicode = static_cast(*tag_data); - EXPECT_EQ(multi_localized_unicode.records().size(), 1u); - auto& record = multi_localized_unicode.records()[0]; - EXPECT_EQ(record.text, "sRGB built-in"sv); - } - }); -} - -TEST_CASE(webp_extended_lossless) -{ - auto file = MUST(Core::MappedFile::map(TEST_INPUT("icc/extended-lossless.webp"sv))); - auto webp = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); - auto icc_bytes = MUST(webp->icc_data()); - EXPECT(icc_bytes.has_value()); - - auto icc_profile = MUST(Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_bytes.value())); - EXPECT(icc_profile->is_v2()); -} - -TEST_CASE(webp_extended_lossy) -{ - auto file = MUST(Core::MappedFile::map(TEST_INPUT("icc/extended-lossy.webp"sv))); - auto webp = MUST(Gfx::WebPImageDecoderPlugin::create(file->bytes())); - auto icc_bytes = MUST(webp->icc_data()); - EXPECT(icc_bytes.has_value()); - - auto icc_profile = MUST(Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_bytes.value())); - EXPECT(icc_profile->is_v2()); -} - -TEST_CASE(tiff) -{ - auto file = MUST(Core::MappedFile::map(TEST_INPUT("icc/icc.tiff"sv))); - auto tiff = MUST(Gfx::TIFFImageDecoderPlugin::create(file->bytes())); - auto icc_bytes = MUST(tiff->icc_data()); - EXPECT(icc_bytes.has_value()); - - auto icc_profile = MUST(Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_bytes.value())); - EXPECT(icc_profile->is_v4()); -} - -TEST_CASE(serialize_icc) -{ - auto file = MUST(Core::MappedFile::map(TEST_INPUT("icc/p3-v4.icc"sv))); - auto icc_profile = MUST(Gfx::ICC::Profile::try_load_from_externally_owned_memory(file->bytes())); - EXPECT(icc_profile->is_v4()); - - auto serialized_bytes = MUST(Gfx::ICC::encode(*icc_profile)); - EXPECT_EQ(serialized_bytes, file->bytes()); -} - -TEST_CASE(built_in_sRGB) -{ - auto sRGB = MUST(Gfx::ICC::sRGB()); - auto serialized_bytes = MUST(Gfx::ICC::encode(sRGB)); - - // We currently exactly match the curve in GIMP's built-in sRGB profile. It's a type 3 'para' curve with 5 parameters. - u32 para[] = { 0x70617261, 0x00000000, 0x00030000, 0x00026666, 0x0000F2A7, 0x00000D59, 0x000013D0, 0x00000A5B }; - for (u32& i : para) - i = AK::convert_between_host_and_big_endian(i); - EXPECT(memmem(serialized_bytes.data(), serialized_bytes.size(), para, sizeof(para)) != nullptr); - - // We currently exactly match the chromatic adaptation matrix in GIMP's (and other's) built-in sRGB profile. - u32 sf32[] = { 0x73663332, 0x00000000, 0x00010C42, 0x000005DE, 0xFFFFF325, 0x00000793, 0x0000FD90, 0xFFFFFBA1, 0xFFFFFDA2, 0x000003DC, 0x0000C06E }; - for (u32& i : sf32) - i = AK::convert_between_host_and_big_endian(i); - EXPECT(memmem(serialized_bytes.data(), serialized_bytes.size(), sf32, sizeof(sf32)) != nullptr); -} - -TEST_CASE(to_pcs) -{ - auto sRGB = MUST(Gfx::ICC::sRGB()); - EXPECT(sRGB->data_color_space() == Gfx::ICC::ColorSpace::RGB); - EXPECT(sRGB->connection_space() == Gfx::ICC::ColorSpace::PCSXYZ); - - auto sRGB_curve_pointer = MUST(Gfx::ICC::sRGB_curve()); - VERIFY(sRGB_curve_pointer->type() == Gfx::ICC::ParametricCurveTagData::Type); - auto const& sRGB_curve = static_cast(*sRGB_curve_pointer); - EXPECT_EQ(sRGB_curve.evaluate(0.f), 0.f); - EXPECT_EQ(sRGB_curve.evaluate(1.f), 1.f); - - auto xyz_from_sRGB = [&sRGB](u8 r, u8 g, u8 b) { - u8 rgb[3] = { r, g, b }; - return MUST(sRGB->to_pcs(rgb)); - }; - - auto vec3_from_xyz = [](Gfx::ICC::XYZ const& xyz) { - return FloatVector3 { xyz.X, xyz.Y, xyz.Z }; - }; - -#define EXPECT_APPROXIMATE_VECTOR3(v1, v2) \ - EXPECT_APPROXIMATE((v1)[0], (v2)[0]); \ - EXPECT_APPROXIMATE((v1)[1], (v2)[1]); \ - EXPECT_APPROXIMATE((v1)[2], (v2)[2]); - - // At 0 and 255, the gamma curve is (exactly) 0 and 1, so these just test the matrix part. - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(0, 0, 0), FloatVector3(0, 0, 0)); - - auto r_xyz = vec3_from_xyz(sRGB->red_matrix_column()); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(255, 0, 0), r_xyz); - - auto g_xyz = vec3_from_xyz(sRGB->green_matrix_column()); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(0, 255, 0), g_xyz); - - auto b_xyz = vec3_from_xyz(sRGB->blue_matrix_column()); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(0, 0, 255), b_xyz); - - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(255, 255, 0), r_xyz + g_xyz); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(255, 0, 255), r_xyz + b_xyz); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(0, 255, 255), g_xyz + b_xyz); - - // FIXME: This should also be equal to sRGB->pcs_illuminant() and to the profiles mediaWhitePointTag, - // but at the moment it's off by a bit too much. See also FIXME in WellKnownProfiles.cpp. - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(255, 255, 255), r_xyz + g_xyz + b_xyz); - - // These test the curve part. - float f64 = sRGB_curve.evaluate(64 / 255.f); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(64, 64, 64), (r_xyz + g_xyz + b_xyz) * f64); - - float f128 = sRGB_curve.evaluate(128 / 255.f); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(128, 128, 128), (r_xyz + g_xyz + b_xyz) * f128); - - // Test for curve and matrix combined. - float f192 = sRGB_curve.evaluate(192 / 255.f); - EXPECT_APPROXIMATE_VECTOR3(xyz_from_sRGB(64, 128, 192), r_xyz * f64 + g_xyz * f128 + b_xyz * f192); -} - -TEST_CASE(from_pcs) -{ - auto sRGB = MUST(Gfx::ICC::sRGB()); - - auto sRGB_curve_pointer = MUST(Gfx::ICC::sRGB_curve()); - VERIFY(sRGB_curve_pointer->type() == Gfx::ICC::ParametricCurveTagData::Type); - auto const& sRGB_curve = static_cast(*sRGB_curve_pointer); - - auto sRGB_from_xyz = [&sRGB](FloatVector3 const& XYZ) { - u8 rgb[3]; - // The first parameter, the source profile, is used to check if the PCS data is XYZ or LAB, - // and what the source whitepoint is. We just need any profile with an XYZ PCS space, - // so passing sRGB as source profile too is fine. - MUST(sRGB->from_pcs(sRGB, XYZ, rgb)); - return Color(rgb[0], rgb[1], rgb[2]); - }; - - auto vec3_from_xyz = [](Gfx::ICC::XYZ const& xyz) { - return FloatVector3 { xyz.X, xyz.Y, xyz.Z }; - }; - - // At 0 and 255, the gamma curve is (exactly) 0 and 1, so these just test the matrix part. - EXPECT_EQ(sRGB_from_xyz(FloatVector3 { 0, 0, 0 }), Color(0, 0, 0)); - - auto r_xyz = vec3_from_xyz(sRGB->red_matrix_column()); - EXPECT_EQ(sRGB_from_xyz(r_xyz), Color(255, 0, 0)); - - auto g_xyz = vec3_from_xyz(sRGB->green_matrix_column()); - EXPECT_EQ(sRGB_from_xyz(g_xyz), Color(0, 255, 0)); - - auto b_xyz = vec3_from_xyz(sRGB->blue_matrix_column()); - EXPECT_EQ(sRGB_from_xyz(b_xyz), Color(0, 0, 255)); - - EXPECT_EQ(sRGB_from_xyz(r_xyz + g_xyz), Color(255, 255, 0)); - EXPECT_EQ(sRGB_from_xyz(r_xyz + b_xyz), Color(255, 0, 255)); - EXPECT_EQ(sRGB_from_xyz(g_xyz + b_xyz), Color(0, 255, 255)); - EXPECT_EQ(sRGB_from_xyz(r_xyz + g_xyz + b_xyz), Color(255, 255, 255)); - - // Test the inverse curve transform. - float f64 = sRGB_curve.evaluate(64 / 255.f); - EXPECT_EQ(sRGB_from_xyz((r_xyz + g_xyz + b_xyz) * f64), Color(64, 64, 64)); - - float f128 = sRGB_curve.evaluate(128 / 255.f); - EXPECT_EQ(sRGB_from_xyz((r_xyz + g_xyz + b_xyz) * f128), Color(128, 128, 128)); - - // Test for curve and matrix combined. - float f192 = sRGB_curve.evaluate(192 / 255.f); - EXPECT_EQ(sRGB_from_xyz(r_xyz * f64 + g_xyz * f128 + b_xyz * f192), Color(64, 128, 192)); -} - -TEST_CASE(to_lab) -{ - auto sRGB = MUST(Gfx::ICC::sRGB()); - auto lab_from_sRGB = [&sRGB](u8 r, u8 g, u8 b) { - u8 rgb[3] = { r, g, b }; - return MUST(sRGB->to_lab(rgb)); - }; - - // The `expected` numbers are from https://colorjs.io/notebook/ for this snippet of code: - // new Color("srgb", [0, 0, 0]).lab.toString(); - // - // new Color("srgb", [1, 0, 0]).lab.toString(); - // new Color("srgb", [0, 1, 0]).lab.toString(); - // new Color("srgb", [0, 0, 1]).lab.toString(); - // - // new Color("srgb", [1, 1, 0]).lab.toString(); - // new Color("srgb", [1, 0, 1]).lab.toString(); - // new Color("srgb", [0, 1, 1]).lab.toString(); - // - // new Color("srgb", [1, 1, 1]).lab.toString(); - - Gfx::CIELAB expected[] = { - { 0, 0, 0 }, - { 54.29054294696968, 80.80492033462421, 69.89098825896275 }, - { 87.81853633115202, -79.27108223854806, 80.99459785152247 }, - { 29.56829715344471, 68.28740665215547, -112.02971798617645 }, - { 97.60701009682253, -15.749846639252663, 93.39361164266089 }, - { 60.16894098715946, 93.53959546199253, -60.50080231921204 }, - { 90.66601315791455, -50.65651077286893, -14.961666625736525 }, - { 100.00000139649632, -0.000007807961277528364, 0.000006766250648659877 }, - }; - - // We're off by more than the default EXPECT_APPROXIMATE() error, so use EXPECT_APPROXIMATE_WITH_ERROR(). - // The difference is not too bad: ranges for L*, a*, b* are [0, 100], [-125, 125], [-125, 125], - // so this is an error of considerably less than 0.1 for u8 channels. -#define EXPECT_APPROXIMATE_LAB(l1, l2) \ - EXPECT_APPROXIMATE_WITH_ERROR((l1).L, (l2).L, 0.01); \ - EXPECT_APPROXIMATE_WITH_ERROR((l1).a, (l2).a, 0.03); \ - EXPECT_APPROXIMATE_WITH_ERROR((l1).b, (l2).b, 0.02); - - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(0, 0, 0), expected[0]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(255, 0, 0), expected[1]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(0, 255, 0), expected[2]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(0, 0, 255), expected[3]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(255, 255, 0), expected[4]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(255, 0, 255), expected[5]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(0, 255, 255), expected[6]); - EXPECT_APPROXIMATE_LAB(lab_from_sRGB(255, 255, 255), expected[7]); -} - -TEST_CASE(malformed_profile) -{ - Array test_inputs = { - TEST_INPUT("icc/oss-fuzz-testcase-57426.icc"sv), - TEST_INPUT("icc/oss-fuzz-testcase-59551.icc"sv), - TEST_INPUT("icc/oss-fuzz-testcase-60281.icc"sv) - }; - - for (auto test_input : test_inputs) { - auto file = MUST(Core::MappedFile::map(test_input)); - auto profile_or_error = Gfx::ICC::Profile::try_load_from_externally_owned_memory(file->bytes()); - EXPECT(profile_or_error.is_error()); - } -} diff --git a/Tests/LibGfx/TestImageWriter.cpp b/Tests/LibGfx/TestImageWriter.cpp index 6e53bf5e87e9..64198333cabb 100644 --- a/Tests/LibGfx/TestImageWriter.cpp +++ b/Tests/LibGfx/TestImageWriter.cpp @@ -6,9 +6,6 @@ #include #include -#include -#include -#include #include #include #include @@ -188,23 +185,6 @@ TEST_CASE(test_webp_color_indexing_transform_single_channel) } } -TEST_CASE(test_webp_icc) -{ - auto sRGB_icc_profile = MUST(Gfx::ICC::sRGB()); - auto sRGB_icc_data = MUST(Gfx::ICC::encode(sRGB_icc_profile)); - - auto rgba_bitmap = TRY_OR_FAIL(create_test_rgba_bitmap()); - Gfx::WebPEncoderOptions options; - options.icc_data = sRGB_icc_data; - auto encoded_rgba_bitmap = TRY_OR_FAIL((encode_bitmap(rgba_bitmap, options))); - - auto decoded_rgba_plugin = TRY_OR_FAIL(Gfx::WebPImageDecoderPlugin::create(encoded_rgba_bitmap)); - expect_bitmaps_equal(*TRY_OR_FAIL(expect_single_frame_of_size(*decoded_rgba_plugin, rgba_bitmap->size())), rgba_bitmap); - auto decoded_rgba_profile = TRY_OR_FAIL(Gfx::ICC::Profile::try_load_from_externally_owned_memory(TRY_OR_FAIL(decoded_rgba_plugin->icc_data()).value())); - auto reencoded_icc_data = TRY_OR_FAIL(Gfx::ICC::encode(decoded_rgba_profile)); - EXPECT_EQ(sRGB_icc_data, reencoded_icc_data); -} - TEST_CASE(test_webp_animation) { auto rgb_bitmap = TRY_OR_FAIL(create_test_rgb_bitmap()); diff --git a/Utilities/icc.cpp b/Utilities/icc.cpp deleted file mode 100644 index cbfd02e27427..000000000000 --- a/Utilities/icc.cpp +++ /dev/null @@ -1,605 +0,0 @@ -/* - * Copyright (c) 2022-2023, Nico Weber - * - * SPDX-License-Identifier: BSD-2-Clause - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -template -static ErrorOr hyperlink(URL::URL const& target, T const& label) -{ - return String::formatted("\033]8;;{}\033\\{}\033]8;;\033\\", target, label); -} - -template -static void out_optional(char const* label, Optional const& optional) -{ - out("{}: ", label); - if (optional.has_value()) - outln("{}", *optional); - else - outln("(not set)"); -} - -static void out_curve(Gfx::ICC::CurveTagData const& curve, int indent_amount) -{ - if (curve.values().is_empty()) { - outln("{: >{}}identity curve", "", indent_amount); - } else if (curve.values().size() == 1) { - outln("{: >{}}gamma: {}", "", indent_amount, AK::FixedPoint<8, u16>::create_raw(curve.values()[0])); - } else { - // FIXME: Maybe print the actual points if -v is passed? - outln("{: >{}}curve with {} points", "", indent_amount, curve.values().size()); - } -} - -static void out_parametric_curve(Gfx::ICC::ParametricCurveTagData const& parametric_curve, int indent_amount) -{ - switch (parametric_curve.function_type()) { - case Gfx::ICC::ParametricCurveTagData::FunctionType::Type0: - outln("{: >{}}Y = X**{}", "", indent_amount, parametric_curve.g()); - break; - case Gfx::ICC::ParametricCurveTagData::FunctionType::Type1: - outln("{: >{}}Y = ({}*X + {})**{} if X >= -{}/{}", "", indent_amount, - parametric_curve.a(), parametric_curve.b(), parametric_curve.g(), parametric_curve.b(), parametric_curve.a()); - outln("{: >{}}Y = 0 else", "", indent_amount); - break; - case Gfx::ICC::ParametricCurveTagData::FunctionType::Type2: - outln("{: >{}}Y = ({}*X + {})**{} + {} if X >= -{}/{}", "", indent_amount, - parametric_curve.a(), parametric_curve.b(), parametric_curve.g(), parametric_curve.c(), parametric_curve.b(), parametric_curve.a()); - outln("{: >{}}Y = {} else", "", indent_amount, parametric_curve.c()); - break; - case Gfx::ICC::ParametricCurveTagData::FunctionType::Type3: - outln("{: >{}}Y = ({}*X + {})**{} if X >= {}", "", indent_amount, - parametric_curve.a(), parametric_curve.b(), parametric_curve.g(), parametric_curve.d()); - outln("{: >{}}Y = {}*X else", "", indent_amount, parametric_curve.c()); - break; - case Gfx::ICC::ParametricCurveTagData::FunctionType::Type4: - outln("{: >{}}Y = ({}*X + {})**{} + {} if X >= {}", "", indent_amount, - parametric_curve.a(), parametric_curve.b(), parametric_curve.g(), parametric_curve.e(), parametric_curve.d()); - outln("{: >{}}Y = {}*X + {} else", "", indent_amount, parametric_curve.c(), parametric_curve.f()); - break; - } -} - -static float curve_distance_u8(Gfx::ICC::TagData const& tag1, Gfx::ICC::TagData const& tag2) -{ - VERIFY(tag1.type() == Gfx::ICC::CurveTagData::Type || tag1.type() == Gfx::ICC::ParametricCurveTagData::Type); - VERIFY(tag2.type() == Gfx::ICC::CurveTagData::Type || tag2.type() == Gfx::ICC::ParametricCurveTagData::Type); - - float curve1_data[256]; - if (tag1.type() == Gfx::ICC::CurveTagData::Type) { - auto& curve1 = static_cast(tag1); - for (int i = 0; i < 256; ++i) - curve1_data[i] = curve1.evaluate(i / 255.f); - } else { - auto& parametric_curve1 = static_cast(tag1); - for (int i = 0; i < 256; ++i) - curve1_data[i] = parametric_curve1.evaluate(i / 255.f); - } - - float curve2_data[256]; - if (tag2.type() == Gfx::ICC::CurveTagData::Type) { - auto& curve2 = static_cast(tag2); - for (int i = 0; i < 256; ++i) - curve2_data[i] = curve2.evaluate(i / 255.f); - } else { - auto& parametric_curve2 = static_cast(tag2); - for (int i = 0; i < 256; ++i) - curve2_data[i] = parametric_curve2.evaluate(i / 255.f); - } - - float distance = 0; - for (int i = 0; i < 256; ++i) - distance += fabsf(curve1_data[i] - curve2_data[i]); - return distance; -} - -static ErrorOr out_curve_tag(Gfx::ICC::TagData const& tag, int indent_amount) -{ - VERIFY(tag.type() == Gfx::ICC::CurveTagData::Type || tag.type() == Gfx::ICC::ParametricCurveTagData::Type); - if (tag.type() == Gfx::ICC::CurveTagData::Type) - out_curve(static_cast(tag), indent_amount); - if (tag.type() == Gfx::ICC::ParametricCurveTagData::Type) - out_parametric_curve(static_cast(tag), indent_amount); - - auto sRGB_curve = TRY(Gfx::ICC::sRGB_curve()); - - // Some example values (for abs distance summed over the 256 values of an u8): - // In Compact-ICC-Profiles/profiles: - // AdobeCompat-v2.icc: 1.14 (this is a gamma 2.2 curve, so not really sRGB but close) - // AdobeCompat-v4.icc: 1.13 - // AppleCompat-v2.icc: 11.94 (gamma 1.8 curve) - // DCI-P3-v4.icc: 8.29 (gamma 2.6 curve) - // DisplayP3-v2-magic.icc: 0.000912 (looks sRGB-ish) - // DisplayP3-v2-micro.icc: 0.010819 - // DisplayP3-v4.icc: 0.001062 (yes, definitely sRGB) - // Rec2020-g24-v4.icc: 4.119216 (gamma 2.4 curve) - // Rec2020-v4.icc: 7.805417 (custom non-sRGB curve) - // Rec709-v4.icc: 7.783267 (same custom non-sRGB curve as Rec2020) - // sRGB-v2-magic.icc: 0.000912 - // sRGB-v2-micro.icc: 0.010819 - // sRGB-v2-nano.icc: 0.052516 - // sRGB-v4.icc: 0.001062 - // scRGB-v2.icc: 48.379859 (linear identity curve) - // Google sRGB IEC61966-2.1 (from a Pixel jpeg, parametric): 0 - // Google sRGB IEC61966-2.1 (from a Pixel jpeg, LUT curve): 0.00096 - // Apple 2015 Display P3 (from iPhone 7, parametric): 0.011427 (has the old, left intersection for switching from linear to exponent) - // HP sRGB: 0.00096 - // color.org sRGB2014.icc: 0.00096 - // color.org sRGB_ICC_v4_Appearance.icc, AToB1Tag, a curves: 0.441926 -- but this is not _really_ sRGB - // color.org sRGB_v4_ICC_preference.icc, AToB1Tag, a curves: 2.205453 -- not really sRGB either - // So `< 0.06` identifies sRGB in practice (for u8 values). - float u8_distance_to_sRGB = curve_distance_u8(*sRGB_curve, tag); - if (u8_distance_to_sRGB < 0.06f) - outln("{: >{}}Looks like sRGB's curve (distance {})", "", indent_amount, u8_distance_to_sRGB); - else - outln("{: >{}}Does not look like sRGB's curve (distance: {})", "", indent_amount, u8_distance_to_sRGB); - - return {}; -} - -static ErrorOr out_curves(Vector const& curves) -{ - for (auto const& curve : curves) { - VERIFY(curve->type() == Gfx::ICC::CurveTagData::Type || curve->type() == Gfx::ICC::ParametricCurveTagData::Type); - outln(" type {}, relative offset {}, size {}", curve->type(), curve->offset(), curve->size()); - TRY(out_curve_tag(*curve, /*indent=*/12)); - } - return {}; -} - -static ErrorOr perform_debug_roundtrip(Gfx::ICC::Profile const& profile) -{ - size_t num_channels = Gfx::ICC::number_of_components_in_color_space(profile.data_color_space()); - Vector input, output; - input.resize(num_channels); - output.resize(num_channels); - - size_t const num_total_roundtrips = 500; - size_t num_lossless_roundtrips = 0; - - for (size_t i = 0; i < num_total_roundtrips; ++i) { - for (size_t j = 0; j < num_channels; ++j) - input[j] = get_random(); - auto color_in_profile_connection_space = TRY(profile.to_pcs(input)); - TRY(profile.from_pcs(profile, color_in_profile_connection_space, output)); - if (input != output) { - outln("roundtrip failed for {} -> {}", input, output); - } else { - ++num_lossless_roundtrips; - } - } - outln("lossless roundtrips: {} / {}", num_lossless_roundtrips, num_total_roundtrips); - return {}; -} - -static ErrorOr print_profile_measurement(Gfx::ICC::Profile const& profile) -{ - auto lab_from_rgb = [&profile](u8 r, u8 g, u8 b) { - u8 rgb[3] = { r, g, b }; - return profile.to_lab(rgb); - }; - float largest = -1, smallest = 1000; - Color largest_color1, largest_color2, smallest_color1, smallest_color2; - for (u8 r = 0; r < 254; ++r) { - out("\r{}/254", r + 1); - fflush(stdout); - for (u8 g = 0; g < 254; ++g) { - for (u8 b = 0; b < 254; ++b) { - auto lab = TRY(lab_from_rgb(r, g, b)); - u8 delta_r[] = { 1, 0, 0 }; - u8 delta_g[] = { 0, 1, 0 }; - u8 delta_b[] = { 0, 0, 1 }; - for (unsigned i = 0; i < sizeof(delta_r); ++i) { - auto lab2 = TRY(lab_from_rgb(r + delta_r[i], g + delta_g[i], b + delta_b[i])); - float delta = Gfx::DeltaE(lab, lab2); - if (delta > largest) { - largest = delta; - largest_color1 = Color(r, g, b); - largest_color2 = Color(r + delta_r[i], g + delta_g[i], b + delta_b[i]); - } - if (delta < smallest) { - smallest = delta; - smallest_color1 = Color(r, g, b); - smallest_color2 = Color(r + delta_r[i], g + delta_g[i], b + delta_b[i]); - } - } - } - } - } - outln("\rlargest difference between neighboring colors: {}, between {} and {}", largest, largest_color1, largest_color2); - outln("smallest difference between neighboring colors: {}, between {} and {}", smallest, smallest_color1, smallest_color2); - return {}; -} - -ErrorOr serenity_main(Main::Arguments arguments) -{ - Core::ArgsParser args_parser; - - StringView path; - args_parser.add_positional_argument(path, "Path to ICC profile or to image containing ICC profile", "FILE", Core::ArgsParser::Required::No); - - StringView name; - args_parser.add_option(name, "Name of a built-in profile, such as 'sRGB'", "name", 'n', "NAME"); - - StringView dump_out_path; - args_parser.add_option(dump_out_path, "Dump unmodified ICC profile bytes to this path", "dump-to", 0, "FILE"); - - StringView reencode_out_path; - args_parser.add_option(reencode_out_path, "Reencode ICC profile to this path", "reencode-to", 0, "FILE"); - - bool debug_roundtrip = false; - args_parser.add_option(debug_roundtrip, "Check how many u8 colors roundtrip losslessly through the profile. For debugging.", "debug-roundtrip"); - - bool measure = false; - args_parser.add_option(measure, "For RGB ICC profiles, print perceptually smallest and largest color step", "measure"); - - bool force_print = false; - args_parser.add_option(force_print, "Print profile even when writing ICC files", "print"); - - args_parser.parse(arguments); - - if (path.is_empty() && name.is_empty()) { - warnln("need either a path or a profile name"); - return 1; - } - if (!path.is_empty() && !name.is_empty()) { - warnln("can't have both a path and a profile name"); - return 1; - } - if (path.is_empty() && !dump_out_path.is_empty()) { - warnln("--dump-to only valid with path, not with profile name; use --reencode-to instead"); - return 1; - } - - ReadonlyBytes icc_bytes; - NonnullRefPtr profile = TRY([&]() -> ErrorOr> { - if (!name.is_empty()) { - if (name == "sRGB") - return Gfx::ICC::sRGB(); - return Error::from_string_literal("unknown profile name"); - } - auto file = TRY(Core::MappedFile::map(path)); - - auto decoder = TRY(Gfx::ImageDecoder::try_create_for_raw_bytes(file->bytes())); - if (decoder) { - if (auto embedded_icc_bytes = TRY(decoder->icc_data()); embedded_icc_bytes.has_value()) { - icc_bytes = *embedded_icc_bytes; - } else { - outln("image contains no embedded ICC profile"); - exit(1); - } - } else { - icc_bytes = file->bytes(); - } - - if (!dump_out_path.is_empty()) { - auto output_stream = TRY(Core::File::open(dump_out_path, Core::File::OpenMode::Write)); - TRY(output_stream->write_until_depleted(icc_bytes)); - } - return Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_bytes); - }()); - - if (!reencode_out_path.is_empty()) { - auto reencoded_bytes = TRY(Gfx::ICC::encode(profile)); - auto output_stream = TRY(Core::File::open(reencode_out_path, Core::File::OpenMode::Write)); - TRY(output_stream->write_until_depleted(reencoded_bytes)); - } - - if (debug_roundtrip) { - TRY(perform_debug_roundtrip(*profile)); - return 0; - } - - if (measure) { - if (profile->data_color_space() != Gfx::ICC::ColorSpace::RGB) { - warnln("--measure only works for RGB ICC profiles"); - return 1; - } - TRY(print_profile_measurement(*profile)); - } - - bool do_print = (dump_out_path.is_empty() && reencode_out_path.is_empty() && !measure) || force_print; - if (!do_print) - return 0; - - outln(" size: {} bytes", profile->on_disk_size()); - out_optional(" preferred CMM type", profile->preferred_cmm_type()); - outln(" version: {}", profile->version()); - outln(" device class: {}", Gfx::ICC::device_class_name(profile->device_class())); - outln(" data color space: {}", Gfx::ICC::data_color_space_name(profile->data_color_space())); - outln(" connection space: {}", Gfx::ICC::profile_connection_space_name(profile->connection_space())); - - if (auto time = profile->creation_timestamp().to_time_t(); !time.is_error()) { - // Print in friendly localtime for valid profiles. - outln("creation date and time: {}", Core::DateTime::from_timestamp(time.release_value())); - } else { - outln("creation date and time: {:04}-{:02}-{:02} {:02}:{:02}:{:02} UTC (invalid)", - profile->creation_timestamp().year, profile->creation_timestamp().month, profile->creation_timestamp().day, - profile->creation_timestamp().hours, profile->creation_timestamp().minutes, profile->creation_timestamp().seconds); - } - - out_optional(" primary platform", profile->primary_platform().map([](auto platform) { return primary_platform_name(platform); })); - - auto flags = profile->flags(); - outln(" flags: {:#08x}", flags.bits()); - outln(" - {}embedded in file", flags.is_embedded_in_file() ? "" : "not "); - outln(" - can{} be used independently of embedded color data", flags.can_be_used_independently_of_embedded_color_data() ? "" : "not"); - if (auto unknown_icc_bits = flags.icc_bits() & ~Gfx::ICC::Flags::KnownBitsMask) - outln(" other unknown ICC bits: {:#04x}", unknown_icc_bits); - if (auto color_management_module_bits = flags.color_management_module_bits()) - outln(" CMM bits: {:#04x}", color_management_module_bits); - - out_optional(" device manufacturer", TRY(profile->device_manufacturer().map([](auto device_manufacturer) { - return hyperlink(device_manufacturer_url(device_manufacturer), device_manufacturer); - }))); - out_optional(" device model", TRY(profile->device_model().map([](auto device_model) { - return hyperlink(device_model_url(device_model), device_model); - }))); - - auto device_attributes = profile->device_attributes(); - outln(" device attributes: {:#016x}", device_attributes.bits()); - outln(" media is:"); - outln(" - {}", - device_attributes.media_reflectivity() == Gfx::ICC::DeviceAttributes::MediaReflectivity::Reflective ? "reflective" : "transparent"); - outln(" - {}", - device_attributes.media_glossiness() == Gfx::ICC::DeviceAttributes::MediaGlossiness::Glossy ? "glossy" : "matte"); - outln(" - {}", - device_attributes.media_polarity() == Gfx::ICC::DeviceAttributes::MediaPolarity::Positive ? "of positive polarity" : "of negative polarity"); - outln(" - {}", - device_attributes.media_color() == Gfx::ICC::DeviceAttributes::MediaColor::Colored ? "colored" : "black and white"); - VERIFY((flags.icc_bits() & ~Gfx::ICC::DeviceAttributes::KnownBitsMask) == 0); - if (auto vendor_bits = device_attributes.vendor_bits()) - outln(" vendor bits: {:#08x}", vendor_bits); - - outln(" rendering intent: {}", Gfx::ICC::rendering_intent_name(profile->rendering_intent())); - outln(" pcs illuminant: {}", profile->pcs_illuminant()); - out_optional(" creator", profile->creator()); - out_optional(" id", profile->id()); - - size_t profile_disk_size = icc_bytes.size(); - if (profile_disk_size != profile->on_disk_size()) { - VERIFY(profile_disk_size > profile->on_disk_size()); - outln("{} trailing bytes after profile data", profile_disk_size - profile->on_disk_size()); - } - - outln(""); - - outln("tags:"); - HashMap tag_data_to_first_signature; - TRY(profile->try_for_each_tag([&tag_data_to_first_signature](auto tag_signature, auto tag_data) -> ErrorOr { - if (auto name = tag_signature_spec_name(tag_signature); name.has_value()) - out("{} ({}): ", *name, tag_signature); - else - out("Unknown tag ({}): ", tag_signature); - outln("type {}, offset {}, size {}", tag_data->type(), tag_data->offset(), tag_data->size()); - - // Print tag data only the first time it's seen. - // (Different sigatures can refer to the same data.) - auto it = tag_data_to_first_signature.find(tag_data); - if (it != tag_data_to_first_signature.end()) { - outln(" (see {} above)", it->value); - return {}; - } - tag_data_to_first_signature.set(tag_data, tag_signature); - - if (tag_data->type() == Gfx::ICC::ChromaticityTagData::Type) { - auto& chromaticity = static_cast(*tag_data); - outln(" phosphor or colorant type: {}", Gfx::ICC::ChromaticityTagData::phosphor_or_colorant_type_name(chromaticity.phosphor_or_colorant_type())); - for (auto const& xy : chromaticity.xy_coordinates()) - outln(" x, y: {}, {}", xy.x, xy.y); - } else if (tag_data->type() == Gfx::ICC::CicpTagData::Type) { - auto& cicp = static_cast(*tag_data); - outln(" color primaries: {} - {}", cicp.color_primaries(), - Media::color_primaries_to_string((Media::ColorPrimaries)cicp.color_primaries())); - outln(" transfer characteristics: {} - {}", cicp.transfer_characteristics(), - Media::transfer_characteristics_to_string((Media::TransferCharacteristics)cicp.transfer_characteristics())); - outln(" matrix coefficients: {} - {}", cicp.matrix_coefficients(), - Media::matrix_coefficients_to_string((Media::MatrixCoefficients)cicp.matrix_coefficients())); - outln(" video full range flag: {} - {}", cicp.video_full_range_flag(), - Media::video_full_range_flag_to_string((Media::VideoFullRangeFlag)cicp.video_full_range_flag())); - } else if (tag_data->type() == Gfx::ICC::CurveTagData::Type) { - TRY(out_curve_tag(*tag_data, /*indent=*/4)); - } else if (tag_data->type() == Gfx::ICC::Lut16TagData::Type) { - auto& lut16 = static_cast(*tag_data); - outln(" input table: {} channels x {} entries", lut16.number_of_input_channels(), lut16.number_of_input_table_entries()); - outln(" output table: {} channels x {} entries", lut16.number_of_output_channels(), lut16.number_of_output_table_entries()); - outln(" color lookup table: {} grid points, {} total entries", lut16.number_of_clut_grid_points(), lut16.clut_values().size()); - - auto const& e = lut16.e_matrix(); - outln(" e = [ {}, {}, {},", e[0], e[1], e[2]); - outln(" {}, {}, {},", e[3], e[4], e[5]); - outln(" {}, {}, {} ]", e[6], e[7], e[8]); - } else if (tag_data->type() == Gfx::ICC::Lut8TagData::Type) { - auto& lut8 = static_cast(*tag_data); - outln(" input table: {} channels x {} entries", lut8.number_of_input_channels(), lut8.number_of_input_table_entries()); - outln(" output table: {} channels x {} entries", lut8.number_of_output_channels(), lut8.number_of_output_table_entries()); - outln(" color lookup table: {} grid points, {} total entries", lut8.number_of_clut_grid_points(), lut8.clut_values().size()); - - auto const& e = lut8.e_matrix(); - outln(" e = [ {}, {}, {},", e[0], e[1], e[2]); - outln(" {}, {}, {},", e[3], e[4], e[5]); - outln(" {}, {}, {} ]", e[6], e[7], e[8]); - } else if (tag_data->type() == Gfx::ICC::LutAToBTagData::Type) { - auto& a_to_b = static_cast(*tag_data); - outln(" {} input channels, {} output channels", a_to_b.number_of_input_channels(), a_to_b.number_of_output_channels()); - - if (auto const& optional_a_curves = a_to_b.a_curves(); optional_a_curves.has_value()) { - outln(" a curves: {} curves", optional_a_curves->size()); - TRY(out_curves(optional_a_curves.value())); - } else { - outln(" a curves: (not set)"); - } - - if (auto const& optional_clut = a_to_b.clut(); optional_clut.has_value()) { - auto const& clut = optional_clut.value(); - outln(" color lookup table: {} grid points, {}", - TRY(String::join(" x "sv, clut.number_of_grid_points_in_dimension)), - TRY(clut.values.visit( - [](Vector const& v) { return String::formatted("{} u8 entries", v.size()); }, - [](Vector const& v) { return String::formatted("{} u16 entries", v.size()); }))); - } else { - outln(" color lookup table: (not set)"); - } - - if (auto const& optional_m_curves = a_to_b.m_curves(); optional_m_curves.has_value()) { - outln(" m curves: {} curves", optional_m_curves->size()); - TRY(out_curves(optional_m_curves.value())); - } else { - outln(" m curves: (not set)"); - } - - if (auto const& optional_e = a_to_b.e_matrix(); optional_e.has_value()) { - auto const& e = optional_e.value(); - outln(" e = [ {}, {}, {}, {},", e[0], e[1], e[2], e[9]); - outln(" {}, {}, {}, {},", e[3], e[4], e[5], e[10]); - outln(" {}, {}, {}, {} ]", e[6], e[7], e[8], e[11]); - } else { - outln(" e = (not set)"); - } - - outln(" b curves: {} curves", a_to_b.b_curves().size()); - TRY(out_curves(a_to_b.b_curves())); - } else if (tag_data->type() == Gfx::ICC::LutBToATagData::Type) { - auto& b_to_a = static_cast(*tag_data); - outln(" {} input channels, {} output channels", b_to_a.number_of_input_channels(), b_to_a.number_of_output_channels()); - - outln(" b curves: {} curves", b_to_a.b_curves().size()); - TRY(out_curves(b_to_a.b_curves())); - - if (auto const& optional_e = b_to_a.e_matrix(); optional_e.has_value()) { - auto const& e = optional_e.value(); - outln(" e = [ {}, {}, {}, {},", e[0], e[1], e[2], e[9]); - outln(" {}, {}, {}, {},", e[3], e[4], e[5], e[10]); - outln(" {}, {}, {}, {} ]", e[6], e[7], e[8], e[11]); - } else { - outln(" e = (not set)"); - } - - if (auto const& optional_m_curves = b_to_a.m_curves(); optional_m_curves.has_value()) { - outln(" m curves: {} curves", optional_m_curves->size()); - TRY(out_curves(optional_m_curves.value())); - } else { - outln(" m curves: (not set)"); - } - - if (auto const& optional_clut = b_to_a.clut(); optional_clut.has_value()) { - auto const& clut = optional_clut.value(); - outln(" color lookup table: {} grid points, {}", - TRY(String::join(" x "sv, clut.number_of_grid_points_in_dimension)), - TRY(clut.values.visit( - [](Vector const& v) { return String::formatted("{} u8 entries", v.size()); }, - [](Vector const& v) { return String::formatted("{} u16 entries", v.size()); }))); - } else { - outln(" color lookup table: (not set)"); - } - - if (auto const& optional_a_curves = b_to_a.a_curves(); optional_a_curves.has_value()) { - outln(" a curves: {} curves", optional_a_curves->size()); - TRY(out_curves(optional_a_curves.value())); - } else { - outln(" a curves: (not set)"); - } - } else if (tag_data->type() == Gfx::ICC::MeasurementTagData::Type) { - auto& measurement = static_cast(*tag_data); - outln(" standard observer: {}", Gfx::ICC::MeasurementTagData::standard_observer_name(measurement.standard_observer())); - outln(" tristimulus value for measurement backing: {}", measurement.tristimulus_value_for_measurement_backing()); - outln(" measurement geometry: {}", Gfx::ICC::MeasurementTagData::measurement_geometry_name(measurement.measurement_geometry())); - outln(" measurement flare: {} %", measurement.measurement_flare() * 100); - outln(" standard illuminant: {}", Gfx::ICC::MeasurementTagData::standard_illuminant_name(measurement.standard_illuminant())); - } else if (tag_data->type() == Gfx::ICC::MultiLocalizedUnicodeTagData::Type) { - auto& multi_localized_unicode = static_cast(*tag_data); - for (auto& record : multi_localized_unicode.records()) { - outln(" {:c}{:c}/{:c}{:c}: \"{}\"", - record.iso_639_1_language_code >> 8, record.iso_639_1_language_code & 0xff, - record.iso_3166_1_country_code >> 8, record.iso_3166_1_country_code & 0xff, - record.text); - } - } else if (tag_data->type() == Gfx::ICC::NamedColor2TagData::Type) { - auto& named_colors = static_cast(*tag_data); - outln(" vendor specific flag: {:#08x}", named_colors.vendor_specific_flag()); - outln(" common name prefix: \"{}\"", named_colors.prefix()); - outln(" common name suffix: \"{}\"", named_colors.suffix()); - outln(" {} colors:", named_colors.size()); - for (size_t i = 0; i < min(named_colors.size(), 5u); ++i) { - auto const& pcs = named_colors.pcs_coordinates(i); - - // FIXME: Display decoded values? (See ICC v4 6.3.4.2 and 10.8.) - out(" \"{}\", PCS coordinates: {:#04x} {:#04x} {:#04x}", TRY(named_colors.color_name(i)), pcs.xyz.x, pcs.xyz.y, pcs.xyz.z); - if (auto number_of_device_coordinates = named_colors.number_of_device_coordinates(); number_of_device_coordinates > 0) { - out(", device coordinates:"); - for (size_t j = 0; j < number_of_device_coordinates; ++j) - out(" {:#04x}", named_colors.device_coordinates(i)[j]); - } - outln(); - } - if (named_colors.size() > 5u) - outln(" ..."); - } else if (tag_data->type() == Gfx::ICC::ParametricCurveTagData::Type) { - TRY(out_curve_tag(*tag_data, /*indent=*/4)); - } else if (tag_data->type() == Gfx::ICC::S15Fixed16ArrayTagData::Type) { - // This tag can contain arbitrarily many fixed-point numbers, but in practice it's - // exclusively used for the 'chad' tag, where it always contains 9 values that - // represent a 3x3 matrix. So print the values in groups of 3. - auto& fixed_array = static_cast(*tag_data); - out(" ["); - int i = 0; - for (auto value : fixed_array.values()) { - if (i > 0) { - out(","); - if (i % 3 == 0) { - outln(); - out(" "); - } - } - out(" {}", value); - i++; - } - outln(" ]"); - } else if (tag_data->type() == Gfx::ICC::SignatureTagData::Type) { - auto& signature = static_cast(*tag_data); - - if (auto name = signature.name_for_tag(tag_signature); name.has_value()) { - outln(" signature: {}", name.value()); - } else { - outln(" signature: Unknown ('{:c}{:c}{:c}{:c}' / {:#08x})", - signature.signature() >> 24, (signature.signature() >> 16) & 0xff, (signature.signature() >> 8) & 0xff, signature.signature() & 0xff, - signature.signature()); - } - } else if (tag_data->type() == Gfx::ICC::TextDescriptionTagData::Type) { - auto& text_description = static_cast(*tag_data); - outln(" ascii: \"{}\"", text_description.ascii_description()); - out_optional(" unicode", TRY(text_description.unicode_description().map([](auto description) { return String::formatted("\"{}\"", description); }))); - outln(" unicode language code: 0x{}", text_description.unicode_language_code()); - out_optional(" macintosh", TRY(text_description.macintosh_description().map([](auto description) { return String::formatted("\"{}\"", description); }))); - } else if (tag_data->type() == Gfx::ICC::TextTagData::Type) { - outln(" text: \"{}\"", static_cast(*tag_data).text()); - } else if (tag_data->type() == Gfx::ICC::ViewingConditionsTagData::Type) { - auto& viewing_conditions = static_cast(*tag_data); - outln(" unnormalized CIEXYZ values for illuminant (in which Y is in cd/m²): {}", viewing_conditions.unnormalized_ciexyz_values_for_illuminant()); - outln(" unnormalized CIEXYZ values for surround (in which Y is in cd/m²): {}", viewing_conditions.unnormalized_ciexyz_values_for_surround()); - outln(" illuminant type: {}", Gfx::ICC::MeasurementTagData::standard_illuminant_name(viewing_conditions.illuminant_type())); - } else if (tag_data->type() == Gfx::ICC::XYZTagData::Type) { - for (auto& xyz : static_cast(*tag_data).xyzs()) - outln(" {}", xyz); - } - return {}; - })); - - return 0; -} diff --git a/Utilities/image.cpp b/Utilities/image.cpp index a9039665211b..71a224e3dbac 100644 --- a/Utilities/image.cpp +++ b/Utilities/image.cpp @@ -7,7 +7,6 @@ #include #include #include -#include #include #include #include @@ -122,41 +121,6 @@ static ErrorOr strip_alpha(LoadedImage& image) return {}; } -static ErrorOr> convert_image_profile(LoadedImage& image, StringView convert_color_profile_path, OwnPtr maybe_source_icc_file) -{ - if (!image.icc_data.has_value()) - return Error::from_string_literal("No source color space embedded in image. Pass one with --assign-color-profile."); - - auto source_icc_file = move(maybe_source_icc_file); - auto source_icc_data = image.icc_data.value(); - auto icc_file = TRY(Core::MappedFile::map(convert_color_profile_path)); - image.icc_data = icc_file->bytes(); - - auto source_profile = TRY(Gfx::ICC::Profile::try_load_from_externally_owned_memory(source_icc_data)); - auto destination_profile = TRY(Gfx::ICC::Profile::try_load_from_externally_owned_memory(icc_file->bytes())); - - if (destination_profile->data_color_space() != Gfx::ICC::ColorSpace::RGB) - return Error::from_string_literal("Can only convert to RGB at the moment, but destination color space is not RGB"); - - if (image.bitmap.has>()) { - if (source_profile->data_color_space() != Gfx::ICC::ColorSpace::CMYK) - return Error::from_string_literal("Source image data is CMYK but source color space is not CMYK"); - - auto& cmyk_frame = image.bitmap.get>(); - auto rgb_frame = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, cmyk_frame->size())); - TRY(destination_profile->convert_cmyk_image(*rgb_frame, *cmyk_frame, *source_profile)); - image.bitmap = RefPtr(move(rgb_frame)); - image.internal_format = Gfx::NaturalFrameFormat::RGB; - } else { - // FIXME: This likely wrong for grayscale images because they've been converted to - // RGB at this point, but their embedded color profile is still for grayscale. - auto& frame = image.bitmap.get>(); - TRY(destination_profile->convert_image(*frame, *source_profile)); - } - - return icc_file; -} - static ErrorOr save_image(LoadedImage& image, StringView out_path, u8 jpeg_quality, Optional webp_allowed_transforms) { auto stream = [out_path]() -> ErrorOr> { @@ -262,8 +226,6 @@ static ErrorOr parse_options(Main::Arguments arguments) args_parser.add_option(options.move_alpha_to_rgb, "Copy alpha channel to rgb, clear alpha", "move-alpha-to-rgb", {}); args_parser.add_option(options.strip_alpha, "Remove alpha channel", "strip-alpha", {}); args_parser.add_option(options.assign_color_profile_path, "Load color profile from file and assign it to output image", "assign-color-profile", {}, "FILE"); - args_parser.add_option(options.convert_color_profile_path, "Load color profile from file and convert output image from current profile to loaded profile", "convert-to-color-profile", {}, "FILE"); - args_parser.add_option(options.strip_color_profile, "Do not write color profile to output", "strip-color-profile", {}); args_parser.add_option(options.quality, "Quality used for the JPEG encoder, the default value is 75 on a scale from 0 to 100", "quality", {}, {}); StringView webp_allowed_transforms = "default"sv; args_parser.add_option(webp_allowed_transforms, "Comma-separated list of allowed transforms (predictor,p,color,c,subtract-green,sg,color-indexing,ci) for WebP output (default: all allowed)", "webp-allowed-transforms", {}, {}); @@ -309,9 +271,6 @@ ErrorOr serenity_main(Main::Arguments arguments) image.icc_data = icc_file->bytes(); } - if (!options.convert_color_profile_path.is_empty()) - icc_file = TRY(convert_image_profile(image, options.convert_color_profile_path, move(icc_file))); - if (options.strip_color_profile) image.icc_data.clear();