LibGfx: Remove ICC::Profile and friends

This is not really used anymore since the fork.
This commit is contained in:
Lucas CHOLLET 2024-12-15 20:37:28 -05:00 committed by Jelle Raaijmakers
commit 2174e5dfcc
Notes: github-actions[bot] 2024-12-16 06:40:43 +00:00
30 changed files with 0 additions and 7490 deletions

View file

@ -1,18 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* 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*
};
}

View file

@ -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

View file

@ -1,89 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Math.h>
#include <LibGfx/DeltaE.h>
#include <math.h>
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<float>(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);
}
}

View file

@ -1,21 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <LibGfx/CIELAB.h>
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&);
}

View file

@ -1,170 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Endian.h>
#include <LibGfx/ICC/DistinctFourCC.h>
#include <LibGfx/ICC/Profile.h>
#include <LibGfx/ICC/TagTypes.h>
#include <math.h>
namespace Gfx::ICC {
// ICC V4, 4.2 dateTimeNumber
// "All the dateTimeNumber values in a profile shall be in Coordinated Universal Time [...]."
struct DateTimeNumber {
BigEndian<u16> year;
BigEndian<u16> month;
BigEndian<u16> day;
BigEndian<u16> hours;
BigEndian<u16> minutes;
BigEndian<u16> 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<s15Fixed16Number> X;
BigEndian<s15Fixed16Number> Y;
BigEndian<s15Fixed16Number> 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<u32> profile_size;
BigEndian<PreferredCMMType> preferred_cmm_type;
u8 profile_version_major;
u8 profile_version_minor_bugfix;
BigEndian<u16> profile_version_zero;
BigEndian<DeviceClass> profile_device_class;
BigEndian<ColorSpace> data_color_space;
BigEndian<ColorSpace> profile_connection_space; // "PCS" in the spec.
DateTimeNumber profile_creation_time;
BigEndian<u32> profile_file_signature;
BigEndian<PrimaryPlatform> primary_platform;
BigEndian<u32> profile_flags;
BigEndian<DeviceManufacturer> device_manufacturer;
BigEndian<DeviceModel> device_model;
BigEndian<u64> device_attributes;
BigEndian<RenderingIntent> rendering_intent;
XYZNumber pcs_illuminant;
BigEndian<Creator> profile_creator;
u8 profile_id[16];
u8 reserved[28];
};
static_assert(AssertSize<ICCHeader, 128>());
// 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<TagSignature> tag_signature;
BigEndian<u32> offset_to_beginning_of_tag_data_element;
BigEndian<u32> size_of_tag_data_element;
};
static_assert(AssertSize<TagTableEntry, 12>());
// 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<s15Fixed16Number> e_parameters[9];
};
static_assert(AssertSize<LUTHeader, 40>());
// 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<u16> reserved_for_padding;
BigEndian<u32> offset_to_b_curves;
BigEndian<u32> offset_to_matrix;
BigEndian<u32> offset_to_m_curves;
BigEndian<u32> offset_to_clut;
BigEndian<u32> offset_to_a_curves;
};
static_assert(AssertSize<AdvancedLUTHeader, 24>());
// 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<CLUTHeader, 20>());
// Table 49 — measurementType structure
struct MeasurementHeader {
BigEndian<MeasurementTagData::StandardObserver> standard_observer;
XYZNumber tristimulus_value_for_measurement_backing;
BigEndian<MeasurementTagData::MeasurementGeometry> measurement_geometry;
BigEndian<u16Fixed16Number> measurement_flare;
BigEndian<MeasurementTagData::StandardIlluminant> standard_illuminant;
};
static_assert(AssertSize<MeasurementHeader, 28>());
// ICC v4, 10.15 multiLocalizedUnicodeType
struct MultiLocalizedUnicodeRawRecord {
BigEndian<u16> language_code;
BigEndian<u16> country_code;
BigEndian<u32> string_length_in_bytes;
BigEndian<u32> string_offset_in_bytes;
};
static_assert(AssertSize<MultiLocalizedUnicodeRawRecord, 12>());
// Table 66 — namedColor2Type encoding
struct NamedColorHeader {
BigEndian<u32> vendor_specific_flag;
BigEndian<u32> count_of_named_colors;
BigEndian<u32> 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<NamedColorHeader, 76>());
// 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<MeasurementTagData::StandardIlluminant> illuminant_type;
};
static_assert(AssertSize<ViewingConditionsHeader, 28>());
}

View file

