Skip to content

Truly independent web browser

LibGfx+LibMediaCodecs+Compositor+Tests: Support RGB video

Zaggy102416a4f1405869
diff --git a/Libraries/LibGfx/Rust/src/yuv.rs b/Libraries/LibGfx/Rust/src/yuv.rs
index df3ea4b9b41..f594f7998c2 100644
--- a/Libraries/LibGfx/Rust/src/yuv.rs
+++ b/Libraries/LibGfx/Rust/src/yuv.rs
@@ -194,13 +194,15 @@ fn biplanar_plane_length(stride: u32, row_length: usize, rows: usize) -> Option<
/// Each plane's last row may end without padding up to its stride.
/// `dst` must point to a buffer of at least `dst_stride * height` bytes.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn yuv_nv12_to_rgba(
+pub unsafe extern "C" fn yuv_biplanar_u8_to_rgba(
y_plane: *const u8,
y_stride: u32,
uv_plane: *const u8,
uv_stride: u32,
width: u32,
height: u32,
+ subsampling_x: bool,
+ subsampling_y: bool,
dst: *mut u8,
dst_stride: u32,
range: YUVRange,
@@ -209,8 +211,9 @@ pub unsafe extern "C" fn yuv_nv12_to_rgba(
let Some(y_len) = biplanar_plane_length(y_stride, width as usize, height as usize) else {
return false;
};
- let Some(uv_len) = biplanar_plane_length(uv_stride, width.div_ceil(2) as usize * 2, height.div_ceil(2) as usize)
- else {
+ let chroma_width = if subsampling_x { width.div_ceil(2) } else { width } as usize;
+ let chroma_height = if subsampling_y { height.div_ceil(2) } else { height } as usize;
+ let Some(uv_len) = biplanar_plane_length(uv_stride, chroma_width * 2, chroma_height) else {
return false;
};
@@ -226,7 +229,14 @@ pub unsafe extern "C" fn yuv_nv12_to_rgba(
let dst_len = dst_stride as usize * height as usize;
let dst_slice = unsafe { ak::slice_from_raw_parts_mut(dst, dst_len) };
- yuv::yuv_nv12_to_rgba(
+ let convert = match (subsampling_x, subsampling_y) {
+ (true, true) => yuv::yuv_nv12_to_rgba,
+ (true, false) => yuv::yuv_nv16_to_rgba,
+ (false, true) => return false,
+ (false, false) => yuv::yuv_nv24_to_rgba,
+ };
+
+ convert(
&bi_planar_image,
dst_slice,
dst_stride,
@@ -242,14 +252,17 @@ pub unsafe extern "C" fn yuv_nv12_to_rgba(
/// Strides are in components per row, not bytes.
/// Each plane's last row may end without padding up to its stride.
/// `dst` must point to a buffer of at least `dst_stride * height` bytes.
+/// Samples must sit in the high 10 bits of each u16.
#[unsafe(no_mangle)]
-pub unsafe extern "C" fn yuv_p010_to_rgba(
+pub unsafe extern "C" fn yuv_biplanar_u16_to_rgba(
y_plane: *const u16,
y_stride: u32,
uv_plane: *const u16,
uv_stride: u32,
width: u32,
height: u32,
+ subsampling_x: bool,
+ subsampling_y: bool,
dst: *mut u8,
dst_stride: u32,
range: YUVRange,
@@ -258,8 +271,9 @@ pub unsafe extern "C" fn yuv_p010_to_rgba(
let Some(y_len) = biplanar_plane_length(y_stride, width as usize, height as usize) else {
return false;
};
- let Some(uv_len) = biplanar_plane_length(uv_stride, width.div_ceil(2) as usize * 2, height.div_ceil(2) as usize)
- else {
+ let chroma_width = if subsampling_x { width.div_ceil(2) } else { width } as usize;
+ let chroma_height = if subsampling_y { height.div_ceil(2) } else { height } as usize;
+ let Some(uv_len) = biplanar_plane_length(uv_stride, chroma_width * 2, chroma_height) else {
return false;
};
@@ -275,7 +289,14 @@ pub unsafe extern "C" fn yuv_p010_to_rgba(
let dst_len = dst_stride as usize * height as usize;
let dst_slice = unsafe { ak::slice_from_raw_parts_mut(dst, dst_len) };
- yuv::p010_to_rgba(
+ let convert = match (subsampling_x, subsampling_y) {
+ (true, true) => yuv::p010_to_rgba,
+ (true, false) => yuv::p210_to_rgba,
+ (false, true) => return false,
+ (false, false) => yuv::p410_to_rgba,
+ };
+
+ convert(
&bi_planar_image,
dst_slice,
dst_stride,
diff --git a/Libraries/LibGfx/VideoSurfaceImage.h b/Libraries/LibGfx/VideoSurfaceImage.h
index b28906847dc..0f9faf1554c 100644
--- a/Libraries/LibGfx/VideoSurfaceImage.h
+++ b/Libraries/LibGfx/VideoSurfaceImage.h
@@ -11,15 +11,27 @@
#ifdef AK_OS_MACOS
# include <AK/Optional.h>
+# include <AK/Vector.h>
# include <LibCore/IOSurface.h>
# include <LibGfx/Forward.h>
# include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>
+# include <LibMediaCodecs/Subsampling.h>
namespace Gfx {
// The formats a platform decoder hands back hold luma alone in the first plane and the two chroma components
-// interleaved in the second. Returns the bit depth of a surface in one of these formats.
-Optional<u8> biplanar_bit_depth_for_pixel_format(u32 pixel_format);
+// interleaved in the second. An RGB picture is held in the same layout, with green as luma, then blue and red.
+struct BiplanarPixelFormat {
+ u32 pixel_format;
+ u8 bit_depth;
+ Media::Subsampling subsampling;
+ Media::VideoFullRangeFlag range;
+};
+
+Optional<BiplanarPixelFormat> biplanar_pixel_format(u32 pixel_format);
+
+// The formats that hold a picture of the given bit depth and subsampling, one per range. Empty if there are none.
+Vector<BiplanarPixelFormat, 2> biplanar_pixel_formats_holding(u8 bit_depth, Media::Subsampling);
ErrorOr<void> validate_biplanar_video_surface(Core::IOSurfaceHandle const&);
diff --git a/Libraries/LibGfx/VideoSurfaceImage.mm b/Libraries/LibGfx/VideoSurfaceImage.mm
index c1b9ee35452..7631d7485e4 100644
--- a/Libraries/LibGfx/VideoSurfaceImage.mm
+++ b/Libraries/LibGfx/VideoSurfaceImage.mm
@@ -16,24 +16,42 @@
namespace Gfx {
-Optional<u8> biplanar_bit_depth_for_pixel_format(u32 pixel_format)
+static constexpr Array biplanar_pixel_formats = {
+ BiplanarPixelFormat { kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, 8, Media::Subsampling::yuv420(), Media::VideoFullRangeFlag::Studio },
+ BiplanarPixelFormat { kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, 8, Media::Subsampling::yuv420(), Media::VideoFullRangeFlag::Full },
+ BiplanarPixelFormat { kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange, 10, Media::Subsampling::yuv420(), Media::VideoFullRangeFlag::Studio },
+ BiplanarPixelFormat { kCVPixelFormatType_420YpCbCr10BiPlanarFullRange, 10, Media::Subsampling::yuv420(), Media::VideoFullRangeFlag::Full },
+ BiplanarPixelFormat { kCVPixelFormatType_444YpCbCr8BiPlanarVideoRange, 8, Media::Subsampling::yuv444(), Media::VideoFullRangeFlag::Studio },
+ BiplanarPixelFormat { kCVPixelFormatType_444YpCbCr8BiPlanarFullRange, 8, Media::Subsampling::yuv444(), Media::VideoFullRangeFlag::Full },
+ BiplanarPixelFormat { kCVPixelFormatType_444YpCbCr10BiPlanarVideoRange, 10, Media::Subsampling::yuv444(), Media::VideoFullRangeFlag::Studio },
+ BiplanarPixelFormat { kCVPixelFormatType_444YpCbCr10BiPlanarFullRange, 10, Media::Subsampling::yuv444(), Media::VideoFullRangeFlag::Full },
+};
+
+Optional<BiplanarPixelFormat> biplanar_pixel_format(u32 pixel_format)
+{
+ for (auto const& format : biplanar_pixel_formats) {
+ if (format.pixel_format == pixel_format)
+ return format;
+ }
+ return {};
+}
+
+Vector<BiplanarPixelFormat, 2> biplanar_pixel_formats_holding(u8 bit_depth, Media::Subsampling subsampling)
{
- switch (pixel_format) {
- case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange:
- case kCVPixelFormatType_420YpCbCr8BiPlanarFullRange:
- return 8;
- case kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange:
- case kCVPixelFormatType_420YpCbCr10BiPlanarFullRange:
- return 10;
- default:
- return {};
+ // A picture deeper than any format is held in the deepest one.
+ auto format_bit_depth = bit_depth > 8 ? 10 : 8;
+ Vector<BiplanarPixelFormat, 2> formats;
+ for (auto const& format : biplanar_pixel_formats) {
+ if (format.bit_depth == format_bit_depth && format.subsampling == subsampling)
+ formats.append(format);
}
+ return formats;
}
ErrorOr<void> validate_biplanar_video_surface(Core::IOSurfaceHandle const& io_surface)
{
- auto bit_depth = biplanar_bit_depth_for_pixel_format(io_surface.pixel_format());
- if (!bit_depth.has_value() || io_surface.plane_count() != 2)
+ auto format = biplanar_pixel_format(io_surface.pixel_format());
+ if (!format.has_value() || io_surface.plane_count() != 2)
return Error::from_string_literal("Video surface is not in a supported bi-planar format");
auto width = io_surface.plane_width(0);
@@ -41,9 +59,10 @@ ErrorOr<void> validate_biplanar_video_surface(Core::IOSurfaceHandle const& io_su
if (width == 0 || height == 0 || width > Media::MAX_VIDEO_FRAME_DIMENSION || height > Media::MAX_VIDEO_FRAME_DIMENSION)
return Error::from_string_literal("Video surface has an unsupported size");
- size_t bytes_per_sample = *bit_depth > 8 ? 2 : 1;
- auto chroma_width = (width + 1) / 2;
- auto chroma_height = (height + 1) / 2;
+ size_t bytes_per_sample = format->bit_depth > 8 ? 2 : 1;
+ auto chroma_size = format->subsampling.subsampled_size(Size<size_t> { width, height });
+ auto chroma_width = chroma_size.width();
+ auto chroma_height = chroma_size.height();
struct PlaneExtent {
size_t width;
size_t height;
@@ -77,8 +96,8 @@ ErrorOr<void> validate_biplanar_video_surface(Core::IOSurfaceHandle const& io_su
ErrorOr<NonnullRefPtr<Bitmap>> bitmap_from_video_surface(Core::IOSurfaceHandle const& io_surface, Media::CodingIndependentCodePoints cicp)
{
- auto bit_depth = biplanar_bit_depth_for_pixel_format(io_surface.pixel_format());
- if (!bit_depth.has_value() || io_surface.plane_count() != 2)
+ auto format = biplanar_pixel_format(io_surface.pixel_format());
+ if (!format.has_value() || io_surface.plane_count() != 2)
return Error::from_string_literal("Unsupported video surface pixel format");
if (!io_surface.lock_read_only())
@@ -94,7 +113,7 @@ ErrorOr<NonnullRefPtr<Bitmap>> bitmap_from_video_surface(Core::IOSurfaceHandle c
};
IntSize size { static_cast<int>(io_surface.plane_width(0)), static_cast<int>(io_surface.plane_height(0)) };
- return biplanar_yuv_to_bitmap(size, *bit_depth, cicp, plane(0), plane(1));
+ return biplanar_yuv_to_bitmap(size, format->bit_depth, format->subsampling, cicp, plane(0), plane(1));
}
}
diff --git a/Libraries/LibGfx/YUVData.cpp b/Libraries/LibGfx/YUVData.cpp
index 34203009800..1ad247a44c7 100644
--- a/Libraries/LibGfx/YUVData.cpp
+++ b/Libraries/LibGfx/YUVData.cpp
@@ -92,6 +92,43 @@ static FFI::YUVMatrix yuv_matrix_for_cicp(Media::CodingIndependentCodePoints con
}
}
+// Where one of the components of an RGB picture lies, in a plane of its own or interleaved with another.
+struct RGBComponent {
+ u8 const* first_sample;
+ size_t row_stride;
+ size_t samples_per_pixel;
+};
+
+// Each stored sample holds padding_bit_count unused bits below its value.
+template<typename Sample>
+static void rgb_components_to_bitmap(Bitmap& bitmap, u8 bit_depth, u8 padding_bit_count, Media::VideoFullRangeFlag range, RGBComponent green, RGBComponent blue, RGBComponent red)
+{
+ auto bits_beyond_eight = max(bit_depth, 8) - 8;
+ // ITU-T H.273, 8.3: studio range RGB spans 16 to 235 at 8 bits, scaled up for deeper samples.
+ auto is_studio_range = range == Media::VideoFullRangeFlag::Studio;
+ u32 black = 16u << bits_beyond_eight;
+ u32 span = 219u << bits_beyond_eight;
+
+ auto size = bitmap.size();
+ for (int row = 0; row < size.height(); row++) {
+ auto* destination = bitmap.scanline_u8(row);
+ auto sample_at = [&](RGBComponent const& component, int column) -> u8 {
+ auto const* samples = reinterpret_cast<Sample const*>(component.first_sample + (static_cast<size_t>(row) * component.row_stride));
+ u32 sample = samples[static_cast<size_t>(column) * component.samples_per_pixel] >> padding_bit_count;
+ if (!is_studio_range)
+ return static_cast<u8>(sample >> bits_beyond_eight);
+ sample = clamp(sample, black, black + span) - black;
+ return static_cast<u8>(((sample * 255) + (span / 2)) / span);
+ };
+ for (int column = 0; column < size.width(); column++) {
+ destination[(column * 4) + 0] = sample_at(red, column);
+ destination[(column * 4) + 1] = sample_at(green, column);
+ destination[(column * 4) + 2] = sample_at(blue, column);
+ destination[(column * 4) + 3] = 255;
+ }
+ }
+}
+
ErrorOr<NonnullRefPtr<Bitmap>> YUVData::to_bitmap() const
{
VERIFY(m_bit_depth <= 12);
@@ -107,45 +144,18 @@ ErrorOr<NonnullRefPtr<Bitmap>> YUVData::to_bitmap() const
if (m_subsampling.x() || m_subsampling.y())
return Error::from_string_literal("Subsampled RGB is unsupported");
+ // The planes hold green, blue and red, in that order.
if (m_bit_depth <= 8) {
- auto const* y_data = m_y_data.data();
- auto const* u_data = m_u_data.data();
- auto const* v_data = m_v_data.data();
- auto y_stride = static_cast<int>(width);
-
- for (u32 row = 0; row < height; row++) {
- auto* dst_row = dst + (static_cast<size_t>(row) * dst_stride);
- auto const* y_row = y_data + (static_cast<size_t>(row) * y_stride);
- auto const* u_row = u_data + (static_cast<size_t>(row) * y_stride);
- auto const* v_row = v_data + (static_cast<size_t>(row) * y_stride);
- for (u32 col = 0; col < width; col++) {
- dst_row[(col * 4) + 0] = v_row[col];
- dst_row[(col * 4) + 1] = y_row[col];
- dst_row[(col * 4) + 2] = u_row[col];
- dst_row[(col * 4) + 3] = 255;
- }
- }
+ RGBComponent green { m_y_data.data(), width, 1 };
+ RGBComponent blue { m_u_data.data(), width, 1 };
+ RGBComponent red { m_v_data.data(), width, 1 };
+ rgb_components_to_bitmap<u8>(*bitmap, m_bit_depth, 0, m_cicp.video_full_range_flag(), green, blue, red);
} else {
- // Our buffers hold native N-bit values in the low bits of each u16; shift right to reduce
- // to 8-bit for the output.
- auto shift = m_bit_depth - 8;
- auto const* y_data = reinterpret_cast<u16 const*>(m_y_data.data());
- auto const* u_data = reinterpret_cast<u16 const*>(m_u_data.data());
- auto const* v_data = reinterpret_cast<u16 const*>(m_v_data.data());
- auto y_stride = static_cast<int>(width);
-
- for (u32 row = 0; row < height; row++) {
- auto* dst_row = dst + (static_cast<size_t>(row) * dst_stride);
- auto const* y_row = y_data + (static_cast<size_t>(row) * y_stride);
- auto const* u_row = u_data + (static_cast<size_t>(row) * y_stride);
- auto const* v_row = v_data + (static_cast<size_t>(row) * y_stride);
- for (u32 col = 0; col < width; col++) {
- dst_row[(col * 4) + 0] = static_cast<u8>(v_row[col] >> shift);
- dst_row[(col * 4) + 1] = static_cast<u8>(y_row[col] >> shift);
- dst_row[(col * 4) + 2] = static_cast<u8>(u_row[col] >> shift);
- dst_row[(col * 4) + 3] = 255;
- }
- }
+ auto row_stride = width * sizeof(u16);
+ RGBComponent green { m_y_data.data(), row_stride, 1 };
+ RGBComponent blue { m_u_data.data(), row_stride, 1 };
+ RGBComponent red { m_v_data.data(), row_stride, 1 };
+ rgb_components_to_bitmap<u16>(*bitmap, m_bit_depth, 0, m_cicp.video_full_range_flag(), green, blue, red);
}
return bitmap;
@@ -188,9 +198,10 @@ ErrorOr<NonnullRefPtr<Bitmap>> YUVData::to_bitmap() const
return bitmap;
}
-ErrorOr<NonnullRefPtr<Bitmap>> biplanar_yuv_to_bitmap(IntSize size, u8 bit_depth, Media::CodingIndependentCodePoints cicp, BiplanarYUVPlane luma, BiplanarYUVPlane chroma)
+ErrorOr<NonnullRefPtr<Bitmap>> biplanar_yuv_to_bitmap(IntSize size, u8 bit_depth, Media::Subsampling subsampling, Media::CodingIndependentCodePoints cicp, BiplanarYUVPlane luma, BiplanarYUVPlane chroma)
{
- if (cicp.matrix_coefficients() == Media::MatrixCoefficients::Identity)
+ auto is_rgb = cicp.matrix_coefficients() == Media::MatrixCoefficients::Identity;
+ if (is_rgb && subsampling != Media::Subsampling::yuv444())
return Error::from_string_literal("Subsampled RGB is unsupported");
if (size.is_empty())
return Error::from_string_literal("Bi-planar YUV size is empty");
@@ -204,8 +215,9 @@ ErrorOr<NonnullRefPtr<Bitmap>> biplanar_yuv_to_bitmap(IntSize size, u8 bit_depth
required_size += row_byte_count;
return !required_size.has_overflow() && plane.data.size() >= required_size.value();
};
- auto chroma_width = (static_cast<size_t>(size.width()) + 1) / 2;
- auto chroma_height = (static_cast<size_t>(size.height()) + 1) / 2;
+ auto chroma_size = subsampling.subsampled_size(size.to_type<size_t>());
+ auto chroma_width = chroma_size.width();
+ auto chroma_height = chroma_size.height();
if (!plane_covers_rows(luma, size.width() * bytes_per_sample, size.height()) || !plane_covers_rows(chroma, chroma_width * 2 * bytes_per_sample, chroma_height))
return Error::from_string_literal("Bi-planar YUV planes are smaller than their size requires");
@@ -216,23 +228,37 @@ ErrorOr<NonnullRefPtr<Bitmap>> biplanar_yuv_to_bitmap(IntSize size, u8 bit_depth
auto width = static_cast<u32>(size.width());
auto height = static_cast<u32>(size.height());
+ if (is_rgb) {
+ // The luma plane holds green, and the chroma plane holds blue and red in that order.
+ RGBComponent green { luma.data.data(), luma.stride, 1 };
+ RGBComponent blue { chroma.data.data(), chroma.stride, 2 };
+ RGBComponent red { chroma.data.data() + bytes_per_sample, chroma.stride, 2 };
+ if (bytes_per_sample == 1)
+ rgb_components_to_bitmap<u8>(*bitmap, bit_depth, 0, cicp.video_full_range_flag(), green, blue, red);
+ else
+ rgb_components_to_bitmap<u16>(*bitmap, bit_depth, 16 - bit_depth, cicp.video_full_range_flag(), green, blue, red);
+ return bitmap;
+ }
+
bool full_range = cicp.video_full_range_flag() == Media::VideoFullRangeFlag::Full;
auto range = full_range ? FFI::YUVRange::Full : FFI::YUVRange::Limited;
auto matrix = yuv_matrix_for_cicp(cicp);
bool success;
if (bit_depth <= 8) {
- success = FFI::yuv_nv12_to_rgba(
+ success = FFI::yuv_biplanar_u8_to_rgba(
luma.data.data(), static_cast<u32>(luma.stride),
chroma.data.data(), static_cast<u32>(chroma.stride),
width, height,
+ subsampling.x(), subsampling.y(),
destination, destination_stride,
range, matrix);
} else {
- success = FFI::yuv_p010_to_rgba(
+ success = FFI::yuv_biplanar_u16_to_rgba(
reinterpret_cast<u16 const*>(luma.data.data()), static_cast<u32>(luma.stride / sizeof(u16)),
reinterpret_cast<u16 const*>(chroma.data.data()), static_cast<u32>(chroma.stride / sizeof(u16)),
width, height,
+ subsampling.x(), subsampling.y(),
destination, destination_stride,
range, matrix);
}
diff --git a/Libraries/LibGfx/YUVData.h b/Libraries/LibGfx/YUVData.h
index e7251d7c758..139658018e8 100644
--- a/Libraries/LibGfx/YUVData.h
+++ b/Libraries/LibGfx/YUVData.h
@@ -64,7 +64,8 @@ struct BiplanarYUVPlane {
size_t stride;
};
-// Converts NV12 pixels, or P010 for bit depths above 8, the 4:2:0 layouts hardware decoders hand back.
-ErrorOr<NonnullRefPtr<Bitmap>> biplanar_yuv_to_bitmap(IntSize, u8 bit_depth, Media::CodingIndependentCodePoints, BiplanarYUVPlane luma, BiplanarYUVPlane chroma);
+// Converts the bi-planar layouts hardware decoders hand back, such as NV12, or P010 for bit depths above 8. Samples deeper
+// than 8 bits sit in the high bits of each 16-bit component.
+ErrorOr<NonnullRefPtr<Bitmap>> biplanar_yuv_to_bitmap(IntSize, u8 bit_depth, Media::Subsampling, Media::CodingIndependentCodePoints, BiplanarYUVPlane luma, BiplanarYUVPlane chroma);
}
diff --git a/Libraries/LibMediaCodecs/Codecs/H264.cpp b/Libraries/LibMediaCodecs/Codecs/H264.cpp
index b0e6e0ba107..01aac3cd2ae 100644
--- a/Libraries/LibMediaCodecs/Codecs/H264.cpp
+++ b/Libraries/LibMediaCodecs/Codecs/H264.cpp
@@ -104,10 +104,16 @@ static void skip_hrd_parameters(Codecs::RBSPBitReader& reader)
static constexpr u8 MAXIMUM_REORDER_FRAME_COUNT = 16;
+struct VideoUsabilityInformation {
+ CodingIndependentCodePoints cicp;
+ Optional<u32> stated_max_reorder_frame_count;
+};
+
// ITU-T H.264 (08/2024), E.1.1: vui_parameters(), through max_num_reorder_frames.
-// Returns the max_num_reorder_frames the bitstream restriction states, if it states one at all.
-static Optional<u32> parse_stated_max_reorder_frame_count(Codecs::RBSPBitReader& reader)
+static VideoUsabilityInformation parse_video_usability_information(Codecs::RBSPBitReader& reader)
{
+ VideoUsabilityInformation information;
+
static constexpr u8 EXTENDED_SAMPLE_ASPECT_RATIO = 255;
if (reader.read_bit()) { // aspect_ratio_info_present_flag
@@ -117,15 +123,16 @@ static Optional<u32> parse_stated_max_reorder_frame_count(Codecs::RBSPBitReader&
reader.skip_bits(16); // sar_height
}
}
- if (reader.read_bit()) // overscan_info_present_flag
- reader.skip_bits(1); // overscan_appropriate_flag
- if (reader.read_bit()) { // video_signal_type_present_flag
- reader.skip_bits(3); // video_format
- reader.skip_bits(1); // video_full_range_flag
+ if (reader.read_bit()) // overscan_info_present_flag
+ reader.skip_bits(1); // overscan_appropriate_flag
+ if (reader.read_bit()) { // video_signal_type_present_flag
+ reader.skip_bits(3); // video_format
+ auto video_full_range_flag = reader.read_bit();
+ information.cicp.set_video_full_range_flag(video_full_range_flag ? VideoFullRangeFlag::Full : VideoFullRangeFlag::Studio);
if (reader.read_bit()) { // colour_description_present_flag
- reader.skip_bits(8); // colour_primaries
- reader.skip_bits(8); // transfer_characteristics
- reader.skip_bits(8); // matrix_coefficients
+ information.cicp.set_color_primaries(static_cast<ColorPrimaries>(reader.read_bits<u8>(8)));
+ information.cicp.set_transfer_characteristics(static_cast<TransferCharacteristics>(reader.read_bits<u8>(8)));
+ information.cicp.set_matrix_coefficients(static_cast<MatrixCoefficients>(reader.read_bits<u8>(8)));
}
}
if (reader.read_bit()) { // chroma_loc_info_present_flag
@@ -149,13 +156,14 @@ static Optional<u32> parse_stated_max_reorder_frame_count(Codecs::RBSPBitReader&
reader.skip_bits(1); // pic_struct_present_flag
if (!reader.read_bit()) // bitstream_restriction_flag
- return {};
- reader.skip_bits(1); // motion_vectors_over_pic_boundaries_flag
- reader.read_unsigned_exp_golomb(); // max_bytes_per_pic_denom
- reader.read_unsigned_exp_golomb(); // max_bits_per_mb_denom
- reader.read_unsigned_exp_golomb(); // log2_max_mv_length_horizontal
- reader.read_unsigned_exp_golomb(); // log2_max_mv_length_vertical
- return reader.read_unsigned_exp_golomb(); // max_num_reorder_frames
+ return information;
+ reader.skip_bits(1); // motion_vectors_over_pic_boundaries_flag
+ reader.read_unsigned_exp_golomb(); // max_bytes_per_pic_denom
+ reader.read_unsigned_exp_golomb(); // max_bits_per_mb_denom
+ reader.read_unsigned_exp_golomb(); // log2_max_mv_length_horizontal
+ reader.read_unsigned_exp_golomb(); // log2_max_mv_length_vertical
+ information.stated_max_reorder_frame_count = reader.read_unsigned_exp_golomb(); // max_num_reorder_frames
+ return information;
}
static u8 max_reorder_frame_count_for_level(u8 level_idc, u32 macroblocks_per_frame)
@@ -309,9 +317,10 @@ Optional<H264::SequenceParameterSet> H264::parse_sequence_parameter_set(Readonly
reader.read_unsigned_exp_golomb(); // frame_crop_bottom_offset
}
- Optional<u32> stated_count;
+ VideoUsabilityInformation video_usability_information;
if (reader.read_bit()) // vui_parameters_present_flag
- stated_count = parse_stated_max_reorder_frame_count(reader);
+ video_usability_information = parse_video_usability_information(reader);
+ auto stated_count = video_usability_information.stated_max_reorder_frame_count;
// ITU-T H.264 (08/2024), 7.4.2.1.1: chroma_format_idc is in 0 to 3, bit_depth_luma_minus8 in 0 to 6.
if (reader.has_overrun() || chroma_format_idc > 3 || bit_depth_luma_minus8 > 6)
@@ -324,6 +333,7 @@ Optional<H264::SequenceParameterSet> H264::parse_sequence_parameter_set(Readonly
.profile_idc = profile_idc,
.chroma_format_idc = static_cast<u8>(chroma_format_idc),
.bit_depth_luma = static_cast<u8>(bit_depth_luma_minus8 + 8),
+ .cicp = video_usability_information.cicp,
};
if (stated_count.has_value()) {
parameter_set.max_num_reorder_frames = static_cast<u8>(min(*stated_count, static_cast<u32>(MAXIMUM_REORDER_FRAME_COUNT)));
diff --git a/Libraries/LibMediaCodecs/Codecs/H264.h b/Libraries/LibMediaCodecs/Codecs/H264.h
index ee9ddb75169..15ae76d72ab 100644
--- a/Libraries/LibMediaCodecs/Codecs/H264.h
+++ b/Libraries/LibMediaCodecs/Codecs/H264.h
@@ -68,6 +68,7 @@ public:
u8 profile_idc { 0 };
u8 chroma_format_idc { 1 };
u8 bit_depth_luma { 8 };
+ CodingIndependentCodePoints cicp;
};
struct PictureParameterSet {
diff --git a/Libraries/LibMediaCodecs/Codecs/H265.cpp b/Libraries/LibMediaCodecs/Codecs/H265.cpp
index 984fd085298..f5110e8ec40 100644
--- a/Libraries/LibMediaCodecs/Codecs/H265.cpp
+++ b/Libraries/LibMediaCodecs/Codecs/H265.cpp
@@ -263,7 +263,201 @@ Optional<H265::VideoParameterSet> H265::parse_video_parameter_set(ReadonlyBytes
return VideoParameterSet { .vps_video_parameter_set_id = vps_video_parameter_set_id };
}
-// ITU-T H.265 (07/2024), 7.3.2.2.1: seq_parameter_set_rbsp(), through the sub-layer ordering information.
+// ITU-T H.265 (07/2024), 7.3.4: scaling_list_data()
+static void skip_scaling_list_data(RBSPBitReader& reader)
+{
+ for (u32 size_id = 0; size_id < 4; size_id++) {
+ for (u32 matrix_id = 0; matrix_id < 6; matrix_id += size_id == 3 ? 3 : 1) {
+ auto scaling_list_pred_mode_flag = reader.read_bit();
+ if (!scaling_list_pred_mode_flag) {
+ reader.read_unsigned_exp_golomb(); // scaling_list_pred_matrix_id_delta
+ continue;
+ }
+ auto coefficient_count = min(64u, 1u << (4 + (size_id << 1)));
+ if (size_id > 1)
+ reader.read_signed_exp_golomb(); // scaling_list_dc_coef_minus8
+ for (u32 index = 0; index < coefficient_count; index++)
+ reader.read_signed_exp_golomb(); // scaling_list_delta_coef
+ }
+ }
+}
+
+static constexpr u32 MAXIMUM_SHORT_TERM_REFERENCE_PICTURE_SET_COUNT = 64;
+static constexpr u32 MAXIMUM_DECODED_PICTURE_BUFFER_SIZE = 16;
+
+struct ShortTermReferencePictureSet {
+ Vector<i32, MAXIMUM_DECODED_PICTURE_BUFFER_SIZE> negative_picture_order_count_deltas;
+ Vector<i32, MAXIMUM_DECODED_PICTURE_BUFFER_SIZE> positive_picture_order_count_deltas;
+};
+
+// ITU-T H.265 (07/2024), 7.3.7: st_ref_pic_set(stRpsIdx), as it appears in a sequence parameter set.
+// Only the picture order count deltas are kept, since a later set can be predicted from them.
+static Optional<ShortTermReferencePictureSet> parse_short_term_reference_picture_set(RBSPBitReader& reader, ReadonlySpan<ShortTermReferencePictureSet> previous_sets)
+{
+ ShortTermReferencePictureSet result;
+
+ auto inter_ref_pic_set_prediction_flag = !previous_sets.is_empty() && reader.read_bit();
+ if (inter_ref_pic_set_prediction_flag) {
+ auto delta_rps_sign = reader.read_bit();
+ auto abs_delta_rps_minus1 = reader.read_unsigned_exp_golomb();
+ // ITU-T H.265 (07/2024), 7.4.8: abs_delta_rps_minus1 is in 0 to 2^15 - 1.
+ if (reader.has_overrun() || abs_delta_rps_minus1 > 0x7FFF)
+ return {};
+ // In a sequence parameter set, delta_idx_minus1 is absent and inferred to be 0, so the set predicts from the
+ // one before it.
+ auto const& reference = previous_sets.last();
+ auto delta_rps = (1 - 2 * static_cast<i32>(delta_rps_sign)) * static_cast<i32>(abs_delta_rps_minus1 + 1);
+
+ auto reference_negative_count = reference.negative_picture_order_count_deltas.size();
+ auto reference_positive_count = reference.positive_picture_order_count_deltas.size();
+ auto reference_delta_count = reference_negative_count + reference_positive_count;
+ Vector<bool, MAXIMUM_DECODED_PICTURE_BUFFER_SIZE + 1> use_delta_flags;
+ for (size_t j = 0; j <= reference_delta_count; j++) {
+ auto used_by_curr_pic_flag = reader.read_bit();
+ // When use_delta_flag[ j ] is not present, its value is inferred to be equal to 1.
+ auto use_delta_flag = used_by_curr_pic_flag || reader.read_bit();
+ use_delta_flags.append(use_delta_flag);
+ }
+
+ // ITU-T H.265 (07/2024), 7.4.8: the derivation of DeltaPocS0 and DeltaPocS1 for a predicted set.
+ auto& negative = result.negative_picture_order_count_deltas;
+ auto& positive = result.positive_picture_order_count_deltas;
+ auto append_if_room = [](auto& deltas, i32 delta) {
+ if (deltas.size() >= MAXIMUM_DECODED_PICTURE_BUFFER_SIZE)
+ return false;
+ deltas.append(delta);
+ return true;
+ };
+ for (auto j = static_cast<ssize_t>(reference_positive_count) - 1; j >= 0; j--) {
+ auto delta = reference.positive_picture_order_count_deltas[j] + delta_rps;
+ if (delta < 0 && use_delta_flags[reference_negative_count + j] && !append_if_room(negative, delta))
+ return {};
+ }
+ if (delta_rps < 0 && use_delta_flags[reference_delta_count] && !append_if_room(negative, delta_rps))
+ return {};
+ for (size_t j = 0; j < reference_negative_count; j++) {
+ auto delta = reference.negative_picture_order_count_deltas[j] + delta_rps;
+ if (delta < 0 && use_delta_flags[j] && !append_if_room(negative, delta))
+ return {};
+ }
+
+ for (auto j = static_cast<ssize_t>(reference_negative_count) - 1; j >= 0; j--) {
+ auto delta = reference.negative_picture_order_count_deltas[j] + delta_rps;
+ if (delta > 0 && use_delta_flags[j] && !append_if_room(positive, delta))
+ return {};
+ }
+ if (delta_rps > 0 && use_delta_flags[reference_delta_count] && !append_if_room(positive, delta_rps))
+ return {};
+ for (size_t j = 0; j < reference_positive_count; j++) {
+ auto delta = reference.positive_picture_order_count_deltas[j] + delta_rps;
+ if (delta > 0 && use_delta_flags[reference_negative_count + j] && !append_if_room(positive, delta))
+ return {};
+ }
+ return result;
+ }
+
+ auto num_negative_pics = reader.read_unsigned_exp_golomb();
+ auto num_positive_pics = reader.read_unsigned_exp_golomb();
+ if (reader.has_overrun() || num_negative_pics > MAXIMUM_DECODED_PICTURE_BUFFER_SIZE || num_positive_pics > MAXIMUM_DECODED_PICTURE_BUFFER_SIZE - num_negative_pics)
+ return {};
+ // ITU-T H.265 (07/2024), 7.4.8: the derivation of DeltaPocS0 and DeltaPocS1 for an explicit set.
+ i32 picture_order_count = 0;
+ for (u32 index = 0; index < num_negative_pics; index++) {
+ auto delta_poc_s0_minus1 = reader.read_unsigned_exp_golomb();
+ reader.skip_bits(1); // used_by_curr_pic_s0_flag
+ if (reader.has_overrun() || delta_poc_s0_minus1 > 0x7FFF)
+ return {};
+ picture_order_count -= static_cast<i32>(delta_poc_s0_minus1 + 1);
+ result.negative_picture_order_count_deltas.append(picture_order_count);
+ }
+ picture_order_count = 0;
+ for (u32 index = 0; index < num_positive_pics; index++) {
+ auto delta_poc_s1_minus1 = reader.read_unsigned_exp_golomb();
+ reader.skip_bits(1); // used_by_curr_pic_s1_flag
+ if (reader.has_overrun() || delta_poc_s1_minus1 > 0x7FFF)
+ return {};
+ picture_order_count += static_cast<i32>(delta_poc_s1_minus1 + 1);
+ result.positive_picture_order_count_deltas.append(picture_order_count);
+ }
+ return result;
+}
+
+// ITU-T H.265 (07/2024), 7.3.2.2.1: seq_parameter_set_rbsp(), from log2_min_luma_coding_block_size_minus3 through the
+// colour description in vui_parameters(). Returns the colour description, if the sequence parameter set states one.
+static Optional<CodingIndependentCodePoints> parse_sequence_parameter_set_colour_description(RBSPBitReader& reader, u32 log2_max_pic_order_cnt_lsb_minus4)
+{
+ reader.read_unsigned_exp_golomb(); // log2_min_luma_coding_block_size_minus3
+ reader.read_unsigned_exp_golomb(); // log2_diff_max_min_luma_coding_block_size
+ reader.read_unsigned_exp_golomb(); // log2_min_luma_transform_block_size_minus2
+ reader.read_unsigned_exp_golomb(); // log2_diff_max_min_luma_transform_block_size
+ reader.read_unsigned_exp_golomb(); // max_transform_hierarchy_depth_inter
+ reader.read_unsigned_exp_golomb(); // max_transform_hierarchy_depth_intra
+ if (reader.read_bit()) { // scaling_list_enabled_flag
+ if (reader.read_bit()) // sps_scaling_list_data_present_flag
+ skip_scaling_list_data(reader);
+ }
+ reader.skip_bits(1); // amp_enabled_flag
+ reader.skip_bits(1); // sample_adaptive_offset_enabled_flag
+ if (reader.read_bit()) { // pcm_enabled_flag
+ reader.skip_bits(4); // pcm_sample_bit_depth_luma_minus1
+ reader.skip_bits(4); // pcm_sample_bit_depth_chroma_minus1
+ reader.read_unsigned_exp_golomb(); // log2_min_pcm_luma_coding_block_size_minus3
+ reader.read_unsigned_exp_golomb(); // log2_diff_max_min_pcm_luma_coding_block_size
+ reader.skip_bits(1); // pcm_loop_filter_disabled_flag
+ }
+
+ auto num_short_term_ref_pic_sets = reader.read_unsigned_exp_golomb();
+ if (reader.has_overrun() || num_short_term_ref_pic_sets > MAXIMUM_SHORT_TERM_REFERENCE_PICTURE_SET_COUNT)
+ return {};
+ Vector<ShortTermReferencePictureSet> short_term_reference_picture_sets;
+ for (u32 index = 0; index < num_short_term_ref_pic_sets; index++) {
+ auto set = parse_short_term_reference_picture_set(reader, short_term_reference_picture_sets);
+ if (!set.has_value())
+ return {};
+ short_term_reference_picture_sets.append(set.release_value());
+ }
+
+ if (reader.read_bit()) { // long_term_ref_pics_present_flag
+ auto num_long_term_ref_pics_sps = reader.read_unsigned_exp_golomb();
+ // ITU-T H.265 (07/2024), 7.4.3.2.1: num_long_term_ref_pics_sps is in 0 to 32.
+ if (reader.has_overrun() || num_long_term_ref_pics_sps > 32)
+ return {};
+ for (u32 index = 0; index < num_long_term_ref_pics_sps; index++) {
+ reader.skip_bits(log2_max_pic_order_cnt_lsb_minus4 + 4); // lt_ref_pic_poc_lsb_sps
+ reader.skip_bits(1); // used_by_curr_pic_lt_sps_flag
+ }
+ }
+ reader.skip_bits(1); // sps_temporal_mvp_enabled_flag
+ reader.skip_bits(1); // strong_intra_smoothing_enabled_flag
+ if (!reader.read_bit()) // vui_parameters_present_flag
+ return {};
+
+ // ITU-T H.265 (07/2024), E.2.1: vui_parameters(), through matrix_coeffs.
+ static constexpr u8 EXTENDED_SAMPLE_ASPECT_RATIO = 255;
+ if (reader.read_bit()) { // aspect_ratio_info_present_flag
+ if (reader.read_bits<u8>(8) == EXTENDED_SAMPLE_ASPECT_RATIO) {
+ reader.skip_bits(16); // sar_width
+ reader.skip_bits(16); // sar_height
+ }
+ }
+ if (reader.read_bit()) // overscan_info_present_flag
+ reader.skip_bits(1); // overscan_appropriate_flag
+ if (!reader.read_bit()) // video_signal_type_present_flag
+ return {};
+ reader.skip_bits(3); // video_format
+ CodingIndependentCodePoints cicp;
+ cicp.set_video_full_range_flag(reader.read_bit() ? VideoFullRangeFlag::Full : VideoFullRangeFlag::Studio);
+ if (reader.read_bit()) { // colour_description_present_flag
+ cicp.set_color_primaries(static_cast<ColorPrimaries>(reader.read_bits<u8>(8)));
+ cicp.set_transfer_characteristics(static_cast<TransferCharacteristics>(reader.read_bits<u8>(8)));
+ cicp.set_matrix_coefficients(static_cast<MatrixCoefficients>(reader.read_bits<u8>(8)));
+ }
+ if (reader.has_overrun())
+ return {};
+ return cicp;
+}
+
+// ITU-T H.265 (07/2024), 7.3.2.2.1: seq_parameter_set_rbsp(), through the colour description in vui_parameters().
Optional<H265::SequenceParameterSet> H265::parse_sequence_parameter_set(ReadonlyBytes nal_unit)
{
auto header = parse_nal_unit_header(nal_unit);
@@ -294,7 +488,7 @@ Optional<H265::SequenceParameterSet> H265::parse_sequence_parameter_set(Readonly
}
auto bit_depth_luma_minus8 = reader.read_unsigned_exp_golomb();
reader.read_unsigned_exp_golomb(); // bit_depth_chroma_minus8
- reader.read_unsigned_exp_golomb(); // log2_max_pic_order_cnt_lsb_minus4
+ auto log2_max_pic_order_cnt_lsb_minus4 = reader.read_unsigned_exp_golomb();
// ITU-T H.265 (07/2024), 7.4.3.2.1: the counts absent below the highest sub-layer are inferred from it, so the
// last one coded is the one that bounds the whole stream.
@@ -306,18 +500,25 @@ Optional<H265::SequenceParameterSet> H265::parse_sequence_parameter_set(Readonly
reader.read_unsigned_exp_golomb(); // sps_max_latency_increase_plus1
}
- // ITU-T H.265 (07/2024), 7.4.3.2.1: sps_seq_parameter_set_id is in 0 to 15, bit_depth_luma_minus8 in 0 to 8.
- if (reader.has_overrun() || sps_seq_parameter_set_id > 15 || bit_depth_luma_minus8 > 8)
+ // ITU-T H.265 (07/2024), 7.4.3.2.1: sps_seq_parameter_set_id is in 0 to 15, chroma_format_idc in 0 to 3,
+ // bit_depth_luma_minus8 in 0 to 8, and log2_max_pic_order_cnt_lsb_minus4 in 0 to 12.
+ if (reader.has_overrun() || sps_seq_parameter_set_id > 15 || chroma_format_idc > 3 || bit_depth_luma_minus8 > 8 || log2_max_pic_order_cnt_lsb_minus4 > 12)
return {};
+ // The fields up to here are all a decoder needs to be configured, so a colour description that cannot be read is
+ // left unspecified rather than failing the whole set.
+ auto cicp = parse_sequence_parameter_set_colour_description(reader, log2_max_pic_order_cnt_lsb_minus4).value_or({});
+
return SequenceParameterSet {
.sps_seq_parameter_set_id = static_cast<u8>(sps_seq_parameter_set_id),
.sps_video_parameter_set_id = sps_video_parameter_set_id,
.sps_max_sub_layers_minus1 = sps_max_sub_layers_minus1,
.sps_max_num_reorder_pics = static_cast<u8>(min(sps_max_num_reorder_pics, static_cast<u32>(MAXIMUM_REORDER_FRAME_COUNT))),
+ .chroma_format_idc = static_cast<u8>(chroma_format_idc),
.bit_depth_luma = static_cast<u8>(bit_depth_luma_minus8 + 8),
.pic_width_in_luma_samples = pic_width_in_luma_samples,
.pic_height_in_luma_samples = pic_height_in_luma_samples,
+ .cicp = cicp,
};
}
diff --git a/Libraries/LibMediaCodecs/Codecs/H265.h b/Libraries/LibMediaCodecs/Codecs/H265.h
index 34e6bec0a7d..b5e13ff0ce1 100644
--- a/Libraries/LibMediaCodecs/Codecs/H265.h
+++ b/Libraries/LibMediaCodecs/Codecs/H265.h
@@ -78,9 +78,11 @@ public:
u8 sps_video_parameter_set_id;
u8 sps_max_sub_layers_minus1;
u8 sps_max_num_reorder_pics;
+ u8 chroma_format_idc;
u8 bit_depth_luma;
u32 pic_width_in_luma_samples;
u32 pic_height_in_luma_samples;
+ CodingIndependentCodePoints cicp;
};
struct PictureParameterSet {
diff --git a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
index 48cb90829de..1d35c24f0b5 100644
--- a/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
+++ b/Libraries/LibMediaCodecs/FFmpeg/FFmpegVideoDecoder.cpp
@@ -155,14 +155,17 @@ DecoderErrorOr<NonnullRefPtr<VideoFrame>> FFmpegVideoDecoder::take_next_output(C
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUVJ444P:
+ case AV_PIX_FMT_GBRP:
return 8;
case AV_PIX_FMT_YUV420P10:
case AV_PIX_FMT_YUV422P10:
case AV_PIX_FMT_YUV444P10:
+ case AV_PIX_FMT_GBRP10:
return 10;
case AV_PIX_FMT_YUV420P12:
case AV_PIX_FMT_YUV422P12:
case AV_PIX_FMT_YUV444P12:
+ case AV_PIX_FMT_GBRP12:
return 12;
default:
return {};
diff --git a/Libraries/LibMediaCodecs/VideoFrame.cpp b/Libraries/LibMediaCodecs/VideoFrame.cpp
index 2b53e55fbf9..034874f999f 100644
--- a/Libraries/LibMediaCodecs/VideoFrame.cpp
+++ b/Libraries/LibMediaCodecs/VideoFrame.cpp
@@ -36,6 +36,9 @@ VideoFrame::VideoFrame(
, m_color_metadata(move(color_metadata))
, m_storage(move(storage))
{
+ // Only a picture without chroma subsampling can hold RGB, so an identity matrix on any other is a mislabel.
+ if (m_color_metadata.cicp.matrix_coefficients() == MatrixCoefficients::Identity && m_subsampling != Subsampling::yuv444())
+ m_color_metadata.cicp.set_matrix_coefficients(MatrixCoefficients::Unspecified);
}
VideoFrame::~VideoFrame() = default;
diff --git a/Libraries/LibMediaCodecs/VideoFrameMetadata.cpp b/Libraries/LibMediaCodecs/VideoFrameMetadata.cpp
index 3beb850f514..64c47dc7398 100644
--- a/Libraries/LibMediaCodecs/VideoFrameMetadata.cpp
+++ b/Libraries/LibMediaCodecs/VideoFrameMetadata.cpp
@@ -51,6 +51,9 @@ bool VideoFrameMetadata::is_valid() const
return false;
if (video_frame_exceeds_limits(size.width(), size.height()))
return false;
+ // No frame is made with an identity matrix on subsampled planes.
+ if (color_metadata.cicp.matrix_coefficients() == MatrixCoefficients::Identity && subsampling != Subsampling::yuv444())
+ return false;
return color_metadata.cicp.is_valid_or_unspecified();
}
diff --git a/Libraries/LibMediaCodecs/VideoFramePool.cpp b/Libraries/LibMediaCodecs/VideoFramePool.cpp
index dfe8c55c279..3f1fdda8f6b 100644
--- a/Libraries/LibMediaCodecs/VideoFramePool.cpp
+++ b/Libraries/LibMediaCodecs/VideoFramePool.cpp
@@ -254,7 +254,7 @@ ErrorOr<NonnullRefPtr<VideoFrame>> create_received_video_frame(VideoFrameMetadat
if (auto surface = storage->surface()) {
auto surface_size = surface->size();
- if (metadata.subsampling != Subsampling::yuv420() || metadata.size.width() > surface_size.width() || metadata.size.height() > surface_size.height())
+ if (metadata.subsampling != surface->subsampling() || metadata.size.width() > surface_size.width() || metadata.size.height() > surface_size.height())
return Error::from_string_literal("Video frame metadata does not match its surface");
} else {
TRY(yuv_data_in_buffer(storage->pixel_buffer(), metadata.size, metadata.bit_depth, metadata.subsampling, metadata.color_metadata.cicp));
diff --git a/Libraries/LibMediaCodecs/VideoSurface.cpp b/Libraries/LibMediaCodecs/VideoSurface.cpp
index 843134df179..1867cbc19cc 100644
--- a/Libraries/LibMediaCodecs/VideoSurface.cpp
+++ b/Libraries/LibMediaCodecs/VideoSurface.cpp
@@ -28,6 +28,16 @@ Gfx::IntSize VideoSurface::size() const
#endif
}
+Subsampling VideoSurface::subsampling() const
+{
+#if defined(AK_OS_MACOS)
+ if (auto format = Gfx::biplanar_pixel_format(m_io_surface.pixel_format()); format.has_value())
+ return format->subsampling;
+#endif
+ // Every other surface a decoder hands out is NV12 or P010.
+ return Subsampling::yuv420();
+}
+
ErrorOr<NonnullRefPtr<Gfx::Bitmap>> VideoSurface::read_back_bitmap([[maybe_unused]] CodingIndependentCodePoints const& cicp) const
{
#ifdef AK_OS_MACOS
diff --git a/Libraries/LibMediaCodecs/VideoSurface.h b/Libraries/LibMediaCodecs/VideoSurface.h
index 7011918001e..01e75168fa7 100644
--- a/Libraries/LibMediaCodecs/VideoSurface.h
+++ b/Libraries/LibMediaCodecs/VideoSurface.h
@@ -15,6 +15,7 @@
#include <LibIPC/Forward.h>
#include <LibMediaCodecs/Color/CodingIndependentCodePoints.h>
#include <LibMediaCodecs/Export.h>
+#include <LibMediaCodecs/Subsampling.h>
#ifdef AK_OS_MACOS
# include <LibCore/IOSurface.h>
@@ -41,6 +42,7 @@ public:
// Tells the surface apart from every other its sender has handed out, including from an earlier decoder process.
u64 id() const { return m_id; }
Gfx::IntSize size() const;
+ Subsampling subsampling() const;
// Reads the pixels back into memory, which works only where the platform lets this process map the surface.
ErrorOr<NonnullRefPtr<Gfx::Bitmap>> read_back_bitmap(CodingIndependentCodePoints const&) const;
diff --git a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
index 1b21f8c86e3..9037fb74034 100644
--- a/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
+++ b/Libraries/LibMediaCodecs/VideoToolbox/VideoToolboxVideoDecoder.mm
@@ -7,6 +7,7 @@
#include <AK/ByteBuffer.h>
#include <AK/HashMap.h>
#include <AK/NeverDestroyed.h>
+#include <LibGfx/VideoSurfaceImage.h>
#include <LibMediaCodecs/Codecs/AV1.h>
#include <LibMediaCodecs/Codecs/H264.h>
#include <LibMediaCodecs/Codecs/H265.h>
@@ -193,18 +194,46 @@ CodingIndependentCodePoints cicp_of_format_description(CMVideoFormatDescriptionR
};
}
+// H.264 and H.265 number their chroma formats alike.
+Subsampling subsampling_of_chroma_format(u8 chroma_format_idc)
+{
+ switch (chroma_format_idc) {
+ case 2:
+ return Subsampling::yuv422();
+ case 3:
+ return Subsampling::yuv444();
+ default:
+ return Subsampling::yuv420();
+ }
+}
+
+// A format description cannot express an identity matrix, so the colour description of the sequence parameter set is
+// taken over it.
+CodingIndependentCodePoints cicp_of_parameter_sets(CMVideoFormatDescriptionRef description, CodingIndependentCodePoints const& sequence_cicp)
+{
+ auto cicp = cicp_of_format_description(description);
+ cicp.adopt_specified_values(sequence_cicp);
+ return cicp;
+}
+
// Left to choose for itself, a decoder hands back layouts that pack samples across element boundaries, which nothing
// downstream can sample or read. Asking for the documented biplanar formats keeps the output to one sample per
// component, in whichever range the stream is in.
-RetainedRef<CFMutableDictionaryRef> destination_attributes_for_bit_depth(u8 bit_depth)
+// An RGB picture comes back with green, blue and red in place of luma and chroma. The decoder converts between ranges
+// as if they were luma and chroma, so they are only asked for in the range the stream is in.
+RetainedRef<CFMutableDictionaryRef> destination_attributes(u8 bit_depth, Subsampling subsampling, CodingIndependentCodePoints const& cicp)
{
- Array<OSType, 2> pixel_formats { kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange };
- if (bit_depth > 8)
- pixel_formats = { kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr10BiPlanarFullRange };
+ auto formats = Gfx::biplanar_pixel_formats_holding(bit_depth, subsampling);
+ if (formats.is_empty()) {
+ formats = Gfx::biplanar_pixel_formats_holding(bit_depth, Subsampling::yuv420());
+ } else if (cicp.matrix_coefficients() == MatrixCoefficients::Identity && subsampling == Subsampling::yuv444()) {
+ auto range = cicp.video_full_range_flag() == VideoFullRangeFlag::Studio ? VideoFullRangeFlag::Studio : VideoFullRangeFlag::Full;
+ formats.remove_all_matching([&](auto const& format) { return format.range != range; });
+ }
- RetainedRef<CFMutableArrayRef> pixel_format_numbers { CFArrayCreateMutable(kCFAllocatorDefault, pixel_formats.size(), &kCFTypeArrayCallBacks) };
- for (auto pixel_format : pixel_formats) {
- RetainedRef<CFNumberRef> number { CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &pixel_format) };
+ RetainedRef<CFMutableArrayRef> pixel_format_numbers { CFArrayCreateMutable(kCFAllocatorDefault, formats.size(), &kCFTypeArrayCallBacks) };
+ for (auto const& format : formats) {
+ RetainedRef<CFNumberRef> number { CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &format.pixel_format) };
CFArrayAppendValue(pixel_format_numbers.ref(), number.ref());
}
@@ -362,13 +391,22 @@ struct H264State final : FormatState {
Vector<u8 const*, 288> set_pointers;
Vector<size_t, 288> set_sizes;
u8 reorder_frame_count = 0;
+ u8 bit_depth = 8;
+ // Only one sequence parameter set can describe the layout that frames are asked for in, so the first one does.
+ Optional<Subsampling> subsampling;
+ CodingIndependentCodePoints sequence_cicp;
auto requires_hardware_decoder = false;
for (auto const& set : parameter_sets.sequence_parameter_sets()) {
set_pointers.append(set.nal_unit.data());
set_sizes.append(set.nal_unit.size());
// Bound every SPS a slice could select, without parsing slice headers to track activation.
reorder_frame_count = max(reorder_frame_count, set.parameters.max_num_reorder_frames);
+ bit_depth = max(bit_depth, set.parameters.bit_depth_luma);
requires_hardware_decoder |= !software_decoder_can_decode(set.parameters);
+ if (!subsampling.has_value()) {
+ subsampling = subsampling_of_chroma_format(set.parameters.chroma_format_idc);
+ sequence_cicp = set.parameters.cicp;
+ }
}
if (set_pointers.is_empty())
return {};
@@ -387,7 +425,8 @@ struct H264State final : FormatState {
if (CMVideoFormatDescriptionCreateFromH264ParameterSets(kCFAllocatorDefault, set_pointers.size(), set_pointers.data(), set_sizes.data(), nal_unit_length_size, &description) != noErr)
return {};
- return DecoderFormat { RetainedRef<CMVideoFormatDescriptionRef> { description }, destination_attributes_for_bit_depth(8), cicp_of_format_description(description), reorder_frame_count, requires_hardware_decoder };
+ auto cicp = cicp_of_parameter_sets(description, sequence_cicp);
+ return DecoderFormat { RetainedRef<CMVideoFormatDescriptionRef> { description }, destination_attributes(bit_depth, subsampling.value(), cicp), cicp, reorder_frame_count, requires_hardware_decoder };
}
};
@@ -482,6 +521,9 @@ struct H265State final : FormatState {
// and takes them in this order.
u8 reorder_frame_count = 0;
u8 bit_depth = 8;
+ // Only one sequence parameter set can describe the layout that frames are asked for in, so the first one does.
+ Optional<Subsampling> subsampling;
+ CodingIndependentCodePoints sequence_cicp;
for (auto const& set : parameter_sets.video_parameter_sets()) {
auto is_referenced = false;
for (auto const& sequence_set : parameter_sets.sequence_parameter_sets())
@@ -500,6 +542,10 @@ struct H265State final : FormatState {
// Bound every sequence set a slice could select, without parsing slice headers to track activation.
reorder_frame_count = max(reorder_frame_count, set.parameters.sps_max_num_reorder_pics);
bit_depth = max(bit_depth, set.parameters.bit_depth_luma);
+ if (!subsampling.has_value()) {
+ subsampling = subsampling_of_chroma_format(set.parameters.chroma_format_idc);
+ sequence_cicp = set.parameters.cicp;
+ }
}
if (set_pointers.size() == video_count)
return {};
@@ -519,7 +565,8 @@ struct H265State final : FormatState {
if (CMVideoFormatDescriptionCreateFromHEVCParameterSets(kCFAllocatorDefault, set_pointers.size(), set_pointers.data(), set_sizes.data(), nal_unit_length_size, nullptr, &description) != noErr)
return {};
- return DecoderFormat { RetainedRef<CMVideoFormatDescriptionRef> { description }, destination_attributes_for_bit_depth(bit_depth), cicp_of_format_description(description), reorder_frame_count };
+ auto cicp = cicp_of_parameter_sets(description, sequence_cicp);
+ return DecoderFormat { RetainedRef<CMVideoFormatDescriptionRef> { description }, destination_attributes(bit_depth, subsampling.value(), cicp), cicp, reorder_frame_count };
}
};
@@ -563,7 +610,7 @@ struct VP9State final : FormatState {
return DecoderFormat {
.description = RetainedRef<CMVideoFormatDescriptionRef> { description },
- .destination_attributes = destination_attributes_for_bit_depth(header->bit_depth),
+ .destination_attributes = destination_attributes(header->bit_depth, Subsampling::yuv420(), header->color_parameters.cicp),
.cicp = header->color_parameters.cicp,
.requires_hardware_decoder = true,
};
@@ -612,7 +659,7 @@ struct AV1State final : FormatState {
return DecoderFormat {
.description = RetainedRef<CMVideoFormatDescriptionRef> { description },
- .destination_attributes = destination_attributes_for_bit_depth(parameters.bit_depth),
+ .destination_attributes = destination_attributes(parameters.bit_depth, Subsampling::yuv420(), parameters.optional_fields.cicp),
.cicp = parameters.optional_fields.cicp,
.requires_hardware_decoder = true,
};
@@ -867,8 +914,9 @@ void VideoToolboxVideoDecoder::enqueue_decoded_output_while_locked(ColorMetadata
if (surface_or_error.is_error())
return;
- auto pixel_format = CVPixelBufferGetPixelFormatType(pixel_buffer);
- auto is_ten_bit = pixel_format == kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange || pixel_format == kCVPixelFormatType_420YpCbCr10BiPlanarFullRange;
+ auto pixel_format = Gfx::biplanar_pixel_format(CVPixelBufferGetPixelFormatType(pixel_buffer));
+ if (!pixel_format.has_value())
+ return;
if (m_decode_failure.has_value())
return;
@@ -883,8 +931,8 @@ void VideoToolboxVideoDecoder::enqueue_decoded_output_while_locked(ColorMetadata
.timestamp = timestamp,
.duration = duration,
.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(),
+ .bit_depth = pixel_format->bit_depth,
+ .subsampling = pixel_format->subsampling,
.color_metadata = color_metadata,
};
insert_output_in_presentation_order_while_locked(move(output));
diff --git a/Services/Compositor/CoreAnimationWindowServer.mm b/Services/Compositor/CoreAnimationWindowServer.mm
index ccc21817689..4c118145811 100644
--- a/Services/Compositor/CoreAnimationWindowServer.mm
+++ b/Services/Compositor/CoreAnimationWindowServer.mm
@@ -245,7 +245,11 @@ bool CoreAnimationRemoteLayer::can_show(WindowServerPlacement const&, Content co
},
[](NonnullRefPtr<Media::VideoFrame> const& frame) {
// A frame that a decoder left in memory has no surface that the window server could read.
- return frame->surface() != nullptr;
+ if (frame->surface() == nullptr)
+ return false;
+ // The window server converts a surface from YCbCr by the matrix it is tagged with, and no tag names the
+ // identity matrix that an RGB surface needs.
+ return frame->cicp().matrix_coefficients() != Media::MatrixCoefficients::Identity;
});
}
diff --git a/Services/Compositor/VideoFrameSkia.cpp b/Services/Compositor/VideoFrameSkia.cpp
index 82b9e8c25e0..3faaa9a54b1 100644
--- a/Services/Compositor/VideoFrameSkia.cpp
+++ b/Services/Compositor/VideoFrameSkia.cpp
@@ -66,7 +66,7 @@ SkYUVColorSpace skia_yuv_color_space(Media::CodingIndependentCodePoints cicp)
case Media::MatrixCoefficients::SMPTE2085:
return full_range ? kYDZDX_Full_SkYUVColorSpace : kYDZDX_Limited_SkYUVColorSpace;
case Media::MatrixCoefficients::Identity:
- return kIdentity_SkYUVColorSpace;
+ return cicp.video_full_range_flag() == Media::VideoFullRangeFlag::Studio ? kGBR_Limited_SkYUVColorSpace : kGBR_Full_SkYUVColorSpace;
default:
// Default to BT.709 for unsupported matrix coefficients
return full_range ? kRec709_Full_SkYUVColorSpace : kRec709_Limited_SkYUVColorSpace;
diff --git a/Services/Compositor/VideoFrameSkia.mm b/Services/Compositor/VideoFrameSkia.mm
index afc6d4d031c..1dcd09b1c87 100644
--- a/Services/Compositor/VideoFrameSkia.mm
+++ b/Services/Compositor/VideoFrameSkia.mm
@@ -33,14 +33,23 @@ sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const& surface, M
auto const& io_surface = surface.io_surface();
- auto bit_depth = Gfx::biplanar_bit_depth_for_pixel_format(io_surface.pixel_format());
- if (!bit_depth.has_value() || io_surface.plane_count() != 2)
+ auto format = Gfx::biplanar_pixel_format(io_surface.pixel_format());
+ if (!format.has_value() || io_surface.plane_count() != 2)
return nullptr;
- Array plane_formats { Gfx::MetalTextureFormat::R8, Gfx::MetalTextureFormat::RG8 };
// Samples deeper than 8 bits sit in the high bits of each 16-bit component, so they read as full range unexpanded.
- if (*bit_depth > 8)
+ Array plane_formats { Gfx::MetalTextureFormat::R8, Gfx::MetalTextureFormat::RG8 };
+ if (format->bit_depth > 8)
plane_formats = { Gfx::MetalTextureFormat::R16, Gfx::MetalTextureFormat::RG16 };
+
+ auto subsampling = SkYUVAInfo::Subsampling::k420;
+ if (format->subsampling == Media::Subsampling::yuv444())
+ subsampling = SkYUVAInfo::Subsampling::k444;
+ else if (format->subsampling != Media::Subsampling::yuv420())
+ return nullptr;
+ if (cicp.matrix_coefficients() == Media::MatrixCoefficients::Identity && subsampling != SkYUVAInfo::Subsampling::k444)
+ return nullptr;
+
GrBackendTexture plane_textures[SkYUVAInfo::kMaxPlanes];
for (size_t plane = 0; plane < plane_formats.size(); plane++) {
auto metal_texture = skia_backend_context.metal_context().create_texture_from_iosurface(io_surface, plane_formats[plane], plane);
@@ -58,7 +67,7 @@ sk_sp<SkImage> sk_image_from_video_surface(Media::VideoSurface const& surface, M
SkYUVAInfo yuva_info {
SkISize::Make(static_cast<int>(io_surface.plane_width(0)), static_cast<int>(io_surface.plane_height(0))),
SkYUVAInfo::PlaneConfig::kY_UV,
- SkYUVAInfo::Subsampling::k420,
+ subsampling,
skia_yuv_color_space(cicp),
};
diff --git a/Tests/Compositor/TestVideoSurfaceImage.mm b/Tests/Compositor/TestVideoSurfaceImage.mm
index a0d816cbb94..185d7c95c8a 100644
--- a/Tests/Compositor/TestVideoSurfaceImage.mm
+++ b/Tests/Compositor/TestVideoSurfaceImage.mm
@@ -5,7 +5,9 @@
*/
#include <AK/ByteBuffer.h>
+#include <AK/Function.h>
#include <AK/Math.h>
+#include <AK/OwnPtr.h>
#include <Compositor/SkiaBackendContext.h>
#include <Compositor/VideoFrameSkia.h>
#include <LibCore/IOSurface.h>
@@ -371,9 +373,379 @@ TEST_CASE(biplanar_conversion_refuses_planes_shorter_than_the_size)
auto luma = MUST(ByteBuffer::create_zeroed(64 * 48));
auto chroma = MUST(ByteBuffer::create_zeroed(64 * 24));
Gfx::BiplanarYUVPlane luma_plane { .data = luma.bytes(), .stride = 64 };
- EXPECT(!Gfx::biplanar_yuv_to_bitmap({ 64, 48 }, 8, {}, luma_plane, { .data = chroma.bytes(), .stride = 64 }).is_error());
- EXPECT(Gfx::biplanar_yuv_to_bitmap({ 64, 48 }, 8, {}, luma_plane, { .data = chroma.bytes().slice(0, 64), .stride = 64 }).is_error());
- EXPECT(Gfx::biplanar_yuv_to_bitmap({ 64, 48 }, 8, {}, luma_plane, { .data = chroma.bytes(), .stride = 16 }).is_error());
+ EXPECT(!Gfx::biplanar_yuv_to_bitmap({ 64, 48 }, 8, Media::Subsampling::yuv420(), {}, luma_plane, { .data = chroma.bytes(), .stride = 64 }).is_error());
+ EXPECT(Gfx::biplanar_yuv_to_bitmap({ 64, 48 }, 8, Media::Subsampling::yuv420(), {}, luma_plane, { .data = chroma.bytes().slice(0, 64), .stride = 64 }).is_error());
+ EXPECT(Gfx::biplanar_yuv_to_bitmap({ 64, 48 }, 8, Media::Subsampling::yuv420(), {}, luma_plane, { .data = chroma.bytes(), .stride = 16 }).is_error());
+}
+
+namespace {
+
+// Green, blue and red, held where luma, blue chroma and red chroma would be.
+constexpr Sample RGB_TEST_SAMPLE { 40, 200, 120 };
+constexpr Gfx::Color RGB_TEST_COLOR { 120, 40, 200 };
+constexpr Sample TEN_BIT_RGB_TEST_SAMPLE { 160, 800, 480 };
+constexpr Media::CodingIndependentCodePoints RGB_CICP { Media::ColorPrimaries::Unspecified, Media::TransferCharacteristics::Unspecified, Media::MatrixCoefficients::Identity, Media::VideoFullRangeFlag::Full };
+
+bool colors_are_close(Gfx::Color a, Gfx::Color b)
+{
+ auto close = [](u8 x, u8 y) { return AK::abs(static_cast<int>(x) - static_cast<int>(y)) <= 2; };
+ return close(a.red(), b.red()) && close(a.green(), b.green()) && close(a.blue(), b.blue());
+}
+
+// Every component of the pattern is constant within square blocks of this many pixels, and differs between them. At a
+// block's center, chroma upsampling agrees whichever way it filters, but chroma read from the wrong row or column, or
+// with the wrong subsampling, comes from another block.
+constexpr int PATTERN_BLOCK_SIZE = 8;
+
+Sample pattern_sample_at(int x, int y, u8 bit_depth)
+{
+ auto block_x = x / PATTERN_BLOCK_SIZE;
+ auto block_y = y / PATTERN_BLOCK_SIZE;
+ auto scale = 1 << (bit_depth - 8);
+ return {
+ static_cast<u16>((96 + (block_x * 4) + (block_y * 8)) * scale),
+ static_cast<u16>((64 + (block_x * 16)) * scale),
+ static_cast<u16>((80 + (block_y * 16)) * scale),
+ };
+}
+
+void fill_biplanar_surface_with_pattern(Core::IOSurfaceHandle const& handle)
+{
+ auto format = Gfx::biplanar_pixel_format(handle.pixel_format());
+ VERIFY(format.has_value());
+ auto* io_surface = static_cast<IOSurfaceRef>(handle.core_foundation_pointer());
+ IOSurfaceLock(io_surface, 0, nullptr);
+
+ // Samples deeper than eight bits are carried in the high bits of each sixteen.
+ auto bit_depth = format->bit_depth;
+ auto store = [&](u8* row, size_t index, u16 sample) {
+ if (bit_depth <= 8)
+ row[index] = static_cast<u8>(sample);
+ else
+ reinterpret_cast<u16*>(row)[index] = static_cast<u16>(sample << (16 - bit_depth));
+ };
+
+ auto* luma = static_cast<u8*>(IOSurfaceGetBaseAddressOfPlane(io_surface, 0));
+ auto luma_stride = IOSurfaceGetBytesPerRowOfPlane(io_surface, 0);
+ for (size_t row = 0; row < handle.plane_height(0); row++) {
+ for (size_t column = 0; column < handle.plane_width(0); column++)
+ store(luma + (row * luma_stride), column, pattern_sample_at(column, row, bit_depth).luma);
+ }
+
+ auto subsampling = format->subsampling;
+ auto* chroma = static_cast<u8*>(IOSurfaceGetBaseAddressOfPlane(io_surface, 1));
+ auto chroma_stride = IOSurfaceGetBytesPerRowOfPlane(io_surface, 1);
+ for (size_t row = 0; row < handle.plane_height(1); row++) {
+ for (size_t column = 0; column < handle.plane_width(1); column++) {
+ auto sample = pattern_sample_at(column << subsampling.x(), row << subsampling.y(), bit_depth);
+ store(chroma + (row * chroma_stride), column * 2, sample.blue_chroma);
+ store(chroma + (row * chroma_stride), (column * 2) + 1, sample.red_chroma);
+ }
+ }
+
+ IOSurfaceUnlock(io_surface, 0, nullptr);
+}
+
+// The pattern laid out the way a software decoder hands it over, as three separate planes.
+struct PatternPlanes {
+ AK_ALLOC_WITH_KMALLOC;
+
+ ByteBuffer luma;
+ ByteBuffer blue_chroma;
+ ByteBuffer red_chroma;
+ Optional<Gfx::YUVData> data;
+};
+
+NonnullOwnPtr<PatternPlanes> pattern_planes(u8 bit_depth, Media::Subsampling subsampling)
+{
+ auto planes = make<PatternPlanes>();
+ size_t bytes_per_sample = bit_depth > 8 ? 2 : 1;
+ Gfx::Size<size_t> size { TEST_WIDTH, TEST_HEIGHT };
+ auto chroma_size = subsampling.subsampled_size(size);
+ planes->luma = MUST(ByteBuffer::create_uninitialized(size.width() * size.height() * bytes_per_sample));
+ planes->blue_chroma = MUST(ByteBuffer::create_uninitialized(chroma_size.width() * chroma_size.height() * bytes_per_sample));
+ planes->red_chroma = MUST(ByteBuffer::create_uninitialized(chroma_size.width() * chroma_size.height() * bytes_per_sample));
+
+ // Separate planes keep samples deeper than eight bits in the low bits of each sixteen.
+ auto store = [&](ByteBuffer& plane, size_t index, u16 sample) {
+ if (bytes_per_sample == 1)
+ plane[index] = static_cast<u8>(sample);
+ else
+ reinterpret_cast<u16*>(plane.data())[index] = sample;
+ };
+ for (size_t row = 0; row < size.height(); row++) {
+ for (size_t column = 0; column < size.width(); column++)
+ store(planes->luma, (row * size.width()) + column, pattern_sample_at(column, row, bit_depth).luma);
+ }
+ for (size_t row = 0; row < chroma_size.height(); row++) {
+ for (size_t column = 0; column < chroma_size.width(); column++) {
+ auto sample = pattern_sample_at(column << subsampling.x(), row << subsampling.y(), bit_depth);
+ store(planes->blue_chroma, (row * chroma_size.width()) + column, sample.blue_chroma);
+ store(planes->red_chroma, (row * chroma_size.width()) + column, sample.red_chroma);
+ }
+ }
+
+ planes->data = MUST(Gfx::YUVData::create({ TEST_WIDTH, TEST_HEIGHT }, bit_depth, subsampling, {},
+ planes->luma.bytes(), planes->blue_chroma.bytes(), planes->red_chroma.bytes()));
+ return planes;
+}
+
+Optional<SkBitmap> pixels_of(sk_sp<SkImage> const& image, GrDirectContext* gr_context)
+{
+ SkBitmap bitmap;
+ if (!bitmap.tryAllocPixels(SkImageInfo::MakeN32Premul(image->width(), image->height(), SkColorSpace::MakeSRGB())))
+ return {};
+ if (!image->readPixels(gr_context, bitmap.pixmap(), 0, 0))
+ return {};
+ return bitmap;
+}
+
+// Compares the center of every block of the pattern.
+void expect_pattern_blocks_alike(Function<Gfx::Color(int, int)> const& actual_color_at, Function<Gfx::Color(int, int)> const& expected_color_at)
+{
+ for (int block_y = 0; block_y < TEST_HEIGHT / PATTERN_BLOCK_SIZE; block_y++) {
+ for (int block_x = 0; block_x < TEST_WIDTH / PATTERN_BLOCK_SIZE; block_x++) {
+ auto x = (block_x * PATTERN_BLOCK_SIZE) + (PATTERN_BLOCK_SIZE / 2);
+ auto y = (block_y * PATTERN_BLOCK_SIZE) + (PATTERN_BLOCK_SIZE / 2);
+ auto actual = actual_color_at(x, y);
+ auto expected = expected_color_at(x, y);
+ if (!colors_are_close(actual, expected))
+ warnln("Block ({}, {}): got {}, expected {}", block_x, block_y, actual, expected);
+ EXPECT(colors_are_close(actual, expected));
+ }
+ }
+}
+
+// Reads a surface back on the CPU and checks it against its separate planes converted to pixels.
+void expect_surface_reads_back_as_its_pattern(OSType pixel_format)
+{
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, pixel_format);
+ VERIFY(surface.has_value());
+ fill_biplanar_surface_with_pattern(*surface);
+ auto format = Gfx::biplanar_pixel_format(pixel_format).value();
+
+ auto surface_bitmap = MUST(Gfx::bitmap_from_video_surface(*surface, {}));
+ auto planes = pattern_planes(format.bit_depth, format.subsampling);
+ auto planes_bitmap = MUST(planes->data->to_bitmap());
+ auto color_at = [](Gfx::Bitmap const& bitmap) {
+ return Function<Gfx::Color(int, int)>([&bitmap](int x, int y) { return bitmap.get_pixel(x, y); });
+ };
+ expect_pattern_blocks_alike(color_at(*surface_bitmap), color_at(*planes_bitmap));
+}
+
+// Draws a surface on the GPU and checks it against its separate planes drawn the same way.
+void expect_surface_renders_as_its_pattern(OSType pixel_format, Gfx::SkiaBackendContext& context)
+{
+ auto* gr_context = context.sk_context();
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, pixel_format);
+ VERIFY(surface.has_value());
+ fill_biplanar_surface_with_pattern(*surface);
+ auto format = Gfx::biplanar_pixel_format(pixel_format).value();
+
+ auto surface_image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), {}, context);
+ VERIFY(surface_image != nullptr);
+ auto surface_pixels = pixels_of(surface_image, gr_context);
+ VERIFY(surface_pixels.has_value());
+
+ auto planes = pattern_planes(format.bit_depth, format.subsampling);
+ auto planes_image = SkImages::TextureFromYUVAPixmaps(gr_context, Compositor::make_yuva_pixmaps(*planes->data), skgpu::Mipmapped::kNo, false, SkColorSpace::MakeSRGB());
+ VERIFY(planes_image != nullptr);
+ auto planes_pixels = pixels_of(planes_image, gr_context);
+ VERIFY(planes_pixels.has_value());
+
+ auto color_at = [](SkBitmap const& bitmap) {
+ return Function<Gfx::Color(int, int)>([&bitmap](int x, int y) {
+ auto color = bitmap.getColor(x, y);
+ return Gfx::Color(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color));
+ });
+ };
+ expect_pattern_blocks_alike(color_at(*surface_pixels), color_at(*planes_pixels));
+}
+
+}
+
+TEST_CASE(accepts_four_four_four_surfaces_laid_out_like_a_decoders)
+{
+ EXPECT(!Gfx::validate_biplanar_video_surface(create_decoder_shaped_surface(63, 47, kCVPixelFormatType_444YpCbCr8BiPlanarFullRange).release_value()).is_error());
+ EXPECT(!Gfx::validate_biplanar_video_surface(create_decoder_shaped_surface(64, 48, kCVPixelFormatType_444YpCbCr10BiPlanarFullRange).release_value()).is_error());
+}
+
+TEST_CASE(reads_back_a_four_four_four_surface_as_the_same_pixels_its_separate_planes_convert_to)
+{
+ expect_surface_reads_back_as_its_pattern(kCVPixelFormatType_444YpCbCr8BiPlanarVideoRange);
+ expect_surface_reads_back_as_its_pattern(kCVPixelFormatType_444YpCbCr10BiPlanarVideoRange);
+}
+
+TEST_CASE(reads_back_an_rgb_surface_as_its_green_blue_and_red_planes)
+{
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, kCVPixelFormatType_444YpCbCr8BiPlanarFullRange);
+ VERIFY(surface.has_value());
+ fill_biplanar_surface(*surface, RGB_TEST_SAMPLE);
+
+ auto bitmap = MUST(Gfx::bitmap_from_video_surface(*surface, RGB_CICP));
+ EXPECT_EQ(bitmap->get_pixel(TEST_WIDTH / 2, TEST_HEIGHT / 2), RGB_TEST_COLOR);
+}
+
+TEST_CASE(refuses_to_read_back_a_subsampled_surface_as_rgb)
+{
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange);
+ VERIFY(surface.has_value());
+ EXPECT(Gfx::bitmap_from_video_surface(*surface, RGB_CICP).is_error());
+}
+
+TEST_CASE(a_four_four_four_surface_and_separate_planes_of_the_same_samples_render_alike)
+{
+ auto context = gpu_context();
+ if (!context) {
+ warnln("No GPU context available, skipping");
+ return;
+ }
+ expect_surface_renders_as_its_pattern(kCVPixelFormatType_444YpCbCr8BiPlanarVideoRange, *context);
+ expect_surface_renders_as_its_pattern(kCVPixelFormatType_444YpCbCr10BiPlanarVideoRange, *context);
+}
+
+TEST_CASE(an_rgb_surface_renders_as_its_green_blue_and_red_planes)
+{
+ auto context = gpu_context();
+ if (!context) {
+ warnln("No GPU context available, skipping");
+ return;
+ }
+ auto* gr_context = context->sk_context();
+
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, kCVPixelFormatType_444YpCbCr8BiPlanarFullRange);
+ VERIFY(surface.has_value());
+ fill_biplanar_surface(*surface, RGB_TEST_SAMPLE);
+ auto image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), RGB_CICP, *context);
+ VERIFY(image != nullptr);
+ auto color = center_pixel_of(image, gr_context);
+ VERIFY(color.has_value());
+ outln("rgb surface: {} {} {}", color->red(), color->green(), color->blue());
+ EXPECT(colors_are_close(*color, RGB_TEST_COLOR));
+}
+
+TEST_CASE(a_ten_bit_rgb_surface_renders_as_its_green_blue_and_red_planes)
+{
+ auto context = gpu_context();
+ if (!context) {
+ warnln("No GPU context available, skipping");
+ return;
+ }
+ auto* gr_context = context->sk_context();
+
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, kCVPixelFormatType_444YpCbCr10BiPlanarFullRange);
+ VERIFY(surface.has_value());
+ fill_ten_bit_biplanar_surface(*surface, TEN_BIT_RGB_TEST_SAMPLE);
+ auto image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), RGB_CICP, *context);
+ VERIFY(image != nullptr);
+ auto color = center_pixel_of(image, gr_context);
+ VERIFY(color.has_value());
+ outln("ten-bit rgb surface: {} {} {}", color->red(), color->green(), color->blue());
+ EXPECT(colors_are_close(*color, RGB_TEST_COLOR));
+}
+
+TEST_CASE(separate_rgb_planes_render_as_green_blue_and_red)
+{
+ auto context = gpu_context();
+ if (!context) {
+ warnln("No GPU context available, skipping");
+ return;
+ }
+ auto* gr_context = context->sk_context();
+
+ auto green_plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT));
+ auto blue_plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT));
+ auto red_plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT));
+ green_plane.bytes().fill(static_cast<u8>(RGB_TEST_SAMPLE.luma));
+ blue_plane.bytes().fill(static_cast<u8>(RGB_TEST_SAMPLE.blue_chroma));
+ red_plane.bytes().fill(static_cast<u8>(RGB_TEST_SAMPLE.red_chroma));
+ auto yuv_data = MUST(Gfx::YUVData::create({ TEST_WIDTH, TEST_HEIGHT }, 8, Media::Subsampling::yuv444(), RGB_CICP,
+ green_plane.bytes(), blue_plane.bytes(), red_plane.bytes()));
+
+ auto image = SkImages::TextureFromYUVAPixmaps(gr_context, Compositor::make_yuva_pixmaps(yuv_data), skgpu::Mipmapped::kNo, false, SkColorSpace::MakeSRGB());
+ VERIFY(image != nullptr);
+ auto color = center_pixel_of(image, gr_context);
+ VERIFY(color.has_value());
+ EXPECT(colors_are_close(*color, RGB_TEST_COLOR));
+ EXPECT_EQ(MUST(yuv_data.to_bitmap())->get_pixel(TEST_WIDTH / 2, TEST_HEIGHT / 2), RGB_TEST_COLOR);
+}
+
+TEST_CASE(separate_ten_bit_rgb_planes_render_as_green_blue_and_red)
+{
+ auto context = gpu_context();
+ if (!context) {
+ warnln("No GPU context available, skipping");
+ return;
+ }
+ auto* gr_context = context->sk_context();
+
+ auto make_plane = [](u16 value) {
+ auto plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT * sizeof(u16)));
+ auto* samples = reinterpret_cast<u16*>(plane.data());
+ for (size_t index = 0; index < plane.size() / sizeof(u16); index++)
+ samples[index] = value;
+ return plane;
+ };
+ auto green_plane = make_plane(TEN_BIT_RGB_TEST_SAMPLE.luma);
+ auto blue_plane = make_plane(TEN_BIT_RGB_TEST_SAMPLE.blue_chroma);
+ auto red_plane = make_plane(TEN_BIT_RGB_TEST_SAMPLE.red_chroma);
+ auto yuv_data = MUST(Gfx::YUVData::create({ TEST_WIDTH, TEST_HEIGHT }, 10, Media::Subsampling::yuv444(), RGB_CICP,
+ green_plane.bytes(), blue_plane.bytes(), red_plane.bytes()));
+
+ auto image = SkImages::TextureFromYUVAPixmaps(gr_context, Compositor::make_yuva_pixmaps(yuv_data), skgpu::Mipmapped::kNo, false, SkColorSpace::MakeSRGB());
+ VERIFY(image != nullptr);
+ auto color = center_pixel_of(image, gr_context);
+ VERIFY(color.has_value());
+ EXPECT(colors_are_close(*color, RGB_TEST_COLOR));
+}
+
+// Studio range RGB spans 16 to 235 in every component.
+TEST_CASE(studio_range_rgb_is_stretched_to_full_range)
+{
+ constexpr Sample studio_sample { 16, 235, 126 };
+ constexpr Sample ten_bit_studio_sample { 64, 940, 504 };
+ constexpr Gfx::Color expected_color { 128, 0, 255 };
+ auto studio_cicp = RGB_CICP;
+ studio_cicp.set_video_full_range_flag(Media::VideoFullRangeFlag::Studio);
+
+ auto surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, kCVPixelFormatType_444YpCbCr8BiPlanarVideoRange);
+ VERIFY(surface.has_value());
+ fill_biplanar_surface(*surface, studio_sample);
+ EXPECT_EQ(MUST(Gfx::bitmap_from_video_surface(*surface, studio_cicp))->get_pixel(TEST_WIDTH / 2, TEST_HEIGHT / 2), expected_color);
+
+ auto ten_bit_surface = create_decoder_shaped_surface(TEST_WIDTH, TEST_HEIGHT, kCVPixelFormatType_444YpCbCr10BiPlanarVideoRange);
+ VERIFY(ten_bit_surface.has_value());
+ fill_ten_bit_biplanar_surface(*ten_bit_surface, ten_bit_studio_sample);
+ EXPECT_EQ(MUST(Gfx::bitmap_from_video_surface(*ten_bit_surface, studio_cicp))->get_pixel(TEST_WIDTH / 2, TEST_HEIGHT / 2), expected_color);
+
+ auto green_plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT));
+ auto blue_plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT));
+ auto red_plane = MUST(ByteBuffer::create_uninitialized(TEST_WIDTH * TEST_HEIGHT));
+ green_plane.bytes().fill(static_cast<u8>(studio_sample.luma));
+ blue_plane.bytes().fill(static_cast<u8>(studio_sample.blue_chroma));
+ red_plane.bytes().fill(static_cast<u8>(studio_sample.red_chroma));
+ auto yuv_data = MUST(Gfx::YUVData::create({ TEST_WIDTH, TEST_HEIGHT }, 8, Media::Subsampling::yuv444(), studio_cicp,
+ green_plane.bytes(), blue_plane.bytes(), red_plane.bytes()));
+ EXPECT_EQ(MUST(yuv_data.to_bitmap())->get_pixel(TEST_WIDTH / 2, TEST_HEIGHT / 2), expected_color);
+
+ auto context = gpu_context();
+ if (!context) {
+ warnln("No GPU context available, skipping");
+ return;
+ }
+ auto* gr_context = context->sk_context();
+
+ auto surface_image = Compositor::sk_image_from_video_surface(MUST(Media::VideoSurface::create(surface.release_value())), studio_cicp, *context);
+ VERIFY(surface_image != nullptr);
+ auto surface_color = center_pixel_of(surface_image, gr_context);
+ VERIFY(surface_color.has_value());
+ EXPECT(colors_are_close(*surface_color, expected_color));
+
+ auto planes_image = SkImages::TextureFromYUVAPixmaps(gr_context, Compositor::make_yuva_pixmaps(yuv_data), skgpu::Mipmapped::kNo, false, SkColorSpace::MakeSRGB());
+ VERIFY(planes_image != nullptr);
+ auto planes_color = center_pixel_of(planes_image, gr_context);
+ VERIFY(planes_color.has_value());
+ EXPECT(colors_are_close(*planes_color, expected_color));
}
// Only the rows before a plane's last one have to be padded up to its stride, so a plane can end right after its last
@@ -381,31 +753,32 @@ TEST_CASE(biplanar_conversion_refuses_planes_shorter_than_the_size)
TEST_CASE(biplanar_conversion_reads_planes_whose_last_row_is_not_padded)
{
constexpr Gfx::IntSize size { 5, 3 };
- constexpr size_t chroma_width = 3;
- constexpr size_t chroma_height = 2;
-
- for (u8 bit_depth : { 8, 10 }) {
- size_t bytes_per_sample = bit_depth > 8 ? 2 : 1;
- size_t stride = 8 * bytes_per_sample;
- auto luma_row_byte_count = size.width() * bytes_per_sample;
- auto chroma_row_byte_count = chroma_width * 2 * bytes_per_sample;
-
- auto padded_luma = MUST(ByteBuffer::create_uninitialized(stride * size.height()));
- auto padded_chroma = MUST(ByteBuffer::create_uninitialized(stride * chroma_height));
- for (size_t index = 0; index < padded_luma.size(); index++)
- padded_luma[index] = static_cast<u8>(40 + (index * 7));
- for (size_t index = 0; index < padded_chroma.size(); index++)
- padded_chroma[index] = static_cast<u8>(90 + (index * 13));
-
- // The unpadded planes are copies in buffers of their own, which end right after their last sample.
- auto unpadded_luma = MUST(ByteBuffer::copy(padded_luma.bytes().trim((stride * (size.height() - 1)) + luma_row_byte_count)));
- auto unpadded_chroma = MUST(ByteBuffer::copy(padded_chroma.bytes().trim((stride * (chroma_height - 1)) + chroma_row_byte_count)));
-
- auto padded = MUST(Gfx::biplanar_yuv_to_bitmap(size, bit_depth, {}, { .data = padded_luma.bytes(), .stride = stride }, { .data = padded_chroma.bytes(), .stride = stride }));
- auto unpadded = MUST(Gfx::biplanar_yuv_to_bitmap(size, bit_depth, {}, { .data = unpadded_luma.bytes(), .stride = stride }, { .data = unpadded_chroma.bytes(), .stride = stride }));
- for (int y = 0; y < size.height(); y++) {
- for (int x = 0; x < size.width(); x++)
- EXPECT_EQ(unpadded->get_pixel(x, y), padded->get_pixel(x, y));
+
+ for (auto subsampling : { Media::Subsampling::yuv420(), Media::Subsampling::yuv422(), Media::Subsampling::yuv444() }) {
+ for (u8 bit_depth : { 8, 10 }) {
+ size_t bytes_per_sample = bit_depth > 8 ? 2 : 1;
+ size_t stride = 16 * bytes_per_sample;
+ auto chroma_size = subsampling.subsampled_size(size.to_type<size_t>());
+ auto luma_row_byte_count = size.width() * bytes_per_sample;
+ auto chroma_row_byte_count = chroma_size.width() * 2 * bytes_per_sample;
+
+ auto padded_luma = MUST(ByteBuffer::create_uninitialized(stride * size.height()));
+ auto padded_chroma = MUST(ByteBuffer::create_uninitialized(stride * chroma_size.height()));
+ for (size_t index = 0; index < padded_luma.size(); index++)
+ padded_luma[index] = static_cast<u8>(40 + (index * 7));
+ for (size_t index = 0; index < padded_chroma.size(); index++)
+ padded_chroma[index] = static_cast<u8>(90 + (index * 13));
+
+ // The unpadded planes are copies in buffers of their own, which end right after their last sample.
+ auto unpadded_luma = MUST(ByteBuffer::copy(padded_luma.bytes().trim((stride * (size.height() - 1)) + luma_row_byte_count)));
+ auto unpadded_chroma = MUST(ByteBuffer::copy(padded_chroma.bytes().trim((stride * (chroma_size.height() - 1)) + chroma_row_byte_count)));
+
+ auto padded = MUST(Gfx::biplanar_yuv_to_bitmap(size, bit_depth, subsampling, {}, { .data = padded_luma.bytes(), .stride = stride }, { .data = padded_chroma.bytes(), .stride = stride }));
+ auto unpadded = MUST(Gfx::biplanar_yuv_to_bitmap(size, bit_depth, subsampling, {}, { .data = unpadded_luma.bytes(), .stride = stride }, { .data = unpadded_chroma.bytes(), .stride = stride }));
+ for (int y = 0; y < size.height(); y++) {
+ for (int x = 0; x < size.width(); x++)
+ EXPECT_EQ(unpadded->get_pixel(x, y), padded->get_pixel(x, y));
+ }
}
}
}
diff --git a/Tests/LibMedia/TestCodecConfigurations.cpp b/Tests/LibMedia/TestCodecConfigurations.cpp
index 1c1b94daf3b..c62b5ba662e 100644
--- a/Tests/LibMedia/TestCodecConfigurations.cpp
+++ b/Tests/LibMedia/TestCodecConfigurations.cpp
@@ -767,6 +767,84 @@ TEST_CASE(h265_sequence_parameter_set_returns_its_ids_and_reorder_depth)
EXPECT(!Media::Codecs::H265::parse_sequence_parameter_set(hevc_sequence_parameter_set.span().trim(6)).has_value());
}
+// x265's sequence parameter set for a 4:4:4 RGB stream, which states an identity matrix in its VUI.
+static constexpr Array<u8, 43> hevc_rgb_sequence_parameter_set {
+ 0x42, 0x01, 0x01, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x9e, 0x08, 0x00, 0x00, 0x03, 0x00, 0x00,
+ 0x3c, 0x90, 0x01, 0x41, 0x01, 0xe2, 0xcb, 0x2b, 0x34, 0x92, 0x65, 0x78, 0x0b, 0x70, 0x20, 0x20,
+ 0x00, 0x40, 0x00, 0x00, 0x03, 0x00, 0x40, 0x00, 0x00, 0x06, 0x42
+};
+
+// A 4:4:4 sequence parameter set whose VUI follows scaling lists, PCM, three short-term reference picture sets (the
+// second predicted from the first) and two long-term reference pictures. It states BT.709 primaries, the sRGB transfer
+// and an identity matrix in full range.
+static constexpr Array<u8, 76> hevc_sequence_parameter_set_with_reference_picture_sets {
+ 0x42, 0x01, 0x01, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x90, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03,
+ 0x00, 0x5d, 0x90, 0x01, 0x41, 0x01, 0xe2, 0xcb, 0x2b, 0xc9, 0x27, 0xaa, 0xaa, 0xaa, 0xed, 0x34,
+ 0xd3, 0x4d, 0x34, 0xd3, 0x4d, 0x34, 0xd3, 0x4d, 0x34, 0xd3, 0x4d, 0x34, 0xd3, 0x4d, 0x34, 0xd3,
+ 0x4d, 0x34, 0xd3, 0x4d, 0x34, 0xd3, 0x4a, 0xaa, 0xf7, 0x7c, 0x46, 0xbf, 0xf6, 0x15, 0xec, 0x16,
+ 0x12, 0xff, 0xf0, 0x00, 0x10, 0x00, 0x1b, 0x70, 0x10, 0xd0, 0x00, 0x08
+};
+
+TEST_CASE(h265_sequence_parameter_set_reads_its_chroma_format_and_colour_description)
+{
+ auto parameter_set = Media::Codecs::H265::parse_sequence_parameter_set(hevc_rgb_sequence_parameter_set);
+ EXPECT(parameter_set.has_value());
+ if (!parameter_set.has_value())
+ return;
+ EXPECT_EQ(parameter_set->chroma_format_idc, 3);
+ EXPECT_EQ(parameter_set->cicp.matrix_coefficients(), Media::MatrixCoefficients::Identity);
+ EXPECT_EQ(parameter_set->cicp.video_full_range_flag(), Media::VideoFullRangeFlag::Full);
+
+ parameter_set = Media::Codecs::H265::parse_sequence_parameter_set(hevc_sequence_parameter_set);
+ EXPECT(parameter_set.has_value());
+ if (!parameter_set.has_value())
+ return;
+ EXPECT_EQ(parameter_set->chroma_format_idc, 1);
+}
+
+TEST_CASE(h265_sequence_parameter_set_reads_the_colour_description_past_reference_picture_sets)
+{
+ auto parameter_set = Media::Codecs::H265::parse_sequence_parameter_set(hevc_sequence_parameter_set_with_reference_picture_sets);
+ EXPECT(parameter_set.has_value());
+ if (!parameter_set.has_value())
+ return;
+ EXPECT_EQ(parameter_set->chroma_format_idc, 3);
+ EXPECT_EQ(parameter_set->sps_max_num_reorder_pics, 2);
+ EXPECT_EQ(parameter_set->cicp.color_primaries(), Media::ColorPrimaries::BT709);
+ EXPECT_EQ(parameter_set->cicp.transfer_characteristics(), Media::TransferCharacteristics::SRGB);
+ EXPECT_EQ(parameter_set->cicp.matrix_coefficients(), Media::MatrixCoefficients::Identity);
+ EXPECT_EQ(parameter_set->cicp.video_full_range_flag(), Media::VideoFullRangeFlag::Full);
+}
+
+TEST_CASE(h265_sequence_parameter_set_without_a_readable_colour_description_reports_unspecified_color)
+{
+ // Cut well before the VUI, but after every field a decoder is configured from.
+ auto parameter_set = Media::Codecs::H265::parse_sequence_parameter_set(hevc_sequence_parameter_set_with_reference_picture_sets.span().trim(56));
+ EXPECT(parameter_set.has_value());
+ if (!parameter_set.has_value())
+ return;
+ EXPECT_EQ(parameter_set->chroma_format_idc, 3);
+ EXPECT_EQ(parameter_set->cicp, Media::CodingIndependentCodePoints {});
+}
+
+// x264's sequence parameter set for a High 4:4:4 Predictive RGB stream, which states an identity matrix in its VUI.
+static constexpr Array<u8, 29> avc_rgb_sequence_parameter_set {
+ 0x67, 0xf4, 0x00, 0x0d, 0x91, 0x9b, 0x28, 0x28, 0x3f, 0x60, 0x2d, 0xc0, 0x80, 0x80, 0x10, 0x00,
+ 0x00, 0x03, 0x00, 0x10, 0x00, 0x00, 0x03, 0x03, 0x20, 0xf1, 0x42, 0x99, 0x60
+};
+
+TEST_CASE(h264_sequence_parameter_set_reads_its_chroma_format_and_colour_description)
+{
+ auto parameter_set = Media::Codecs::H264::parse_sequence_parameter_set(avc_rgb_sequence_parameter_set);
+ EXPECT(parameter_set.has_value());
+ if (!parameter_set.has_value())
+ return;
+ EXPECT_EQ(parameter_set->chroma_format_idc, 3);
+ EXPECT_EQ(parameter_set->bit_depth_luma, 8);
+ EXPECT_EQ(parameter_set->cicp.matrix_coefficients(), Media::MatrixCoefficients::Identity);
+ EXPECT_EQ(parameter_set->cicp.video_full_range_flag(), Media::VideoFullRangeFlag::Full);
+}
+
TEST_CASE(h265_video_and_picture_parameter_sets_return_their_ids)
{
auto video_parameter_set = Media::Codecs::H265::parse_video_parameter_set(hevc_video_parameter_set);
diff --git a/Tests/LibMedia/TestVideoFramePool.cpp b/Tests/LibMedia/TestVideoFramePool.cpp
index 16660d25e08..9276f3df5f5 100644
--- a/Tests/LibMedia/TestVideoFramePool.cpp
+++ b/Tests/LibMedia/TestVideoFramePool.cpp
@@ -386,6 +386,27 @@ TEST_CASE(received_frames_must_be_ones_a_decoder_could_produce)
auto too_wide = make_metadata();
too_wide.size = { static_cast<int>(Media::MAX_VIDEO_FRAME_DIMENSION) + 1, 1 };
EXPECT(!too_wide.is_valid());
+
+ auto subsampled_rgb = make_metadata();
+ subsampled_rgb.color_metadata.cicp.set_matrix_coefficients(Media::MatrixCoefficients::Identity);
+ EXPECT(receive(subsampled_rgb).is_error());
+ subsampled_rgb.subsampling = Media::Subsampling::yuv444();
+ EXPECT(!receive(subsampled_rgb).is_error());
+}
+
+// Only a picture without chroma subsampling can hold RGB.
+TEST_CASE(frames_keep_an_identity_matrix_only_without_subsampling)
+{
+ auto pool = make_pool();
+ auto slot = pool->try_acquire(MUST(Media::frame_plane_layout(RESOLVED_FRAME_SIZE, 8, Media::Subsampling::yuv444())).total_byte_count).release_value();
+ Media::ColorMetadata color_metadata;
+ color_metadata.cicp.set_matrix_coefficients(Media::MatrixCoefficients::Identity);
+ auto make_frame = [&](Media::Subsampling subsampling) {
+ return make_ref_counted<Media::VideoFrame>(AK::Duration::zero(), AK::Duration::zero(), RESOLVED_FRAME_SIZE.to_type<u32>(), 8, subsampling, color_metadata, slot.storage);
+ };
+ EXPECT_EQ(make_frame(Media::Subsampling::yuv444())->cicp().matrix_coefficients(), Media::MatrixCoefficients::Identity);
+ EXPECT_EQ(make_frame(Media::Subsampling::yuv420())->cicp().matrix_coefficients(), Media::MatrixCoefficients::Unspecified);
+ EXPECT_EQ(make_frame(Media::Subsampling::yuv422())->cicp().matrix_coefficients(), Media::MatrixCoefficients::Unspecified);
}
TEST_CASE(metadata_that_could_not_have_been_decoded_is_refused_over_ipc)