Skip to content

Truly independent web browser

LibMediaCodecs+Tests: Extract color metadata from video bitstreams

Zaggy1024e589350fe675
diff --git a/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h b/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h
index 7236233b42d..1c3baad44f3 100644
--- a/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h
+++ b/Libraries/LibMedia/Containers/ISOBMFF/Boxes.h
@@ -325,6 +325,7 @@ inline Track track_from_track_entry(TrackEntry const& track_entry, bool is_first
.cicp = video.cicp.value_or({}),
.mastering_display_color_volume = video.mastering_display_color_volume,
.content_light_level_information = video.content_light_level_information,
+ .maximum_scene_luminance = {},
},
});
} else if (track.type() == TrackType::Audio && sample_entry->audio.has_value()) {
diff --git a/Libraries/LibMedia/Containers/Matroska/Document.h b/Libraries/LibMedia/Containers/Matroska/Document.h
index afd4180b57e..28bb9574ba2 100644
--- a/Libraries/LibMedia/Containers/Matroska/Document.h
+++ b/Libraries/LibMedia/Containers/Matroska/Document.h
@@ -126,6 +126,7 @@ public:
.cicp = to_cicp(),
.mastering_display_color_volume = mastering_display_color_volume,
.content_light_level_information = content_light_level_information,
+ .maximum_scene_luminance = {},
};
}
};
diff --git a/Libraries/LibMediaCodecs/BitReader.h b/Libraries/LibMediaCodecs/BitReader.h
index 1d923868120..d8128239aeb 100644
--- a/Libraries/LibMediaCodecs/BitReader.h
+++ b/Libraries/LibMediaCodecs/BitReader.h
@@ -73,9 +73,11 @@ public:
auto byte = read_bits<u8>(8);
value |= static_cast<u64>(byte & 0x7f) << (index * 7);
if ((byte & 0x80) == 0)
- break;
+ return value;
}
- return value;
+ // The last byte a value may take says that another follows, which makes the value malformed.
+ m_has_overrun = true;
+ return 0;
}
void skip_bits(size_t count)
diff --git a/Libraries/LibMediaCodecs/CMakeLists.txt b/Libraries/LibMediaCodecs/CMakeLists.txt
index 6cf6a1a5542..24bcc60931a 100644
--- a/Libraries/LibMediaCodecs/CMakeLists.txt
+++ b/Libraries/LibMediaCodecs/CMakeLists.txt
@@ -3,9 +3,13 @@ set(SOURCES
CodecParameters.cpp
Codecs/AAC.cpp
Codecs/AV1.cpp
+ Codecs/DolbyVision.cpp
Codecs/H264.cpp
Codecs/H265.cpp
+ Codecs/HDR10Plus.cpp
+ Codecs/HighDynamicRangeMetadataTracker.cpp
Codecs/MPEG4Audio.cpp
+ Codecs/SupplementalEnhancementInformation.cpp
Codecs/VP9.cpp
Color/CodingIndependentCodePoints.cpp
Color/ColorMetadata.cpp
diff --git a/Libraries/LibMediaCodecs/Codecs/AV1.cpp b/Libraries/LibMediaCodecs/Codecs/AV1.cpp
index a57e9ecd982..0775ce03f5c 100644
--- a/Libraries/LibMediaCodecs/Codecs/AV1.cpp
+++ b/Libraries/LibMediaCodecs/Codecs/AV1.cpp
@@ -9,6 +9,8 @@
#include <LibMediaCodecs/BitReader.h>
#include <LibMediaCodecs/Codecs/AV1.h>
#include <LibMediaCodecs/Codecs/CodecString.h>
+#include <LibMediaCodecs/Codecs/DolbyVision.h>
+#include <LibMediaCodecs/Codecs/HDR10Plus.h>
namespace Media::Codecs {
@@ -164,6 +166,10 @@ Optional<AV1::Parameters> AV1::parse_codec_parameters(GenericLexer& lexer)
}
static constexpr u8 OBU_SEQUENCE_HEADER = 1;
+static constexpr u8 OBU_METADATA = 5;
+static constexpr u64 METADATA_TYPE_HDR_CLL = 1;
+static constexpr u64 METADATA_TYPE_HDR_MDCV = 2;
+static constexpr u64 METADATA_TYPE_ITUT_T35 = 4;
static constexpr u8 SELECT_SCREEN_CONTENT_TOOLS = 2;
static u8 bit_depth_from_configuration_record(u8 profile, bool high_bitdepth, bool twelve_bit)
@@ -313,14 +319,28 @@ static Optional<AV1::SequenceHeader> parse_sequence_header_obu(ReadonlyBytes obu
return sequence_header;
}
+struct OBU {
+ u8 type { 0 };
+ ReadonlyBytes payload;
+};
+
// https://aomediacodec.github.io/av1-spec/#obu-syntax
-Optional<AV1::SequenceHeader> AV1::parse_sequence_header(ReadonlyBytes obus)
-{
- auto remaining = obus;
- while (!remaining.is_empty()) {
- BitReader reader { remaining };
- if (reader.read_bit()) // obu_forbidden_bit
+// Walks a series of OBUs, stopping at the first malformed one.
+class OBUIterator {
+public:
+ explicit OBUIterator(ReadonlyBytes data)
+ : m_remaining_data(data)
+ {
+ }
+
+ Optional<OBU> next()
+ {
+ if (m_has_error || m_remaining_data.is_empty())
return {};
+
+ BitReader reader { m_remaining_data };
+ if (reader.read_bit()) // obu_forbidden_bit
+ return fail();
auto obu_type = reader.read_bits<u8>(4);
auto has_extension = reader.read_bit();
auto has_size_field = reader.read_bit();
@@ -330,24 +350,111 @@ Optional<AV1::SequenceHeader> AV1::parse_sequence_header(ReadonlyBytes obus)
auto payload_size = has_size_field ? reader.read_leb128() : 0;
if (reader.has_overrun())
- return {};
+ return fail();
auto header_size = reader.bit_position() / 8;
- auto payload = remaining.slice(header_size);
+ auto payload = m_remaining_data.slice(header_size);
if (has_size_field) {
if (payload_size > payload.size())
- return {};
+ return fail();
payload = payload.trim(payload_size);
}
- if (obu_type == OBU_SEQUENCE_HEADER)
- return parse_sequence_header_obu(payload);
+ m_remaining_data = m_remaining_data.slice(header_size + payload.size());
+ return OBU { obu_type, payload };
+ }
+
+private:
+ Optional<OBU> fail()
+ {
+ m_has_error = true;
+ return {};
+ }
+
+ ReadonlyBytes m_remaining_data;
+ bool m_has_error { false };
+};
+
+Optional<AV1::SequenceHeader> AV1::parse_sequence_header(ReadonlyBytes obus)
+{
+ OBUIterator iterator { obus };
+ for (auto obu = iterator.next(); obu.has_value(); obu = iterator.next()) {
+ if (obu->type == OBU_SEQUENCE_HEADER)
+ return parse_sequence_header_obu(obu->payload);
+ }
+ return {};
+}
- remaining = remaining.slice(header_size + payload.size());
+// https://aomediacodec.github.io/av1-spec/#metadata-obu-syntax
+// https://aomediacodec.github.io/av1-spec/#trailing-bits-syntax
+// The metadata read here ends on a byte boundary, so its trailing one bit starts a byte of its own.
+static Optional<ReadonlyBytes> without_byte_aligned_trailing_bits(ReadonlyBytes payload)
+{
+ constexpr u8 trailing_one_bit_byte = 0x80;
+ for (size_t size = payload.size(); size > 0; size--) {
+ if (payload[size - 1] == 0)
+ continue;
+ if (payload[size - 1] != trailing_one_bit_byte)
+ return {};
+ return payload.trim(size - 1);
}
return {};
}
+static void read_high_dynamic_range_metadata_obu(ReadonlyBytes obu, ColorMetadata& metadata)
+{
+ auto payload = without_byte_aligned_trailing_bits(obu);
+ if (!payload.has_value())
+ return;
+ BitReader reader { payload.value() };
+ auto metadata_type = reader.read_leb128();
+ if (metadata_type == METADATA_TYPE_HDR_CLL) {
+ ContentLightLevelInformation information;
+ information.maximum_content_light_level = reader.read_bits<u16>(16);
+ information.maximum_frame_average_light_level = reader.read_bits<u16>(16);
+ if (!reader.has_overrun())
+ metadata.content_light_level_information = information;
+ } else if (metadata_type == METADATA_TYPE_HDR_MDCV) {
+ // The chromaticities are 0.16 fixed point, and the maximum and minimum luminances are 24.8 and 18.14.
+ constexpr float chromaticity_units_per_unit = 65'536.0f;
+ constexpr float maximum_luminance_units_per_candela_per_square_metre = 256.0f;
+ constexpr float minimum_luminance_units_per_candela_per_square_metre = 16'384.0f;
+ auto read_chromaticity = [&] {
+ Chromaticity chromaticity;
+ chromaticity.x = static_cast<float>(reader.read_bits<u16>(16)) / chromaticity_units_per_unit;
+ chromaticity.y = static_cast<float>(reader.read_bits<u16>(16)) / chromaticity_units_per_unit;
+ return chromaticity;
+ };
+ MasteringDisplayColorVolume volume;
+ volume.red = read_chromaticity();
+ volume.green = read_chromaticity();
+ volume.blue = read_chromaticity();
+ volume.white_point = read_chromaticity();
+ volume.maximum_luminance = static_cast<float>(reader.read_bits<u32>(32)) / maximum_luminance_units_per_candela_per_square_metre;
+ volume.minimum_luminance = static_cast<float>(reader.read_bits<u32>(32)) / minimum_luminance_units_per_candela_per_square_metre;
+ if (!reader.has_overrun())
+ metadata.mastering_display_color_volume = volume;
+ } else if (metadata_type == METADATA_TYPE_ITUT_T35 && !reader.has_overrun()) {
+ auto t35_message = payload->slice(reader.bit_position() / 8);
+ auto luminance = hdr10_plus_maximum_scene_luminance(t35_message);
+ if (!luminance.has_value())
+ luminance = dolby_vision_maximum_scene_luminance_of_t35(t35_message);
+ if (luminance.has_value())
+ metadata.maximum_scene_luminance = luminance;
+ }
+}
+
+ColorMetadata AV1::high_dynamic_range_metadata_of_obus(ReadonlyBytes obus)
+{
+ ColorMetadata metadata;
+ OBUIterator iterator { obus };
+ for (auto obu = iterator.next(); obu.has_value(); obu = iterator.next()) {
+ if (obu->type == OBU_METADATA)
+ read_high_dynamic_range_metadata_obu(obu->payload, metadata);
+ }
+ return metadata;
+}
+
// https://aomediacodec.github.io/av1-isobmff/#av1codecconfigurationbox-syntax
Optional<AV1::Parameters> AV1::parse_configuration_record(ReadonlyBytes record)
{
diff --git a/Libraries/LibMediaCodecs/Codecs/AV1.h b/Libraries/LibMediaCodecs/Codecs/AV1.h
index c020f3554e5..2622a0ee835 100644
--- a/Libraries/LibMediaCodecs/Codecs/AV1.h
+++ b/Libraries/LibMediaCodecs/Codecs/AV1.h
@@ -10,7 +10,7 @@
#include <AK/Optional.h>
#include <AK/Span.h>
#include <LibGfx/Size.h>
-#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>
+#include <LibMediaCodecs/Color/ColorMetadata.h>
#include <LibMediaCodecs/Export.h>
#include <LibMediaCodecs/Subsampling.h>
@@ -61,6 +61,9 @@ public:
// Reads the sequence header out of a series of OBUs, whether they are a coded frame or a configuration record's
// own OBUs. Only the coded frames that begin a coded video sequence carry one.
static MEDIACODECS_API Optional<SequenceHeader> parse_sequence_header(ReadonlyBytes obus);
+
+ // The HDR metadata of the metadata OBUs in a series of OBUs. Fields that no OBU carries are left empty.
+ static MEDIACODECS_API ColorMetadata high_dynamic_range_metadata_of_obus(ReadonlyBytes obus);
};
}
diff --git a/Libraries/LibMediaCodecs/Codecs/DolbyVision.cpp b/Libraries/LibMediaCodecs/Codecs/DolbyVision.cpp
new file mode 100644
index 00000000000..56361219b96
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/DolbyVision.cpp
@@ -0,0 +1,247 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/Math.h>
+#include <LibMediaCodecs/BitReader.h>
+#include <LibMediaCodecs/Codecs/DolbyVision.h>
+
+// Dolby does not publish the RPU syntax, so this follows FFmpeg's parser in libavcodec/dovi_rpudec.c. Only the fields
+// that precede the level 1 metadata are read, and everything else is skipped.
+
+namespace Media::Codecs {
+
+static constexpr u8 RPU_PREFIX = 0x19;
+static constexpr u8 RPU_TYPE_WITH_DISPLAY_MANAGEMENT = 2;
+static constexpr u16 RPU_FORMAT_PROFILE_MASK = 0x700;
+static constexpr u8 FIXED_POINT_COEFFICIENTS = 0;
+static constexpr u8 FLOATING_POINT_COEFFICIENTS = 1;
+static constexpr u64 MINIMUM_FIXED_POINT_FRACTION_BITS = 13;
+static constexpr u64 MAXIMUM_FIXED_POINT_FRACTION_BITS = 32;
+static constexpr u64 MAXIMUM_BIT_DEPTH_MINUS_8 = 8;
+static constexpr u64 MAXIMUM_PIVOT_COUNT_MINUS_2 = 7;
+static constexpr u64 POLYNOMIAL_MAPPING = 0;
+static constexpr u64 MULTIVARIATE_MULTIPLE_REGRESSION_MAPPING = 1;
+static constexpr u64 MAXIMUM_POLYNOMIAL_ORDER_MINUS_1 = 1;
+static constexpr u8 MAXIMUM_MULTIVARIATE_MULTIPLE_REGRESSION_ORDER_MINUS_1 = 2;
+static constexpr size_t MULTIVARIATE_MULTIPLE_REGRESSION_COEFFICIENTS_PER_ORDER = 7;
+static constexpr u8 LINEAR_DEAD_ZONE_QUANTIZATION = 0;
+
+// The colour transform of the display management metadata: the YCbCr to RGB matrix and offsets, the RGB to LMS matrix,
+// the signal's transfer, bit depth, colour space, chroma format and range, and the source display's luminance range
+// and diagonal.
+static constexpr size_t DISPLAY_MANAGEMENT_COLOR_TRANSFORM_BIT_COUNT = 9 * 16 + 3 * 32 + 9 * 16 + 3 * 16 + 32 + 5 + 2 + 2 + 2 + 12 + 12 + 10;
+static constexpr u8 LEVEL_1_EXTENSION_BLOCK = 1;
+static constexpr size_t PERCEPTUAL_QUANTIZER_CODE_BIT_COUNT = 12;
+
+static float luminance_of_perceptual_quantizer_code(u16 code)
+{
+ // SMPTE ST 2084's EOTF.
+ constexpr double m1 = 2610.0 / 16384;
+ constexpr double m2 = 2523.0 / 4096 * 128;
+ constexpr double c1 = 3424.0 / 4096;
+ constexpr double c2 = 2413.0 / 4096 * 32;
+ constexpr double c3 = 2392.0 / 4096 * 32;
+ constexpr double peak_luminance = 10000;
+ auto signal = static_cast<double>(code) / ((1 << PERCEPTUAL_QUANTIZER_CODE_BIT_COUNT) - 1);
+ auto signal_power = AK::pow(signal, 1 / m2);
+ auto linear = AK::pow(max(signal_power - c1, 0.0) / (c2 - c3 * signal_power), 1 / m1);
+ return static_cast<float>(linear * peak_luminance);
+}
+
+Optional<float> dolby_vision_maximum_scene_luminance(ReadonlyBytes rpu)
+{
+ if (rpu.is_empty() || rpu[0] != RPU_PREFIX)
+ return {};
+
+ BitReader reader { rpu.slice(1) };
+ if (reader.read_bits<u8>(6) != RPU_TYPE_WITH_DISPLAY_MANAGEMENT)
+ return {};
+ auto rpu_format = reader.read_bits<u16>(11);
+ reader.skip_bits(4 + 4); // vdr_rpu_profile, vdr_rpu_level
+
+ if (!reader.read_bit()) // vdr_seq_info_present_flag
+ return {};
+ reader.skip_bits(1); // chroma_resampling_explicit_filter_flag
+ auto coefficient_data_type = reader.read_bits<u8>(2);
+ u64 coefficient_fraction_bit_count = 0;
+ if (coefficient_data_type == FIXED_POINT_COEFFICIENTS) {
+ coefficient_fraction_bit_count = reader.read_exp_golomb();
+ if (coefficient_fraction_bit_count < MINIMUM_FIXED_POINT_FRACTION_BITS || coefficient_fraction_bit_count > MAXIMUM_FIXED_POINT_FRACTION_BITS)
+ return {};
+ } else if (coefficient_data_type != FLOATING_POINT_COEFFICIENTS) {
+ return {};
+ }
+ reader.skip_bits(2 + 1); // vdr_rpu_normalized_idc, bl_video_full_range_flag
+
+ if ((rpu_format & RPU_FORMAT_PROFILE_MASK) != 0)
+ return {};
+ auto base_layer_bit_depth_minus_8 = reader.read_exp_golomb();
+ // The upper bits of the enhancement layer's bit depth hold the ext_mapping_idc.
+ auto enhancement_layer_bit_depth_minus_8 = reader.read_exp_golomb() & 0xFF;
+ reader.read_exp_golomb(); // vdr_bit_depth_minus8
+ if (base_layer_bit_depth_minus_8 > MAXIMUM_BIT_DEPTH_MINUS_8 || enhancement_layer_bit_depth_minus_8 > MAXIMUM_BIT_DEPTH_MINUS_8)
+ return {};
+ auto base_layer_bit_depth = base_layer_bit_depth_minus_8 + 8;
+ auto enhancement_layer_bit_depth = enhancement_layer_bit_depth_minus_8 + 8;
+ reader.skip_bits(1); // spatial_resampling_filter_flag
+ auto display_management_compression = reader.read_bits<u8>(3);
+ reader.skip_bits(1); // el_spatial_resampling_filter_flag
+ auto uses_nonlinear_quantization = !reader.read_bit(); // disable_residual_flag
+
+ auto display_management_metadata_is_present = reader.read_bit();
+ if (display_management_compression > 1)
+ return {};
+
+ auto skip_coefficient = [&] {
+ if (coefficient_data_type == FIXED_POINT_COEFFICIENTS) {
+ reader.read_exp_golomb();
+ reader.skip_bits(coefficient_fraction_bit_count);
+ } else {
+ reader.skip_bits(32);
+ }
+ };
+
+ if (reader.read_bit()) { // use_prev_vdr_rpu_flag
+ reader.read_exp_golomb(); // prev_vdr_rpu_id
+ } else {
+ reader.read_exp_golomb(); // vdr_rpu_id
+ reader.read_exp_golomb(); // mapping_color_space
+ reader.read_exp_golomb(); // mapping_chroma_format_idc
+
+ Array<u64, 3> pivot_counts {};
+ for (auto& pivot_count : pivot_counts) {
+ auto pivot_count_minus_2 = reader.read_exp_golomb();
+ if (pivot_count_minus_2 > MAXIMUM_PIVOT_COUNT_MINUS_2)
+ return {};
+ pivot_count = pivot_count_minus_2 + 2;
+ reader.skip_bits(pivot_count * base_layer_bit_depth);
+ }
+
+ u8 nonlinear_quantization_method = 0;
+ if (uses_nonlinear_quantization) {
+ nonlinear_quantization_method = reader.read_bits<u8>(3);
+ if (nonlinear_quantization_method > LINEAR_DEAD_ZONE_QUANTIZATION)
+ return {};
+ reader.skip_bits(2 * base_layer_bit_depth); // nlq_pred_pivot_value
+ }
+ reader.read_exp_golomb(); // num_x_partitions_minus1
+ reader.read_exp_golomb(); // num_y_partitions_minus1
+
+ for (auto pivot_count : pivot_counts) {
+ for (u64 piece = 0; piece + 1 < pivot_count; piece++) {
+ auto mapping = reader.read_exp_golomb();
+ if (mapping == POLYNOMIAL_MAPPING) {
+ auto order_minus_1 = reader.read_exp_golomb();
+ if (order_minus_1 > MAXIMUM_POLYNOMIAL_ORDER_MINUS_1)
+ return {};
+ if (order_minus_1 == 0 && reader.read_bit()) // linear_interp_flag
+ return {};
+ for (u64 coefficient = 0; coefficient < order_minus_1 + 2; coefficient++)
+ skip_coefficient();
+ } else if (mapping == MULTIVARIATE_MULTIPLE_REGRESSION_MAPPING) {
+ auto order_minus_1 = reader.read_bits<u8>(2);
+ if (order_minus_1 > MAXIMUM_MULTIVARIATE_MULTIPLE_REGRESSION_ORDER_MINUS_1)
+ return {};
+ skip_coefficient(); // mmr_constant
+ for (size_t coefficient = 0; coefficient < (order_minus_1 + 1u) * MULTIVARIATE_MULTIPLE_REGRESSION_COEFFICIENTS_PER_ORDER; coefficient++)
+ skip_coefficient();
+ } else {
+ return {};
+ }
+ }
+ }
+
+ if (uses_nonlinear_quantization) {
+ for (size_t component = 0; component < 3; component++) {
+ reader.skip_bits(enhancement_layer_bit_depth); // nlq_offset
+ skip_coefficient(); // vdr_in_max
+ if (nonlinear_quantization_method == LINEAR_DEAD_ZONE_QUANTIZATION) {
+ skip_coefficient(); // linear_deadzone_slope
+ skip_coefficient(); // linear_deadzone_threshold
+ }
+ }
+ }
+ }
+
+ if (!display_management_metadata_is_present)
+ return {};
+ reader.read_exp_golomb(); // affected_dm_metadata_id
+ reader.read_exp_golomb(); // current_dm_metadata_id
+ reader.read_exp_golomb(); // scene_refresh_flag
+ if (display_management_compression == 0)
+ reader.skip_bits(DISPLAY_MANAGEMENT_COLOR_TRANSFORM_BIT_COUNT);
+
+ // The level 1 metadata is among the content mapping version 2.9 extension blocks, which come first.
+ auto block_count = reader.read_exp_golomb();
+ reader.align_to_byte();
+ for (u64 block = 0; block < block_count && !reader.has_overrun(); block++) {
+ auto block_byte_count = reader.read_exp_golomb();
+ auto level = reader.read_bits<u8>(8);
+ if (level == LEVEL_1_EXTENSION_BLOCK) {
+ // min_pq, max_pq and avg_pq
+ if (block_byte_count * 8 < 3 * PERCEPTUAL_QUANTIZER_CODE_BIT_COUNT)
+ return {};
+ reader.skip_bits(PERCEPTUAL_QUANTIZER_CODE_BIT_COUNT); // min_pq
+ auto maximum_code = reader.read_bits<u16>(PERCEPTUAL_QUANTIZER_CODE_BIT_COUNT);
+ if (reader.has_overrun() || maximum_code == 0)
+ return {};
+ return luminance_of_perceptual_quantizer_code(maximum_code);
+ }
+ reader.skip_bits(block_byte_count * 8);
+ }
+ return {};
+}
+
+static constexpr u8 UNITED_STATES_COUNTRY_CODE = 0xB5;
+static constexpr u16 DOLBY_TERMINAL_PROVIDER_CODE = 0x003B;
+static constexpr u32 DOLBY_VISION_TERMINAL_PROVIDER_ORIENTED_CODE = 0x00000800;
+// The fields of an EMDF container header are fixed for Dolby Vision, so they read as one 27-bit value.
+static constexpr u32 EMDF_HEADER = 0x01BE6841;
+static constexpr size_t EMDF_HEADER_BIT_COUNT = 27;
+static constexpr u32 MINIMUM_EMDF_PAYLOAD_SIZE = 6;
+static constexpr u32 MAXIMUM_EMDF_PAYLOAD_SIZE = 512;
+
+// EMDF's variable_bits(): a value that grows by another group of bits for as long as a following bit is set. Two
+// groups of 8 bits are enough for any payload size up to the maximum, so a third makes the size invalid.
+static Optional<u32> read_emdf_payload_size(BitReader& reader)
+{
+ constexpr size_t group_bit_count = 8;
+ u32 value = reader.read_bits<u32>(group_bit_count);
+ if (!reader.read_bit())
+ return value;
+ value = ((value + 1) << group_bit_count) | reader.read_bits<u32>(group_bit_count);
+ if (reader.read_bit())
+ return {};
+ return value;
+}
+
+Optional<float> dolby_vision_maximum_scene_luminance_of_t35(ReadonlyBytes t35_message)
+{
+ BitReader reader { t35_message };
+ if (reader.read_bits<u8>(8) != UNITED_STATES_COUNTRY_CODE)
+ return {};
+ if (reader.read_bits<u16>(16) != DOLBY_TERMINAL_PROVIDER_CODE)
+ return {};
+ if (reader.read_bits<u32>(32) != DOLBY_VISION_TERMINAL_PROVIDER_ORIENTED_CODE)
+ return {};
+ if (reader.read_bits<u32>(EMDF_HEADER_BIT_COUNT) != EMDF_HEADER)
+ return {};
+ auto payload_size = read_emdf_payload_size(reader).value_or(0);
+ if (reader.has_overrun() || payload_size < MINIMUM_EMDF_PAYLOAD_SIZE || payload_size > MAXIMUM_EMDF_PAYLOAD_SIZE)
+ return {};
+
+ // The payload is off byte alignment by a bit, and the RPU in it lacks the prefix an H.265 NAL unit gives it.
+ Array<u8, MAXIMUM_EMDF_PAYLOAD_SIZE + 1> rpu;
+ rpu[0] = RPU_PREFIX;
+ for (size_t index = 0; index < payload_size; index++)
+ rpu[index + 1] = reader.read_bits<u8>(8);
+ if (reader.has_overrun())
+ return {};
+ return dolby_vision_maximum_scene_luminance(ReadonlyBytes { rpu.data(), payload_size + 1 });
+}
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/DolbyVision.h b/Libraries/LibMediaCodecs/Codecs/DolbyVision.h
new file mode 100644
index 00000000000..8dc05beeb35
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/DolbyVision.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/Span.h>
+#include <LibMediaCodecs/Export.h>
+
+namespace Media::Codecs {
+
+// The brightest light in the scene in cd/m², from the level 1 metadata of a Dolby Vision RPU. The RPU is unescaped and
+// begins with its 0x19 prefix, which is how an H.265 NAL unit of type 62 carries it after its header. Empty for an RPU
+// that carries no display management metadata.
+MEDIACODECS_API Optional<float> dolby_vision_maximum_scene_luminance(ReadonlyBytes rpu);
+
+// The same, from an ITU-T T.35 message that begins with its country code, which is how an AV1 metadata OBU carries an
+// RPU. Empty for any other message.
+MEDIACODECS_API Optional<float> dolby_vision_maximum_scene_luminance_of_t35(ReadonlyBytes t35_message);
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/H264.cpp b/Libraries/LibMediaCodecs/Codecs/H264.cpp
index f06d025dc8d..3286125c12e 100644
--- a/Libraries/LibMediaCodecs/Codecs/H264.cpp
+++ b/Libraries/LibMediaCodecs/Codecs/H264.cpp
@@ -10,6 +10,7 @@
#include <LibMediaCodecs/Codecs/H264.h>
#include <LibMediaCodecs/Codecs/NALUnit.h>
#include <LibMediaCodecs/Codecs/RBSPBitReader.h>
+#include <LibMediaCodecs/Codecs/SupplementalEnhancementInformation.h>
namespace Media::Codecs {
@@ -49,6 +50,7 @@ Optional<H264::Parameters> H264::parse_configuration_record(ReadonlyBytes record
}
static constexpr size_t NAL_UNIT_HEADER_SIZE = 1;
+static constexpr u8 FORBIDDEN_ZERO_BIT_MASK = 0x80;
static constexpr u8 NAL_UNIT_TYPE_MASK = 0x1F;
static constexpr u8 SEQUENCE_PARAMETER_SET_NAL_UNIT_TYPE = 7;
static constexpr u8 PICTURE_PARAMETER_SET_NAL_UNIT_TYPE = 8;
@@ -58,6 +60,8 @@ static constexpr u8 NAL_REF_IDC_MASK = 0x60;
static constexpr u8 NAL_REF_IDC_SHIFT = 5;
static constexpr u8 FIRST_CODED_SLICE_NAL_UNIT_TYPE = 1;
static constexpr u8 LAST_CODED_SLICE_NAL_UNIT_TYPE = 5;
+static constexpr u8 INSTANTANEOUS_DECODING_REFRESH_NAL_UNIT_TYPE = 5;
+static constexpr u8 SUPPLEMENTAL_ENHANCEMENT_INFORMATION_NAL_UNIT_TYPE = 6;
// The profiles whose sequence parameter sets carry the chroma format and scaling matrix fields.
// ITU-T H.264 (08/2024), 7.3.2.1.1.
@@ -213,6 +217,20 @@ u8 H264::nal_ref_idc(u8 nal_unit_header)
}
// ITU-T H.264 (08/2024), Table 7-1.
+ColorMetadata H264::high_dynamic_range_metadata_of_nal_unit(ReadonlyBytes nal_unit)
+{
+ if (nal_unit.size() <= NAL_UNIT_HEADER_SIZE || (nal_unit[0] & FORBIDDEN_ZERO_BIT_MASK) != 0)
+ return {};
+ if ((nal_unit[0] & NAL_UNIT_TYPE_MASK) != SUPPLEMENTAL_ENHANCEMENT_INFORMATION_NAL_UNIT_TYPE)
+ return {};
+ return high_dynamic_range_metadata_of_sei_payload(nal_unit.slice(NAL_UNIT_HEADER_SIZE));
+}
+
+bool H264::begins_coded_video_sequence(u8 nal_unit_header)
+{
+ return (nal_unit_header & NAL_UNIT_TYPE_MASK) == INSTANTANEOUS_DECODING_REFRESH_NAL_UNIT_TYPE;
+}
+
bool H264::is_parameter_set(u8 nal_unit_header)
{
auto nal_unit_type = nal_unit_header & NAL_UNIT_TYPE_MASK;
@@ -225,7 +243,9 @@ bool H264::is_parameter_set(u8 nal_unit_header)
// ITU-T H.264 (08/2024), 7.3.2.1.1: seq_parameter_set_data().
Optional<H264::SequenceParameterSet> H264::parse_sequence_parameter_set(ReadonlyBytes nal_unit)
{
- if (nal_unit.is_empty() || (nal_unit[0] & NAL_UNIT_TYPE_MASK) != SEQUENCE_PARAMETER_SET_NAL_UNIT_TYPE || (nal_unit[0] & 0x80) != 0)
+ if (nal_unit.is_empty() || (nal_unit[0] & FORBIDDEN_ZERO_BIT_MASK) != 0)
+ return {};
+ if ((nal_unit[0] & NAL_UNIT_TYPE_MASK) != SEQUENCE_PARAMETER_SET_NAL_UNIT_TYPE)
return {};
Codecs::RBSPBitReader reader { nal_unit.slice(NAL_UNIT_HEADER_SIZE) };
auto profile_idc = reader.read_bits<u8>(8);
@@ -307,7 +327,9 @@ Optional<H264::SequenceParameterSet> H264::parse_sequence_parameter_set(Readonly
// ITU-T H.264 (08/2024), 7.3.2.2: pic_parameter_set_rbsp(), through seq_parameter_set_id.
Optional<H264::PictureParameterSet> H264::parse_picture_parameter_set(ReadonlyBytes nal_unit)
{
- if (nal_unit.is_empty() || (nal_unit[0] & NAL_UNIT_TYPE_MASK) != PICTURE_PARAMETER_SET_NAL_UNIT_TYPE || (nal_unit[0] & 0x80) != 0)
+ if (nal_unit.is_empty() || (nal_unit[0] & FORBIDDEN_ZERO_BIT_MASK) != 0)
+ return {};
+ if ((nal_unit[0] & NAL_UNIT_TYPE_MASK) != PICTURE_PARAMETER_SET_NAL_UNIT_TYPE)
return {};
Codecs::RBSPBitReader reader { nal_unit.slice(NAL_UNIT_HEADER_SIZE) };
auto pic_parameter_set_id = reader.read_unsigned_exp_golomb();
diff --git a/Libraries/LibMediaCodecs/Codecs/H264.h b/Libraries/LibMediaCodecs/Codecs/H264.h
index c7bbdd53844..1e73649bdb9 100644
--- a/Libraries/LibMediaCodecs/Codecs/H264.h
+++ b/Libraries/LibMediaCodecs/Codecs/H264.h
@@ -12,6 +12,7 @@
#include <AK/Optional.h>
#include <AK/Span.h>
#include <AK/Vector.h>
+#include <LibMediaCodecs/Color/ColorMetadata.h>
#include <LibMediaCodecs/Export.h>
namespace Media::Codecs {
@@ -108,8 +109,14 @@ public:
// Read the NAL unit header byte's fields (H.264, 7.4.1 and Table 7-1).
static MEDIACODECS_API bool is_coded_slice(u8 nal_unit_header);
static MEDIACODECS_API u8 nal_ref_idc(u8 nal_unit_header);
+ // Only an IDR picture starts a coded video sequence.
+ static MEDIACODECS_API bool begins_coded_video_sequence(u8 nal_unit_header);
static MEDIACODECS_API bool is_parameter_set(u8 nal_unit_header);
+ // The HDR metadata a NAL unit carries, if any. The scene peak applies to the picture the NAL unit is part of, and
+ // the rest to its coded video sequence.
+ static MEDIACODECS_API ColorMetadata high_dynamic_range_metadata_of_nal_unit(ReadonlyBytes nal_unit);
+
// Parse the fields needed for parameter-set tracking and output reordering from a complete NAL unit,
// including its header. These do not validate the remaining syntax of the parameter set.
static MEDIACODECS_API Optional<SequenceParameterSet> parse_sequence_parameter_set(ReadonlyBytes nal_unit);
diff --git a/Libraries/LibMediaCodecs/Codecs/H265.cpp b/Libraries/LibMediaCodecs/Codecs/H265.cpp
index 5da737e9a6d..984fd085298 100644
--- a/Libraries/LibMediaCodecs/Codecs/H265.cpp
+++ b/Libraries/LibMediaCodecs/Codecs/H265.cpp
@@ -6,9 +6,11 @@
#include <LibMediaCodecs/BitReader.h>
#include <LibMediaCodecs/Codecs/CodecString.h>
+#include <LibMediaCodecs/Codecs/DolbyVision.h>
#include <LibMediaCodecs/Codecs/H265.h>
#include <LibMediaCodecs/Codecs/NALUnit.h>
#include <LibMediaCodecs/Codecs/RBSPBitReader.h>
+#include <LibMediaCodecs/Codecs/SupplementalEnhancementInformation.h>
namespace Media::Codecs {
@@ -24,6 +26,12 @@ static constexpr u8 LAST_RASL_NAL_UNIT_TYPE = 9;
static constexpr u8 FIRST_BLA_NAL_UNIT_TYPE = 16;
static constexpr u8 LAST_BLA_NAL_UNIT_TYPE = 18;
static constexpr u8 CRA_NAL_UNIT_TYPE = 21;
+static constexpr u8 LAST_IDR_NAL_UNIT_TYPE = 20;
+static constexpr u8 END_OF_SEQUENCE_NAL_UNIT_TYPE = 36;
+static constexpr u8 END_OF_BITSTREAM_NAL_UNIT_TYPE = 37;
+static constexpr u8 PREFIX_SUPPLEMENTAL_ENHANCEMENT_INFORMATION_NAL_UNIT_TYPE = 39;
+// Dolby Vision puts its RPUs in the first of the unspecified NAL unit types.
+static constexpr u8 DOLBY_VISION_REFERENCE_PROCESSING_UNIT_NAL_UNIT_TYPE = 62;
static constexpr u8 MAXIMUM_REORDER_FRAME_COUNT = 16;
Optional<H265::Parameters> H265::parse_codec_parameters(GenericLexer& lexer)
@@ -173,6 +181,46 @@ bool H265::has_random_access_skipped_leading_pictures(NALUnitHeader const& heade
return is_broken_link_access || header.nal_unit_type == CRA_NAL_UNIT_TYPE;
}
+static ColorMetadata high_dynamic_range_metadata_of_dolby_vision_nal_unit(ReadonlyBytes nal_unit)
+{
+ Vector<u8, 1024> rpu;
+ Codecs::RBSPBitReader reader { nal_unit.slice(NAL_UNIT_HEADER_SIZE) };
+ while (reader.remaining_byte_count() > 0) {
+ auto byte = reader.read_bits<u8>(8);
+ if (reader.has_overrun())
+ break;
+ if (rpu.try_append(byte).is_error())
+ return {};
+ }
+
+ ColorMetadata metadata;
+ metadata.maximum_scene_luminance = dolby_vision_maximum_scene_luminance(rpu);
+ return metadata;
+}
+
+// ITU-T H.265 (07/2024), Table 7-1: BLA_W_LP through IDR_N_LP.
+bool H265::begins_coded_video_sequence(NALUnitHeader const& header)
+{
+ return header.nuh_layer_id == 0 && header.nal_unit_type >= FIRST_BLA_NAL_UNIT_TYPE && header.nal_unit_type <= LAST_IDR_NAL_UNIT_TYPE;
+}
+
+bool H265::ends_coded_video_sequence(NALUnitHeader const& header)
+{
+ return header.nal_unit_type == END_OF_SEQUENCE_NAL_UNIT_TYPE || header.nal_unit_type == END_OF_BITSTREAM_NAL_UNIT_TYPE;
+}
+
+ColorMetadata H265::high_dynamic_range_metadata_of_nal_unit(ReadonlyBytes nal_unit)
+{
+ auto header = parse_nal_unit_header(nal_unit);
+ if (!header.has_value() || header->nuh_layer_id != 0)
+ return {};
+ if (header->nal_unit_type == PREFIX_SUPPLEMENTAL_ENHANCEMENT_INFORMATION_NAL_UNIT_TYPE)
+ return high_dynamic_range_metadata_of_sei_payload(nal_unit.slice(NAL_UNIT_HEADER_SIZE));
+ if (header->nal_unit_type == DOLBY_VISION_REFERENCE_PROCESSING_UNIT_NAL_UNIT_TYPE)
+ return high_dynamic_range_metadata_of_dolby_vision_nal_unit(nal_unit);
+ return {};
+}
+
// ITU-T H.265 (07/2024), 7.3.3: the spec notes that the constraint flag branches do not affect the structure's
// width, so reaching what follows only takes counting bits.
static void skip_profile_tier_level(RBSPBitReader& reader, u8 max_sub_layers_minus1)
diff --git a/Libraries/LibMediaCodecs/Codecs/H265.h b/Libraries/LibMediaCodecs/Codecs/H265.h
index 9ac0e42dd52..34e6bec0a7d 100644
--- a/Libraries/LibMediaCodecs/Codecs/H265.h
+++ b/Libraries/LibMediaCodecs/Codecs/H265.h
@@ -13,6 +13,7 @@
#include <AK/Optional.h>
#include <AK/Span.h>
#include <AK/Vector.h>
+#include <LibMediaCodecs/Color/ColorMetadata.h>
#include <LibMediaCodecs/Export.h>
namespace Media::Codecs {
@@ -137,6 +138,15 @@ public:
static MEDIACODECS_API bool is_random_access_point(NALUnitHeader const&);
static MEDIACODECS_API bool is_random_access_skipped_leading(NALUnitHeader const&);
static MEDIACODECS_API bool has_random_access_skipped_leading_pictures(NALUnitHeader const&);
+ // IDR and BLA pictures always start a coded video sequence. A CRA picture only starts one at the start of the
+ // bitstream or after an end of sequence, which its header cannot tell.
+ static MEDIACODECS_API bool begins_coded_video_sequence(NALUnitHeader const&);
+ // The picture after an end of sequence or end of bitstream NAL unit starts a coded video sequence, whatever its type.
+ static MEDIACODECS_API bool ends_coded_video_sequence(NALUnitHeader const&);
+
+ // The HDR metadata a base layer NAL unit carries, if any. The scene peak applies to the picture the NAL unit is part
+ // of, and the rest to its coded video sequence.
+ static MEDIACODECS_API ColorMetadata high_dynamic_range_metadata_of_nal_unit(ReadonlyBytes nal_unit);
// Parse the fields needed for parameter-set tracking and output reordering from a complete NAL unit,
// including its header. These do not validate the remaining syntax of the parameter set.
diff --git a/Libraries/LibMediaCodecs/Codecs/HDR10Plus.cpp b/Libraries/LibMediaCodecs/Codecs/HDR10Plus.cpp
new file mode 100644
index 00000000000..277e3e1afa5
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/HDR10Plus.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibMediaCodecs/BitReader.h>
+#include <LibMediaCodecs/Codecs/HDR10Plus.h>
+
+namespace Media::Codecs {
+
+static constexpr u8 UNITED_STATES_COUNTRY_CODE = 0xB5;
+static constexpr u16 SAMSUNG_TERMINAL_PROVIDER_CODE = 0x003C;
+static constexpr u16 HDR10_PLUS_TERMINAL_PROVIDER_ORIENTED_CODE = 0x0001;
+static constexpr u8 HDR10_PLUS_APPLICATION_IDENTIFIER = 4;
+static constexpr u8 LATEST_APPLICATION_VERSION = 1;
+
+// The corners, ellipse and overlap option of each processing window after the first, which covers the whole picture.
+static constexpr size_t PROCESSING_WINDOW_BIT_COUNT = 153;
+static constexpr size_t TARGETED_SYSTEM_DISPLAY_MAXIMUM_LUMINANCE_BIT_COUNT = 27;
+static constexpr size_t ACTUAL_PEAK_LUMINANCE_DIMENSION_BIT_COUNT = 5;
+static constexpr size_t ACTUAL_PEAK_LUMINANCE_BIT_COUNT = 4;
+static constexpr size_t MAXSCL_BIT_COUNT = 17;
+static constexpr u32 MAXIMUM_MAXSCL = 100'000;
+
+Optional<float> hdr10_plus_maximum_scene_luminance(ReadonlyBytes t35_message)
+{
+ BitReader reader { t35_message };
+ if (reader.read_bits<u8>(8) != UNITED_STATES_COUNTRY_CODE)
+ return {};
+ if (reader.read_bits<u16>(16) != SAMSUNG_TERMINAL_PROVIDER_CODE)
+ return {};
+ if (reader.read_bits<u16>(16) != HDR10_PLUS_TERMINAL_PROVIDER_ORIENTED_CODE)
+ return {};
+ if (reader.read_bits<u8>(8) != HDR10_PLUS_APPLICATION_IDENTIFIER)
+ return {};
+ if (reader.read_bits<u8>(8) > LATEST_APPLICATION_VERSION)
+ return {};
+
+ auto window_count = reader.read_bits<u8>(2);
+ if (window_count == 0)
+ return {};
+ reader.skip_bits(PROCESSING_WINDOW_BIT_COUNT * (window_count - 1));
+
+ reader.skip_bits(TARGETED_SYSTEM_DISPLAY_MAXIMUM_LUMINANCE_BIT_COUNT);
+ if (reader.read_bit()) {
+ auto rows = reader.read_bits<u8>(ACTUAL_PEAK_LUMINANCE_DIMENSION_BIT_COUNT);
+ auto columns = reader.read_bits<u8>(ACTUAL_PEAK_LUMINANCE_DIMENSION_BIT_COUNT);
+ reader.skip_bits(static_cast<size_t>(rows) * columns * ACTUAL_PEAK_LUMINANCE_BIT_COUNT);
+ }
+
+ // The first window's maxscl, in units of 0.00001 of the 10000 cd/m² that the PQ curve peaks at.
+ u32 maximum_component = 0;
+ for (size_t component = 0; component < 3; component++)
+ maximum_component = max(maximum_component, reader.read_bits<u32>(MAXSCL_BIT_COUNT));
+ if (reader.has_overrun() || maximum_component == 0 || maximum_component > MAXIMUM_MAXSCL)
+ return {};
+ constexpr float maxscl_units_per_candela_per_square_metre = 10.0f;
+ return static_cast<float>(maximum_component) / maxscl_units_per_candela_per_square_metre;
+}
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/HDR10Plus.h b/Libraries/LibMediaCodecs/Codecs/HDR10Plus.h
new file mode 100644
index 00000000000..de0584f46b1
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/HDR10Plus.h
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Optional.h>
+#include <AK/Span.h>
+#include <LibMediaCodecs/Export.h>
+
+namespace Media::Codecs {
+
+// The largest HDR10+ ITU-T T.35 message, from its country code: the six bytes up to its application identifier, then
+// the 907 that FFmpeg's AV_HDR_PLUS_MAX_PAYLOAD_SIZE allows for the rest.
+constexpr size_t HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE = 6 + 907;
+
+// The brightest colour component in the scene in cd/m², from an HDR10+ (SMPTE ST 2094-40) ITU-T T.35 message that
+// begins with its country code. Empty for any other message, or one that gives no peak.
+MEDIACODECS_API Optional<float> hdr10_plus_maximum_scene_luminance(ReadonlyBytes t35_message);
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp
new file mode 100644
index 00000000000..e104591f692
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp
@@ -0,0 +1,129 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibMediaCodecs/Codecs/AV1.h>
+#include <LibMediaCodecs/Codecs/H264.h>
+#include <LibMediaCodecs/Codecs/H265.h>
+#include <LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h>
+#include <LibMediaCodecs/Codecs/NALUnit.h>
+#include <LibMediaCodecs/CodedFrame.h>
+
+namespace Media::Codecs {
+
+HighDynamicRangeMetadataTracker::HighDynamicRangeMetadataTracker(CodecID codec_id, ReadonlyBytes configuration)
+ : m_codec_id(codec_id)
+{
+ apply_configuration(configuration);
+}
+
+void HighDynamicRangeMetadataTracker::apply_configuration(ReadonlyBytes configuration)
+{
+ if (configuration.is_empty())
+ return;
+ forget_stream();
+
+ switch (m_codec_id) {
+ case CodecID::H264:
+ if (auto sets = H264::parse_parameter_sets_from_configuration_record(configuration); sets.has_value())
+ m_nal_unit_length_size = sets->nal_unit_length_size;
+ break;
+ case CodecID::H265:
+ if (auto sets = H265::parse_parameter_sets_from_configuration_record(configuration); sets.has_value())
+ m_nal_unit_length_size = sets->nal_unit_length_size;
+ break;
+ default:
+ break;
+ }
+}
+
+ColorMetadata const& HighDynamicRangeMetadataTracker::apply_coded_frame(CodedFrame const& coded_frame)
+{
+ if (auto configuration = coded_frame.new_codec_configuration(); configuration.has_value())
+ apply_configuration(*configuration);
+ begin_frame();
+
+ switch (m_codec_id) {
+ case CodecID::H264:
+ case CodecID::H265: {
+ NALUnitIterator iterator { coded_frame.data(), m_nal_unit_length_size };
+ for (auto nal_unit = iterator.next(); nal_unit.has_value(); nal_unit = iterator.next())
+ apply_nal_unit(*nal_unit);
+ break;
+ }
+ case CodecID::AV1:
+ take_bitstream_metadata(AV1::high_dynamic_range_metadata_of_obus(coded_frame.data()));
+ break;
+ default:
+ break;
+ }
+ return m_metadata;
+}
+
+void HighDynamicRangeMetadataTracker::forget_stream()
+{
+ m_metadata = {};
+ m_next_picture_begins_coded_video_sequence = false;
+}
+
+// A message replaces the one before it, so a level it leaves unknown does not fall back to the earlier message's.
+void HighDynamicRangeMetadataTracker::take_bitstream_metadata(ColorMetadata const& metadata)
+{
+ if (metadata.mastering_display_color_volume.has_value())
+ m_metadata.mastering_display_color_volume = metadata.mastering_display_color_volume;
+ if (metadata.content_light_level_information.has_value())
+ m_metadata.content_light_level_information = metadata.content_light_level_information;
+ if (metadata.maximum_scene_luminance.has_value())
+ m_metadata.maximum_scene_luminance = metadata.maximum_scene_luminance;
+}
+
+void HighDynamicRangeMetadataTracker::begin_frame()
+{
+ m_metadata.maximum_scene_luminance = {};
+ m_frame_gave_mastering_display_color_volume = false;
+ m_frame_gave_content_light_level_information = false;
+}
+
+void HighDynamicRangeMetadataTracker::apply_nal_unit(ReadonlyBytes nal_unit)
+{
+ if (nal_unit.is_empty())
+ return;
+
+ ColorMetadata nal_unit_metadata;
+ auto begins_coded_video_sequence = false;
+ if (m_codec_id == CodecID::H264) {
+ nal_unit_metadata = H264::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ begins_coded_video_sequence = H264::begins_coded_video_sequence(nal_unit[0]);
+ } else if (m_codec_id == CodecID::H265) {
+ auto header = H265::parse_nal_unit_header(nal_unit);
+ if (!header.has_value())
+ return;
+ if (H265::ends_coded_video_sequence(header.value())) {
+ m_next_picture_begins_coded_video_sequence = true;
+ return;
+ }
+ nal_unit_metadata = H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ begins_coded_video_sequence = H265::begins_coded_video_sequence(header.value());
+ if (H265::is_coded_slice(header.value()) && header->nuh_layer_id == 0)
+ begins_coded_video_sequence |= exchange(m_next_picture_begins_coded_video_sequence, false);
+ } else {
+ return;
+ }
+
+ m_frame_gave_mastering_display_color_volume |= nal_unit_metadata.mastering_display_color_volume.has_value();
+ m_frame_gave_content_light_level_information |= nal_unit_metadata.content_light_level_information.has_value();
+ take_bitstream_metadata(nal_unit_metadata);
+
+ // ITU-T H.265 (07/2024), D.3.28 and D.3.35: the messages only describe the coded video sequence they are part of.
+ // They are prefix SEI messages, so any that the sequence's first picture carries came before this slice.
+ if (begins_coded_video_sequence) {
+ if (!m_frame_gave_mastering_display_color_volume)
+ m_metadata.mastering_display_color_volume = {};
+ if (!m_frame_gave_content_light_level_information)
+ m_metadata.content_light_level_information = {};
+ }
+}
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h
new file mode 100644
index 00000000000..15ede5a135a
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Span.h>
+#include <LibMediaCodecs/CodecID.h>
+#include <LibMediaCodecs/Color/ColorMetadata.h>
+#include <LibMediaCodecs/Export.h>
+#include <LibMediaCodecs/Forward.h>
+
+namespace Media::Codecs {
+
+// Follows the HDR metadata a video bitstream carries alongside its pictures. The scene peak is each frame's own, while
+// the rest carries over to the frames that follow until the bitstream changes it or a new configuration starts over.
+class MEDIACODECS_API HighDynamicRangeMetadataTracker {
+public:
+ HighDynamicRangeMetadataTracker(CodecID, ReadonlyBytes configuration);
+
+ // Takes the frame's new configuration if it has one, then gives back the metadata of the frame.
+ ColorMetadata const& apply_coded_frame(CodedFrame const&);
+
+ // For a decoder that walks the NAL units of H.264 and H.265 frames itself. A new configuration calls for
+ // forget_stream(), and each frame for begin_frame() before its NAL units are applied.
+ void forget_stream();
+ void begin_frame();
+ void apply_nal_unit(ReadonlyBytes);
+
+ ColorMetadata const& metadata() const { return m_metadata; }
+
+private:
+ void apply_configuration(ReadonlyBytes);
+ void take_bitstream_metadata(ColorMetadata const&);
+
+ CodecID m_codec_id;
+ u8 m_nal_unit_length_size { 4 };
+ ColorMetadata m_metadata;
+ // A frame that starts a coded video sequence keeps only the values its own SEI messages gave.
+ bool m_frame_gave_mastering_display_color_volume { false };
+ bool m_frame_gave_content_light_level_information { false };
+ bool m_next_picture_begins_coded_video_sequence { false };
+};
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/RBSPBitReader.h b/Libraries/LibMediaCodecs/Codecs/RBSPBitReader.h
index 02f22371193..9a7fc744a6d 100644
--- a/Libraries/LibMediaCodecs/Codecs/RBSPBitReader.h
+++ b/Libraries/LibMediaCodecs/Codecs/RBSPBitReader.h
@@ -88,6 +88,9 @@ public:
bool has_overrun() const { return m_has_overrun; }
+ // The emulation prevention bytes left to skip count as well, so this is at least the count of RBSP bytes left.
+ size_t remaining_byte_count() const { return m_data.size() - m_byte_index; }
+
private:
void advance_to_next_byte(u8 consumed_byte)
{
diff --git a/Libraries/LibMediaCodecs/Codecs/SupplementalEnhancementInformation.cpp b/Libraries/LibMediaCodecs/Codecs/SupplementalEnhancementInformation.cpp
new file mode 100644
index 00000000000..f9c54301dd5
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/SupplementalEnhancementInformation.cpp
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <AK/Array.h>
+#include <AK/Checked.h>
+#include <LibMediaCodecs/Codecs/HDR10Plus.h>
+#include <LibMediaCodecs/Codecs/RBSPBitReader.h>
+#include <LibMediaCodecs/Codecs/SupplementalEnhancementInformation.h>
+
+namespace Media::Codecs {
+
+static constexpr u32 USER_DATA_REGISTERED_ITU_T_T35_PAYLOAD_TYPE = 4;
+static constexpr u32 MASTERING_DISPLAY_COLOUR_VOLUME_PAYLOAD_TYPE = 137;
+static constexpr u32 CONTENT_LIGHT_LEVEL_INFORMATION_PAYLOAD_TYPE = 144;
+static constexpr u32 MASTERING_DISPLAY_COLOUR_VOLUME_PAYLOAD_SIZE = 24;
+static constexpr u32 CONTENT_LIGHT_LEVEL_INFORMATION_PAYLOAD_SIZE = 4;
+
+// ITU-T H.265 (07/2024), 7.3.5: payloadType and payloadSize are a run of 0xFF bytes added to the byte ending it.
+static Optional<u32> read_sei_message_value(RBSPBitReader& reader)
+{
+ Checked<u32> value = 0;
+ while (true) {
+ auto byte = reader.read_bits<u8>(8);
+ if (reader.has_overrun())
+ return {};
+ value += byte;
+ if (value.has_overflow())
+ return {};
+ if (byte != 0xFF)
+ return value.value();
+ }
+}
+
+// ITU-T H.265 (07/2024), D.3.28: values outside these ranges are unknown or unspecified.
+static constexpr u16 MINIMUM_CHROMATICITY_CODE = 5;
+static constexpr u16 MAXIMUM_CHROMATICITY_X_CODE = 37'000;
+static constexpr u16 MAXIMUM_CHROMATICITY_Y_CODE = 42'000;
+static constexpr u32 MINIMUM_MAXIMUM_LUMINANCE_CODE = 50'000;
+static constexpr u32 MAXIMUM_MAXIMUM_LUMINANCE_CODE = 100'000'000;
+static constexpr u32 MAXIMUM_MINIMUM_LUMINANCE_CODE = 50'000;
+
+static Optional<MasteringDisplayColorVolume> read_mastering_display_color_volume(RBSPBitReader& reader)
+{
+ constexpr float chromaticity_units_per_unit = 50'000.0f;
+ constexpr float luminance_units_per_candela_per_square_metre = 10'000.0f;
+ auto is_specified = true;
+ auto read_chromaticity = [&] {
+ auto x = reader.read_bits<u16>(16);
+ auto y = reader.read_bits<u16>(16);
+ if (x < MINIMUM_CHROMATICITY_CODE || x > MAXIMUM_CHROMATICITY_X_CODE || y < MINIMUM_CHROMATICITY_CODE || y > MAXIMUM_CHROMATICITY_Y_CODE)
+ is_specified = false;
+ return Chromaticity { static_cast<float>(x) / chromaticity_units_per_unit, static_cast<float>(y) / chromaticity_units_per_unit };
+ };
+
+ MasteringDisplayColorVolume volume;
+ // The primaries are coded green, blue, then red, the order SMPTE ST 2086 lists them in.
+ volume.green = read_chromaticity();
+ volume.blue = read_chromaticity();
+ volume.red = read_chromaticity();
+ volume.white_point = read_chromaticity();
+ auto maximum_luminance = reader.read_bits<u32>(32);
+ auto minimum_luminance = reader.read_bits<u32>(32);
+ if (maximum_luminance < MINIMUM_MAXIMUM_LUMINANCE_CODE || maximum_luminance > MAXIMUM_MAXIMUM_LUMINANCE_CODE)
+ is_specified = false;
+ // A minimum of zero is out of range too, but Blu-ray releases use it, so it is accepted as FFmpeg accepts it.
+ if (minimum_luminance > MAXIMUM_MINIMUM_LUMINANCE_CODE || minimum_luminance >= maximum_luminance)
+ is_specified = false;
+ if (!is_specified)
+ return {};
+ volume.maximum_luminance = static_cast<float>(maximum_luminance) / luminance_units_per_candela_per_square_metre;
+ volume.minimum_luminance = static_cast<float>(minimum_luminance) / luminance_units_per_candela_per_square_metre;
+ return volume;
+}
+
+static Optional<float> read_hdr10_plus_maximum_scene_luminance(RBSPBitReader& reader, u32 payload_size)
+{
+ VERIFY(payload_size <= HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE);
+ Array<u8, HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE> message;
+ for (size_t index = 0; index < payload_size; index++)
+ message[index] = reader.read_bits<u8>(8);
+ return hdr10_plus_maximum_scene_luminance(ReadonlyBytes { message.data(), payload_size });
+}
+
+static ContentLightLevelInformation read_content_light_level_information(RBSPBitReader& reader)
+{
+ ContentLightLevelInformation information;
+ information.maximum_content_light_level = reader.read_bits<u16>(16);
+ information.maximum_frame_average_light_level = reader.read_bits<u16>(16);
+ return information;
+}
+
+// ITU-T H.265 (07/2024), 7.3.2.4: sei_rbsp().
+ColorMetadata high_dynamic_range_metadata_of_sei_payload(ReadonlyBytes escaped_sei_payload)
+{
+ ColorMetadata metadata;
+ RBSPBitReader reader { escaped_sei_payload };
+
+ // The last byte holds the RBSP trailing bits rather than the start of another message.
+ while (reader.remaining_byte_count() > 1) {
+ auto payload_type = read_sei_message_value(reader);
+ auto payload_size = read_sei_message_value(reader);
+ if (!payload_type.has_value() || !payload_size.has_value() || payload_size.value() > reader.remaining_byte_count())
+ break;
+
+ Optional<MasteringDisplayColorVolume> volume;
+ Optional<ContentLightLevelInformation> information;
+ Optional<float> maximum_scene_luminance;
+ auto unread_payload_size = payload_size.value();
+ if (payload_type == USER_DATA_REGISTERED_ITU_T_T35_PAYLOAD_TYPE && unread_payload_size <= HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE) {
+ maximum_scene_luminance = read_hdr10_plus_maximum_scene_luminance(reader, unread_payload_size);
+ unread_payload_size = 0;
+ } else if (payload_type == MASTERING_DISPLAY_COLOUR_VOLUME_PAYLOAD_TYPE && unread_payload_size >= MASTERING_DISPLAY_COLOUR_VOLUME_PAYLOAD_SIZE) {
+ volume = read_mastering_display_color_volume(reader);
+ unread_payload_size -= MASTERING_DISPLAY_COLOUR_VOLUME_PAYLOAD_SIZE;
+ } else if (payload_type == CONTENT_LIGHT_LEVEL_INFORMATION_PAYLOAD_TYPE && unread_payload_size >= CONTENT_LIGHT_LEVEL_INFORMATION_PAYLOAD_SIZE) {
+ information = read_content_light_level_information(reader);
+ unread_payload_size -= CONTENT_LIGHT_LEVEL_INFORMATION_PAYLOAD_SIZE;
+ }
+ reader.skip_bits(static_cast<size_t>(unread_payload_size) * 8);
+ // A message that runs into the RBSP trailing bits is missing some of its own.
+ if (reader.has_overrun() || reader.remaining_byte_count() == 0)
+ break;
+
+ if (volume.has_value())
+ metadata.mastering_display_color_volume = volume;
+ if (information.has_value())
+ metadata.content_light_level_information = information;
+ if (maximum_scene_luminance.has_value())
+ metadata.maximum_scene_luminance = maximum_scene_luminance;
+ }
+ return metadata;
+}
+
+}
diff --git a/Libraries/LibMediaCodecs/Codecs/SupplementalEnhancementInformation.h b/Libraries/LibMediaCodecs/Codecs/SupplementalEnhancementInformation.h
new file mode 100644
index 00000000000..163e32abc4d
--- /dev/null
+++ b/Libraries/LibMediaCodecs/Codecs/SupplementalEnhancementInformation.h
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#pragma once
+
+#include <AK/Span.h>
+#include <LibMediaCodecs/Color/ColorMetadata.h>
+
+namespace Media::Codecs {
+
+// The payload is an H.264 or H.265 SEI NAL unit without its header, with its emulation prevention bytes still in place.
+ColorMetadata high_dynamic_range_metadata_of_sei_payload(ReadonlyBytes escaped_sei_payload);
+
+}
diff --git a/Libraries/LibMediaCodecs/Color/ColorMetadata.cpp b/Libraries/LibMediaCodecs/Color/ColorMetadata.cpp
index 5137846aca8..719e14afac1 100644
--- a/Libraries/LibMediaCodecs/Color/ColorMetadata.cpp
+++ b/Libraries/LibMediaCodecs/Color/ColorMetadata.cpp
@@ -63,17 +63,26 @@ ErrorOr<void> encode(Encoder& encoder, Media::ColorMetadata const& metadata)
TRY(encoder.encode(metadata.cicp));
TRY(encoder.encode(metadata.mastering_display_color_volume));
TRY(encoder.encode(metadata.content_light_level_information));
+ TRY(encoder.encode(metadata.maximum_scene_luminance));
return {};
}
template<>
ErrorOr<Media::ColorMetadata> decode(Decoder& decoder)
{
- return Media::ColorMetadata {
+ Media::ColorMetadata metadata {
.cicp = TRY(decoder.decode<Media::CodingIndependentCodePoints>()),
.mastering_display_color_volume = TRY(decoder.decode<Optional<Media::MasteringDisplayColorVolume>>()),
.content_light_level_information = TRY(decoder.decode<Optional<Media::ContentLightLevelInformation>>()),
+ .maximum_scene_luminance = TRY(decoder.decode<Optional<float>>()),
};
+ if (auto luminance = metadata.maximum_scene_luminance; luminance.has_value()) {
+ if (!isfinite(*luminance))
+ return Error::from_string_literal("IPC: Maximum scene luminance is not finite");
+ if (*luminance <= 0)
+ return Error::from_string_literal("IPC: Maximum scene luminance is not positive");
+ }
+ return metadata;
}
}
diff --git a/Libraries/LibMediaCodecs/Color/ColorMetadata.h b/Libraries/LibMediaCodecs/Color/ColorMetadata.h
index 7fec59411b2..41408b47f63 100644
--- a/Libraries/LibMediaCodecs/Color/ColorMetadata.h
+++ b/Libraries/LibMediaCodecs/Color/ColorMetadata.h
@@ -45,6 +45,8 @@ struct ColorMetadata {
CodingIndependentCodePoints cicp;
Optional<MasteringDisplayColorVolume> mastering_display_color_volume;
Optional<ContentLightLevelInformation> content_light_level_information;
+ // The brightest light in the frame's scene in cd/m².
+ Optional<float> maximum_scene_luminance;
bool operator==(ColorMetadata const&) const = default;
@@ -61,6 +63,8 @@ struct ColorMetadata {
merged_information.maximum_frame_average_light_level = information->maximum_frame_average_light_level;
content_light_level_information = merged_information;
}
+ if (other.maximum_scene_luminance.has_value())
+ maximum_scene_luminance = other.maximum_scene_luminance;
}
};
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp
index efb60575310..11e8e654f28 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegHelpers.cpp
@@ -60,7 +60,8 @@ DecoderErrorOr<u64> VideoFramesAwaitingOutput::add(CodedFrame const& coded_frame
if (stale_frame_count > 0)
dbgln("FFmpeg: {} frames were never output", stale_frame_count);
}
- DECODER_TRY_ALLOC(m_frames.try_set(key, { coded_frame.presentation_timestamp(), coded_frame.duration(), intent }));
+ auto const& high_dynamic_range_metadata = m_high_dynamic_range_metadata_tracker.apply_coded_frame(coded_frame);
+ DECODER_TRY_ALLOC(m_frames.try_set(key, { coded_frame.presentation_timestamp(), coded_frame.duration(), intent, high_dynamic_range_metadata }));
return key;
}
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
index 51c39dec644..48cb90829de 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
@@ -66,7 +66,7 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVideoDecoder>> FFmpegVideoDecoder::try_create
return DecoderError::format(DecoderErrorCategory::Memory, "Failed to create a video frame pool: {}", frame_pool_result.release_error());
memory_guard.disarm();
- return DECODER_TRY_ALLOC(try_make<FFmpegVideoDecoder>(functions, codec_context, packet, frame, frame_pool_result.release_value()));
+ return DECODER_TRY_ALLOC(try_make<FFmpegVideoDecoder>(functions, codec_id, codec_initialization_data, codec_context, packet, frame, frame_pool_result.release_value()));
}
Optional<DecoderCapabilities> FFmpegVideoDecoder::capabilities(ParsedCodec const& codec)
@@ -79,12 +79,13 @@ DecoderErrorOr<NonnullOwnPtr<FFmpegVideoDecoder>> FFmpegVideoDecoder::try_create
return try_create(FFmpegFunctions::bundled(), codec_id, codec_initialization_data);
}
-FFmpegVideoDecoder::FFmpegVideoDecoder(FFmpegFunctions const& functions, AVCodecContext* codec_context, AVPacket* packet, AVFrame* frame, NonnullRefPtr<VideoFramePool> frame_pool)
+FFmpegVideoDecoder::FFmpegVideoDecoder(FFmpegFunctions const& functions, CodecID codec_id, ReadonlyBytes codec_initialization_data, AVCodecContext* codec_context, AVPacket* packet, AVFrame* frame, NonnullRefPtr<VideoFramePool> frame_pool)
: m_functions(functions)
, m_codec_context(codec_context)
, m_packet(packet)
, m_frame(frame)
, m_frame_pool(move(frame_pool))
+ , m_frames_awaiting_output(codec_id, codec_initialization_data)
{
}
@@ -142,6 +143,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVideoDecoder::take_next_output(C
}
auto color_metadata = container_color_metadata;
+ color_metadata.adopt_specified_values(m_pending_frame->high_dynamic_range_metadata);
color_metadata.cicp = coding_independent_code_points_of(m_functions, *m_codec_context, container_color_metadata.cicp);
auto pixel_format = static_cast<AVPixelFormat>(m_frame->format);
@@ -247,7 +249,7 @@ void FFmpegVideoDecoder::flush()
{
m_functions.avcodec_flush_buffers(m_codec_context);
m_pending_frame.clear();
- m_frames_awaiting_output.clear();
+ m_frames_awaiting_output.flush();
}
}
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h
index 0c2c0d28ca4..a66a7266705 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h
@@ -26,7 +26,7 @@ public:
static Optional<DecoderCapabilities> capabilities(ParsedCodec const&);
static DecoderErrorOr<NonnullOwnPtr<FFmpegVideoDecoder>> try_create(FFmpegFunctions const&, CodecID, ReadonlyBytes codec_initialization_data);
static DecoderErrorOr<NonnullOwnPtr<FFmpegVideoDecoder>> try_create(CodecID, ReadonlyBytes codec_initialization_data);
- FFmpegVideoDecoder(FFmpegFunctions const&, AVCodecContext* codec_context, AVPacket* packet, AVFrame* frame, NonnullRefPtr<VideoFramePool> frame_pool);
+ FFmpegVideoDecoder(FFmpegFunctions const&, CodecID, ReadonlyBytes codec_initialization_data, AVCodecContext* codec_context, AVPacket* packet, AVFrame* frame, NonnullRefPtr<VideoFramePool> frame_pool);
virtual ~FFmpegVideoDecoder() override;
virtual void set_storage_freed_callback(Function<void()> callback) override { m_frame_pool->set_slot_freed_callback(move(callback)); }
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
index 4639b47f772..8a59dbbb66f 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVulkanVideoDecoder.cpp
@@ -458,6 +458,7 @@ FFmpegVulkanVideoDecoder::FFmpegVulkanVideoDecoder(FFmpegFunctions const& functi
, m_device_context(device_context)
, m_packet(packet)
, m_received_frame(received_frame)
+ , m_frames_awaiting_output(codec_id, codec_configuration.span())
, m_codec_configuration(move(codec_configuration))
{
}
@@ -1109,6 +1110,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVulkanVideoDecoder::take_next_ou
return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video surface the decoder may hand out is held elsewhere"sv);
auto color_metadata = container_color_metadata;
+ color_metadata.adopt_specified_values(output.timing.high_dynamic_range_metadata);
color_metadata.cicp.adopt_specified_values(output.cicp);
auto frame = DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timing.timestamp, output.timing.duration, output.size, output.bit_depth, Subsampling::yuv420(), move(color_metadata), storage.release_nonnull()));
m_outputs.take_first();
@@ -1118,7 +1120,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVulkanVideoDecoder::take_next_ou
void FFmpegVulkanVideoDecoder::flush()
{
m_functions.avcodec_flush_buffers(m_codec_context);
- m_frames_awaiting_output.clear();
+ m_frames_awaiting_output.flush();
m_received_end_of_stream = false;
Vector<DecodingFrame> stale_frames;
diff --git a/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h b/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h
index a6dfc94fc50..7b9bf7e2bb5 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h
+++ b/Libraries/LibMediaCodecs/FFmpeg/VideoFramesAwaitingOutput.h
@@ -9,6 +9,7 @@
#include <AK/HashMap.h>
#include <AK/Optional.h>
#include <AK/Time.h>
+#include <LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h>
#include <LibMediaCodecs/DecoderError.h>
#include <LibMediaCodecs/Export.h>
#include <LibMediaCodecs/Forward.h>
@@ -17,21 +18,32 @@
namespace Media::FFmpeg {
// FFmpeg returns each packet's timestamp with the frame decoded from it, so a video decoder hands it a key instead and
-// keeps the frame's timing and intent under that key until the frame comes out.
+// keeps the frame's timing, intent and HDR metadata under that key until the frame comes out.
class MEDIACODECS_API VideoFramesAwaitingOutput {
public:
struct Frame {
AK::Duration timestamp;
AK::Duration duration;
DecodeIntent intent;
+ ColorMetadata high_dynamic_range_metadata;
};
+ VideoFramesAwaitingOutput(CodecID codec_id, ReadonlyBytes configuration)
+ : m_high_dynamic_range_metadata_tracker(codec_id, configuration)
+ {
+ }
+
DecoderErrorOr<u64> add(CodedFrame const&, DecodeIntent);
Optional<Frame> take(i64 key);
size_t size() const { return m_frames.size(); }
- void clear() { m_frames.clear(); }
+ void flush()
+ {
+ m_frames.clear();
+ m_high_dynamic_range_metadata_tracker.forget_stream();
+ }
private:
+ Codecs::HighDynamicRangeMetadataTracker m_high_dynamic_range_metadata_tracker;
u64 m_next_key { 0 };
HashMap<u64, Frame> m_frames;
};
diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h
index 25ae507a05d..ff5eb4a4418 100644
--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h
+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.h
@@ -59,7 +59,7 @@ private:
Gfx::IntSize size;
u8 bit_depth { 0 };
Subsampling subsampling;
- CodingIndependentCodePoints cicp;
+ ColorMetadata color_metadata;
};
// What a frame in the media engine was submitted with, which its output is given. The media engine hands the
@@ -68,6 +68,7 @@ private:
u64 submission_id { 0 };
AK::Duration timestamp;
AK::Duration duration;
+ ColorMetadata high_dynamic_range_metadata;
};
VideoToolboxVideoDecoder(CodecID, NonnullOwnPtr<FormatState>);
@@ -76,7 +77,7 @@ private:
void note_decode_completed(CodingIndependentCodePoints const& cicp, u64 submission_id, i32 status, void* image_buffer);
- void enqueue_decoded_output_while_locked(CodingIndependentCodePoints const& cicp, void* image_buffer, AK::Duration timestamp, AK::Duration duration);
+ void enqueue_decoded_output_while_locked(ColorMetadata const&, void* image_buffer, AK::Duration timestamp, AK::Duration duration);
void note_decode_failure_while_locked(i32 status);
void note_frame_left_the_media_engine_while_locked();
diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
index 61d17be25db..8ef68213b4f 100644
--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
@@ -10,6 +10,7 @@
#include <LibMediaCodecs/Codecs/AV1.h>
#include <LibMediaCodecs/Codecs/H264.h>
#include <LibMediaCodecs/Codecs/H265.h>
+#include <LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h>
#include <LibMediaCodecs/Codecs/NALUnit.h>
#include <LibMediaCodecs/Codecs/VP9.h>
#include <LibMediaCodecs/CodedFrame.h>
@@ -271,6 +272,10 @@ bool session_uses_hardware_decoder(VTDecompressionSessionRef session)
}
struct FormatState {
+ explicit FormatState(CodecID codec_id)
+ : high_dynamic_range_metadata_tracker(codec_id, {})
+ {
+ }
virtual ~FormatState() = default;
// Takes whatever the frame says about the stream's format.
@@ -285,11 +290,17 @@ struct FormatState {
bool access_unit_begins_open_gop { false };
// Whether the last frame's picture is such a leading picture.
bool access_unit_is_open_gop_leading_picture { false };
+ Codecs::HighDynamicRangeMetadataTracker high_dynamic_range_metadata_tracker;
};
struct H264State final : FormatState {
AK_ALLOC_WITH_KMALLOC;
+ H264State()
+ : FormatState(CodecID::H264)
+ {
+ }
+
Codecs::H264::ParameterSetStore parameter_sets;
u8 nal_unit_length_size { 4 };
@@ -311,9 +322,12 @@ struct H264State final : FormatState {
if (auto configuration = coded_frame.new_codec_configuration(); configuration.has_value())
TRY(apply_configuration(*configuration));
+ high_dynamic_range_metadata_tracker.begin_frame();
Codecs::NALUnitIterator iterator { coded_frame.data(), nal_unit_length_size };
- for (auto nal_unit = iterator.next(); nal_unit.has_value(); nal_unit = iterator.next())
+ for (auto nal_unit = iterator.next(); nal_unit.has_value(); nal_unit = iterator.next()) {
TRY(apply_nal_unit(*nal_unit));
+ high_dynamic_range_metadata_tracker.apply_nal_unit(*nal_unit);
+ }
if (iterator.has_error())
return DecoderError::corrupted("Invalid H.264 NAL unit length"sv);
return {};
@@ -329,6 +343,7 @@ struct H264State final : FormatState {
parameter_sets = {};
nal_unit_length_size = sets->nal_unit_length_size;
+ high_dynamic_range_metadata_tracker.forget_stream();
dirty = true;
for (auto nal_unit : sets->sequence)
@@ -374,6 +389,11 @@ struct H264State final : FormatState {
struct H265State final : FormatState {
AK_ALLOC_WITH_KMALLOC;
+ H265State()
+ : FormatState(CodecID::H265)
+ {
+ }
+
Codecs::H265::ParameterSetStore parameter_sets;
u8 nal_unit_length_size { 4 };
@@ -398,9 +418,11 @@ struct H265State final : FormatState {
auto saw_random_access_point = false;
auto saw_open_gop_start = false;
auto saw_open_gop_leading_picture = false;
+ high_dynamic_range_metadata_tracker.begin_frame();
Codecs::NALUnitIterator iterator { coded_frame.data(), nal_unit_length_size };
for (auto nal_unit = iterator.next(); nal_unit.has_value(); nal_unit = iterator.next()) {
TRY(apply_nal_unit(*nal_unit));
+ high_dynamic_range_metadata_tracker.apply_nal_unit(*nal_unit);
auto header = Codecs::H265::parse_nal_unit_header(*nal_unit);
if (!header.has_value() || !Codecs::H265::is_coded_slice(*header))
continue;
@@ -429,6 +451,7 @@ struct H265State final : FormatState {
parameter_sets = {};
nal_unit_length_size = sets->nal_unit_length_size;
+ high_dynamic_range_metadata_tracker.forget_stream();
dirty = true;
for (auto nal_unit : sets->video)
@@ -498,6 +521,11 @@ struct H265State final : FormatState {
struct VP9State final : FormatState {
AK_ALLOC_WITH_KMALLOC;
+ VP9State()
+ : FormatState(CodecID::VP9)
+ {
+ }
+
Optional<Codecs::VP9::FrameHeader> header;
virtual DecoderErrorOr<void> apply_coded_frame(CodedFrame const& coded_frame) override
@@ -534,6 +562,11 @@ struct VP9State final : FormatState {
struct AV1State final : FormatState {
AK_ALLOC_WITH_KMALLOC;
+ AV1State()
+ : FormatState(CodecID::AV1)
+ {
+ }
+
Optional<Codecs::AV1::SequenceHeader> sequence_header;
virtual DecoderErrorOr<void> apply_coded_frame(CodedFrame const& coded_frame) override
@@ -543,6 +576,7 @@ struct AV1State final : FormatState {
sequence_header = frame_sequence_header;
dirty = true;
}
+ high_dynamic_range_metadata_tracker.apply_coded_frame(coded_frame);
return {};
}
@@ -755,10 +789,12 @@ void VideoToolboxVideoDecoder::note_decode_completed(CodingIndependentCodePoints
MutexLocker locker { m_output_mutex };
if (auto frame = take_in_flight_frame_while_locked(submission_id); frame.has_value()) {
+ auto color_metadata = frame->high_dynamic_range_metadata;
+ color_metadata.cicp = cicp;
if (status != noErr)
note_decode_failure_while_locked(status);
else if (image_buffer != nullptr)
- enqueue_decoded_output_while_locked(cicp, image_buffer, frame->timestamp, frame->duration);
+ enqueue_decoded_output_while_locked(color_metadata, image_buffer, frame->timestamp, frame->duration);
auto frame_was_decoded_for_reference_only = status == noErr && image_buffer == nullptr;
if (!frame_was_decoded_for_reference_only)
completion = DecodeCompletion::ProducedOutput;
@@ -804,7 +840,7 @@ void VideoToolboxVideoDecoder::insert_output_in_presentation_order_while_locked(
m_outputs.insert(insertion_index, move(output));
}
-void VideoToolboxVideoDecoder::enqueue_decoded_output_while_locked(CodingIndependentCodePoints const& cicp, void* image_buffer, AK::Duration timestamp, AK::Duration duration)
+void VideoToolboxVideoDecoder::enqueue_decoded_output_while_locked(ColorMetadata const& color_metadata, void* image_buffer, AK::Duration timestamp, AK::Duration duration)
{
auto* pixel_buffer = static_cast<CVPixelBufferRef>(image_buffer);
auto* io_surface = CVPixelBufferGetIOSurface(pixel_buffer);
@@ -833,7 +869,7 @@ void VideoToolboxVideoDecoder::enqueue_decoded_output_while_locked(CodingIndepen
.size = { static_cast<int>(CVPixelBufferGetWidth(pixel_buffer)), static_cast<int>(CVPixelBufferGetHeight(pixel_buffer)) },
.bit_depth = static_cast<u8>(is_ten_bit ? 10 : 8),
.subsampling = Subsampling::yuv420(),
- .cicp = cicp,
+ .color_metadata = color_metadata,
};
insert_output_in_presentation_order_while_locked(move(output));
}
@@ -901,7 +937,7 @@ DecoderErrorOr<void> VideoToolboxVideoDecoder::receive_coded_data(CodedFrame con
m_caller_is_waiting_for_output = false;
}
m_frames_in_flight.fetch_add(1, AK::MemoryOrder::memory_order_relaxed);
- m_in_flight_frames.append({ submission_id, coded_frame.presentation_timestamp(), coded_frame.duration() });
+ m_in_flight_frames.append({ submission_id, coded_frame.presentation_timestamp(), coded_frame.duration(), m_format_state->high_dynamic_range_metadata_tracker.metadata() });
}
VTDecodeInfoFlags info_flags = 0;
@@ -983,7 +1019,7 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> VideoToolboxVideoDecoder::adopt_output
return DecoderError::with_description(DecoderErrorCategory::TryAgain, "Every video surface the decoder may hand out is held elsewhere"sv);
auto color_metadata = container_color_metadata;
- color_metadata.cicp.adopt_specified_values(output.cicp);
+ color_metadata.adopt_specified_values(output.color_metadata);
return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(
output.timestamp, output.duration, output.size.to_type<u32>(),
@@ -994,6 +1030,7 @@ void VideoToolboxVideoDecoder::flush()
{
m_reached_end_of_stream = false;
m_awaiting_first_submitted_frame = true;
+ m_format_state->high_dynamic_range_metadata_tracker.forget_stream();
MutexLocker locker { m_output_mutex };
// The media engine still hands back the frames it was decoding, which are discarded once nothing awaits them.
diff --git a/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp b/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp
index 80ae211e973..9256f1c1a76 100644
--- a/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp
+++ b/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.cpp
@@ -43,6 +43,7 @@ struct WindowsMediaFoundationVideoDecoder::DecodedOutput {
AK::Duration timestamp;
AK::Duration duration;
u64 generation { 0 };
+ ColorMetadata high_dynamic_range_metadata;
};
struct WindowsMediaFoundationVideoDecoder::Transform {
@@ -224,7 +225,7 @@ DecoderErrorOr<NonnullOwnPtr<WindowsMediaFoundationVideoDecoder>> WindowsMediaFo
if (frame_pool_result.is_error())
return DecoderError::format(DecoderErrorCategory::Memory, "Failed to create a video frame pool: {}", frame_pool_result.release_error());
- auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) WindowsMediaFoundationVideoDecoder(codec_id, move(transform), thread_data, frame_pool_result.release_value())));
+ auto decoder = DECODER_TRY_ALLOC(adopt_nonnull_own_or_enomem(new (nothrow) WindowsMediaFoundationVideoDecoder(codec_id, codec_initialization_data, move(transform), thread_data, frame_pool_result.release_value())));
TRY(decoder->apply_codec_configuration(codec_initialization_data));
// Some decoders refuse every output format until they have seen input, so this is retried when they ask.
(void)decoder->negotiate_output_format();
@@ -238,11 +239,12 @@ DecoderErrorOr<NonnullOwnPtr<WindowsMediaFoundationVideoDecoder>> WindowsMediaFo
return decoder;
}
-WindowsMediaFoundationVideoDecoder::WindowsMediaFoundationVideoDecoder(CodecID codec_id, NonnullOwnPtr<Transform> transform, NonnullRefPtr<ThreadData> thread_data, NonnullRefPtr<VideoFramePool> frame_pool)
+WindowsMediaFoundationVideoDecoder::WindowsMediaFoundationVideoDecoder(CodecID codec_id, ReadonlyBytes codec_initialization_data, NonnullOwnPtr<Transform> transform, NonnullRefPtr<ThreadData> thread_data, NonnullRefPtr<VideoFramePool> frame_pool)
: m_codec_id(codec_id)
, m_transform(move(transform))
, m_thread_data(move(thread_data))
, m_frame_pool(move(frame_pool))
+ , m_high_dynamic_range_metadata_tracker(codec_id, codec_initialization_data)
{
}
@@ -316,6 +318,7 @@ DecoderErrorOr<void> WindowsMediaFoundationVideoDecoder::receive_coded_data(Code
TRY(apply_codec_configuration(*configuration));
auto access_unit = TRY(annex_b_access_unit_for(coded_frame));
+ auto const& high_dynamic_range_metadata = m_high_dynamic_range_metadata_tracker.apply_coded_frame(coded_frame);
auto sample = TRY(create_input_sample(access_unit, coded_frame.presentation_timestamp(), coded_frame.duration()));
auto sample_time = sample_time_from_duration(coded_frame.presentation_timestamp());
@@ -324,7 +327,7 @@ DecoderErrorOr<void> WindowsMediaFoundationVideoDecoder::receive_coded_data(Code
if (m_next_input_is_discontinuous)
sample->SetUINT32(MFSampleExtension_Discontinuity, TRUE);
- auto submitted_frame = SubmittedFrame { sample_time, coded_frame.presentation_timestamp(), coded_frame.duration(), intent };
+ auto submitted_frame = SubmittedFrame { sample_time, coded_frame.presentation_timestamp(), coded_frame.duration(), intent, high_dynamic_range_metadata };
auto insertion_index = m_submitted_frames.size();
while (insertion_index > 0 && m_submitted_frames[insertion_index - 1].sample_time > sample_time)
insertion_index--;
@@ -444,6 +447,7 @@ DecoderErrorOr<void> WindowsMediaFoundationVideoDecoder::collect_available_outpu
decoded_output.format = m_transform->output_format;
decoded_output.timestamp = submitted_frame.timestamp;
decoded_output.duration = submitted_frame.duration;
+ decoded_output.high_dynamic_range_metadata = submitted_frame.high_dynamic_range_metadata;
m_thread_data->enqueue(move(decoded_output));
}
}
@@ -702,13 +706,16 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> WindowsMediaFoundationVideoDecoder::co
}
}
- return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timestamp, output.duration, format.aperture_size, format.bit_depth, subsampling, container_color_metadata, acquired_slot->storage));
+ auto color_metadata = container_color_metadata;
+ color_metadata.adopt_specified_values(output.high_dynamic_range_metadata);
+ return DECODER_TRY_ALLOC(try_make_ref_counted<VideoFrame>(output.timestamp, output.duration, format.aperture_size, format.bit_depth, subsampling, move(color_metadata), acquired_slot->storage));
}
void WindowsMediaFoundationVideoDecoder::flush()
{
m_transform->transform->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);
m_submitted_frames.clear();
+ m_high_dynamic_range_metadata_tracker.forget_stream();
m_draining = false;
m_drained = false;
m_next_input_is_discontinuous = true;
diff --git a/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.h b/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.h
index 3a3a7228ce3..f42f6f4287e 100644
--- a/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.h
+++ b/Libraries/LibMediaCodecs/WindowsMediaFoundation/WindowsMediaFoundationVideoDecoder.h
@@ -13,6 +13,7 @@
#include <AK/kmalloc.h>
#include <LibMediaCodecs/CodecID.h>
#include <LibMediaCodecs/CodecParameters.h>
+#include <LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h>
#include <LibMediaCodecs/DecoderCapabilities.h>
#include <LibMediaCodecs/Export.h>
#include <LibMediaCodecs/VideoDecoder.h>
@@ -53,9 +54,10 @@ private:
AK::Duration timestamp;
AK::Duration duration;
DecodeIntent intent { DecodeIntent::Output };
+ ColorMetadata high_dynamic_range_metadata {};
};
- WindowsMediaFoundationVideoDecoder(CodecID, NonnullOwnPtr<Transform>, NonnullRefPtr<ThreadData>, NonnullRefPtr<VideoFramePool>);
+ WindowsMediaFoundationVideoDecoder(CodecID, ReadonlyBytes codec_initialization_data, NonnullOwnPtr<Transform>, NonnullRefPtr<ThreadData>, NonnullRefPtr<VideoFramePool>);
DecoderErrorOr<void> apply_codec_configuration(ReadonlyBytes);
DecoderErrorOr<ByteBuffer> annex_b_access_unit_for(CodedFrame const&);
@@ -75,6 +77,7 @@ private:
u8 m_nal_unit_length_size { 4 };
// The transform never sees the configuration record, so its parameter sets are sent ahead of each keyframe.
ByteBuffer m_annex_b_parameter_sets;
+ Codecs::HighDynamicRangeMetadataTracker m_high_dynamic_range_metadata_tracker;
// Ordered by sample time, which is how the transform hands frames back.
Vector<SubmittedFrame> m_submitted_frames;
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index 7a87a71fd69..c4713a646a5 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -4,6 +4,7 @@ set(TEST_SOURCES
TestADTSDemuxer.cpp
TestADTSFrameHeader.cpp
TestADTSReader.cpp
+ TestAV1Decode.cpp
TestAudioBlockTimingRing.cpp
TestAudioDiscardIntervals.cpp
TestAudioMixer.cpp
@@ -61,7 +62,10 @@ if (WIN32)
)
endif()
if (LINUX)
- list(APPEND TEST_SOURCES TestH264Decode.cpp)
+ list(APPEND TEST_SOURCES
+ TestH264Decode.cpp
+ TestH265Decode.cpp
+ )
if (USE_VULKAN_DMABUF_IMAGES)
list(APPEND TEST_SOURCES TestFFmpegVulkanDecode.cpp)
endif()
diff --git a/Tests/LibMedia/TestAV1Decode.cpp b/Tests/LibMedia/TestAV1Decode.cpp
new file mode 100644
index 00000000000..e649b22488c
--- /dev/null
+++ b/Tests/LibMedia/TestAV1Decode.cpp
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibMedia/DemuxerRegistry.h>
+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>
+
+#include "TestMediaCommon.h"
+
+// The file's mastering display and content light levels are only in metadata OBUs, not in its Matroska Colour element.
+TEST_CASE(frames_carry_the_high_dynamic_range_metadata_in_their_bitstream)
+{
+ auto file = MUST(Core::File::open("./av1_hdr_metadata_in_webm.webm"sv, Core::File::OpenMode::Read));
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
+ auto demuxer = MUST(Media::create_demuxer(stream));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video));
+ VERIFY(track.has_value());
+ EXPECT(!track->video_data().color_metadata.mastering_display_color_volume.has_value());
+ EXPECT(!track->video_data().color_metadata.content_light_level_information.has_value());
+ MUST(demuxer->create_context_for_track(*track));
+
+ auto first_frame = MUST(demuxer->get_next_sample_for_track(*track));
+ auto decoder = MUST(Media::FFmpeg::FFmpegVideoDecoder::try_create(first_frame.codec_id(), first_frame.new_codec_configuration().value_or({})));
+ MUST(decoder->receive_coded_data(first_frame, Media::DecodeIntent::Output));
+ decoder->signal_end_of_stream();
+ auto frame = MUST(decoder->take_next_output({}));
+ auto const& color_metadata = frame->color_metadata();
+
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ if (color_metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_content_light_level, 1005);
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_frame_average_light_level, 315);
+ }
+
+ EXPECT(color_metadata.mastering_display_color_volume.has_value());
+ if (!color_metadata.mastering_display_color_volume.has_value())
+ return;
+ auto const& volume = *color_metadata.mastering_display_color_volume;
+ // AV1 codes chromaticities in units of 2^-16, and the minimum luminance in units of 2^-14 cd/m².
+ static constexpr double chromaticity_error = 1.0 / (1 << 16);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.red.x, 0.708, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.red.y, 0.292, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.green.x, 0.170, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.green.y, 0.797, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.blue.x, 0.131, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.blue.y, 0.046, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.white_point.x, 0.3127, chromaticity_error);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.white_point.y, 0.3290, chromaticity_error);
+ EXPECT_APPROXIMATE(volume.maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE_WITH_ERROR(volume.minimum_luminance, 0.005, 1.0 / (1 << 14));
+}
+
+TEST_CASE(a_flush_forgets_the_high_dynamic_range_metadata_of_earlier_frames)
+{
+ // clang-format off
+ auto metadata_obus = to_array<u8>({
+ 0x2a, 0x06, // metadata
+ 0x01, 0x03, 0xed, 0x01, 0x3b, // HDR_CLL: 1005 and 315
+ 0x80, // trailing bits
+ });
+ // clang-format on
+ auto temporal_delimiter = to_array<u8>({ 0x12, 0x00 });
+ auto coded_frame = [](ReadonlyBytes data, i64 milliseconds) {
+ auto timestamp = AK::Duration::from_milliseconds(milliseconds);
+ return Media::CodedFrame(Media::CodecID::AV1, timestamp, timestamp, AK::Duration::from_milliseconds(33), Media::FrameFlags::Keyframe, MUST(FixedArray<u8>::create(data)));
+ };
+
+ Media::FFmpeg::VideoFramesAwaitingOutput frames { Media::CodecID::AV1, {} };
+ auto key = MUST(frames.add(coded_frame(metadata_obus, 0), Media::DecodeIntent::Output));
+ EXPECT(frames.take(static_cast<i64>(key))->high_dynamic_range_metadata.content_light_level_information.has_value());
+
+ key = MUST(frames.add(coded_frame(temporal_delimiter, 33), Media::DecodeIntent::Output));
+ EXPECT(frames.take(static_cast<i64>(key))->high_dynamic_range_metadata.content_light_level_information.has_value());
+
+ frames.flush();
+ key = MUST(frames.add(coded_frame(temporal_delimiter, 0), Media::DecodeIntent::Output));
+ EXPECT(!frames.take(static_cast<i64>(key))->high_dynamic_range_metadata.content_light_level_information.has_value());
+}
diff --git a/Tests/LibMedia/TestBitReader.cpp b/Tests/LibMedia/TestBitReader.cpp
index 820a566ebb5..e336a88ca05 100644
--- a/Tests/LibMedia/TestBitReader.cpp
+++ b/Tests/LibMedia/TestBitReader.cpp
@@ -158,3 +158,17 @@ TEST_CASE(leb128_stops_after_its_final_byte)
EXPECT_EQ(reader.read_leb128(), 1u);
EXPECT_EQ(reader.bit_position(), 8u);
}
+
+TEST_CASE(leb128_whose_last_possible_byte_says_another_follows_is_malformed)
+{
+ Array<u8, 8> unterminated { 0x86, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 };
+ Media::BitReader reader { unterminated };
+ EXPECT_EQ(reader.read_leb128(), 0u);
+ EXPECT(reader.has_overrun());
+
+ // The same value spread over all eight bytes, with the last one ending it, is still valid.
+ Array<u8, 8> padded { 0x86, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00 };
+ Media::BitReader padded_reader { padded };
+ EXPECT_EQ(padded_reader.read_leb128(), 6u);
+ EXPECT(!padded_reader.has_overrun());
+}
diff --git a/Tests/LibMedia/TestCodecConfigurations.cpp b/Tests/LibMedia/TestCodecConfigurations.cpp
index b6a8f655002..1c294b21c1f 100644
--- a/Tests/LibMedia/TestCodecConfigurations.cpp
+++ b/Tests/LibMedia/TestCodecConfigurations.cpp
@@ -10,13 +10,18 @@
#include <LibMediaCodecs/CodecParameters.h>
#include <LibMediaCodecs/Codecs/AAC.h>
#include <LibMediaCodecs/Codecs/AV1.h>
+#include <LibMediaCodecs/Codecs/DolbyVision.h>
#include <LibMediaCodecs/Codecs/H264.h>
#include <LibMediaCodecs/Codecs/H265.h>
+#include <LibMediaCodecs/Codecs/HDR10Plus.h>
+#include <LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h>
#include <LibMediaCodecs/Codecs/NALUnit.h>
#include <LibMediaCodecs/Codecs/VP9.h>
#include <LibMediaCodecs/Limits.h>
#include <LibTest/TestCase.h>
+#include "TestMediaCommon.h"
+
TEST_CASE(opus_isobmff_configuration_is_normalized_to_opus_head)
{
Array<u8, 15> configuration {
@@ -1257,3 +1262,608 @@ TEST_CASE(aac_configuration_record_refuses_sample_rates_outside_the_supported_ra
EXPECT_EQ(create(Media::MAX_AUDIO_SAMPLE_RATE / 2, Media::MAX_AUDIO_SAMPLE_RATE + 2).error().category(), Media::DecoderErrorCategory::NotImplemented);
EXPECT_EQ(create(Media::MIN_AUDIO_SAMPLE_RATE - 1, (Media::MIN_AUDIO_SAMPLE_RATE - 1) * 2).error().category(), Media::DecoderErrorCategory::NotImplemented);
}
+
+// G(13250, 34500) B(7500, 3000) R(34000, 16000) WP(15635, 16450) L(10000000, 50), as x265 is given them.
+static void expect_h26x_mastering_display_color_volume(Media::ColorMetadata const& metadata)
+{
+ EXPECT(metadata.mastering_display_color_volume.has_value());
+ if (metadata.mastering_display_color_volume.has_value()) {
+ auto const& volume = metadata.mastering_display_color_volume.value();
+ EXPECT_APPROXIMATE(volume.green.x, 0.265);
+ EXPECT_APPROXIMATE(volume.green.y, 0.69);
+ EXPECT_APPROXIMATE(volume.blue.x, 0.15);
+ EXPECT_APPROXIMATE(volume.blue.y, 0.06);
+ EXPECT_APPROXIMATE(volume.red.x, 0.68);
+ EXPECT_APPROXIMATE(volume.red.y, 0.32);
+ EXPECT_APPROXIMATE(volume.white_point.x, 0.3127);
+ EXPECT_APPROXIMATE(volume.white_point.y, 0.329);
+ EXPECT_APPROXIMATE(volume.maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE(volume.minimum_luminance, 0.005);
+ }
+}
+
+TEST_CASE(h265_prefix_sei_gives_the_mastering_display_and_content_light_levels)
+{
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x4e, 0x01, // prefix SEI, layer 0
+ 0x05, 0x02, 0xaa, 0xbb, // an unregistered user data message, which is skipped
+ 0x89, 0x18, // mastering display colour volume
+ 0x33, 0xc2, 0x86, 0xc4, 0x1d, 0x4c, 0x0b, 0xb8, 0x84, 0xd0, 0x3e, 0x80,
+ 0x3d, 0x13, 0x40, 0x42,
+ 0x00, 0x98, 0x96, 0x80,
+ 0x00, 0x00, 0x03, 0x00, 0x32, // an emulation prevention byte follows the two zero bytes
+ 0x90, 0x04, // content light level information
+ 0x03, 0xe8, 0x01, 0x90,
+ 0x80, // RBSP trailing bits
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ expect_h26x_mastering_display_color_volume(metadata);
+ EXPECT(metadata.content_light_level_information.has_value());
+ if (metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(metadata.content_light_level_information->maximum_content_light_level, 1000);
+ EXPECT_EQ(metadata.content_light_level_information->maximum_frame_average_light_level, 400);
+ }
+}
+
+TEST_CASE(h265_sei_message_running_past_its_nal_unit_is_ignored)
+{
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x4e, 0x01,
+ 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, // a complete content light level message
+ 0x89, 0x18, 0x33, 0xc2, // a mastering display colour volume with only one of its fields
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.mastering_display_color_volume.has_value());
+ EXPECT(metadata.content_light_level_information.has_value());
+ if (metadata.content_light_level_information.has_value())
+ EXPECT_EQ(metadata.content_light_level_information->maximum_content_light_level, 1000);
+}
+
+TEST_CASE(h265_sei_mastering_display_with_an_unspecified_peak_is_left_out)
+{
+ // A maximum luminance code of 200,000,000 is outside the range H.265 gives meaning to.
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x4e, 0x01,
+ 0x89, 0x18,
+ 0x33, 0xc2, 0x86, 0xc4, 0x1d, 0x4c, 0x0b, 0xb8, 0x84, 0xd0, 0x3e, 0x80, 0x3d, 0x13, 0x40, 0x42,
+ 0x0b, 0xeb, 0xc2, 0x00,
+ 0x00, 0x03, 0x00, 0x00, 0x32,
+ 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90,
+ 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.mastering_display_color_volume.has_value());
+ EXPECT(metadata.content_light_level_information.has_value());
+}
+
+TEST_CASE(h265_sei_mastering_display_with_a_zero_minimum_is_kept)
+{
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x4e, 0x01,
+ 0x89, 0x18,
+ 0x33, 0xc2, 0x86, 0xc4, 0x1d, 0x4c, 0x0b, 0xb8, 0x84, 0xd0, 0x3e, 0x80, 0x3d, 0x13, 0x40, 0x42,
+ 0x00, 0x98, 0x96, 0x80,
+ 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90,
+ 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(metadata.mastering_display_color_volume.has_value());
+ if (metadata.mastering_display_color_volume.has_value()) {
+ EXPECT_APPROXIMATE(metadata.mastering_display_color_volume->maximum_luminance, 1000.0);
+ EXPECT_EQ(metadata.mastering_display_color_volume->minimum_luminance, 0.0f);
+ }
+}
+
+TEST_CASE(h265_sei_message_whose_size_overflows_is_ignored)
+{
+ // Without its overflow being caught, a size of 16,843,009 0xFF bytes and a 0x05 adds up to 4.
+ ByteBuffer nal_unit;
+ nal_unit.append(0x4e);
+ nal_unit.append(0x01);
+ nal_unit.append(0x90);
+ MUST(nal_unit.try_resize(nal_unit.size() + 16'843'009));
+ nal_unit.bytes().slice(3).fill(0xff);
+ for (u8 byte : { 0x05, 0x03, 0xe8, 0x01, 0x90, 0x80 })
+ nal_unit.append(byte);
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.content_light_level_information.has_value());
+}
+
+TEST_CASE(h264_nal_unit_with_the_forbidden_zero_bit_set_gives_nothing)
+{
+ auto nal_unit = to_array<u8>({ 0x86, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80 });
+ EXPECT(!Media::Codecs::H264::high_dynamic_range_metadata_of_nal_unit(nal_unit).content_light_level_information.has_value());
+}
+
+TEST_CASE(h265_sei_message_running_into_the_trailing_bits_is_ignored)
+{
+ // A content light level message missing its last byte, which the RBSP stop byte would otherwise complete.
+ auto nal_unit = to_array<u8>({ 0x4e, 0x01, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x80 });
+ EXPECT(!Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit).content_light_level_information.has_value());
+}
+
+TEST_CASE(h265_nal_units_other_than_base_layer_prefix_sei_give_nothing)
+{
+ // A suffix SEI, a prefix SEI in layer 1 and a sequence parameter set, each followed by a content light level.
+ // clang-format off
+ Array<Array<u8, 9>, 3> nal_units { {
+ { 0x50, 0x01, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80 },
+ { 0x4e, 0x09, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80 },
+ { 0x42, 0x01, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80 },
+ } };
+ // clang-format on
+
+ for (auto const& nal_unit : nal_units) {
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.content_light_level_information.has_value());
+ }
+}
+
+TEST_CASE(h264_sei_gives_the_mastering_display_and_content_light_levels)
+{
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x06, // SEI
+ 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90,
+ 0x89, 0x18,
+ 0x33, 0xc2, 0x86, 0xc4, 0x1d, 0x4c, 0x0b, 0xb8, 0x84, 0xd0, 0x3e, 0x80,
+ 0x3d, 0x13, 0x40, 0x42,
+ 0x00, 0x98, 0x96, 0x80,
+ 0x00, 0x00, 0x03, 0x00, 0x32,
+ 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H264::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ expect_h26x_mastering_display_color_volume(metadata);
+ EXPECT(metadata.content_light_level_information.has_value());
+ if (metadata.content_light_level_information.has_value())
+ EXPECT_EQ(metadata.content_light_level_information->maximum_frame_average_light_level, 400);
+}
+
+TEST_CASE(av1_metadata_obus_give_the_mastering_display_and_content_light_levels)
+{
+ // clang-format off
+ auto obus = to_array<u8>({
+ 0x12, 0x00, // a temporal delimiter, which is skipped
+ 0x2a, 0x06, // metadata
+ 0x01, 0x03, 0xed, 0x01, 0x3b, // HDR_CLL: 1005 and 315
+ 0x80, // trailing bits
+ 0x2a, 0x1a, // metadata
+ 0x02, // HDR_MDCV
+ 0xb5, 0x40, 0x4a, 0xc0, // red (46400, 19136)
+ 0x2b, 0x85, 0xcc, 0x08, // green (11141, 52232)
+ 0x21, 0x8a, 0x0b, 0xc7, // blue (8586, 3015)
+ 0x50, 0x0d, 0x54, 0x39, // white point (20493, 21561)
+ 0x00, 0x03, 0xe8, 0x00, // 1000 cd/m² in 24.8
+ 0x00, 0x00, 0x00, 0x52, // 82 / 2^14 cd/m² in 18.14
+ 0x80, // trailing bits
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::AV1::high_dynamic_range_metadata_of_obus(obus);
+ EXPECT(metadata.content_light_level_information.has_value());
+ if (metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(metadata.content_light_level_information->maximum_content_light_level, 1005);
+ EXPECT_EQ(metadata.content_light_level_information->maximum_frame_average_light_level, 315);
+ }
+
+ EXPECT(metadata.mastering_display_color_volume.has_value());
+ if (metadata.mastering_display_color_volume.has_value()) {
+ auto const& volume = metadata.mastering_display_color_volume.value();
+ EXPECT_APPROXIMATE(volume.red.x, 46400 / 65536.0);
+ EXPECT_APPROXIMATE(volume.red.y, 19136 / 65536.0);
+ EXPECT_APPROXIMATE(volume.green.x, 11141 / 65536.0);
+ EXPECT_APPROXIMATE(volume.green.y, 52232 / 65536.0);
+ EXPECT_APPROXIMATE(volume.blue.x, 8586 / 65536.0);
+ EXPECT_APPROXIMATE(volume.blue.y, 3015 / 65536.0);
+ EXPECT_APPROXIMATE(volume.white_point.x, 20493 / 65536.0);
+ EXPECT_APPROXIMATE(volume.white_point.y, 21561 / 65536.0);
+ EXPECT_APPROXIMATE(volume.maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE(volume.minimum_luminance, 82 / 16384.0);
+ }
+}
+
+TEST_CASE(av1_metadata_obu_running_into_its_trailing_bits_is_ignored)
+{
+ // An HDR_CLL missing its last byte, which the trailing bits would otherwise complete.
+ auto obus = to_array<u8>({ 0x2a, 0x05, 0x01, 0x03, 0xed, 0x01, 0x80 });
+ EXPECT(!Media::Codecs::AV1::high_dynamic_range_metadata_of_obus(obus).content_light_level_information.has_value());
+}
+
+TEST_CASE(av1_obus_after_a_malformed_one_are_not_read)
+{
+ // clang-format off
+ auto obus = to_array<u8>({
+ 0x2a, 0x10, 0x01, // metadata claiming more payload than there is
+ 0x2a, 0x06, 0x01, 0x03, 0xed, 0x01, 0x3b, 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::AV1::high_dynamic_range_metadata_of_obus(obus);
+ EXPECT(!metadata.content_light_level_information.has_value());
+}
+
+// One processing window whose maxscl is (1294, 3641, 1064), in units of 0.00001 of 10000 cd/m².
+// clang-format off
+static constexpr auto hdr10_plus_with_one_window = to_array<u8>({
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0x40, 0x00, 0x0c, 0x80, 0x0a, 0x1c, 0x0e, 0x39, 0x02,
+ 0x14, 0x01, 0x0a, 0x04, 0x08, 0x01, 0x90, 0x00, 0x00,
+});
+// clang-format on
+
+TEST_CASE(hdr10_plus_gives_the_brightest_component_of_the_first_window)
+{
+ auto luminance = Media::Codecs::hdr10_plus_maximum_scene_luminance(hdr10_plus_with_one_window);
+ EXPECT(luminance.has_value());
+ if (luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(luminance.value(), 364.1, 0.01);
+}
+
+TEST_CASE(hdr10_plus_skips_further_windows_and_the_actual_peak_luminances)
+{
+ // Three windows, the later two with a maxscl of 99999, and a three by two actual peak luminance matrix.
+ // clang-format off
+ auto message = to_array<u8>({
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0xc4, 0x8d, 0x04, 0x8d, 0x04, 0x8d, 0x04, 0x8d, 0x04,
+ 0x8d, 0x04, 0x8d, 0x15, 0x9e, 0x26, 0x9e, 0x26, 0x9e, 0x26, 0xa2, 0x46, 0x82, 0x46, 0x82, 0x46,
+ 0x82, 0x46, 0x82, 0x46, 0x82, 0x46, 0x8a, 0xcf, 0x13, 0x4f, 0x13, 0x4f, 0x13, 0x50, 0x00, 0x03,
+ 0x21, 0x18, 0x80, 0x48, 0xd1, 0x40, 0xa1, 0xc0, 0xe3, 0x90, 0x21, 0x40, 0x10, 0xa0, 0x40, 0x80,
+ 0x19, 0x00, 0x0c, 0x34, 0xfe, 0x1a, 0x7f, 0x0d, 0x3f, 0x86, 0x9f, 0x10, 0x20, 0x06, 0x40, 0x03,
+ 0x0d, 0x3f, 0x86, 0x9f, 0xc3, 0x4f, 0xe1, 0xa7, 0xc4, 0x08, 0x01, 0x90, 0x00, 0x00,
+ });
+ // clang-format on
+
+ auto luminance = Media::Codecs::hdr10_plus_maximum_scene_luminance(message);
+ EXPECT(luminance.has_value());
+ if (luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(luminance.value(), 364.1, 0.01);
+}
+
+TEST_CASE(hdr10_plus_rejects_other_messages_and_unknown_versions)
+{
+ auto other_provider = hdr10_plus_with_one_window;
+ other_provider[2] = 0x90;
+ EXPECT(!Media::Codecs::hdr10_plus_maximum_scene_luminance(other_provider).has_value());
+
+ auto later_version = hdr10_plus_with_one_window;
+ later_version[6] = 0x02;
+ EXPECT(!Media::Codecs::hdr10_plus_maximum_scene_luminance(later_version).has_value());
+
+ auto truncated = ReadonlyBytes { hdr10_plus_with_one_window }.trim(12);
+ EXPECT(!Media::Codecs::hdr10_plus_maximum_scene_luminance(truncated).has_value());
+}
+
+TEST_CASE(hdr10_plus_maxscl_beyond_its_range_gives_nothing)
+{
+ // A maxscl of 120,000 fits the 17-bit field, but HDR10+ only gives meaning to values up to 100,000.
+ // clang-format off
+ auto message = to_array<u8>({
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0x40, 0x00, 0x0c, 0x83, 0xa9, 0x80, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x04, 0x08, 0x01, 0x90, 0x00, 0x00,
+ });
+ // clang-format on
+
+ EXPECT(!Media::Codecs::hdr10_plus_maximum_scene_luminance(message).has_value());
+}
+
+TEST_CASE(hdr10_plus_with_an_unknown_peak_gives_nothing)
+{
+ // clang-format off
+ auto message = to_array<u8>({
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0x40, 0x00, 0x0c, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x04, 0x08, 0x01, 0x90, 0x00, 0x00,
+ });
+ // clang-format on
+
+ EXPECT(!Media::Codecs::hdr10_plus_maximum_scene_luminance(message).has_value());
+}
+
+TEST_CASE(h265_prefix_sei_gives_the_hdr10_plus_scene_peak)
+{
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x4e, 0x01, // prefix SEI, layer 0
+ 0x04, 0x19, // user data registered by ITU-T T.35
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0x40, 0x00, 0x0c, 0x80, 0x0a, 0x1c, 0x0e, 0x39, 0x02,
+ 0x14, 0x01, 0x0a, 0x04, 0x08, 0x01, 0x90, 0x00, 0x00,
+ 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, // content light level information
+ 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(metadata.maximum_scene_luminance.has_value());
+ if (metadata.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(metadata.maximum_scene_luminance.value(), 364.1, 0.01);
+ EXPECT(metadata.content_light_level_information.has_value());
+}
+
+TEST_CASE(h265_sei_itu_t_t35_message_too_large_to_be_hdr10_plus_is_skipped)
+{
+ // HDR10+ that would still read as such with the padding after it, then a content light level.
+ ByteBuffer message;
+ message.append(hdr10_plus_with_one_window.span());
+ while (message.size() <= Media::Codecs::HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE)
+ message.append(0x11);
+
+ ByteBuffer nal_unit;
+ for (u8 byte : { 0x4e, 0x01, 0x04 })
+ nal_unit.append(byte);
+ for (auto size = message.size(); true; size -= 0xff) {
+ nal_unit.append(static_cast<u8>(min<size_t>(size, 0xff)));
+ if (size < 0xff)
+ break;
+ }
+ nal_unit.append(message);
+ for (u8 byte : { 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80 })
+ nal_unit.append(byte);
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.maximum_scene_luminance.has_value());
+ EXPECT(metadata.content_light_level_information.has_value());
+}
+
+TEST_CASE(av1_metadata_obu_gives_the_hdr10_plus_scene_peak)
+{
+ // clang-format off
+ auto obus = to_array<u8>({
+ 0x2a, 0x1b, // metadata
+ 0x04, // ITUT_T35
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0x40, 0x00, 0x0c, 0x80, 0x0a, 0x1c, 0x0e, 0x39, 0x02,
+ 0x14, 0x01, 0x0a, 0x04, 0x08, 0x01, 0x90, 0x00, 0x00,
+ 0x80, // trailing bits
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::AV1::high_dynamic_range_metadata_of_obus(obus);
+ EXPECT(metadata.maximum_scene_luminance.has_value());
+ if (metadata.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(metadata.maximum_scene_luminance.value(), 364.1, 0.01);
+}
+
+TEST_CASE(h265_prefix_sei_hdr10_plus_drops_its_emulation_prevention_bytes)
+{
+ // The maxscl (0, 0, 3641) codes two zero bytes followed by a byte below 4, so an emulation prevention byte splits it.
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x4e, 0x01,
+ 0x04, 0x19,
+ 0xb5, 0x00, 0x3c, 0x00, 0x01, 0x04, 0x01, 0x40, 0x00, 0x0c, 0x80, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x07, 0x1c, 0x80, 0x00, 0x04, 0x08, 0x01, 0x90, 0x00, 0x00,
+ 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(metadata.maximum_scene_luminance.has_value());
+ if (metadata.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(metadata.maximum_scene_luminance.value(), 364.1, 0.01);
+
+ // Read with the emulation prevention byte left in, the same message gives another peak.
+ auto escaped_message = Media::Codecs::hdr10_plus_maximum_scene_luminance(ReadonlyBytes { nal_unit }.slice(4, 26));
+ EXPECT(!escaped_message.has_value() || fabsf(escaped_message.value() - 364.1f) > 0.01f);
+}
+
+// These are the first two RPUs of Chromium's glass-blowing2-dolby-vision-profile-8-1-frag.mp4, whose level 1 maximums
+// FFmpeg reads as 3615 and 3687.
+TEST_CASE(h265_dolby_vision_nal_unit_gives_the_level_1_scene_peak)
+{
+ // clang-format off
+ auto first_nal_unit = to_array<u8>({
+ 0x7c, 0x01, 0x19, 0x08, 0x09, 0x08, 0x40, 0x61, 0x36, 0x50, 0x6f, 0x00, 0x3f, 0xf8, 0x01, 0xff,
+ 0xc0, 0x0f, 0xff, 0xd0, 0x00, 0x00, 0x08, 0x00, 0x00, 0x06, 0x80, 0x00, 0x00, 0x40, 0x00, 0x00,
+ 0x34, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x03, 0x01, 0xc9, 0x59, 0x80, 0x00, 0x0d, 0x7a, 0x89,
+ 0x59, 0xbe, 0x7f, 0x3a, 0xc7, 0x09, 0x59, 0x91, 0x32, 0x80, 0x00, 0x00, 0x40, 0x00, 0x00, 0x03,
+ 0x02, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x07, 0x0d, 0x88, 0x90, 0xc0, 0x61,
+ 0x82, 0x97, 0x8c, 0x23, 0x81, 0x45, 0x00, 0x00, 0x03, 0x00, 0x69, 0x8f, 0x96, 0xbf, 0xff, 0xc0,
+ 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x18, 0x08, 0x1f, 0x73, 0x80, 0x54,
+ 0x60, 0x30, 0x08, 0x01, 0x70, 0xfa, 0xf6, 0x00, 0xc0, 0x28, 0x21, 0x80, 0x08, 0x00, 0x80, 0x06,
+ 0x06, 0x80, 0x01, 0x00, 0x02, 0x02, 0x28, 0x39, 0x1e, 0x88, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x03, 0x00, 0x00, 0x03, 0x00, 0x12, 0x0c, 0x1f, 0x40, 0x00, 0x64, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x59, 0xfc, 0x25, 0x44, 0x80,
+ });
+ auto second_nal_unit = to_array<u8>({
+ 0x7c, 0x01, 0x19, 0x08, 0x09, 0x08, 0x40, 0x61, 0x36, 0x50, 0x6f, 0x00, 0x3f, 0xf8, 0x01, 0xff,
+ 0xc0, 0x0f, 0xff, 0xd0, 0x00, 0x00, 0x08, 0x00, 0x00, 0x06, 0x80, 0x00, 0x00, 0x40, 0x00, 0x00,
+ 0x34, 0x00, 0x00, 0x03, 0x02, 0x00, 0x00, 0x03, 0x01, 0xc9, 0x59, 0x80, 0x00, 0x0d, 0x7a, 0x89,
+ 0x59, 0xbe, 0x7f, 0x3a, 0xc7, 0x09, 0x59, 0x91, 0x32, 0x80, 0x00, 0x00, 0x40, 0x00, 0x00, 0x03,
+ 0x02, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x07, 0x0d, 0x88, 0x90, 0xc0, 0x61,
+ 0x82, 0x97, 0x8c, 0x23, 0x81, 0x45, 0x00, 0x00, 0x03, 0x00, 0x69, 0x8f, 0x96, 0xbf, 0xff, 0xc0,
+ 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, 0x00, 0x18, 0x08, 0x1f, 0x73, 0x80, 0x54,
+ 0x60, 0x30, 0x08, 0x01, 0x73, 0x3b, 0x18, 0x00, 0xc0, 0x28, 0x21, 0x80, 0x08, 0x00, 0x80, 0x06,
+ 0xa2, 0x6c, 0xb1, 0x00, 0x02, 0x02, 0x30, 0xb9, 0xd9, 0x88, 0x05, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x03, 0x00, 0x00, 0x03, 0x00, 0x12, 0x0c, 0x1f, 0x40, 0x00, 0x64, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x4b, 0xf6, 0x1b, 0xb2, 0x80,
+ });
+ // clang-format on
+
+ auto first = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(first_nal_unit);
+ EXPECT(first.maximum_scene_luminance.has_value());
+ if (first.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(first.maximum_scene_luminance.value(), 3330.0, 0.5);
+ auto second = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(second_nal_unit);
+ EXPECT(second.maximum_scene_luminance.has_value());
+ if (second.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(second.maximum_scene_luminance.value(), 3918.9, 0.5);
+}
+
+TEST_CASE(h265_dolby_vision_nal_unit_reusing_a_mapping_gives_the_level_1_scene_peak)
+{
+ // An RPU that reuses an earlier one's mapping and leaves out the colour transform, with a level 1 maximum of 2851.
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x7c, 0x01, 0x19, 0x08, 0x09, 0x08, 0x40, 0x61, 0x36, 0xc5, 0xfa, 0x60, 0x18, 0x05, 0x04, 0x30,
+ 0x43, 0x04, 0x30, 0x43, 0x04, 0x30, 0x42, 0xff, 0xf0, 0x60, 0x10, 0x0c, 0xb2, 0x33, 0x33, 0x00,
+ 0x83, 0xd7, 0xab, 0x17, 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(metadata.maximum_scene_luminance.has_value());
+ if (metadata.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(metadata.maximum_scene_luminance.value(), 599.56, 0.5);
+}
+
+TEST_CASE(h265_dolby_vision_nal_unit_with_a_zero_level_1_maximum_gives_nothing)
+{
+ // The RPU above, with its level 1 maximum cleared.
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x7c, 0x01, 0x19, 0x08, 0x09, 0x08, 0x40, 0x61, 0x36, 0xc5, 0xfa, 0x60, 0x18, 0x05, 0x04, 0x30,
+ 0x43, 0x04, 0x30, 0x43, 0x04, 0x30, 0x42, 0xff, 0xf0, 0x60, 0x10, 0x0c, 0x00, 0x03, 0x33, 0x00,
+ 0x83, 0xd7, 0xab, 0x17, 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.maximum_scene_luminance.has_value());
+}
+
+TEST_CASE(h265_dolby_vision_level_1_block_shorter_than_its_fields_gives_nothing)
+{
+ // The RPU's level 1 block declares two bytes, which cannot hold its three 12-bit fields.
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x7c, 0x01, 0x19, 0x08, 0x09, 0x08, 0x40, 0x61, 0x36, 0xc5, 0xfa, 0x60, 0x18, 0x05, 0x04, 0x30,
+ 0x43, 0x04, 0x30, 0x43, 0x04, 0x30, 0x42, 0xff, 0xf0, 0xc0, 0x40, 0x32, 0xb4, 0xcc, 0xcc, 0x00,
+ 0x4a, 0x2b, 0x73, 0x8c, 0x80,
+ });
+ // clang-format on
+
+ EXPECT(!Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit).maximum_scene_luminance.has_value());
+}
+
+TEST_CASE(h265_dolby_vision_nal_unit_without_display_management_gives_nothing)
+{
+ // clang-format off
+ auto nal_unit = to_array<u8>({
+ 0x7c, 0x01, 0x19, 0x08, 0x09, 0x08, 0x40, 0x61, 0x36, 0xc1, 0x3c, 0x00, 0xff, 0xe0, 0x07, 0xff,
+ 0x00, 0x3f, 0xff, 0x40, 0x00, 0x00, 0x20, 0x00, 0x00, 0x1a, 0x00, 0x00, 0x03, 0x01, 0x00, 0x00,
+ 0x03, 0x00, 0xd0, 0x00, 0x00, 0x08, 0x00, 0x00, 0x03, 0x00, 0x0f, 0x3e, 0x9d, 0x3e, 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(nal_unit);
+ EXPECT(!metadata.maximum_scene_luminance.has_value());
+}
+
+TEST_CASE(av1_metadata_obu_gives_the_dolby_vision_scene_peak)
+{
+ // An ITU-T T.35 metadata OBU holding an EMDF-wrapped RPU with a level 1 maximum of 2081.
+ // clang-format off
+ auto obus = to_array<u8>({
+ 0x2a, 0x98, 0x01, 0x04, 0xb5, 0x00, 0x3b, 0x00, 0x00, 0x08, 0x00, 0x37, 0xcd, 0x08, 0x31, 0x00,
+ 0x80, 0x90, 0x84, 0x06, 0x13, 0x6c, 0x1b, 0xc0, 0x0f, 0xfe, 0x00, 0x7f, 0xf0, 0x03, 0xff, 0xf4,
+ 0x00, 0x00, 0x02, 0x00, 0x00, 0x01, 0xa0, 0x00, 0x00, 0x10, 0x00, 0x00, 0x0d, 0x00, 0x00, 0x00,
+ 0x80, 0x00, 0x00, 0x68, 0x95, 0x98, 0x00, 0x00, 0xd7, 0xa8, 0x95, 0x9b, 0xe7, 0xf3, 0xac, 0x70,
+ 0x95, 0x99, 0x13, 0x28, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x20, 0x00,
+ 0x00, 0x00, 0x70, 0xd8, 0x89, 0x0c, 0x06, 0x18, 0x29, 0x78, 0xc2, 0x38, 0x14, 0x50, 0x00, 0x00,
+ 0x06, 0x98, 0xf9, 0x6b, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x01,
+ 0xf7, 0x38, 0x05, 0x44, 0x01, 0x80, 0x50, 0x43, 0x04, 0x30, 0x43, 0x04, 0x30, 0x43, 0x04, 0x2f,
+ 0xff, 0x06, 0x01, 0x00, 0xc8, 0x21, 0x33, 0x30, 0x12, 0x0c, 0x07, 0xd0, 0x00, 0x02, 0x00, 0x00,
+ 0x00, 0x00, 0x03, 0x14, 0xde, 0x09, 0xe8, 0x00, 0x20, 0x00, 0x80,
+ });
+ // clang-format on
+
+ auto metadata = Media::Codecs::AV1::high_dynamic_range_metadata_of_obus(obus);
+ EXPECT(metadata.maximum_scene_luminance.has_value());
+ if (metadata.maximum_scene_luminance.has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(metadata.maximum_scene_luminance.value(), 100.1, 0.5);
+}
+
+TEST_CASE(h265_dolby_vision_rpus_of_every_kind_give_their_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_dolby_vision_rpus_scene_peaks };
+ auto file = MUST(Core::File::open("./hevc_dolby_vision_rpus.mkv"sv, Core::File::OpenMode::Read));
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
+ auto demuxer = MUST(Media::create_demuxer(stream));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();
+ MUST(demuxer->create_context_for_track(track));
+
+ u8 nal_unit_length_size = 4;
+ size_t sample_count = 0;
+ while (true) {
+ auto sample_result = demuxer->get_next_sample_for_track(track);
+ if (sample_result.is_error()) {
+ EXPECT_EQ(sample_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ auto const& sample = sample_result.value();
+ if (auto configuration = sample.new_codec_configuration(); configuration.has_value())
+ nal_unit_length_size = Media::Codecs::H265::parse_parameter_sets_from_configuration_record(*configuration).value().nal_unit_length_size;
+
+ Media::ColorMetadata metadata;
+ Media::Codecs::NALUnitIterator iterator { sample.data(), nal_unit_length_size };
+ for (auto nal_unit = iterator.next(); nal_unit.has_value(); nal_unit = iterator.next())
+ metadata.adopt_specified_values(Media::Codecs::H265::high_dynamic_range_metadata_of_nal_unit(*nal_unit));
+ scene_peaks.check(sample.presentation_timestamp(), metadata.maximum_scene_luminance);
+ sample_count++;
+ }
+ EXPECT_EQ(sample_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
+
+// Length-prefixed H.265 NAL units: content light level SEIs, slices of IDR, trailing and CRA pictures, and an end of
+// sequence.
+// clang-format off
+constexpr auto h265_content_light_level_sei = to_array<u8>({ 0x00, 0x00, 0x00, 0x09, 0x4e, 0x01, 0x90, 0x04, 0x03, 0xe8, 0x01, 0x90, 0x80 });
+constexpr auto h265_unknown_peak_content_light_level_sei = to_array<u8>({ 0x00, 0x00, 0x00, 0x0a, 0x4e, 0x01, 0x90, 0x04, 0x00, 0x00, 0x03, 0x00, 0xc8, 0x80 });
+constexpr auto h265_idr_slice = to_array<u8>({ 0x00, 0x00, 0x00, 0x03, 0x26, 0x01, 0xaf });
+constexpr auto h265_trailing_slice = to_array<u8>({ 0x00, 0x00, 0x00, 0x03, 0x02, 0x01, 0xaf });
+constexpr auto h265_clean_random_access_slice = to_array<u8>({ 0x00, 0x00, 0x00, 0x03, 0x2a, 0x01, 0xaf });
+constexpr auto h265_end_of_sequence = to_array<u8>({ 0x00, 0x00, 0x00, 0x02, 0x48, 0x01 });
+// clang-format on
+
+static Media::CodedFrame h265_coded_frame(Vector<ReadonlyBytes> nal_units, i64 milliseconds)
+{
+ ByteBuffer data;
+ for (auto nal_unit : nal_units)
+ data.append(nal_unit);
+ auto timestamp = AK::Duration::from_milliseconds(milliseconds);
+ return Media::CodedFrame(Media::CodecID::H265, timestamp, timestamp, AK::Duration::from_milliseconds(33), Media::FrameFlags::Keyframe, MUST(FixedArray<u8>::create(data.bytes())));
+}
+
+TEST_CASE(h265_static_metadata_ends_with_its_coded_video_sequence)
+{
+ Media::Codecs::HighDynamicRangeMetadataTracker tracker { Media::CodecID::H265, {} };
+ EXPECT(tracker.apply_coded_frame(h265_coded_frame({ h265_content_light_level_sei, h265_idr_slice }, 0)).content_light_level_information.has_value());
+ EXPECT(tracker.apply_coded_frame(h265_coded_frame({ h265_trailing_slice }, 33)).content_light_level_information.has_value());
+ EXPECT(!tracker.apply_coded_frame(h265_coded_frame({ h265_idr_slice }, 67)).content_light_level_information.has_value());
+}
+
+TEST_CASE(h265_static_metadata_ends_at_an_end_of_sequence)
+{
+ Media::Codecs::HighDynamicRangeMetadataTracker tracker { Media::CodecID::H265, {} };
+ EXPECT(tracker.apply_coded_frame(h265_coded_frame({ h265_content_light_level_sei, h265_idr_slice }, 0)).content_light_level_information.has_value());
+ // A CRA picture alone may be in the middle of a coded video sequence.
+ EXPECT(tracker.apply_coded_frame(h265_coded_frame({ h265_clean_random_access_slice }, 33)).content_light_level_information.has_value());
+ EXPECT(tracker.apply_coded_frame(h265_coded_frame({ h265_trailing_slice, h265_end_of_sequence }, 67)).content_light_level_information.has_value());
+ EXPECT(!tracker.apply_coded_frame(h265_coded_frame({ h265_clean_random_access_slice }, 100)).content_light_level_information.has_value());
+}
+
+TEST_CASE(h265_content_light_level_message_replaces_the_previous_one)
+{
+ Media::Codecs::HighDynamicRangeMetadataTracker tracker { Media::CodecID::H265, {} };
+ tracker.apply_coded_frame(h265_coded_frame({ h265_content_light_level_sei, h265_idr_slice }, 0));
+ auto const& metadata = tracker.apply_coded_frame(h265_coded_frame({ h265_unknown_peak_content_light_level_sei, h265_idr_slice }, 33));
+ EXPECT(metadata.content_light_level_information.has_value());
+ if (metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(metadata.content_light_level_information->maximum_content_light_level, 0);
+ EXPECT_EQ(metadata.content_light_level_information->maximum_frame_average_light_level, 200);
+ }
+}
diff --git a/Tests/LibMedia/TestFFmpegVulkanDecode.cpp b/Tests/LibMedia/TestFFmpegVulkanDecode.cpp
index 2ec440f730c..6ff90ef0c11 100644
--- a/Tests/LibMedia/TestFFmpegVulkanDecode.cpp
+++ b/Tests/LibMedia/TestFFmpegVulkanDecode.cpp
@@ -184,3 +184,55 @@ TEST_CASE(vp9_inter_frame_size_change_needs_another_decoder)
for (auto const& frame : frames)
EXPECT_EQ(frame.size, Gfx::Size<u32>(1280, 720));
}
+
+// The file's mastering display and content light levels are only in metadata OBUs, which must survive the copy of a frame
+// made for export.
+TEST_CASE(frames_carry_the_high_dynamic_range_metadata_in_their_bitstream)
+{
+ auto decoding = open_decoding("./av1_hdr_metadata_in_webm.webm"sv, Media::CodecID::AV1);
+ if (!decoding.has_value())
+ return;
+
+ auto frame = MUST(decoding->next_frame());
+ auto const& color_metadata = frame->color_metadata();
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ if (color_metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_content_light_level, 1005);
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_frame_average_light_level, 315);
+ }
+ EXPECT(color_metadata.mastering_display_color_volume.has_value());
+ if (color_metadata.mastering_display_color_volume.has_value())
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->maximum_luminance, 1000.0);
+}
+
+static void expect_scene_peaks_of_every_frame(StringView path, Span<ExpectedScenePeak const> expected_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { expected_scene_peaks };
+ auto decoding = open_decoding(path, Media::CodecID::H265);
+ if (!decoding.has_value())
+ return;
+
+ size_t frame_count = 0;
+ while (true) {
+ auto frame_result = decoding->next_frame();
+ if (frame_result.is_error()) {
+ EXPECT_EQ(frame_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ auto const& frame = *frame_result.value();
+ scene_peaks.check(frame.timestamp(), frame.color_metadata().maximum_scene_luminance);
+ frame_count++;
+ }
+ EXPECT_EQ(frame_count, expected_scene_peaks.size());
+ scene_peaks.expect_every_frame_checked();
+}
+
+TEST_CASE(h265_frames_carry_their_own_hdr10_plus_scene_peaks)
+{
+ expect_scene_peaks_of_every_frame("./hevc_hdr10_plus_in_sei.mkv"sv, hevc_hdr10_plus_in_sei_scene_peaks);
+}
+
+TEST_CASE(h265_frames_carry_their_own_dolby_vision_scene_peaks)
+{
+ expect_scene_peaks_of_every_frame("./hevc_dolby_vision_rpus.mkv"sv, hevc_dolby_vision_rpus_scene_peaks);
+}
diff --git a/Tests/LibMedia/TestH265Decode.cpp b/Tests/LibMedia/TestH265Decode.cpp
new file mode 100644
index 00000000000..e578e4091c6
--- /dev/null
+++ b/Tests/LibMedia/TestH265Decode.cpp
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibMedia/DemuxerRegistry.h>
+#include <LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.h>
+#include <LibMediaCodecs/FFmpeg/SystemFFmpeg.h>
+
+#include "TestMediaCommon.h"
+
+// H.265 is left out of the bundled FFmpeg, so these run against whatever system libavcodec decodes it.
+static Media::FFmpeg::SystemFFmpeg const* h265_library()
+{
+ Media::FFmpeg::SystemFFmpeg::load();
+ auto const* library = Media::FFmpeg::SystemFFmpeg::the();
+ if (library == nullptr || !library->has_decoder(Media::CodecID::H265)) {
+ warnln("No system FFmpeg decodes H.265, skipping");
+ return nullptr;
+ }
+ return library;
+}
+
+static size_t for_each_frame(Media::FFmpeg::SystemFFmpeg const& library, StringView path, Function<void(Media::VideoFrame const&)> callback)
+{
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
+ auto demuxer = MUST(Media::create_demuxer(stream));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video));
+ VERIFY(track.has_value());
+ MUST(demuxer->create_context_for_track(*track));
+
+ auto first_sample = MUST(demuxer->get_next_sample_for_track(*track));
+ auto decoder = MUST(Media::FFmpeg::FFmpegVideoDecoder::try_create(library.functions(), Media::CodecID::H265, first_sample.new_codec_configuration().value_or({})));
+ MUST(decoder->receive_coded_data(first_sample, Media::DecodeIntent::Output));
+
+ size_t frame_count = 0;
+ while (true) {
+ auto frame_result = decoder->take_next_output(track->video_data().color_metadata);
+ if (!frame_result.is_error()) {
+ callback(*frame_result.value());
+ frame_count++;
+ continue;
+ }
+ if (frame_result.error().category() == Media::DecoderErrorCategory::EndOfStream)
+ return frame_count;
+ if (frame_result.error().category() != Media::DecoderErrorCategory::NeedsMoreInput) {
+ FAIL(ByteString::formatted("Decoding failed: {}", frame_result.error().description()));
+ return frame_count;
+ }
+
+ auto sample_result = demuxer->get_next_sample_for_track(*track);
+ if (!sample_result.is_error()) {
+ MUST(decoder->receive_coded_data(sample_result.value(), Media::DecodeIntent::Output));
+ continue;
+ }
+ if (sample_result.error().category() != Media::DecoderErrorCategory::EndOfStream) {
+ FAIL(ByteString::formatted("Demuxing failed: {}", sample_result.error().description()));
+ return frame_count;
+ }
+ decoder->signal_end_of_stream();
+ }
+}
+
+// The file's mastering display and content light levels are only in its SEI, not in its sample entry.
+TEST_CASE(h265_frames_carry_the_high_dynamic_range_metadata_in_their_bitstream)
+{
+ auto const* library = h265_library();
+ if (library == nullptr)
+ return;
+
+ auto frame_count = for_each_frame(*library, "./hevc_hdr_metadata_in_sei.mp4"sv, [](Media::VideoFrame const& frame) {
+ auto const& color_metadata = frame.color_metadata();
+ EXPECT(color_metadata.mastering_display_color_volume.has_value());
+ if (color_metadata.mastering_display_color_volume.has_value()) {
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->red.x, 0.68);
+ }
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ if (color_metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_content_light_level, 1000);
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_frame_average_light_level, 400);
+ }
+ });
+ EXPECT_EQ(frame_count, 6u);
+}
+
+TEST_CASE(h265_frames_carry_their_own_hdr10_plus_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_hdr10_plus_in_sei_scene_peaks };
+ auto const* library = h265_library();
+ if (library == nullptr)
+ return;
+
+ auto frame_count = for_each_frame(*library, "./hevc_hdr10_plus_in_sei.mkv"sv, [&](Media::VideoFrame const& frame) {
+ scene_peaks.check(frame.timestamp(), frame.color_metadata().maximum_scene_luminance);
+ });
+ EXPECT_EQ(frame_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
+
+TEST_CASE(h265_frames_carry_their_own_dolby_vision_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_dolby_vision_rpus_scene_peaks };
+ auto const* library = h265_library();
+ if (library == nullptr)
+ return;
+
+ auto frame_count = for_each_frame(*library, "./hevc_dolby_vision_rpus.mkv"sv, [&](Media::VideoFrame const& frame) {
+ scene_peaks.check(frame.timestamp(), frame.color_metadata().maximum_scene_luminance);
+ });
+ EXPECT_EQ(frame_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
diff --git a/Tests/LibMedia/TestMediaCommon.h b/Tests/LibMedia/TestMediaCommon.h
index 997b7dbfc78..b0b5a7881ad 100644
--- a/Tests/LibMedia/TestMediaCommon.h
+++ b/Tests/LibMedia/TestMediaCommon.h
@@ -6,6 +6,7 @@
#pragma once
+#include <AK/Array.h>
#include <AK/Function.h>
#include <AK/Mutex.h>
#include <AK/NeverDestroyed.h>
@@ -269,3 +270,70 @@ static inline auto seek_to_resume_and_pump_until_woken_with_data(Core::EventLoop
size_t seek_count = 0;
return seek_to_resume_and_pump_until_woken_with_data(loop, producer, timestamp, seek_count);
}
+
+struct ExpectedScenePeak {
+ i64 milliseconds;
+ Optional<double> luminance;
+};
+
+// The frames of these files were given scene peaks in decoding order, so a peak that does not follow its frame through
+// reordering lands on a frame expecting another.
+static constexpr Array<ExpectedScenePeak, 6> hevc_hdr10_plus_in_sei_scene_peaks { {
+ { 0, 100 },
+ { 33, 400 },
+ { 67, 500 },
+ { 100, 300 },
+ { 133, 600 },
+ { 167, 200 },
+} };
+// Each frame's RPU takes another path through the syntax: a polynomial mapping, floating point coefficients, a reused
+// mapping with compressed display management, nonlinear quantization, no display management at all, and MMR.
+static constexpr Array<ExpectedScenePeak, 6> hevc_dolby_vision_rpus_scene_peaks { {
+ { 0, 100.1 },
+ { 33, 300.33 },
+ { 67, 599.56 },
+ { 100, 500.44 },
+ { 133, {} },
+ { 167, 399.72 },
+} };
+
+// Each expected frame has to be checked exactly once, whatever order the frames come in.
+class ScenePeakChecker {
+public:
+ explicit ScenePeakChecker(Span<ExpectedScenePeak const> expected_scene_peaks)
+ : m_expected_scene_peaks(expected_scene_peaks)
+ {
+ m_checked.resize(expected_scene_peaks.size());
+ }
+
+ void check(AK::Duration timestamp, Optional<float> maximum_scene_luminance)
+ {
+ Optional<size_t> expected_index;
+ for (size_t index = 0; index < m_expected_scene_peaks.size(); index++) {
+ if (m_expected_scene_peaks[index].milliseconds == timestamp.to_milliseconds())
+ expected_index = index;
+ }
+ EXPECT(expected_index.has_value());
+ if (!expected_index.has_value())
+ return;
+ EXPECT(!m_checked[expected_index.value()]);
+ m_checked[expected_index.value()] = true;
+
+ auto const& expected = m_expected_scene_peaks[expected_index.value()];
+ EXPECT_EQ(maximum_scene_luminance.has_value(), expected.luminance.has_value());
+ if (!maximum_scene_luminance.has_value() || !expected.luminance.has_value())
+ return;
+ EXPECT(isfinite(maximum_scene_luminance.value()));
+ EXPECT_APPROXIMATE_WITH_ERROR(maximum_scene_luminance.value(), expected.luminance.value(), 0.5);
+ }
+
+ void expect_every_frame_checked() const
+ {
+ for (auto checked : m_checked)
+ EXPECT(checked);
+ }
+
+private:
+ Span<ExpectedScenePeak const> m_expected_scene_peaks;
+ Vector<bool> m_checked;
+};
diff --git a/Tests/LibMedia/TestVideoFramePool.cpp b/Tests/LibMedia/TestVideoFramePool.cpp
index dab1aa1439f..16660d25e08 100644
--- a/Tests/LibMedia/TestVideoFramePool.cpp
+++ b/Tests/LibMedia/TestVideoFramePool.cpp
@@ -64,6 +64,7 @@ static Media::VideoFrameMetadata make_metadata()
},
.mastering_display_color_volume = {},
.content_light_level_information = {},
+ .maximum_scene_luminance = {},
},
};
}
diff --git a/Tests/LibMedia/TestVideoToolboxDecode.cpp b/Tests/LibMedia/TestVideoToolboxDecode.cpp
index ba86b82d7a2..4b15d74ea3f 100644
--- a/Tests/LibMedia/TestVideoToolboxDecode.cpp
+++ b/Tests/LibMedia/TestVideoToolboxDecode.cpp
@@ -492,3 +492,102 @@ TEST_CASE(input_after_the_end_of_stream_is_rejected_until_flushed)
decoding.decoder->flush();
EXPECT(!decoding.decoder->receive_coded_data(first_frame, Media::DecodeIntent::Output).is_error());
}
+
+// The file's mastering display and content light levels are only in its SEI, not in its sample entry.
+TEST_CASE(h265_frames_carry_the_high_dynamic_range_metadata_in_their_bitstream)
+{
+ auto decoding = open_decoding("./hevc_hdr_metadata_in_sei.mp4"sv, Media::CodecID::H265);
+ EXPECT(!decoding.track.video_data().color_metadata.mastering_display_color_volume.has_value());
+
+ size_t frame_count = 0;
+ while (true) {
+ auto frame_result = decoding.next_frame();
+ if (frame_result.is_error()) {
+ if (decoding_is_unavailable(frame_result.error()))
+ return;
+ EXPECT_EQ(frame_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ auto const& color_metadata = frame_result.value()->color_metadata();
+ EXPECT(color_metadata.mastering_display_color_volume.has_value());
+ if (color_metadata.mastering_display_color_volume.has_value()) {
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->red.x, 0.68);
+ }
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ if (color_metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_content_light_level, 1000);
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_frame_average_light_level, 400);
+ }
+ frame_count++;
+ }
+ EXPECT_EQ(frame_count, 6u);
+}
+
+// The file's mastering display and content light levels are only in metadata OBUs, not in its Matroska Colour element.
+TEST_CASE(av1_frames_carry_the_high_dynamic_range_metadata_in_their_bitstream)
+{
+ auto decoding = open_decoding("./av1_hdr_metadata_in_webm.webm"sv, Media::CodecID::AV1);
+ auto frame_result = decoding.next_frame();
+ if (frame_result.is_error() && decoding_is_unavailable(frame_result.error()))
+ return;
+ auto frame = MUST(move(frame_result));
+ auto const& color_metadata = frame->color_metadata();
+
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ if (color_metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_content_light_level, 1005);
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_frame_average_light_level, 315);
+ }
+ EXPECT(color_metadata.mastering_display_color_volume.has_value());
+ if (color_metadata.mastering_display_color_volume.has_value()) {
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE_WITH_ERROR(color_metadata.mastering_display_color_volume->red.x, 0.708, 1.0 / (1 << 16));
+ }
+}
+
+TEST_CASE(h265_frames_carry_their_own_hdr10_plus_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_hdr10_plus_in_sei_scene_peaks };
+ auto decoding = open_decoding("./hevc_hdr10_plus_in_sei.mkv"sv, Media::CodecID::H265);
+
+ size_t frame_count = 0;
+ while (true) {
+ auto frame_result = decoding.next_frame();
+ if (frame_result.is_error()) {
+ if (decoding_is_unavailable(frame_result.error()))
+ return;
+ EXPECT_EQ(frame_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ auto const& frame = *frame_result.value();
+ auto const& color_metadata = frame.color_metadata();
+ scene_peaks.check(frame.timestamp(), color_metadata.maximum_scene_luminance);
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ frame_count++;
+ }
+ EXPECT_EQ(frame_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
+
+TEST_CASE(h265_frames_carry_their_own_dolby_vision_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_dolby_vision_rpus_scene_peaks };
+ auto decoding = open_decoding("./hevc_dolby_vision_rpus.mkv"sv, Media::CodecID::H265);
+
+ size_t frame_count = 0;
+ while (true) {
+ auto frame_result = decoding.next_frame();
+ if (frame_result.is_error()) {
+ if (decoding_is_unavailable(frame_result.error()))
+ return;
+ EXPECT_EQ(frame_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ break;
+ }
+ auto const& frame = *frame_result.value();
+ scene_peaks.check(frame.timestamp(), frame.color_metadata().maximum_scene_luminance);
+ frame_count++;
+ }
+ EXPECT_EQ(frame_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
diff --git a/Tests/LibMedia/TestWindowsMediaFoundationDecode.cpp b/Tests/LibMedia/TestWindowsMediaFoundationDecode.cpp
index 14faddc83a4..5a87e48ca82 100644
--- a/Tests/LibMedia/TestWindowsMediaFoundationDecode.cpp
+++ b/Tests/LibMedia/TestWindowsMediaFoundationDecode.cpp
@@ -45,7 +45,7 @@ struct DecodeResult {
RefPtr<Media::VideoFrame> first_frame;
};
-DecodeResult decode_all_frames(StringView path, Function<void(Media::VideoFrame const&)> check_frame = {})
+Optional<DecodeResult> decode_all_frames(StringView path, Function<void(Media::VideoFrame const&)> check_frame = {})
{
auto [demuxer, track] = create_demuxer_and_video_track(path);
auto first_sample = MUST(demuxer->get_next_sample_for_track(track));
@@ -115,18 +115,18 @@ void expect_picture_has_detail(Media::VideoFrame const& frame)
TEST_CASE(avc_in_mp4_with_reordered_frames)
{
auto result = decode_all_frames("./avc.mp4"sv);
- if (!result.first_frame)
+ if (!result.has_value())
return;
- EXPECT_EQ(result.frame_count, 50u);
- expect_picture_has_detail(*result.first_frame);
+ EXPECT_EQ(result->frame_count, 50u);
+ expect_picture_has_detail(*result->first_frame);
}
TEST_CASE(avc_in_matroska)
{
auto result = decode_all_frames("./avc_in_matroska.mkv"sv);
- if (!result.first_frame)
+ if (!result.has_value())
return;
- EXPECT_EQ(result.frame_count, 50u);
+ EXPECT_EQ(result->frame_count, 50u);
}
TEST_CASE(hevc_10bit)
@@ -134,13 +134,13 @@ TEST_CASE(hevc_10bit)
auto result = decode_all_frames("./hevc_10bit.mp4"sv, [](Media::VideoFrame const& frame) {
EXPECT_EQ(frame.bit_depth(), 10);
});
- if (!result.first_frame)
+ if (!result.has_value())
return;
- EXPECT(result.frame_count > 0);
- expect_picture_has_detail(*result.first_frame);
+ EXPECT(result->frame_count > 0);
+ expect_picture_has_detail(*result->first_frame);
// Ten significant bits must land in the low end of each sample.
- auto luma = result.first_frame->yuv_data()->y_data();
+ auto luma = result->first_frame->yuv_data()->y_data();
for (size_t i = 0; i + 1 < luma.size(); i += 2)
EXPECT((luma[i + 1] & 0xFC) == 0);
}
@@ -202,3 +202,50 @@ TEST_CASE(flush_restarts_decoding_from_a_keyframe)
EXPECT_EQ(frame->timestamp(), first_sample.presentation_timestamp());
EXPECT_EQ(decoder->take_next_output(track.video_data().color_metadata).error().category(), Media::DecoderErrorCategory::EndOfStream);
}
+
+// The file's mastering display and content light levels are only in its SEI, not in its sample entry.
+TEST_CASE(hevc_frames_carry_the_high_dynamic_range_metadata_in_their_bitstream)
+{
+ auto result = decode_all_frames("./hevc_hdr_metadata_in_sei.mp4"sv, [](Media::VideoFrame const& frame) {
+ auto const& color_metadata = frame.color_metadata();
+ EXPECT(color_metadata.mastering_display_color_volume.has_value());
+ if (color_metadata.mastering_display_color_volume.has_value()) {
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->maximum_luminance, 1000.0);
+ EXPECT_APPROXIMATE(color_metadata.mastering_display_color_volume->red.x, 0.68);
+ }
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ if (color_metadata.content_light_level_information.has_value()) {
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_content_light_level, 1000);
+ EXPECT_EQ(color_metadata.content_light_level_information->maximum_frame_average_light_level, 400);
+ }
+ });
+ if (!result.has_value())
+ return;
+ EXPECT_EQ(result->frame_count, 6u);
+}
+
+TEST_CASE(hevc_frames_carry_their_own_hdr10_plus_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_hdr10_plus_in_sei_scene_peaks };
+ auto result = decode_all_frames("./hevc_hdr10_plus_in_sei.mkv"sv, [&](Media::VideoFrame const& frame) {
+ auto const& color_metadata = frame.color_metadata();
+ scene_peaks.check(frame.timestamp(), color_metadata.maximum_scene_luminance);
+ EXPECT(color_metadata.content_light_level_information.has_value());
+ });
+ if (!result.has_value())
+ return;
+ EXPECT_EQ(result->frame_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
+
+TEST_CASE(hevc_frames_carry_their_own_dolby_vision_scene_peaks)
+{
+ ScenePeakChecker scene_peaks { hevc_dolby_vision_rpus_scene_peaks };
+ auto result = decode_all_frames("./hevc_dolby_vision_rpus.mkv"sv, [&](Media::VideoFrame const& frame) {
+ scene_peaks.check(frame.timestamp(), frame.color_metadata().maximum_scene_luminance);
+ });
+ if (!result.has_value())
+ return;
+ EXPECT_EQ(result->frame_count, 6u);
+ scene_peaks.expect_every_frame_checked();
+}
diff --git a/Tests/LibMedia/av1_hdr_metadata_in_webm.webm b/Tests/LibMedia/av1_hdr_metadata_in_webm.webm
new file mode 100644
index 00000000000..6ca5e6946fd
Binary files /dev/null and b/Tests/LibMedia/av1_hdr_metadata_in_webm.webm differ
diff --git a/Tests/LibMedia/hevc_dolby_vision_rpus.mkv b/Tests/LibMedia/hevc_dolby_vision_rpus.mkv
new file mode 100644
index 00000000000..acd9341d618
Binary files /dev/null and b/Tests/LibMedia/hevc_dolby_vision_rpus.mkv differ
diff --git a/Tests/LibMedia/hevc_hdr10_plus_in_sei.mkv b/Tests/LibMedia/hevc_hdr10_plus_in_sei.mkv
new file mode 100644
index 00000000000..62386ab8429
Binary files /dev/null and b/Tests/LibMedia/hevc_hdr10_plus_in_sei.mkv differ
diff --git a/Tests/LibMedia/hevc_hdr_metadata_in_sei.mp4 b/Tests/LibMedia/hevc_hdr_metadata_in_sei.mp4
new file mode 100644
index 00000000000..28ca1f206cc
Binary files /dev/null and b/Tests/LibMedia/hevc_hdr_metadata_in_sei.mp4 differ