@ -1,748 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Utf16View.h>
#include <LibGfx/ICC/BinaryFormat.h>
#include <LibGfx/ICC/BinaryWriter.h>
#include <LibGfx/ICC/Profile.h>
#include <time.h>
#pragma GCC diagnostic ignored "-Warray-bounds"
namespace Gfx::ICC {
static ErrorOr<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(ChromaticityTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
*bit_cast<BigEndian<u16>*>(bytes.data() + 8) = tag_data.xy_coordinates().size();
*bit_cast<BigEndian<u16>*>(bytes.data() + 10) = static_cast<u16>(tag_data.phosphor_or_colorant_type());
auto* coordinates = bit_cast<BigEndian<u16Fixed16Number>*>(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<ByteBuffer> encode_cipc(CicpTagData const& tag_data)
{
// ICC v4, 10.3 cicpType
auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + 4));
*bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(CicpTagData::Type);
*bit_cast<BigEndian<u32>*>(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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(CurveTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
*bit_cast<BigEndian<u32>*>(bytes.data() + 8) = tag_data.values().size();
auto* values = bit_cast<BigEndian<u16>*>(bytes.data() + 12);
for (size_t i = 0; i < tag_data.values().size(); ++i)
values[i] = tag_data.values()[i];
}
static ErrorOr<ByteBuffer> 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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(Lut16TagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<LUTHeader*>(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<BigEndian<u16>*>(bytes.data() + 8 + sizeof(LUTHeader)) = tag_data.number_of_input_table_entries();
*bit_cast<BigEndian<u16>*>(bytes.data() + 8 + sizeof(LUTHeader) + 2) = tag_data.number_of_output_table_entries();
auto* values = bit_cast<BigEndian<u16>*>(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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(Lut8TagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<LUTHeader*>(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<CurveTagData const&>(*curve));
return parametric_curve_encoded_size(static_cast<ParametricCurveTagData const&>(*curve));
}
static u32 byte_size_of_curves(Vector<LutCurveType> 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<CurveTagData const&>(*curve), bytes);
if (curve->type() == Gfx::ICC::ParametricCurveTagData::Type)
encode_parametric_curve_to(static_cast<ParametricCurveTagData const&>(*curve), bytes);
}
static void write_curves(Bytes bytes, Vector<LutCurveType> 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<u8> const& v) { return v.size(); },
[](Vector<u16> 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<CLUTHeader*>(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<u8> const&) { return 1; },
[](Vector<u16> const&) { return 2; });
memset(clut_header.reserved_for_padding, 0, sizeof(clut_header.reserved_for_padding));
clut.values.visit(
[&bytes](Vector<u8> const& v) {
memcpy(bytes.data() + sizeof(CLUTHeader), v.data(), v.size());
},
[&bytes](Vector<u16> const& v) {
auto* raw_clut = bit_cast<BigEndian<u16>*>(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<BigEndian<s15Fixed16Number>*>(bytes.data());
for (int i = 0; i < 12; ++i)
raw_e[i] = e_matrix.e[i].raw();
}
static ErrorOr<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(LutAToBTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<AdvancedLUTHeader*>(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<u32>& 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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(LutBToATagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<AdvancedLUTHeader*>(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<u32>& 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<ByteBuffer> encode_measurement(MeasurementTagData const& tag_data)
{
// ICC v4, 10.14 measurementType
auto bytes = TRY(ByteBuffer::create_uninitialized(2 * sizeof(u32) + sizeof(MeasurementHeader)));
*bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(MeasurementTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<MeasurementHeader*>(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<ByteBuffer> 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<Utf16Data> 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<BigEndian<u32>*>(bytes.data());
header[0] = static_cast<u32>(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<MultiLocalizedUnicodeRawRecord*>(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<BigEndian<u16>*>(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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = (u32)NamedColor2TagData::Type;
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<NamedColorHeader*>(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<BigEndian<u16>*>(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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(ParametricCurveTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
*bit_cast<BigEndian<u16>*>(bytes.data() + 8) = static_cast<u16>(tag_data.function_type());
*bit_cast<BigEndian<u16>*>(bytes.data() + 10) = 0;
auto* parameters = bit_cast<BigEndian<s15Fixed16Number>*>(bytes.data() + 12);
for (size_t i = 0; i < tag_data.parameter_count(); ++i)
parameters[i] = tag_data.parameter(i).raw();
}
static ErrorOr<ByteBuffer> 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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(S15Fixed16ArrayTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto* values = bit_cast<BigEndian<s15Fixed16Number>*>(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<ByteBuffer> encode_signature(SignatureTagData const& tag_data)
{
// ICC v4, 10.23 signatureType
auto bytes = TRY(ByteBuffer::create_uninitialized(3 * sizeof(u32)));
*bit_cast<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(SignatureTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
*bit_cast<BigEndian<u32>*>(bytes.data() + 8) = tag_data.signature();
return bytes;
}
static ErrorOr<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(TextDescriptionTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
// ASCII
*bit_cast<BigEndian<u32>*>(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<u32> 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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(TextTagData::Type);
*bit_cast<BigEndian<u32>*>(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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(ViewingConditionsTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto& header = *bit_cast<ViewingConditionsHeader*>(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<ByteBuffer> 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<BigEndian<u32>*>(bytes.data()) = static_cast<u32>(XYZTagData::Type);
*bit_cast<BigEndian<u32>*>(bytes.data() + 4) = 0;
auto* xyzs = bit_cast<XYZNumber*>(bytes.data() + 8);
for (size_t i = 0; i < tag_data.xyzs().size(); ++i)
xyzs[i] = tag_data.xyzs()[i];
return bytes;
}
static ErrorOr<Optional<ByteBuffer>> encode_tag_data(TagData const& tag_data)
{
switch (tag_data.type()) {
case ChromaticityTagData::Type:
return encode_chromaticity(static_cast<ChromaticityTagData const&>(tag_data));
case CicpTagData::Type:
return encode_cipc(static_cast<CicpTagData const&>(tag_data));
case CurveTagData::Type:
return encode_curve(static_cast<CurveTagData const&>(tag_data));
case Lut16TagData::Type:
return encode_lut_16(static_cast<Lut16TagData const&>(tag_data));
case Lut8TagData::Type:
return encode_lut_8(static_cast<Lut8TagData const&>(tag_data));
case LutAToBTagData::Type:
return encode_lut_a_to_b(static_cast<LutAToBTagData const&>(tag_data));
case LutBToATagData::Type:
return encode_lut_b_to_a(static_cast<LutBToATagData const&>(tag_data));
case MeasurementTagData::Type:
return encode_measurement(static_cast<MeasurementTagData const&>(tag_data));
case MultiLocalizedUnicodeTagData::Type:
return encode_multi_localized_unicode(static_cast<MultiLocalizedUnicodeTagData const&>(tag_data));
case NamedColor2TagData::Type:
return encode_named_color_2(static_cast<NamedColor2TagData const&>(tag_data));
case ParametricCurveTagData::Type:
return encode_parametric_curve(static_cast<ParametricCurveTagData const&>(tag_data));
case S15Fixed16ArrayTagData::Type:
return encode_s15_fixed_array(static_cast<S15Fixed16ArrayTagData const&>(tag_data));
case SignatureTagData::Type:
return encode_signature(static_cast<SignatureTagData const&>(tag_data));
case TextDescriptionTagData::Type:
return encode_text_description(static_cast<TextDescriptionTagData const&>(tag_data));
case TextTagData::Type:
return encode_text(static_cast<TextTagData const&>(tag_data));
case ViewingConditionsTagData::Type:
return encode_viewing_conditions(static_cast<ViewingConditionsTagData const&>(tag_data));
case XYZTagData::Type:
return encode_xyz(static_cast<XYZTagData const&>(tag_data));
}
return OptionalNone {};
}
static ErrorOr<Vector<ByteBuffer>> encode_tag_datas(Profile const& profile, HashMap<TagData*, size_t>& tag_data_map)
{
Vector<ByteBuffer> tag_data_bytes;
TRY(tag_data_bytes.try_ensure_capacity(profile.tag_count()));
TRY(profile.try_for_each_tag([&](auto, auto tag_data) -> ErrorOr<void> {
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<void> encode_tag_table(ByteBuffer& bytes, Profile const& profile, u32 number_of_serialized_tags, Vector<size_t> const& offsets,
Vector<ByteBuffer> const& tag_data_bytes, HashMap<TagData*, size_t> 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<BigEndian<u32>*>(bytes.data() + sizeof(ICCHeader)) = number_of_serialized_tags;
TagTableEntry* tag_table_entries = bit_cast<TagTableEntry*>(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<void> encode_header(ByteBuffer& bytes, Profile const& profile)
{
VERIFY(bytes.size() >= sizeof(ICCHeader));
auto& raw_header = *bit_cast<ICCHeader*>(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<ByteBuffer> encode(Profile const& profile)
{
// Valid profiles always have tags. Profile only represents valid profiles.
VERIFY(profile.tag_count() > 0);
HashMap<TagData*, size_t> tag_data_map;
Vector<ByteBuffer> 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<size_t> 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;
}
}

View file

@ -1,21 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* 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<ByteBuffer> encode(Profile const&);
}

View file

@ -1,78 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Format.h>
#include <AK/Types.h>
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<FourCCType type>
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<FourCCType::PreferredCMMType>; // ICC v4, "7.2.3 Preferred CMM type field"
using DeviceManufacturer = DistinctFourCC<FourCCType::DeviceManufacturer>; // ICC v4, "7.2.12 Device manufacturer field"
using DeviceModel = DistinctFourCC<FourCCType::DeviceModel>; // ICC v4, "7.2.13 Device model field"
using Creator = DistinctFourCC<FourCCType::Creator>; // ICC v4, "7.2.17 Profile creator field"
using TagSignature = DistinctFourCC<FourCCType::TagSignature>; // ICC v4, "9.2 Tag listing"
using TagTypeSignature = DistinctFourCC<FourCCType::TagTypeSignature>; // ICC v4, "10 Tag type definitions"
}
template<Gfx::ICC::FourCCType Type>
struct AK::Formatter<Gfx::ICC::DistinctFourCC<Type>> : StandardFormatter {
ErrorOr<void> format(FormatBuilder& builder, Gfx::ICC::DistinctFourCC<Type> 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<Gfx::ICC::FourCCType Type>
struct AK::Traits<Gfx::ICC::DistinctFourCC<Type>> : public DefaultTraits<Gfx::ICC::DistinctFourCC<Type>> {
static unsigned hash(Gfx::ICC::DistinctFourCC<Type> const& key)
{
return int_hash(key.value);
}
static bool equals(Gfx::ICC::DistinctFourCC<Type> const& a, Gfx::ICC::DistinctFourCC<Type> const& b)
{
return a == b;
}
};

View file

@ -1,178 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGfx/ICC/Enums.h>
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();
}
}

View file

@ -1,77 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/StringView.h>
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);
}

File diff suppressed because it is too large Load diff

View file

@ -1,356 +0,0 @@
/*
* Copyright (c) 2022-2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Error.h>
#include <AK/Format.h>
#include <AK/HashMap.h>
#include <AK/NonnullRefPtr.h>
#include <AK/RefCounted.h>
#include <AK/Span.h>
#include <LibCrypto/Hash/MD5.h>
#include <LibGfx/Bitmap.h>
#include <LibGfx/CIELAB.h>
#include <LibGfx/ICC/DistinctFourCC.h>
#include <LibGfx/ICC/TagTypes.h>
#include <LibGfx/Matrix3x3.h>
#include <LibGfx/Vector3.h>
#include <LibURL/URL.h>
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<time_t> to_time_t() const;
static ErrorOr<DateTime> from_time_t(time_t);
};
struct ProfileHeader {
u32 on_disk_size { 0 };
Optional<PreferredCMMType> preferred_cmm_type;
Version version;
DeviceClass device_class {};
ColorSpace data_color_space {};
ColorSpace connection_space {};
DateTime creation_timestamp;
Optional<PrimaryPlatform> primary_platform {};
Flags flags;
Optional<DeviceManufacturer> device_manufacturer;
Optional<DeviceModel> device_model;
DeviceAttributes device_attributes;
RenderingIntent rendering_intent {};
XYZ pcs_illuminant;
Optional<Creator> creator;
Optional<Crypto::Hash::MD5::DigestType> 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<CurveTagData const&>(trc).evaluate(f);
return static_cast<ParametricCurveTagData const&>(trc).evaluate(f);
};
auto evaluate_curve_inverse = [](TagData const& trc, float f) {
if (trc.type() == CurveTagData::Type)
return static_cast<CurveTagData const&>(trc).evaluate_inverse(f);
return static_cast<ParametricCurveTagData const&>(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<Profile> {
public:
static ErrorOr<NonnullRefPtr<Profile>> try_load_from_externally_owned_memory(ReadonlyBytes);
static ErrorOr<NonnullRefPtr<Profile>> create(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> tag_table);
Optional<PreferredCMMType> 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<PrimaryPlatform> primary_platform() const { return m_header.primary_platform; }
Flags flags() const { return m_header.flags; }
Optional<DeviceManufacturer> device_manufacturer() const { return m_header.device_manufacturer; }
Optional<DeviceModel> 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> creator() const { return m_header.creator; }
Optional<Crypto::Hash::MD5::DigestType> const& id() const { return m_header.id; }
static Crypto::Hash::MD5::DigestType compute_id(ReadonlyBytes);
template<typename Callback>
void for_each_tag(Callback callback) const
{
for (auto const& tag : m_tag_table)
callback(tag.key, tag.value);
}
template<FallibleFunction<TagSignature, NonnullRefPtr<TagData>> Callback>
ErrorOr<void> try_for_each_tag(Callback&& callback) const
{
for (auto const& tag : m_tag_table)
TRY(callback(tag.key, tag.value));
return {};
}
Optional<TagData const&> tag_data(TagSignature signature) const
{
return m_tag_table.get(signature).map([](auto it) -> TagData const& { return *it; });
}
Optional<String> 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<FloatVector3> 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<void> from_pcs(Profile const& source_profile, FloatVector3, Bytes) const;
ErrorOr<CIELAB> to_lab(ReadonlyBytes) const;
ErrorOr<void> convert_image(Bitmap&, Profile const& source_profile) const;
ErrorOr<void> 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<MatrixMatrixConversion> matrix_matrix_conversion(Profile const& source_profile) const;
private:
Profile(ProfileHeader const& header, OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> 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<XYZTagData const&>(data).xyz();
}
ErrorOr<void> check_required_tags();
ErrorOr<void> check_tag_types();
ProfileHeader m_header;
OrderedHashMap<TagSignature, NonnullRefPtr<TagData>> m_tag_table;
// FIXME: The color conversion stuff should be in some other class.
ErrorOr<FloatVector3> to_pcs_a_to_b(TagData const& tag_data, ReadonlyBytes) const;
ErrorOr<void> from_pcs_b_to_a(TagData const& tag_data, FloatVector3 const&, Bytes) const;
ErrorOr<void> 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<FloatMatrix3x3> xyz_to_rgb_matrix() const;
FloatMatrix3x3 rgb_to_xyz_matrix() const;
mutable Optional<FloatMatrix3x3> m_cached_xyz_to_rgb_matrix;
struct OneElementCLUTCache {
Vector<u8, 4> key;
FloatVector3 value;
};
mutable Optional<OneElementCLUTCache> m_to_pcs_clut_cache;
};
}
template<>
struct AK::Formatter<Gfx::ICC::Version> : Formatter<FormatString> {
ErrorOr<void> format(FormatBuilder& builder, Gfx::ICC::Version const& version)
{
return Formatter<FormatString>::format(builder, "{}.{}.{}"sv, version.major_version(), version.minor_version(), version.bugfix_version());
}
};

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,23 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGfx/ICC/Tags.h>
namespace Gfx::ICC {
Optional<StringView> 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 {};
}
}

View file

@ -1,89 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Optional.h>
#include <AK/StringView.h>
#include <LibGfx/ICC/DistinctFourCC.h>
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<StringView> tag_signature_spec_name(TagSignature);
}

View file

@ -1,89 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibGfx/ICC/Profile.h>
#include <LibGfx/ICC/Tags.h>
#include <LibGfx/ICC/WellKnownProfiles.h>
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<NonnullRefPtr<MultiLocalizedUnicodeTagData>> en_US(StringView text)
{
Vector<MultiLocalizedUnicodeTagData::Record> records;
TRY(records.try_append({ ('e' << 8) | 'n', ('U' << 8) | 'S', TRY(String::from_utf8(text)) }));
return try_make_ref_counted<MultiLocalizedUnicodeTagData>(0, 0, records);
}
static ErrorOr<NonnullRefPtr<XYZTagData>> XYZ_data(XYZ xyz)
{
Vector<XYZ> xyzs;
TRY(xyzs.try_append(xyz));
return try_make_ref_counted<XYZTagData>(0, 0, move(xyzs));
}
ErrorOr<NonnullRefPtr<TagData>> sRGB_curve()
{
// Numbers from https://en.wikipedia.org/wiki/SRGB#From_sRGB_to_CIE_XYZ
Array<S15Fixed16, 7> curve_parameters = { 2.4, 1 / 1.055, 0.055 / 1.055, 1 / 12.92, 0.04045 };
return try_make_ref_counted<ParametricCurveTagData>(0, 0, ParametricCurveTagData::FunctionType::sRGB, curve_parameters);
}
ErrorOr<NonnullRefPtr<Profile>> 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<TagSignature, NonnullRefPtr<TagData>> 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<S15Fixed16, 9> 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<S15Fixed16ArrayTagData>(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));
}
}

View file

@ -1,21 +0,0 @@
/*
* Copyright (c) 2023, Nico Weber <thakis@chromium.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/Error.h>
#include <AK/NonnullRefPtr.h>
namespace Gfx::ICC {
class Profile;
class TagData;
ErrorOr<NonnullRefPtr<Profile>> sRGB();
ErrorOr<NonnullRefPtr<TagData>> sRGB_curve();
}