Skip to content

Truly independent web browser

LibMedia+Tests: Read HDR metadata in Matroska BlockAdditional elements

Zaggy102461bbc1edea38
diff --git a/Libraries/LibMedia/Containers/Matroska/Document.h b/Libraries/LibMedia/Containers/Matroska/Document.h
index 28bb9574ba2..ce828aa8840 100644
--- a/Libraries/LibMedia/Containers/Matroska/Document.h
+++ b/Libraries/LibMedia/Containers/Matroska/Document.h
@@ -390,6 +390,9 @@ public:
void set_lacing(Lacing lacing) { m_lacing = lacing; }
bool discardable() const { return m_discardable; }
void set_discardable(bool discardable) { m_discardable = discardable; }
+ // The brightest light in the scene in cd/m², from HDR10+ carried alongside the block.
+ Optional<float> maximum_scene_luminance() const { return m_maximum_scene_luminance; }
+ void set_maximum_scene_luminance(Optional<float> luminance) { m_maximum_scene_luminance = luminance; }
size_t data_position() const { return m_data_position; }
size_t data_size() const { return m_data_size; }
void set_data(size_t position, size_t size)
@@ -406,6 +409,7 @@ private:
bool m_invisible { false };
Lacing m_lacing { None };
bool m_discardable { true };
+ Optional<float> m_maximum_scene_luminance;
size_t m_data_position { 0 };
size_t m_data_size { 0 };
};
diff --git a/Libraries/LibMedia/Containers/Matroska/ElementIDs.h b/Libraries/LibMedia/Containers/Matroska/ElementIDs.h
index 56880f8b892..3eeb75a5774 100644
--- a/Libraries/LibMedia/Containers/Matroska/ElementIDs.h
+++ b/Libraries/LibMedia/Containers/Matroska/ElementIDs.h
@@ -96,6 +96,10 @@ constexpr u32 BLOCK_GROUP_ID = 0xA0;
constexpr u32 BLOCK_ID = 0xA1;
constexpr u32 BLOCK_DURATION_ID = 0x9B;
constexpr u32 REFERENCE_BLOCK_ID = 0xFB;
+constexpr u32 BLOCK_ADDITIONS_ID = 0x75A1;
+constexpr u32 BLOCK_MORE_ID = 0xA6;
+constexpr u32 BLOCK_ADD_ID_ID = 0xEE;
+constexpr u32 BLOCK_ADDITIONAL_ID = 0xA5;
// Cues
constexpr u32 CUES_ID = 0x1C53BB6B;
diff --git a/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp b/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp
index 9fd627b8d60..2082ff2fd25 100644
--- a/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp
+++ b/Libraries/LibMedia/Containers/Matroska/MatroskaDemuxer.cpp
@@ -199,8 +199,9 @@ DecoderErrorOr<CodedFrame> MatroskaDemuxer::get_next_sample_for_track(Track cons
auto duration = status.block->duration().value_or(AK::Duration::zero());
auto flags = status.block->only_keyframes() ? FrameFlags::Keyframe : FrameFlags::None;
- return CodedFrame(codec_id, timestamp, timestamp, duration, flags,
- move(status.frames[status.frame_index++]), move(codec_configuration));
+ CodedFrame frame { codec_id, timestamp, timestamp, duration, flags, move(status.frames[status.frame_index++]), move(codec_configuration) };
+ frame.set_maximum_scene_luminance(status.block->maximum_scene_luminance());
+ return frame;
}
DecoderErrorOr<AK::Duration> MatroskaDemuxer::total_duration()
diff --git a/Libraries/LibMedia/Containers/Matroska/Reader.cpp b/Libraries/LibMedia/Containers/Matroska/Reader.cpp
index 6554b0a0a75..d852dc08b4f 100644
--- a/Libraries/LibMedia/Containers/Matroska/Reader.cpp
+++ b/Libraries/LibMedia/Containers/Matroska/Reader.cpp
@@ -23,6 +23,7 @@
#include <LibMediaCodecs/Codecs/AV1.h>
#include <LibMediaCodecs/Codecs/H264.h>
#include <LibMediaCodecs/Codecs/H265.h>
+#include <LibMediaCodecs/Codecs/HDR10Plus.h>
#include <LibMediaCodecs/Limits.h>
#include "Reader.h"
@@ -993,6 +994,71 @@ DecoderErrorOr<Block> Reader::parse_simple_block(Streamer& streamer, AK::Duratio
return block;
}
+// https://www.matroska.org/technical/codec_specs.html#block-addition-mappings
+// An ITU-T T.35 message, which is how WebM carries HDR10+ for VP9.
+static constexpr u64 ITU_T_T35_BLOCK_ADD_ID = 4;
+
+static DecoderErrorOr<void> parse_block_additions(Streamer& streamer, Block& block)
+{
+ TRY(Reader::parse_master_element(streamer, "BlockAdditions"sv, [&](u64 element_id) -> DecoderErrorOr<ElementIterationDecision> {
+ if (element_id != BLOCK_MORE_ID) {
+ TRY(streamer.read_unknown_element());
+ return ElementIterationDecision::Continue;
+ }
+
+ // https://www.matroska.org/technical/elements.html
+ // BlockAddID: default 1
+ u64 block_add_id = 1;
+ Optional<FixedArray<u8>> block_additional;
+ TRY(Reader::parse_master_element(streamer, "BlockMore"sv, [&](u64 block_more_element_id) -> DecoderErrorOr<ElementIterationDecision> {
+ switch (block_more_element_id) {
+ case BLOCK_ADD_ID_ID:
+ block_add_id = TRY(streamer.read_u64());
+ break;
+ case BLOCK_ADDITIONAL_ID: {
+ auto size = TRY(streamer.read_variable_size_integer());
+ // An addition too large to be HDR10+ is skipped rather than read, whatever its BlockAddID.
+ if (size > Codecs::HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE) {
+ block_additional.clear();
+ Checked<size_t> end = streamer.position();
+ end += size;
+ if (end.has_overflow())
+ return DecoderError::corrupted("BlockAdditional extends past the representable size"sv);
+ TRY(streamer.seek_to_position(end.value()));
+ break;
+ }
+ block_additional = TRY(streamer.read_raw_octets(size));
+ break;
+ }
+ default:
+ TRY(streamer.read_unknown_element());
+ break;
+ }
+ return ElementIterationDecision::Continue;
+ }));
+
+ if (block_add_id == ITU_T_T35_BLOCK_ADD_ID && block_additional.has_value()) {
+ if (auto luminance = Codecs::hdr10_plus_maximum_scene_luminance(block_additional->span()); luminance.has_value())
+ block.set_maximum_scene_luminance(luminance);
+ }
+ return ElementIterationDecision::Continue;
+ }));
+ return {};
+}
+
+static DecoderErrorOr<void> parse_or_skip_block_additions(Streamer& streamer, Block& block)
+{
+ auto additions_position = streamer.position();
+ auto result = parse_block_additions(streamer, block);
+ if (!result.is_error() || result.error().category() == DecoderErrorCategory::EndOfStream)
+ return result;
+
+ // Malformed additions are skipped as an unrecognized element would be, rather than failing the block they accompany.
+ block.set_maximum_scene_luminance({});
+ TRY(streamer.seek_to_position(additions_position));
+ return streamer.read_unknown_element();
+}
+
DecoderErrorOr<Block> Reader::parse_block_group(Streamer& streamer, AK::Duration cluster_timestamp, u64 segment_timestamp_scale, TrackBlockContexts& contexts)
{
Block block;
@@ -1040,6 +1106,10 @@ DecoderErrorOr<Block> Reader::parse_block_group(Streamer& streamer, AK::Duration
TRY(streamer.read_unknown_element());
break;
}
+ case BLOCK_ADDITIONS_ID: {
+ TRY(parse_or_skip_block_additions(streamer, block));
+ break;
+ }
default:
TRY(streamer.read_unknown_element());
break;
diff --git a/Libraries/LibMedia/MediaSourceExtensions/WebMByteStreamParser.cpp b/Libraries/LibMedia/MediaSourceExtensions/WebMByteStreamParser.cpp
index b009268b0ba..83a24565663 100644
--- a/Libraries/LibMedia/MediaSourceExtensions/WebMByteStreamParser.cpp
+++ b/Libraries/LibMedia/MediaSourceExtensions/WebMByteStreamParser.cpp
@@ -287,16 +287,18 @@ Media::DecoderErrorOr<ParseMediaSegmentResult> WebMByteStreamParser::parse_media
if (m_tracks_needing_codec_configuration.remove(block.track_number()))
codec_configuration = MUST(FixedArray<u8>::create(codec_initialization_data_for_track(block.track_number())));
+ auto coded_frame = Media::CodedFrame(
+ codec_id_for_track(block.track_number()),
+ block.timestamp().value(),
+ block.timestamp().value(),
+ block.duration().value_or(AK::Duration::zero()),
+ block.only_keyframes() ? Media::FrameFlags::Keyframe : Media::FrameFlags::None,
+ move(frame_data),
+ move(codec_configuration));
+ coded_frame.set_maximum_scene_luminance(block.maximum_scene_luminance());
result.coded_frames.append({
.track_number = block.track_number(),
- .coded_frame = Media::CodedFrame(
- codec_id_for_track(block.track_number()),
- block.timestamp().value(),
- block.timestamp().value(),
- block.duration().value_or(AK::Duration::zero()),
- block.only_keyframes() ? Media::FrameFlags::Keyframe : Media::FrameFlags::None,
- move(frame_data),
- move(codec_configuration)),
+ .coded_frame = move(coded_frame),
});
return IterationDecision::Continue;
}
diff --git a/Libraries/LibMedia/RemoteVideoDecoder.cpp b/Libraries/LibMedia/RemoteVideoDecoder.cpp
index d7e2ea62f5b..c0ea9622779 100644
--- a/Libraries/LibMedia/RemoteVideoDecoder.cpp
+++ b/Libraries/LibMedia/RemoteVideoDecoder.cpp
@@ -703,7 +703,7 @@ DecoderErrorOr<void> RemoteVideoDecoder::receive_coded_data(CodedFrame const& co
MutexLocker locker { m_state->mutex };
m_state->submissions_in_flight.append({ m_ring_serial, ring_offset, coded_frame.data().size(), m_state->generation });
m_state->connection.with_target([&](auto& connection) {
- connection.async_submit_coded_frame(m_state->decoder_id, m_state->generation, ring_offset, coded_frame.data().size(), coded_frame.presentation_timestamp(), coded_frame.decode_timestamp(), coded_frame.duration(), coded_frame.flags(), move(new_codec_configuration), intent, m_output_target);
+ connection.async_submit_coded_frame(m_state->decoder_id, m_state->generation, ring_offset, coded_frame.data().size(), coded_frame.presentation_timestamp(), coded_frame.decode_timestamp(), coded_frame.duration(), coded_frame.flags(), coded_frame.maximum_scene_luminance(), move(new_codec_configuration), intent, m_output_target);
});
return {};
}
diff --git a/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp
index e104591f692..dfbac505f59 100644
--- a/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp
+++ b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.cpp
@@ -43,7 +43,7 @@ ColorMetadata const& HighDynamicRangeMetadataTracker::apply_coded_frame(CodedFra
{
if (auto configuration = coded_frame.new_codec_configuration(); configuration.has_value())
apply_configuration(*configuration);
- begin_frame();
+ begin_frame(coded_frame);
switch (m_codec_id) {
case CodecID::H264:
@@ -79,9 +79,9 @@ void HighDynamicRangeMetadataTracker::take_bitstream_metadata(ColorMetadata cons
m_metadata.maximum_scene_luminance = metadata.maximum_scene_luminance;
}
-void HighDynamicRangeMetadataTracker::begin_frame()
+void HighDynamicRangeMetadataTracker::begin_frame(CodedFrame const& coded_frame)
{
- m_metadata.maximum_scene_luminance = {};
+ m_metadata.maximum_scene_luminance = coded_frame.maximum_scene_luminance();
m_frame_gave_mastering_display_color_volume = false;
m_frame_gave_content_light_level_information = false;
}
diff --git a/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h
index 15ede5a135a..5a83b116463 100644
--- a/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h
+++ b/Libraries/LibMediaCodecs/Codecs/HighDynamicRangeMetadataTracker.h
@@ -24,9 +24,10 @@ public:
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.
+ // forget_stream(), and each frame for begin_frame() before its NAL units are applied. The frame starts from the
+ // scene peak its container gave it, which the bitstream may replace.
void forget_stream();
- void begin_frame();
+ void begin_frame(CodedFrame const&);
void apply_nal_unit(ReadonlyBytes);
ColorMetadata const& metadata() const { return m_metadata; }
diff --git a/Libraries/LibMediaCodecs/CodedFrame.h b/Libraries/LibMediaCodecs/CodedFrame.h
index 0b7be9541bd..b3c3bda9441 100644
--- a/Libraries/LibMediaCodecs/CodedFrame.h
+++ b/Libraries/LibMediaCodecs/CodedFrame.h
@@ -33,6 +33,7 @@ public:
{
m_leading_discard = other.m_leading_discard;
m_trailing_discard = other.m_trailing_discard;
+ m_maximum_scene_luminance = other.m_maximum_scene_luminance;
}
CodedFrame(CodedFrame&&) = default;
@@ -61,6 +62,14 @@ public:
void set_trailing_discard(AK::Duration discard) { m_trailing_discard = discard; }
AK::Duration decoded_start_timestamp() const { return m_presentation_timestamp - m_leading_discard; }
FrameFlags flags() const { return m_flags; }
+ // The brightest light in the frame's scene in cd/m², where the container carries it apart from the bitstream.
+ Optional<float> maximum_scene_luminance() const
+ {
+ if (m_maximum_scene_luminance > 0)
+ return m_maximum_scene_luminance;
+ return {};
+ }
+ void set_maximum_scene_luminance(Optional<float> luminance) { m_maximum_scene_luminance = luminance.value_or(0); }
bool is_keyframe() const { return has_flag(m_flags, FrameFlags::Keyframe); }
ReadonlyBytes data() const LIFETIME_BOUND { return m_data.span(); }
Optional<ReadonlyBytes> new_codec_configuration() const LIFETIME_BOUND
@@ -87,6 +96,8 @@ private:
CodecID m_codec_id;
FrameFlags m_flags;
bool m_has_new_codec_configuration { false };
+ // Stored here to fit in padding.
+ float m_maximum_scene_luminance { 0 };
AK::Duration m_presentation_timestamp;
AK::Duration m_decode_timestamp;
AK::Duration m_duration;
diff --git a/Libraries/LibMediaCodecs/VideoDecoderServer.ipc b/Libraries/LibMediaCodecs/VideoDecoderServer.ipc
index a498a78a480..212f3cfc196 100644
--- a/Libraries/LibMediaCodecs/VideoDecoderServer.ipc
+++ b/Libraries/LibMediaCodecs/VideoDecoderServer.ipc
@@ -18,7 +18,7 @@ endpoint VideoDecoderServer
destroy_decoder(u64 decoder_id) =|
// The coded data of the frames submitted after this lives in this ring, until it is replaced again.
replace_coded_data_ring(u64 decoder_id, Core::AnonymousBuffer ring) =|
- submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, Media::FrameFlags flags, Optional<ByteBuffer> new_codec_configuration, Media::DecodeIntent intent, Optional<AK::Duration> output_target) =|
+ submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, Media::FrameFlags flags, Optional<float> maximum_scene_luminance, Optional<ByteBuffer> new_codec_configuration, Media::DecodeIntent intent, Optional<AK::Duration> output_target) =|
signal_end_of_stream(u64 decoder_id, u32 generation) =|
flush(u64 decoder_id, u32 generation) =|
diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp
index c19a7f05674..0bf86ceac33 100644
--- a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp
+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.cpp
@@ -6,6 +6,7 @@
#include <AK/Checked.h>
#include <AK/ConditionVariable.h>
+#include <AK/Math.h>
#include <AK/Queue.h>
#include <AK/Variant.h>
#include <LibCore/EventLoop.h>
@@ -28,6 +29,7 @@ public:
AK::Duration decode_timestamp;
AK::Duration duration;
FrameFlags flags { FrameFlags::None };
+ Optional<float> maximum_scene_luminance;
Optional<ByteBuffer> new_codec_configuration;
DecodeIntent intent { DecodeIntent::Output };
Optional<AK::Duration> output_target;
@@ -210,11 +212,16 @@ private:
if (!m_ring.is_valid() || end.has_overflow() || end.value() > m_ring.size())
return DecoderError::with_description(DecoderErrorCategory::Invalid, "A coded frame lies outside its ring"sv);
+ if (auto luminance = submission.maximum_scene_luminance; luminance.has_value() && (!isfinite(*luminance) || *luminance <= 0))
+ return DecoderError::with_description(DecoderErrorCategory::Invalid, "A coded frame's scene peak is not a positive luminance"sv);
+
auto data = DECODER_TRY_ALLOC(FixedArray<u8>::create(m_ring.bytes().slice(submission.ring_offset, submission.size)));
Optional<FixedArray<u8>> new_codec_configuration;
if (submission.new_codec_configuration.has_value())
new_codec_configuration = DECODER_TRY_ALLOC(FixedArray<u8>::create(submission.new_codec_configuration->bytes()));
- return CodedFrame { m_codec_id, submission.presentation_timestamp, submission.decode_timestamp, submission.duration, submission.flags, move(data), move(new_codec_configuration) };
+ CodedFrame coded_frame { m_codec_id, submission.presentation_timestamp, submission.decode_timestamp, submission.duration, submission.flags, move(data), move(new_codec_configuration) };
+ coded_frame.set_maximum_scene_luminance(submission.maximum_scene_luminance);
+ return coded_frame;
}
void decode_submission(Submission& submission)
@@ -425,7 +432,7 @@ void VideoDecoderServerConnection::replace_coded_data_ring(u64 decoder_id, Core:
(*session)->enqueue(DecoderSession::ReplaceRing { move(ring) });
}
-void VideoDecoderServerConnection::submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, FrameFlags flags, Optional<ByteBuffer> new_codec_configuration, DecodeIntent intent, Optional<AK::Duration> output_target)
+void VideoDecoderServerConnection::submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, FrameFlags flags, Optional<float> maximum_scene_luminance, Optional<ByteBuffer> new_codec_configuration, DecodeIntent intent, Optional<AK::Duration> output_target)
{
auto session = m_sessions.get(decoder_id);
if (!session.has_value())
@@ -438,6 +445,7 @@ void VideoDecoderServerConnection::submit_coded_frame(u64 decoder_id, u32 genera
.decode_timestamp = decode_timestamp,
.duration = duration,
.flags = flags,
+ .maximum_scene_luminance = maximum_scene_luminance,
.new_codec_configuration = move(new_codec_configuration),
.intent = intent,
.output_target = output_target,
diff --git a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h
index 8cfd5250627..38a5bab74da 100644
--- a/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h
+++ b/Libraries/LibMediaCodecs/VideoDecoderServerConnection.h
@@ -48,7 +48,7 @@ private:
virtual void create_decoder(u64 decoder_id, u32 generation, CodecID codec_id, ByteBuffer codec_initialization_data) override;
virtual void destroy_decoder(u64 decoder_id) override;
virtual void replace_coded_data_ring(u64 decoder_id, Core::AnonymousBuffer ring) override;
- virtual void submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, FrameFlags flags, Optional<ByteBuffer> new_codec_configuration, DecodeIntent intent, Optional<AK::Duration> output_target) override;
+ virtual void submit_coded_frame(u64 decoder_id, u32 generation, u64 ring_offset, u64 size, AK::Duration presentation_timestamp, AK::Duration decode_timestamp, AK::Duration duration, FrameFlags flags, Optional<float> maximum_scene_luminance, Optional<ByteBuffer> new_codec_configuration, DecodeIntent intent, Optional<AK::Duration> output_target) override;
virtual void signal_end_of_stream(u64 decoder_id, u32 generation) override;
virtual void flush(u64 decoder_id, u32 generation) override;
virtual void release_frame(u64 frame_id) override;
diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
index 8ef68213b4f..063c2af41c7 100644
--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
@@ -322,7 +322,7 @@ 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();
+ high_dynamic_range_metadata_tracker.begin_frame(coded_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));
@@ -418,7 +418,7 @@ 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();
+ high_dynamic_range_metadata_tracker.begin_frame(coded_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));
@@ -535,6 +535,7 @@ struct VP9State final : FormatState {
header = frame_header;
dirty = true;
}
+ high_dynamic_range_metadata_tracker.apply_coded_frame(coded_frame);
return {};
}
diff --git a/Tests/LibMedia/CMakeLists.txt b/Tests/LibMedia/CMakeLists.txt
index c4713a646a5..47ddcd3e21b 100644
--- a/Tests/LibMedia/CMakeLists.txt
+++ b/Tests/LibMedia/CMakeLists.txt
@@ -45,6 +45,7 @@ set(TEST_SOURCES
TestVideoFramePool.cpp
TestVorbisDecode.cpp
TestVP9Decode.cpp
+ TestWebMByteStreamParser.cpp
TestWav.cpp
TestWAVDemuxer.cpp
)
diff --git a/Tests/LibMedia/TestParseMatroska.cpp b/Tests/LibMedia/TestParseMatroska.cpp
index c94c1e09073..d1fa8608b26 100644
--- a/Tests/LibMedia/TestParseMatroska.cpp
+++ b/Tests/LibMedia/TestParseMatroska.cpp
@@ -15,6 +15,7 @@
#include <LibMedia/Containers/Matroska/MatroskaDemuxer.h>
#include <LibMedia/IncrementallyPopulatedStream.h>
#include <LibMedia/ReadonlyBytesCursor.h>
+#include <LibMediaCodecs/Codecs/HDR10Plus.h>
#include <LibMediaCodecs/Limits.h>
#include <LibTest/TestCase.h>
@@ -163,7 +164,7 @@ enum class WithColorElement : u8 {
WithOutOfRangeMasteringChromaticity,
};
-ByteBuffer make_matroska_with_av1_track(WithColorElement with_color_element)
+ByteBuffer make_matroska_with_av1_track(WithColorElement with_color_element, Function<void(ByteBuffer&)> const& append_cluster_contents = {})
{
ByteBuffer data;
auto ebml_header = begin_ebml_master(data, Media::Matroska::EBML_MASTER_ELEMENT_ID);
@@ -219,7 +220,11 @@ ByteBuffer make_matroska_with_av1_track(WithColorElement with_color_element)
finish_ebml_master(data, track_entry);
finish_ebml_master(data, tracks);
- append_empty_ebml_master(data, Media::Matroska::CLUSTER_ELEMENT_ID);
+ auto cluster = begin_ebml_master(data, Media::Matroska::CLUSTER_ELEMENT_ID);
+ append_ebml_uint(data, Media::Matroska::TIMESTAMP_ID, 0);
+ if (append_cluster_contents)
+ append_cluster_contents(data);
+ finish_ebml_master(data, cluster);
finish_ebml_master(data, segment);
return data;
}
@@ -1355,6 +1360,90 @@ TEST_CASE(mastering_metadata_with_a_float_of_an_invalid_size_is_left_out)
EXPECT(color_metadata.content_light_level_information.has_value());
}
+// HDR10+ with one processing window whose brightest component is 364.1 cd/m².
+// clang-format off
+constexpr auto HDR10_PLUS_T35_MESSAGE = 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
+
+enum class BlockAdditionsDefect : u8 {
+ None,
+ OversizedBlockAddID,
+ OversizedBlockAdditional,
+};
+
+static void append_block_group_with_hdr10_plus(ByteBuffer& data, i16 timestamp, BlockAdditionsDefect defect)
+{
+ auto block_group = begin_ebml_master(data, Media::Matroska::BLOCK_GROUP_ID);
+ // Track 1, the timestamp, no flags, and a temporal delimiter OBU as the frame.
+ Array<u8, 6> block { 0x81, static_cast<u8>(timestamp >> 8), static_cast<u8>(timestamp & 0xff), 0x00, 0x12, 0x00 };
+ append_ebml_binary(data, Media::Matroska::BLOCK_ID, block);
+ auto block_additions = begin_ebml_master(data, Media::Matroska::BLOCK_ADDITIONS_ID);
+ auto block_more = begin_ebml_master(data, Media::Matroska::BLOCK_MORE_ID);
+ if (defect == BlockAdditionsDefect::OversizedBlockAddID) {
+ append_ebml_id(data, Media::Matroska::BLOCK_ADD_ID_ID);
+ append_ebml_size(data, 9);
+ for (u8 byte : { 0, 0, 0, 0, 0, 0, 0, 0, 4 })
+ data.append(byte);
+ } else {
+ append_ebml_uint(data, Media::Matroska::BLOCK_ADD_ID_ID, 4);
+ }
+ if (defect == BlockAdditionsDefect::OversizedBlockAdditional) {
+ // The message still reads as HDR10+ with the padding after it.
+ ByteBuffer message;
+ message.append(HDR10_PLUS_T35_MESSAGE.span());
+ while (message.size() <= Media::Codecs::HDR10_PLUS_MAXIMUM_T35_MESSAGE_SIZE)
+ message.append(0);
+ append_ebml_id(data, Media::Matroska::BLOCK_ADDITIONAL_ID);
+ append_ebml_size(data, message.size(), 2);
+ data.append(message);
+ } else {
+ append_ebml_binary(data, Media::Matroska::BLOCK_ADDITIONAL_ID, HDR10_PLUS_T35_MESSAGE);
+ }
+ finish_ebml_master(data, block_more);
+ finish_ebml_master(data, block_additions);
+ finish_ebml_master(data, block_group);
+}
+
+TEST_CASE(malformed_block_additions_are_skipped_without_losing_their_block)
+{
+ auto data = make_matroska_with_av1_track(WithColorElement::No, [](ByteBuffer& data) {
+ append_block_group_with_hdr10_plus(data, 0, BlockAdditionsDefect::OversizedBlockAddID);
+ append_block_group_with_hdr10_plus(data, 33, BlockAdditionsDefect::None);
+ });
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
+ auto reader = MUST(Media::Matroska::Reader::from_stream(stream->create_cursor()));
+ auto iterator = MUST(reader.create_sample_iterator(stream->create_cursor(), 1));
+
+ auto first_block = MUST(iterator.next_block());
+ EXPECT_EQ(first_block.timestamp().value().to_milliseconds(), 0);
+ EXPECT(!first_block.maximum_scene_luminance().has_value());
+
+ auto second_block = MUST(iterator.next_block());
+ EXPECT_EQ(second_block.timestamp().value().to_milliseconds(), 33);
+ EXPECT(second_block.maximum_scene_luminance().has_value());
+ if (second_block.maximum_scene_luminance().has_value())
+ EXPECT_APPROXIMATE_WITH_ERROR(second_block.maximum_scene_luminance().value(), 364.1, 0.01);
+}
+
+TEST_CASE(block_additional_too_large_to_be_hdr10_plus_is_skipped)
+{
+ auto data = make_matroska_with_av1_track(WithColorElement::No, [](ByteBuffer& data) {
+ append_block_group_with_hdr10_plus(data, 0, BlockAdditionsDefect::OversizedBlockAdditional);
+ append_block_group_with_hdr10_plus(data, 33, BlockAdditionsDefect::None);
+ });
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(data);
+ auto reader = MUST(Media::Matroska::Reader::from_stream(stream->create_cursor()));
+ auto iterator = MUST(reader.create_sample_iterator(stream->create_cursor(), 1));
+
+ auto first_block = MUST(iterator.next_block());
+ EXPECT(!first_block.maximum_scene_luminance().has_value());
+ auto second_block = MUST(iterator.next_block());
+ EXPECT(second_block.maximum_scene_luminance().has_value());
+}
+
TEST_CASE(simple_block_extending_past_the_representable_size_is_corrupted)
{
// A SimpleBlock placed as high as a cursor can be seeked, whose declared size reaches past that.
diff --git a/Tests/LibMedia/TestRemoteVideoDecoder.cpp b/Tests/LibMedia/TestRemoteVideoDecoder.cpp
index 75795ce43d4..8d9a3ea1266 100644
--- a/Tests/LibMedia/TestRemoteVideoDecoder.cpp
+++ b/Tests/LibMedia/TestRemoteVideoDecoder.cpp
@@ -555,3 +555,58 @@ TEST_CASE(a_server_out_of_slots_is_waited_for_until_a_frame_is_released)
EXPECT(frame.value()->timestamp() > last_held_timestamp);
EXPECT_EQ(storage_freed_count, 1u);
}
+
+// The file was encoded from hevc_hdr10_plus_in_sei.mkv, so its frames carry the same HDR10+, in BlockAdditions.
+TEST_CASE(scene_peaks_from_the_container_reach_the_server_with_their_frames)
+{
+ ScenePeakChecker scene_peaks { hevc_hdr10_plus_in_sei_scene_peaks };
+ auto file = MUST(Core::File::open("./vp9_hdr10_plus_in_block_additions.webm"sv, Core::File::OpenMode::Read));
+ auto stream = Media::IncrementallyPopulatedStream::create_from_buffer(MUST(file->read_until_eof()));
+ NonnullRefPtr<Media::Demuxer> demuxer = MUST(Media::Matroska::MatroskaDemuxer::from_stream(stream));
+ auto track = MUST(demuxer->get_preferred_track_for_type(Media::TrackType::Video)).release_value();
+ TRY_OR_FAIL(demuxer->create_context_for_track(track));
+
+ Mutex wake_mutex;
+ ConditionVariable wake_condition { wake_mutex };
+ auto first_coded_frame = TRY_OR_FAIL(demuxer->get_next_sample_for_track(track));
+ auto decoder = TRY_OR_FAIL(Media::RemoteVideoDecoder::try_create(first_coded_frame.codec_id(), first_coded_frame.new_codec_configuration().value()));
+ decoder->set_decode_completed_callback([&](Media::DecodeCompletion) {
+ MutexLocker locker { wake_mutex };
+ wake_condition.broadcast();
+ });
+
+ TRY_OR_FAIL(decoder->receive_coded_data(first_coded_frame, Media::DecodeIntent::Output));
+ while (true) {
+ auto sample = demuxer->get_next_sample_for_track(track);
+ if (sample.is_error())
+ break;
+ TRY_OR_FAIL(decoder->receive_coded_data(sample.release_value(), Media::DecodeIntent::Output));
+ }
+ decoder->signal_end_of_stream();
+
+ size_t frame_count = 0;
+ auto reached_end_of_stream = false;
+ auto deadline = MonotonicTime::now() + AK::Duration::from_seconds(5);
+ while (MonotonicTime::now() < deadline) {
+ auto result = decoder->take_next_output({});
+ if (!result.is_error()) {
+ auto const& frame = result.value();
+ scene_peaks.check(frame->timestamp(), frame->color_metadata().maximum_scene_luminance);
+ frame_count++;
+ continue;
+ }
+ if (result.error().category() == Media::DecoderErrorCategory::EndOfStream) {
+ reached_end_of_stream = true;
+ break;
+ }
+ if (result.error().category() != Media::DecoderErrorCategory::NeedsMoreInput) {
+ FAIL(ByteString::formatted("Unexpected decoder error: {}", result.error().description()));
+ return;
+ }
+ MutexLocker locker { wake_mutex };
+ wake_condition.wait_for(AK::Duration::from_milliseconds(100));
+ }
+ EXPECT(reached_end_of_stream);
+ EXPECT_EQ(frame_count, hevc_hdr10_plus_in_sei_scene_peaks.size());
+ scene_peaks.expect_every_frame_checked();
+}
diff --git a/Tests/LibMedia/TestVP9Decode.cpp b/Tests/LibMedia/TestVP9Decode.cpp
index ee76920c3b2..f7abc27b45a 100644
--- a/Tests/LibMedia/TestVP9Decode.cpp
+++ b/Tests/LibMedia/TestVP9Decode.cpp
@@ -47,3 +47,49 @@ TEST_CASE(input_after_the_end_of_stream_is_rejected_until_flushed)
decoder->flush();
MUST(decoder->receive_coded_data(first_frame, Media::DecodeIntent::Output));
}
+
+// The file was encoded from hevc_hdr10_plus_in_sei.mkv, so its frames carry the same HDR10+, in BlockAdditions.
+TEST_CASE(frames_carry_their_own_hdr10_plus_scene_peaks_from_block_additions)
+{
+ ScenePeakChecker scene_peaks { hevc_hdr10_plus_in_sei_scene_peaks };
+ auto file = MUST(Core::File::open("./vp9_hdr10_plus_in_block_additions.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());
+ 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()));
+ MUST(decoder->receive_coded_data(first_frame, 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()) {
+ auto const& frame = *frame_result.value();
+ scene_peaks.check(frame.timestamp(), frame.color_metadata().maximum_scene_luminance);
+ frame_count++;
+ continue;
+ }
+ if (frame_result.error().category() == Media::DecoderErrorCategory::EndOfStream)
+ break;
+ if (frame_result.error().category() != Media::DecoderErrorCategory::NeedsMoreInput) {
+ FAIL(ByteString::formatted("Decoding failed: {}", frame_result.error().description()));
+ return;
+ }
+
+ 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;
+ }
+ decoder->signal_end_of_stream();
+ }
+ EXPECT_EQ(frame_count, hevc_hdr10_plus_in_sei_scene_peaks.size());
+ scene_peaks.expect_every_frame_checked();
+}
diff --git a/Tests/LibMedia/TestWebMByteStreamParser.cpp b/Tests/LibMedia/TestWebMByteStreamParser.cpp
new file mode 100644
index 00000000000..6a81c3e3780
--- /dev/null
+++ b/Tests/LibMedia/TestWebMByteStreamParser.cpp
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+#include <LibCore/File.h>
+#include <LibMedia/MediaSourceExtensions/WebMByteStreamParser.h>
+#include <LibMedia/ReadonlyBytesCursor.h>
+
+#include "TestMediaCommon.h"
+
+static Vector<Media::CodedFrame> parse_every_coded_frame(StringView path)
+{
+ auto file = MUST(Core::File::open(path, Core::File::OpenMode::Read));
+ auto data = MUST(file->read_until_eof());
+ auto cursor = adopt_ref(*new Media::ReadonlyBytesCursor(data.bytes()));
+ Media::MediaSourceExtensions::WebMByteStreamParser parser;
+
+ Vector<Media::CodedFrame> coded_frames;
+ while (true) {
+ // The segment parser loop waits for more data where the bytes run out.
+ if (auto skip_result = parser.skip_ignored_bytes(*cursor); skip_result.is_error()) {
+ EXPECT_EQ(skip_result.error().category(), Media::DecoderErrorCategory::EndOfStream);
+ return coded_frames;
+ }
+ if (cursor->position() >= data.size())
+ return coded_frames;
+
+ auto segment_type = MUST(parser.sniff_segment_type(*cursor));
+ if (segment_type == Media::MediaSourceExtensions::SegmentType::InitializationSegment) {
+ MUST(parser.parse_initialization_segment(*cursor));
+ continue;
+ }
+ VERIFY(segment_type == Media::MediaSourceExtensions::SegmentType::MediaSegment);
+ while (true) {
+ auto position = cursor->position();
+ auto result = MUST(parser.parse_media_segment(*cursor));
+ auto made_progress = !result.coded_frames.is_empty() || cursor->position() != position;
+ for (auto& demuxed_coded_frame : result.coded_frames)
+ coded_frames.append(move(demuxed_coded_frame.coded_frame));
+ if (result.completed_segment)
+ break;
+ // All of the file is already given to the parser, so a cluster it cannot finish will never finish.
+ if (!made_progress) {
+ FAIL("The file ends inside a cluster");
+ return coded_frames;
+ }
+ }
+ }
+}
+
+// The file was encoded from hevc_hdr10_plus_in_sei.mkv, so its frames carry the same HDR10+, in BlockAdditions.
+TEST_CASE(coded_frames_carry_the_hdr10_plus_scene_peaks_of_their_block_additions)
+{
+ ScenePeakChecker scene_peaks { hevc_hdr10_plus_in_sei_scene_peaks };
+ auto coded_frames = parse_every_coded_frame("./vp9_hdr10_plus_in_block_additions.webm"sv);
+ EXPECT_EQ(coded_frames.size(), hevc_hdr10_plus_in_sei_scene_peaks.size());
+ for (auto const& coded_frame : coded_frames)
+ scene_peaks.check(coded_frame.presentation_timestamp(), coded_frame.maximum_scene_luminance());
+ scene_peaks.expect_every_frame_checked();
+}
diff --git a/Tests/LibMedia/vp9_hdr10_plus_in_block_additions.webm b/Tests/LibMedia/vp9_hdr10_plus_in_block_additions.webm
new file mode 100644
index 00000000000..fc4e7570947
Binary files /dev/null and b/Tests/LibMedia/vp9_hdr10_plus_in_block_additions.webm differ