🔥 Delete the paravirt glue from reims-vgpu
reims-vgpu wrapped core's paravirt device for the C API: the device, its displays and their windows, frames and frame targets, the IOSurface device, the VideoToolbox and M2 scaler devices, the KVM dirty source and the display statistics. With apple-gfx gone they go, and the crate is the reims-graphics device's: its memory map (memory.rs), its cursor callbacks (cursor.rs), the window link that ends its window, and Error cut to the four refusals it makes. The platform's ApiPlatform keeps what the graphics device asks: its GPU, a texture's pixels, the lease on the guest's RAM (no dirty log now), the region and the video. The surface lending the video device used goes, and so do the frame queues and the fake host screen. src/video keeps only runtime.rs, the runtime the device's video arms build on, and device_writes keeps its writers' entry point; both are marked as waiting for those arms. reims-vgpu no longer depends on the VA-API, NVIDIA and VideoToolbox crates.
This commit is contained in:
1 parent
3db95eb188
commit
110b53637b
56 files changed
+247
-13845
No files matched your search
+2
-5
@@ -36,12 +36,9 @@ reims-vgpu = { path = "crates/reims-vgpu", default-features = false }
|
||||
reims-vgpu-vulkan = { path = "crates/reims-vgpu-vulkan" }
|
||||
# The reims-graphics device: its wire format and host side.
|
||||
reims-graphics = { path = "crates/reims-graphics" }
|
||||
# The VideoToolbox device's host side (`crate::video` of `reims-vgpu`).
|
||||
# The video crates' runtime and memory, which the reims-graphics device's video arms share
|
||||
# (`crate::video` of `reims-vgpu`).
|
||||
reims-vgpu-video-core = { path = "crates/reims-vgpu-video-core" }
|
||||
# Its decoders on the host's GPU through libva, on Linux.
|
||||
reims-vgpu-video-vaapi = { path = "crates/reims-vgpu-video-vaapi" }
|
||||
# Its decoders and encoders on an NVIDIA GPU through NVDEC and NVENC, on Linux, loaded at run time.
|
||||
reims-vgpu-video-nvidia = { path = "crates/reims-vgpu-video-nvidia" }
|
||||
# Its decoders, encoders and scaler on VideoToolbox, on macOS.
|
||||
reims-vgpu-video-videotoolbox = { path = "crates/reims-vgpu-video-videotoolbox" }
|
||||
# The reims-graphics device's hardware video on the Vulkan platform: Vulkan Video on the runtime's
|
||||
|
||||
@@ -29,7 +29,7 @@ vulkan = [
|
||||
[dependencies]
|
||||
reims-vgpu-core.workspace = true
|
||||
reims-vgpu-window.workspace = true
|
||||
# The video device's host session (`video`).
|
||||
# The video crates' runtime, which the reims-graphics device's video arms run on (`video`).
|
||||
reims-vgpu-video-core.workspace = true
|
||||
# The reims-graphics device's host side (`graphics`).
|
||||
reims-graphics.workspace = true
|
||||
@@ -38,21 +38,17 @@ zerocopy.workspace = true
|
||||
# A library's content key, by which the reims-graphics device keeps the libraries it made
|
||||
# (`graphics::decode::library`).
|
||||
sha2.workspace = true
|
||||
# A window frame that fails, or a window that gets no sink (`window::vulkan`).
|
||||
# A window frame that fails, or a window that gets no sink (`graphics::sink`).
|
||||
log.workspace = true
|
||||
# The reims-graphics decoder's lock, which a doorbell's thread takes and its queue's service thread
|
||||
# lets go (`graphics`'s take on a doorbell): `arc_lock`'s owned guard, and `send_guard`, which lets
|
||||
# it cross threads.
|
||||
parking_lot = { workspace = true, features = ["arc_lock", "send_guard"] }
|
||||
# KVM's dirty-log ioctls, in a host's dirty source's harvest (`dirty`); on Linux, the guest's RAM
|
||||
# as a host maps it, a shared mapping of a file (`platform::tests`).
|
||||
# The host's page size, which the window's import of the scanout's pages is aligned to
|
||||
# (`graphics::sink`); on Linux, the guest's RAM as a host maps it in the tests (`platform::tests`).
|
||||
libc.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
# The video device's backends on Linux (`video::backend_choice`): VA-API, on libva and libva-drm;
|
||||
# NVIDIA's NVDEC and NVENC, whose libraries it loads at run time.
|
||||
reims-vgpu-video-vaapi.workspace = true
|
||||
reims-vgpu-video-nvidia.workspace = true
|
||||
# The Vulkan platform, the library's only one on Linux: the dependencies of the `vulkan` feature,
|
||||
# which on macOS are optional (below).
|
||||
reims-vgpu-vulkan.workspace = true
|
||||
@@ -62,11 +58,9 @@ reims-vgpu-video-vulkan.workspace = true
|
||||
metal2vulkan-runtime.workspace = true
|
||||
ash.workspace = true
|
||||
|
||||
# The Metal platform, the product on macOS, and its window's drawable (`window::metal::MetalSink`,
|
||||
# `window::vulkan`'s macOS sink).
|
||||
# The Metal platform, the product on macOS, and its window's drawable (`graphics::metal`,
|
||||
# `graphics::vulkan`'s macOS sink).
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
# The video and scaler devices' backend on macOS: VideoToolbox (`video::backend_choice`).
|
||||
reims-vgpu-video-videotoolbox.workspace = true
|
||||
reims-vgpu-metal.workspace = true
|
||||
objc2.workspace = true
|
||||
objc2-metal.workspace = true
|
||||
@@ -80,23 +74,10 @@ ash = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
reims-vgpu-core = { workspace = true, features = ["testkit"] }
|
||||
# The scaler's conformance suite, which the scaler backend's tests run (`scaler::gpu`).
|
||||
reims-vgpu-video-conformance = { path = "../reims-vgpu-video-conformance" }
|
||||
|
||||
# A swapchain over a layer of the test's own on macOS, its surface made with ash's types
|
||||
# (`window::vulkan`'s tests).
|
||||
# The decoder's tests of Metal's own stitched functions and arrays (`graphics::decode`).
|
||||
[target.'cfg(target_os = "macos")'.dev-dependencies]
|
||||
ash.workspace = true
|
||||
# The scaler's kernel beside the Mac's own scalers (`scaler::gpu`'s `native` bench).
|
||||
objc2-foundation.workspace = true
|
||||
objc2-io-surface.workspace = true
|
||||
objc2-core-foundation = { workspace = true, features = ["CFCGTypes"] }
|
||||
objc2-quartz-core = { workspace = true, features = [
|
||||
"CALayer",
|
||||
"CAMetalLayer",
|
||||
"objc2-core-foundation",
|
||||
"objc2-metal",
|
||||
] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,24 @@
|
||||
//! The guest's cursor on a graphics device's display, as its host is told it
|
||||
//! ([`GraphicsCallbacks`](crate::GraphicsCallbacks)' `cursor_*`).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
/// The cursor's image, borrowed for the callback.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CursorGlyph<'a> {
|
||||
/// Pixels wide.
|
||||
pub width: u32,
|
||||
/// Pixels high.
|
||||
pub height: u32,
|
||||
/// The hot spot, in pixels from the top left.
|
||||
pub hot_spot: (u16, u16),
|
||||
/// `width * 4` bytes a row, `height` rows: straight-alpha RGBA.
|
||||
pub rgba: &'a [u8],
|
||||
}
|
||||
|
||||
/// The guest set its cursor's image.
|
||||
pub type CursorGlyphFn = Arc<dyn Fn(&CursorGlyph<'_>) + Send + Sync>;
|
||||
/// Whether the cursor shows changed: 1 shows it, 0 hides it.
|
||||
pub type CursorShowFn = Arc<dyn Fn(u8) + Send + Sync>;
|
||||
/// The guest moved the cursor.
|
||||
pub type CursorMoveFn = Arc<dyn Fn() + Send + Sync>;
|
||||
@@ -1,747 +0,0 @@
|
||||
//! [`Device`]: one paravirtualized GPU, made from a [`DeviceConfig`].
|
||||
//!
|
||||
//! A [`Device`] is one counted reference: [`Device::clone_ref`] takes another, and the last
|
||||
//! drop, or the last drop of what keeps it alive (a [`Display`]), is the device's teardown, run
|
||||
//! on the releasing thread, where it may block. Every method may be called from any thread;
|
||||
//! each runs as an entry ([`crate::entry`]), and so does the last drop: marked as the library's,
|
||||
//! so a panic in the library aborts at its op instead of unwinding into the caller, and with
|
||||
//! what the call held or Metal autoreleased on the thread released before it returns.
|
||||
//!
|
||||
//! The host's callbacks are closures ([`HostCallbacks`]), called synchronously on the thread
|
||||
//! core calls them on, with the arguments core passes, in core's order: the order of VM-memory
|
||||
//! operations is core's (docs/api.md section 5). A refused create drops the closures it was given
|
||||
//! before it returns.
|
||||
//!
|
||||
//! A device made over a memory map holds what its platform holds of the guest's RAM for it
|
||||
//! ([`ApiPlatform::guest_memory`], on Linux the files behind the map's ranges, which the Vulkan
|
||||
//! platform's views map), from before core's device is made to after core's teardown: every
|
||||
//! reference to the device and each of its displays keep the lease, and each drops it after its
|
||||
//! core handle.
|
||||
//!
|
||||
//! A device made over a memory map with a host's dirty source ([`DeviceConfig::dirty_source`])
|
||||
//! keeps core's dirty log of the guest's RAM in that lease, harvested from the source on a thread
|
||||
//! of its own ([`crate::dirty`]), and hands the log to the platform's lease. The log is closed
|
||||
//! while each call that stops or rebuilds the device's work runs (reset, pause, stop, suspend and
|
||||
//! resume), so no wait inside one is left for a harvest, and retired with the lease.
|
||||
|
||||
use std::any::Any;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::device::Device as CoreDevice;
|
||||
use reims_vgpu_core::device::config::DeviceConfig as CoreDeviceConfig;
|
||||
use reims_vgpu_core::host::{
|
||||
AddTraceRange, CreateTask, DestroyTask, HostBlocks, HostPtr, MapMemory, RaiseInterrupt,
|
||||
ReadMemory, RemoveTraceRange, UnmapMemory,
|
||||
};
|
||||
use reims_vgpu_core::memory::descriptor::{
|
||||
GuestPhysicalRange, MemoryMapDescriptor as CoreMemoryMap,
|
||||
};
|
||||
use reims_vgpu_core::memory::dirty::DirtyLog;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::rt::Hold;
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::dirty::{DirtySource, Harvester};
|
||||
use crate::display::{Display, DisplayConfig};
|
||||
use crate::entry;
|
||||
use crate::error::{Error, ResumeError};
|
||||
use crate::frame::{FrameTarget, PixelFormat};
|
||||
use crate::platform::{ApiPlatform, api_state};
|
||||
use crate::retained::Ours;
|
||||
|
||||
/// Guest RAM and the host memory behind it, in order, with the file behind each range where the
|
||||
/// host names one. The ranges are copied into the device at its creation; nothing is checked
|
||||
/// until then.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct MemoryMap {
|
||||
ranges: Vec<GuestPhysicalRange>,
|
||||
/// One entry per range, in the ranges' order.
|
||||
files: Vec<Option<MemoryFile>>,
|
||||
}
|
||||
|
||||
/// The file behind one range of a [`MemoryMap`]: the range's host memory is a shared mapping
|
||||
/// (`MAP_SHARED`) of `fd` from byte `offset`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemoryFile {
|
||||
/// The file, held open while any map or device holds it.
|
||||
pub fd: Arc<OwnedFd>,
|
||||
/// The file offset of the range's first byte, a multiple of the host's page size.
|
||||
pub offset: u64,
|
||||
}
|
||||
|
||||
impl MemoryMap {
|
||||
/// An empty map.
|
||||
pub fn new() -> MemoryMap {
|
||||
MemoryMap::default()
|
||||
}
|
||||
|
||||
/// Appends one range with no file, as given (no check, no merge).
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`MemoryMap::push_with_file`].
|
||||
pub unsafe fn push(&mut self, guest_physical_address: u64, length: u64, host: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { self.push_with_file(guest_physical_address, length, host, None) }
|
||||
}
|
||||
|
||||
/// Appends one range and the file behind it, if any, as given (no check, no merge).
|
||||
///
|
||||
/// # Safety
|
||||
/// `host .. host + length` is host memory (`mach_vm_allocate`d or equivalent) that stays
|
||||
/// mapped while any device or IOSurface device made over the map lives: the device remaps
|
||||
/// it and reads and writes the guest's memory through it. With `file`, that memory is a
|
||||
/// shared mapping of `file.fd` from `file.offset`, and the file holds at least `length`
|
||||
/// bytes from there.
|
||||
pub unsafe fn push_with_file(
|
||||
&mut self,
|
||||
guest_physical_address: u64,
|
||||
length: u64,
|
||||
host: *mut u8,
|
||||
file: Option<MemoryFile>,
|
||||
) {
|
||||
self.ranges.push(GuestPhysicalRange {
|
||||
physical_address: guest_physical_address,
|
||||
physical_length: length,
|
||||
host_address: HostPtr::from_ptr(host),
|
||||
});
|
||||
self.files.push(file);
|
||||
}
|
||||
|
||||
/// The ranges, in order.
|
||||
pub fn ranges(&self) -> &[GuestPhysicalRange] {
|
||||
&self.ranges
|
||||
}
|
||||
|
||||
/// The file behind each range, in the ranges' order: `None` for a range with no file.
|
||||
pub fn files(&self) -> &[Option<MemoryFile>] {
|
||||
&self.files
|
||||
}
|
||||
|
||||
/// Core's descriptor of the map.
|
||||
pub(crate) fn to_core(&self) -> CoreMemoryMap {
|
||||
let mut m = CoreMemoryMap::new();
|
||||
for r in &self.ranges {
|
||||
m.add_range(*r);
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's callbacks. `None` is a callback the host does not give: the device behaves as
|
||||
/// for a NULL C function pointer (docs/api.md section 5, and each C typedef's comment).
|
||||
#[derive(Clone, Default)]
|
||||
pub struct HostCallbacks {
|
||||
/// `(vm_size, &mut base) -> task`: reserve `vm_size` bytes of host address space.
|
||||
pub create_task: Option<CreateTask>,
|
||||
/// `(task)`: the task's last call.
|
||||
pub destroy_task: Option<DestroyTask>,
|
||||
/// `(task, range_count, virtual_offset, read_only, ranges) -> ok`.
|
||||
pub map_memory: Option<MapMemory>,
|
||||
/// `(task, virtual_offset, length) -> ok`.
|
||||
pub unmap_memory: Option<UnmapMemory>,
|
||||
/// `(physical_address, length, dst) -> ok`: copy guest memory into `dst`.
|
||||
pub read_memory: Option<ReadMemory>,
|
||||
/// `(vector)`, under the device's signal lock. Without it, the first interrupt ends the
|
||||
/// process.
|
||||
pub raise_interrupt: Option<RaiseInterrupt>,
|
||||
/// `(range, handler) -> trace range`: watch guest writes to the EFI framebuffer.
|
||||
pub add_trace_range: Option<AddTraceRange>,
|
||||
/// `(trace range)`: stop watching.
|
||||
pub remove_trace_range: Option<RemoveTraceRange>,
|
||||
}
|
||||
|
||||
impl HostCallbacks {
|
||||
/// Core's blocks: the same closures.
|
||||
fn into_core(self) -> HostBlocks {
|
||||
HostBlocks {
|
||||
raise_interrupt: self.raise_interrupt,
|
||||
create_task: self.create_task,
|
||||
destroy_task: self.destroy_task,
|
||||
map_memory: self.map_memory,
|
||||
unmap_memory: self.unmap_memory,
|
||||
read_memory: self.read_memory,
|
||||
add_trace_range: self.add_trace_range,
|
||||
remove_trace_range: self.remove_trace_range,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for HostCallbacks {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("HostCallbacks")
|
||||
.field("create_task", &self.create_task.is_some())
|
||||
.field("destroy_task", &self.destroy_task.is_some())
|
||||
.field("map_memory", &self.map_memory.is_some())
|
||||
.field("unmap_memory", &self.unmap_memory.is_some())
|
||||
.field("read_memory", &self.read_memory.is_some())
|
||||
.field("raise_interrupt", &self.raise_interrupt.is_some())
|
||||
.field("add_trace_range", &self.add_trace_range.is_some())
|
||||
.field("remove_trace_range", &self.remove_trace_range.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A device's config.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DeviceConfig {
|
||||
/// The Metal device's registry ID; `None` is the system's default Metal device.
|
||||
pub metal_registry_id: Option<u64>,
|
||||
/// 1 to [`crate::MAX_DISPLAY_PORTS`]; 0 is refused. Default 1.
|
||||
pub display_port_count: u32,
|
||||
/// The feature level: 0 and 4 offer every feature; 1, 2 and 3 cap the binary version the
|
||||
/// guest may choose at 62, 113 and 209, and trim the device info it reads. A level above 4
|
||||
/// is accepted here; the guest's first binary version write then ends the process, as do
|
||||
/// [`Device::reset`] and [`Device::will_resume`] once it applies the state's version.
|
||||
pub feature_level: u64,
|
||||
/// The display port connection types the guest reads (0: none set); below binary version 245
|
||||
/// it reads their low 2 bits. A resume of a state from binary version 238 or later refuses
|
||||
/// one taken with other types.
|
||||
pub display_port_connection_types: u32,
|
||||
/// The guest's RAM, or `None` to reach it through the task and memory callbacks.
|
||||
pub memory_map: Option<MemoryMap>,
|
||||
/// Map guest IOSurfaces through the process's latest [`crate::IoSurfaceDevice`].
|
||||
pub use_iosurface_mapper: bool,
|
||||
/// Run each isolated guest task with the task service's semantics (needs a memory map).
|
||||
pub process_isolation: bool,
|
||||
/// With `process_isolation`: isolate a task other than task 0 only when, as the guest
|
||||
/// defines it, the [`crate::IoSurfaceDevice`] the device maps through has a descriptor table
|
||||
/// base other than 0; otherwise the task runs as without isolation. The guest's mapper
|
||||
/// driver writes the base at its start, before Apple's arm64 GPU driver makes a task. Apple's
|
||||
/// x86-64 driver never touches the IOSurface device, and references IOSurfaces through task
|
||||
/// 0's backings, which an isolated task does not serve. Device info's argument-buffer answer
|
||||
/// follows the same rule, read when the guest asks, since only isolated tasks serve argument
|
||||
/// buffers. Default `false`.
|
||||
pub process_isolation_follows_guest: bool,
|
||||
/// Offer argument buffers: they reach the guest only with process isolation, on a Metal
|
||||
/// device that can detach backing and is not itself paravirtual, and, with
|
||||
/// `process_isolation_follows_guest`, only while the IOSurface device has a descriptor
|
||||
/// table. Default `true`.
|
||||
pub argument_buffers: bool,
|
||||
/// The callbacks.
|
||||
pub callbacks: HostCallbacks,
|
||||
/// With `memory_map`: the host's dirty source, which tells the device which of the guest's
|
||||
/// pages the guest wrote (QEMU under KVM), so that the Vulkan runtime copies again only
|
||||
/// those; `None` for none, and without a memory map. Default `None`.
|
||||
pub dirty_source: Option<DirtySource>,
|
||||
}
|
||||
|
||||
impl Default for DeviceConfig {
|
||||
fn default() -> DeviceConfig {
|
||||
DeviceConfig {
|
||||
metal_registry_id: None,
|
||||
display_port_count: 1,
|
||||
feature_level: 0,
|
||||
display_port_connection_types: 0,
|
||||
memory_map: None,
|
||||
use_iosurface_mapper: false,
|
||||
process_isolation: false,
|
||||
process_isolation_follows_guest: false,
|
||||
argument_buffers: true,
|
||||
callbacks: HostCallbacks::default(),
|
||||
dirty_source: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DeviceConfig {
|
||||
/// Core's config over `device`: the same closures, the map's ranges copied.
|
||||
fn into_core<P: Platform>(self, device: Option<P::Device>) -> CoreDeviceConfig<P> {
|
||||
CoreDeviceConfig {
|
||||
device,
|
||||
display_port_count: self.display_port_count,
|
||||
blocks: self.callbacks.into_core(),
|
||||
memory_map_descriptor: self.memory_map.as_ref().map(|m| Arc::new(m.to_core())),
|
||||
using_iosurface_mapper: self.use_iosurface_mapper,
|
||||
enable_argument_buffers: self.argument_buffers,
|
||||
enable_process_isolation: self.process_isolation,
|
||||
process_isolation_follows_guest: self.process_isolation_follows_guest,
|
||||
device_feature_level: self.feature_level,
|
||||
display_port_connection_types: self.display_port_connection_types,
|
||||
..CoreDeviceConfig::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform's lease on the guest's RAM for one device ([`ApiPlatform::guest_memory`]),
|
||||
/// shared by the device's references and its displays.
|
||||
pub(crate) type GuestMemoryLease = Arc<dyn Any + Send + Sync>;
|
||||
|
||||
/// Whether a device takes its host's dirty source: unless `REIMS_VGPU_DIRTY_PAGE_TRACKING` is `0`,
|
||||
/// read once per process.
|
||||
fn dirty_page_tracking_on() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("REIMS_VGPU_DIRTY_PAGE_TRACKING").is_none_or(|v| v != "0"))
|
||||
}
|
||||
|
||||
/// What a device over a memory map holds of the guest's RAM: the platform's lease, then the
|
||||
/// harvest of the host's dirty source, whose drop retires the log after the lease has gone.
|
||||
struct Lease {
|
||||
_platform: Box<dyn Any + Send + Sync>,
|
||||
_dirty: Option<Harvester>,
|
||||
}
|
||||
|
||||
/// One reference to a device. `P` is the platform: [`DefaultPlatform`] in the product, core's
|
||||
/// fake platform in tests.
|
||||
pub struct Device<P: Platform = DefaultPlatform> {
|
||||
pub(crate) handle: Ours<CoreDevice<P>>,
|
||||
/// The platform the device was made on.
|
||||
platform: Arc<P>,
|
||||
/// The platform's lease on the guest's RAM, for a device made over a memory map. Declared
|
||||
/// after `handle`, so a reference drops it after its core handle: the last drop, core's
|
||||
/// teardown among them, runs before the lease goes.
|
||||
guest_memory: Option<GuestMemoryLease>,
|
||||
/// The dirty log of a device made with a dirty source (the module docs).
|
||||
dirty_log: Option<Arc<DirtyLog>>,
|
||||
}
|
||||
|
||||
impl<P: Platform> std::fmt::Debug for Device<P> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Device")
|
||||
.field("core", &Arc::as_ptr(&**self.handle))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Device {
|
||||
/// A new device on the process's platform ([`Device::with_platform`]).
|
||||
pub fn new(config: DeviceConfig) -> Result<Device, Error> {
|
||||
Device::with_platform(DefaultPlatform::process(), config)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> Device<P> {
|
||||
/// A new device on `platform`. Refusals, in core's order: [`Error::DisplayPortCount`],
|
||||
/// [`Error::NoMetalDevice`], [`Error::MemoryConflict`], [`Error::MemoryMap`],
|
||||
/// [`Error::InvalidArgument`] (`add_trace_range` without `remove_trace_range`),
|
||||
/// [`Error::Metal`], [`Error::IsolationWithoutMap`]. The first device given a Metal device
|
||||
/// makes the process's frame queue for it, before the device is built, even when the device
|
||||
/// is then refused. A refusal has dropped every closure of the config when it returns.
|
||||
///
|
||||
/// With a memory map, the platform's lease on the guest's RAM
|
||||
/// ([`ApiPlatform::guest_memory`]) is taken before core's device is made, and a refusal
|
||||
/// drops it before it returns.
|
||||
pub fn with_platform(platform: Arc<P>, config: DeviceConfig) -> Result<Device<P>, Error> {
|
||||
entry::run(|_| {
|
||||
let metal = platform.metal_device(config.metal_registry_id);
|
||||
if let Some(metal) = &metal {
|
||||
drop(api_state(&platform).frame_queue(metal));
|
||||
}
|
||||
let mut guest_memory: Option<GuestMemoryLease> = None;
|
||||
let mut dirty_log = None;
|
||||
if let Some(map) = &config.memory_map {
|
||||
let dirty = (config.dirty_source.clone())
|
||||
.filter(|_| dirty_page_tracking_on())
|
||||
.map(|source| {
|
||||
let ram: Vec<_> = (map.ranges().iter())
|
||||
.map(|r| r.physical_address..r.physical_address + r.physical_length)
|
||||
.collect();
|
||||
Harvester::new(&ram, source)
|
||||
});
|
||||
dirty_log = dirty.as_ref().map(|h| h.log().clone());
|
||||
guest_memory = Some(Arc::new(Lease {
|
||||
_platform: platform.guest_memory(map, dirty_log.clone()),
|
||||
_dirty: dirty,
|
||||
}));
|
||||
}
|
||||
let core = config.into_core::<P>(metal);
|
||||
match CoreDevice::new(platform.clone(), core) {
|
||||
Ok(handle) => Ok(Device {
|
||||
handle: Ours::new(handle),
|
||||
platform: platform.clone(),
|
||||
guest_memory,
|
||||
dirty_log,
|
||||
}),
|
||||
Err(refusal) => Err(refusal.into()),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A new display. Refusals, in core's order: [`Error::PortOutOfRange`], [`Error::Metal`],
|
||||
/// [`Error::SerialInUse`], [`Error::PortInUse`]. The display keeps the device alive. May
|
||||
/// call back. With a window ([`DisplayConfig::window`]), the display has every callback as
|
||||
/// the guest reads them, and a refusal closes the window before it returns.
|
||||
pub fn new_display(&self, config: DisplayConfig) -> Result<Display<P>, Error> {
|
||||
Display::new(self, config)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Device<P> {
|
||||
/// Another reference to this device. The device ends when the last one drops.
|
||||
#[must_use]
|
||||
pub fn clone_ref(&self) -> Device<P> {
|
||||
Device {
|
||||
handle: Ours::new(self.handle.clone_ref()),
|
||||
platform: self.platform.clone(),
|
||||
guest_memory: self.guest_memory.clone(),
|
||||
dirty_log: self.dirty_log.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform's lease on the guest's RAM, for a device made over a memory map: what a
|
||||
/// display keeps beside its core display, which keeps core's device alive.
|
||||
pub(crate) fn guest_memory_lease(&self) -> Option<GuestMemoryLease> {
|
||||
self.guest_memory.clone()
|
||||
}
|
||||
|
||||
/// Whether both are references to one device.
|
||||
pub fn ptr_eq(&self, other: &Device<P>) -> bool {
|
||||
self.handle.ptr_eq(&other.handle)
|
||||
}
|
||||
|
||||
/// Core's device (tests).
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub fn core(&self) -> &CoreDevice<P> {
|
||||
&self.handle
|
||||
}
|
||||
|
||||
/// The platform the device was made on.
|
||||
pub(crate) fn platform(&self) -> &Arc<P> {
|
||||
&self.platform
|
||||
}
|
||||
|
||||
/// Runs `body` as an entry ([`entry::run`]), with a hold of the entry's holder.
|
||||
fn entry<T>(&self, body: impl for<'u> FnOnce(Hold<'u>, &CoreDevice<P>) -> T) -> T {
|
||||
entry::run(|hold| body(hold, &self.handle))
|
||||
}
|
||||
|
||||
/// As [`Device::entry`], with the dirty log closed while `body` runs (the module docs).
|
||||
fn closed_entry<T>(&self, body: impl for<'u> FnOnce(Hold<'u>, &CoreDevice<P>) -> T) -> T {
|
||||
let Some(log) = &self.dirty_log else {
|
||||
return self.entry(body);
|
||||
};
|
||||
log.close();
|
||||
let r = self.entry(body);
|
||||
log.reopen();
|
||||
r
|
||||
}
|
||||
|
||||
/// A 32-bit read at `offset` in the device's MMIO region. May block and may call back.
|
||||
pub fn mmio_read(&self, offset: u64) -> u32 {
|
||||
self.entry(|_, d| d.mmio_read(offset))
|
||||
}
|
||||
|
||||
/// A 32-bit write at `offset`. May block: a root FIFO write waits for the FIFO's thread,
|
||||
/// and `raise_interrupt` may run inside it.
|
||||
pub fn mmio_write(&self, offset: u64, value: u32) {
|
||||
self.entry(|hold, d| d.mmio_write(hold, offset, value));
|
||||
}
|
||||
|
||||
/// Resets the device as the guest's bus reset does: stops it as [`Device::stop`] does, sets
|
||||
/// the guest's binary version back to 0 and turns EFI off, and returns once it is quiesced.
|
||||
/// Blocks as [`Device::stop`] does, and for the EFI display's present thread. At a
|
||||
/// `feature_level` above 4 it ends the process.
|
||||
pub fn reset(&self) {
|
||||
self.closed_entry(|hold, d| d.reset(hold));
|
||||
}
|
||||
|
||||
/// Pauses the device: each FIFO finishes the commands it started and stops, then the guest's
|
||||
/// displays pause. Blocks until each FIFO's thread has stopped and those commands have
|
||||
/// completed, and hangs while one never does. Where the guest has given a port a display
|
||||
/// page, a second pause before [`Device::unpause`] ends the process.
|
||||
pub fn pause(&self) {
|
||||
self.closed_entry(|_, d| d.pause());
|
||||
}
|
||||
|
||||
/// Resumes the device after [`Device::pause`]: unpauses the guest's displays, starts every
|
||||
/// FIFO and raises one interrupt. Blocks while the FIFOs start on the library's FIFO control
|
||||
/// thread. Where the guest has given a port a display page, an unpause while the guest's
|
||||
/// displays are not paused ends the process: [`Device::pause`] and
|
||||
/// [`Device::finish_suspend`] pause them, and [`Device::will_suspend`] does not.
|
||||
pub fn unpause(&self) {
|
||||
self.entry(|_, d| d.unpause());
|
||||
}
|
||||
|
||||
/// Stops the device as a root page of 0 does: its FIFOs, the guest's tasks and the guest's
|
||||
/// display pages are torn down. Blocks until each FIFO's thread has stopped and the commands
|
||||
/// it started have completed.
|
||||
pub fn stop(&self) {
|
||||
self.closed_entry(|hold, d| d.stop(hold));
|
||||
}
|
||||
|
||||
/// Starts a suspend: from here the device raises no interrupt, and drops those not yet
|
||||
/// raised. It quiesces the FIFOs without waiting for them, and pauses none of the guest's
|
||||
/// displays.
|
||||
pub fn will_suspend(&self) {
|
||||
self.closed_entry(|_, d| d.will_suspend());
|
||||
}
|
||||
|
||||
/// Ends a suspend: the device's state. The device always has one to give, so
|
||||
/// [`Error::Suspend`] never comes. Without [`Device::will_suspend`] before it, it ends the
|
||||
/// process. Blocks until each FIFO's thread has stopped and the commands it started have
|
||||
/// completed, then flushes and ends the guest's tasks and pauses the guest's displays.
|
||||
pub fn finish_suspend(&self) -> Result<Vec<u8>, Error> {
|
||||
self.closed_entry(|_, d| d.finish_suspend())
|
||||
.ok_or(Error::Suspend)
|
||||
}
|
||||
|
||||
/// Offers the device a state [`Device::finish_suspend`] gave, before the guest runs again.
|
||||
/// `None` is no state, which the device refuses as invalid content. A refusal is
|
||||
/// [`Error::Resume`] with the device's reason, or `None` where it stored none. From this call
|
||||
/// until [`Device::did_resume`], whether or not it accepted the state, a new mapping of guest
|
||||
/// memory (the guest's root page write, for one) ends the process. A state whose binary
|
||||
/// version has no EFI display turns EFI off, which waits for the EFI display's present thread.
|
||||
pub fn will_resume(&self, state: Option<&[u8]>) -> Result<(), Error> {
|
||||
self.closed_entry(|_, d| {
|
||||
let mut code = None;
|
||||
if d.will_resume(state, Some(&mut code)) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::Resume(code.and_then(ResumeError::from_code)))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Ends a resume [`Device::will_resume`] accepted: rebuilds the device from the state, starts
|
||||
/// its FIFOs and raises one interrupt. Rebuilding the EFI display waits for its present
|
||||
/// thread, and a root the device still has is torn down as [`Device::stop`] does.
|
||||
pub fn did_resume(&self) {
|
||||
self.closed_entry(|hold, d| d.did_resume(hold));
|
||||
}
|
||||
|
||||
/// A frame target on this device's Metal device: `width` x `height` pixels of `format`,
|
||||
/// each 1 to 16384 ([`Error::InvalidArgument`] otherwise). It holds no reference to the
|
||||
/// device.
|
||||
pub fn new_frame_target(
|
||||
&self,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: PixelFormat,
|
||||
) -> Result<FrameTarget<P>, Error> {
|
||||
FrameTarget::new(
|
||||
self.platform(),
|
||||
self.handle.mtl_device_ref(),
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use reims_vgpu_core::rt::is_our_thread;
|
||||
use reims_vgpu_core::testkit::host::FakeHost;
|
||||
use reims_vgpu_core::testkit::{FakePlatform, GuestRam};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A fake host's callbacks as the API's.
|
||||
pub(crate) fn callbacks(host: &Arc<FakeHost>) -> HostCallbacks {
|
||||
let b = host.blocks();
|
||||
HostCallbacks {
|
||||
create_task: b.create_task,
|
||||
destroy_task: b.destroy_task,
|
||||
map_memory: b.map_memory,
|
||||
unmap_memory: b.unmap_memory,
|
||||
read_memory: b.read_memory,
|
||||
raise_interrupt: b.raise_interrupt,
|
||||
add_trace_range: b.add_trace_range,
|
||||
remove_trace_range: b.remove_trace_range,
|
||||
}
|
||||
}
|
||||
|
||||
fn fake(
|
||||
ports: u32,
|
||||
) -> (
|
||||
Arc<FakePlatform>,
|
||||
Arc<FakeHost>,
|
||||
Result<Device<FakePlatform>, Error>,
|
||||
) {
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let host = FakeHost::new(&p, GuestRam::with_range(0, 0x40_0000).unwrap());
|
||||
let c = DeviceConfig {
|
||||
display_port_count: ports,
|
||||
callbacks: callbacks(&host),
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
let d = Device::with_platform(p.clone(), c);
|
||||
(p, host, d)
|
||||
}
|
||||
|
||||
/// The defaults: one port, argument buffers offered, everything else off
|
||||
#[test]
|
||||
fn config_defaults() {
|
||||
let c = DeviceConfig::default();
|
||||
assert_eq!(c.display_port_count, 1);
|
||||
assert!(c.argument_buffers && !c.process_isolation && !c.use_iosurface_mapper);
|
||||
assert!(!c.process_isolation_follows_guest);
|
||||
assert_eq!((c.feature_level, c.display_port_connection_types), (0, 0));
|
||||
assert!(c.metal_registry_id.is_none() && c.memory_map.is_none());
|
||||
let core = c.into_core::<FakePlatform>(None);
|
||||
let want = CoreDeviceConfig::<FakePlatform>::default();
|
||||
assert_eq!(core.display_port_count, want.display_port_count);
|
||||
assert_eq!(core.enable_argument_buffers, want.enable_argument_buffers);
|
||||
assert_eq!(core.mmio_length, want.mmio_length);
|
||||
assert!(!core.process_isolation_follows_guest);
|
||||
}
|
||||
|
||||
/// Isolation and its following the guest reach core's config as set
|
||||
#[test]
|
||||
fn isolation_fields_reach_core() {
|
||||
for (isolate, follows) in [(true, true), (true, false), (false, true)] {
|
||||
let c = DeviceConfig {
|
||||
process_isolation: isolate,
|
||||
process_isolation_follows_guest: follows,
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
let core = c.into_core::<FakePlatform>(None);
|
||||
assert_eq!(
|
||||
(
|
||||
core.enable_process_isolation,
|
||||
core.process_isolation_follows_guest
|
||||
),
|
||||
(isolate, follows)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Each refusal names its check; the closures of a refused config are dropped
|
||||
#[test]
|
||||
fn refusals() {
|
||||
assert_eq!(fake(0).2.err(), Some(Error::DisplayPortCount));
|
||||
assert_eq!(fake(9).2.err(), Some(Error::DisplayPortCount));
|
||||
assert!(fake(8).2.is_ok());
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let raise: RaiseInterrupt = Arc::new(|_| {});
|
||||
let c = DeviceConfig {
|
||||
metal_registry_id: Some(1),
|
||||
callbacks: HostCallbacks {
|
||||
raise_interrupt: Some(raise.clone()),
|
||||
..HostCallbacks::default()
|
||||
},
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Device::with_platform(p.clone(), c).err(),
|
||||
Some(Error::NoMetalDevice)
|
||||
);
|
||||
assert_eq!(Arc::strong_count(&raise), 1);
|
||||
// add_trace_range alone is an invalid argument.
|
||||
let host = FakeHost::new(&p, GuestRam::new());
|
||||
let mut cb = callbacks(&host);
|
||||
cb.remove_trace_range = None;
|
||||
let c = DeviceConfig {
|
||||
callbacks: cb,
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Device::with_platform(p.clone(), c).err(),
|
||||
Some(Error::InvalidArgument)
|
||||
);
|
||||
// A memory map beside the task callbacks.
|
||||
let c = DeviceConfig {
|
||||
memory_map: Some(MemoryMap::new()),
|
||||
callbacks: callbacks(&host),
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Device::with_platform(p.clone(), c).err(),
|
||||
Some(Error::MemoryConflict)
|
||||
);
|
||||
let c = DeviceConfig {
|
||||
process_isolation: true,
|
||||
callbacks: callbacks(&host),
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
assert_eq!(
|
||||
Device::with_platform(p, c).err(),
|
||||
Some(Error::IsolationWithoutMap)
|
||||
);
|
||||
}
|
||||
|
||||
/// The API answers what core answers, and a write reaches the device; clone_ref is another
|
||||
/// reference and the last drop ends the device
|
||||
#[test]
|
||||
fn mmio_and_references() {
|
||||
let (_p, _h, d) = fake(1);
|
||||
let d = d.unwrap();
|
||||
for off in (0..0x100).step_by(4) {
|
||||
assert_eq!(d.mmio_read(off), d.core().mmio_read(off), "{off:#x}");
|
||||
}
|
||||
d.mmio_write(0x2000, 0);
|
||||
let d2 = d.clone_ref();
|
||||
assert!(d.ptr_eq(&d2));
|
||||
let weak = Arc::downgrade(&**d.core());
|
||||
drop(d);
|
||||
assert!(weak.upgrade().is_some());
|
||||
drop(d2);
|
||||
assert!(weak.upgrade().is_none());
|
||||
assert!(!is_our_thread());
|
||||
}
|
||||
|
||||
/// A device over a memory map holds the platform's lease on the guest's RAM, which its
|
||||
/// references share; a device without a map holds none
|
||||
#[test]
|
||||
fn a_memory_map_takes_the_platform_s_lease() {
|
||||
let (_p, _h, d) = fake(1);
|
||||
assert!(d.unwrap().guest_memory_lease().is_none());
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let c = DeviceConfig {
|
||||
memory_map: Some(MemoryMap::new()),
|
||||
callbacks: HostCallbacks {
|
||||
raise_interrupt: Some(Arc::new(|_| {})),
|
||||
..HostCallbacks::default()
|
||||
},
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
let d = Device::with_platform(p, c).unwrap();
|
||||
let lease = d.guest_memory_lease().unwrap();
|
||||
let d2 = d.clone_ref();
|
||||
assert!(Arc::ptr_eq(&d2.guest_memory_lease().unwrap(), &lease));
|
||||
assert_eq!(Arc::strong_count(&lease), 3);
|
||||
drop((d, d2));
|
||||
assert_eq!(Arc::strong_count(&lease), 1);
|
||||
}
|
||||
|
||||
/// No state is refused as invalid content; a suspend gives a state the device accepts
|
||||
#[test]
|
||||
fn suspend_and_resume() {
|
||||
let (_p, _h, d) = fake(1);
|
||||
let d = d.unwrap();
|
||||
assert_eq!(
|
||||
d.will_resume(None),
|
||||
Err(Error::Resume(Some(ResumeError::InvalidContent)))
|
||||
);
|
||||
d.will_suspend();
|
||||
let state = d.finish_suspend().unwrap();
|
||||
assert_eq!(d.will_resume(Some(&state)), Ok(()));
|
||||
d.did_resume();
|
||||
d.pause();
|
||||
d.unpause();
|
||||
d.reset();
|
||||
d.stop();
|
||||
}
|
||||
|
||||
/// The memory map keeps its ranges in order, and the file behind each beside it
|
||||
#[test]
|
||||
fn memory_map_ranges() {
|
||||
let mut m = MemoryMap::new();
|
||||
let mut page = [0u8; 8];
|
||||
let fd = Arc::new(OwnedFd::from(std::fs::File::open("/dev/null").unwrap()));
|
||||
let file = MemoryFile {
|
||||
fd: fd.clone(),
|
||||
offset: 0x8000,
|
||||
};
|
||||
// SAFETY: nothing is built over this map.
|
||||
unsafe {
|
||||
m.push(0x4000, 0x4000, page.as_mut_ptr());
|
||||
m.push_with_file(0, 0x4000, page.as_mut_ptr(), Some(file));
|
||||
}
|
||||
let got: Vec<u64> = m.ranges().iter().map(|r| r.physical_address).collect();
|
||||
assert_eq!(got, [0x4000, 0]);
|
||||
assert_eq!(m.to_core().ranges(), m.ranges());
|
||||
let files: Vec<Option<u64>> = m
|
||||
.files()
|
||||
.iter()
|
||||
.map(|f| f.as_ref().map(|f| f.offset))
|
||||
.collect();
|
||||
assert_eq!(files, [None, Some(0x8000)]);
|
||||
assert!(Arc::ptr_eq(&m.files()[1].as_ref().unwrap().fd, &fd));
|
||||
// A clone of the map holds the same file.
|
||||
let copy = m.clone();
|
||||
assert_eq!(Arc::strong_count(&fd), 3);
|
||||
drop((m, copy));
|
||||
assert_eq!(Arc::strong_count(&fd), 1);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! The guest's RAM that the host's own devices write, outside any guest GPU work: the video
|
||||
//! devices' frames, written into an IOSurface's pages by a CPU lend
|
||||
//! ([`crate::video::MappedSurface`]'s `write`) or by a device of the host (the decoders' zero
|
||||
//! copy, the scaler's GPU in place).
|
||||
//! The guest's RAM that the host's own devices write, outside any guest GPU work: the frames the
|
||||
//! graphics device's video arms decode into an IOSurface's pages, by the CPU or by a device of the
|
||||
//! host.
|
||||
//!
|
||||
//! A graphics device keeps the GPU's copy of an IOSurface in its GPU's memory where the kext asks
|
||||
//! (`graphics/decode/surface_cache.rs`), filled from the pages only when the guest's CPU
|
||||
@@ -10,8 +9,7 @@
|
||||
//! use fills it from the pages, and no download copies it over them.
|
||||
//!
|
||||
//! The pages are named by their host addresses in the mapping of the guest's RAM the host gave
|
||||
//! the devices' memory maps: the IOSurface device keeps them for each guest page of a surface,
|
||||
//! and a graphics device reaches the same addresses through its own map of the RAM. A watcher is
|
||||
//! the device's memory map, which a graphics device reaches through its own map of the RAM. A watcher is
|
||||
//! called on the writer's thread once the write is in the pages, before the guest is told of it.
|
||||
//! The list's lock is a leaf: watchers are called after it is let go.
|
||||
|
||||
@@ -24,6 +22,10 @@ use reims_vgpu_core::sync::Mutex;
|
||||
pub(crate) trait Watcher: Send + Sync {
|
||||
/// The host's devices wrote `runs`, host addresses in the guest's RAM, in address order and
|
||||
/// apart ([`sorted`]).
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(dead_code, reason = "the graphics device's video arms write the guest's pages")
|
||||
)]
|
||||
fn wrote(&self, runs: &[Range<u64>]);
|
||||
}
|
||||
|
||||
@@ -38,6 +40,10 @@ pub(crate) fn watch(watcher: &Arc<dyn Watcher>) {
|
||||
}
|
||||
|
||||
/// A device of the host wrote `runs`, [`sorted`] (module docs): each live watcher is told.
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(dead_code, reason = "the graphics device's video arms write the guest's pages")
|
||||
)]
|
||||
pub(crate) fn wrote(runs: &[Range<u64>]) {
|
||||
if runs.is_empty() {
|
||||
return;
|
||||
|
||||
@@ -1,470 +0,0 @@
|
||||
//! A host's dirty source ([`DirtySource`]), and the device's harvest of it.
|
||||
//!
|
||||
//! On a discrete GPU, and on an iGPU whose driver cannot reference the guest's memory, the
|
||||
//! Vulkan runtime keeps copies of the guest's pages, and copies again only the pages core's
|
||||
//! [`DirtyLog`] shows written since its last copy. The guest's own writes reach the log here:
|
||||
//! QEMU under KVM gives the device its VM's file descriptor and a [`DirtyHost`], and the device
|
||||
//! reads KVM's dirty log itself, on a thread of its own (`reims-vgpu.dirty`), each time the log
|
||||
//! wants a harvest. A harvest, in this order:
|
||||
//!
|
||||
//! 1. [`DirtyLog::begin`] numbers it and gives the watched runs;
|
||||
//! 2. where the CPU buffers a vCPU's writes until the vCPU exits (Intel's page-modification
|
||||
//! log, `pml` of `kvm_intel` or `kvm_amd`), [`DirtyHost::flush_vcpus`] makes each vCPU in
|
||||
//! `KVM_RUN` leave it once: `KVM_GET_DIRTY_LOG` kicks them, and does not wait;
|
||||
//! 3. for each memory slot that logs ([`DirtyHost::for_each_slot`], under the host's lock on its
|
||||
//! slots) that holds a watched page: one `KVM_GET_DIRTY_LOG`, which under KVM's manual
|
||||
//! dirty-log protection clears nothing, then one `KVM_CLEAR_DIRTY_LOG` of exactly the watched
|
||||
//! pages it shows written, which KVM then protects again; and the host's own writes into those
|
||||
//! pages ([`DirtyHost::take_host_writes`], QEMU's DMA);
|
||||
//! 4. [`DirtyLog::end`] publishes the pages written.
|
||||
//!
|
||||
//! A write between the read and the clear of a page the clear names is in memory before the
|
||||
//! publish, so before any copy the publish allows; one to a page it does not name keeps its
|
||||
//! bit for the next harvest. What the harvest cannot answer reads as written: a page no logged
|
||||
//! slot of address space 0 holds (the log before its start among them), a slot whose read KVM
|
||||
//! refused, a host that reads the log itself ([`DirtyHost::for_each_slot`] false), a flush past
|
||||
//! its time, and the host's writes where a granule's place in the host's record does not keep
|
||||
//! its guest address's offset in a [`GRANULE`]. Each costs a copy, never a missed write.
|
||||
//!
|
||||
//! The log is started ([`DirtyHost::start`]) at the first harvest, not with the device: KVM maps
|
||||
//! a logged slot's pages 4 KiB at a time, so a device whose runtime never asks costs the guest
|
||||
//! no huge pages.
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::{self, JoinHandle, Thread};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_core::memory::dirty::{DirtyLog, DirtyStamp, GRANULE, PAGE_SIZE};
|
||||
|
||||
/// How long a flush of the vCPUs may take: the log's own wait, past which a harvest no longer
|
||||
/// spares the copy it was wanted for.
|
||||
const FLUSH_TIMEOUT: Duration = Duration::from_millis(4);
|
||||
|
||||
/// One memory slot of the host's KVM VM that logs dirty pages ([`DirtyHost::for_each_slot`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct KvmSlot {
|
||||
/// As `KVM_GET_DIRTY_LOG` and `KVM_CLEAR_DIRTY_LOG` take it: the address space's ID << 16 |
|
||||
/// the slot's ID.
|
||||
pub slot: u32,
|
||||
/// The guest physical address of its first page.
|
||||
pub guest_physical_address: u64,
|
||||
/// Its length in bytes, a multiple of 4 KiB.
|
||||
pub length: u64,
|
||||
/// Where its first page lies in the host's own record of its writes
|
||||
/// ([`DirtyHost::take_host_writes`]): QEMU's `ram_addr_t`.
|
||||
pub host_offset: u64,
|
||||
}
|
||||
|
||||
/// What the host does for a harvest. Each method is called on the device's harvest thread, one
|
||||
/// at a time, and must not wait for the library or take a lock the host holds while it calls the
|
||||
/// library (QEMU's BQL).
|
||||
pub trait DirtyHost: Send + Sync {
|
||||
/// Starts logging the guest's RAM's dirty pages, with KVM's manual dirty-log protection and
|
||||
/// every page logged as written at its start (`KVM_DIRTY_LOG_INITIALLY_SET`). Called once, at
|
||||
/// the first harvest. It must not block: the log may start later, and until it does
|
||||
/// [`DirtyHost::for_each_slot`] lists none of the RAM's slots.
|
||||
fn start(&self);
|
||||
|
||||
/// Waits until each vCPU that was inside `KVM_RUN` has returned from it once, so that KVM has
|
||||
/// drained the CPU's buffer of its writes into the slots' logs, `timeout` at most. False at
|
||||
/// the timeout. Called only where the CPU buffers them.
|
||||
fn flush_vcpus(&self, timeout: Duration) -> bool;
|
||||
|
||||
/// Calls `slot` for each memory slot that logs dirty pages, holding the host's lock on its
|
||||
/// slots, so none changes before it returns. False, calling none, where the host reads and
|
||||
/// clears the log itself (QEMU's global dirty tracking).
|
||||
fn for_each_slot(&self, slot: &mut dyn FnMut(KvmSlot)) -> bool;
|
||||
|
||||
/// ORs into `words`, one bit a 4 KiB page from `host_offset`, the pages of `length` bytes
|
||||
/// the host itself wrote since its last take, and clears them in its record. Called only
|
||||
/// inside [`DirtyHost::for_each_slot`]'s `slot`, with `host_offset` and `length` multiples
|
||||
/// of [`GRANULE`].
|
||||
fn take_host_writes(&self, host_offset: u64, length: u64, words: &mut [u64]);
|
||||
}
|
||||
|
||||
/// A host's dirty source ([`crate::DeviceConfig::dirty_source`]).
|
||||
#[derive(Clone)]
|
||||
pub struct DirtySource {
|
||||
/// The KVM VM's file descriptor, open while the device lives.
|
||||
pub kvm_vm_fd: i32,
|
||||
/// What the host does for a harvest.
|
||||
pub host: Arc<dyn DirtyHost>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DirtySource {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DirtySource")
|
||||
.field("kvm_vm_fd", &self.kvm_vm_fd)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// KVM's two dirty-log ioctls on one slot (the VM's in the product, a fake in tests).
|
||||
pub(crate) trait KvmLog: Send {
|
||||
/// `KVM_GET_DIRTY_LOG` into `bitmap`, which holds a bit for each of the slot's pages.
|
||||
fn get(&self, slot: u32, bitmap: &mut [u64]) -> bool;
|
||||
/// `KVM_CLEAR_DIRTY_LOG` of the pages `bitmap` sets, from `first_page` (a multiple of 64)
|
||||
/// for `num_pages`.
|
||||
fn clear(&self, slot: u32, first_page: u64, num_pages: u32, bitmap: &[u64]) -> bool;
|
||||
}
|
||||
|
||||
/// The VM's file descriptor, borrowed from the host.
|
||||
struct VmFd(i32);
|
||||
|
||||
/// `struct kvm_dirty_log` (linux/kvm.h).
|
||||
#[repr(C)]
|
||||
struct KvmDirtyLog {
|
||||
slot: u32,
|
||||
padding1: u32,
|
||||
dirty_bitmap: *mut u64,
|
||||
}
|
||||
|
||||
/// `struct kvm_clear_dirty_log` (linux/kvm.h).
|
||||
#[repr(C)]
|
||||
struct KvmClearDirtyLog {
|
||||
slot: u32,
|
||||
num_pages: u32,
|
||||
first_page: u64,
|
||||
dirty_bitmap: *const u64,
|
||||
}
|
||||
|
||||
/// `_IOW(KVMIO, 0x42, struct kvm_dirty_log)`.
|
||||
const KVM_GET_DIRTY_LOG: u64 = 0x4010_ae42;
|
||||
/// `_IOWR(KVMIO, 0xc0, struct kvm_clear_dirty_log)`.
|
||||
const KVM_CLEAR_DIRTY_LOG: u64 = 0xc018_aec0;
|
||||
|
||||
const _: () = assert!(size_of::<KvmDirtyLog>() == 16 && size_of::<KvmClearDirtyLog>() == 24);
|
||||
|
||||
impl KvmLog for VmFd {
|
||||
fn get(&self, slot: u32, bitmap: &mut [u64]) -> bool {
|
||||
let mut log = KvmDirtyLog {
|
||||
slot,
|
||||
padding1: 0,
|
||||
dirty_bitmap: bitmap.as_mut_ptr(),
|
||||
};
|
||||
// SAFETY: KVM writes the slot's bitmap, a bit a page rounded up to a 64-bit word, which
|
||||
// `bitmap` holds: the host's lock on its slots keeps the slot as listed.
|
||||
unsafe { libc::ioctl(self.0, KVM_GET_DIRTY_LOG as _, &raw mut log) == 0 }
|
||||
}
|
||||
|
||||
fn clear(&self, slot: u32, first_page: u64, num_pages: u32, bitmap: &[u64]) -> bool {
|
||||
let mut log = KvmClearDirtyLog {
|
||||
slot,
|
||||
num_pages,
|
||||
first_page,
|
||||
dirty_bitmap: bitmap.as_ptr(),
|
||||
};
|
||||
// SAFETY: KVM reads `num_pages` bits of `bitmap`, which holds them.
|
||||
unsafe { libc::ioctl(self.0, KVM_CLEAR_DIRTY_LOG as _, &raw mut log) == 0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the CPU buffers a vCPU's dirty pages until the vCPU exits: `pml` of `kvm_intel`, or
|
||||
/// of `kvm_amd` where KVM has it. Without it KVM write-protects a logged page, and marks it in the
|
||||
/// slot's log at the fault, before the write completes.
|
||||
fn cpu_buffers_writes() -> bool {
|
||||
[
|
||||
"/sys/module/kvm_intel/parameters/pml",
|
||||
"/sys/module/kvm_amd/parameters/pml",
|
||||
]
|
||||
.iter()
|
||||
.any(|p| std::fs::read(p).is_ok_and(|v| matches!(v.first(), Some(b'Y' | b'1'))))
|
||||
}
|
||||
|
||||
/// The scratch one harvest uses, kept for the next.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Scratch {
|
||||
watched: Vec<Range<u64>>,
|
||||
/// The pages written, a word a granule of `watched`.
|
||||
written: Vec<u64>,
|
||||
/// The pages a logged slot of address space 0 answered for, a word a granule.
|
||||
known: Vec<u64>,
|
||||
/// The first granule of each run of `watched`, in their order.
|
||||
firsts: Vec<usize>,
|
||||
log: Vec<u64>,
|
||||
clear: Vec<u64>,
|
||||
}
|
||||
|
||||
/// The `n` bits of `bitmap` from bit `at`, `n` at most 64, in the low bits of the result.
|
||||
fn bits(bitmap: &[u64], at: u64, n: u64) -> u64 {
|
||||
let (w, s) = ((at / 64) as usize, at % 64);
|
||||
let lo = bitmap.get(w).copied().unwrap_or(0) >> s;
|
||||
let hi = if s == 0 {
|
||||
0
|
||||
} else {
|
||||
bitmap.get(w + 1).copied().unwrap_or(0) << (64 - s)
|
||||
};
|
||||
let all = lo | hi;
|
||||
if n >= 64 {
|
||||
all
|
||||
} else {
|
||||
all & ((1u64 << n) - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets in `bitmap` the low `n` bits of `value` from bit `at`.
|
||||
fn set_bits(bitmap: &mut [u64], at: u64, value: u64) {
|
||||
let (w, s) = ((at / 64) as usize, at % 64);
|
||||
if let Some(x) = bitmap.get_mut(w) {
|
||||
*x |= value << s;
|
||||
}
|
||||
if s != 0
|
||||
&& let Some(x) = bitmap.get_mut(w + 1)
|
||||
{
|
||||
*x |= value >> (64 - s);
|
||||
}
|
||||
}
|
||||
|
||||
/// One slot's part of a harvest (step 3 of the module docs).
|
||||
fn harvest_slot(host: &dyn DirtyHost, kvm: &dyn KvmLog, s: &mut Scratch, slot: KvmSlot) {
|
||||
let base = slot.guest_physical_address;
|
||||
let end = base.saturating_add(slot.length);
|
||||
let pages = slot.length / PAGE_SIZE;
|
||||
let primary = slot.slot >> 16 == 0;
|
||||
// The granules of the watched runs this slot holds a page of, by run.
|
||||
let mut parts: Vec<(usize, Range<u64>)> = Vec::new();
|
||||
for (i, run) in s.watched.iter().enumerate() {
|
||||
let (a, b) = (run.start.max(base), run.end.min(end));
|
||||
if a < b {
|
||||
parts.push((i, a..b));
|
||||
}
|
||||
}
|
||||
let (Some(first), Some(last)) = (parts.first(), parts.last()) else {
|
||||
return;
|
||||
};
|
||||
let lo = (first.1.start - base) / PAGE_SIZE;
|
||||
let hi = (last.1.end - base).div_ceil(PAGE_SIZE);
|
||||
s.log.clear();
|
||||
s.log.resize(pages.div_ceil(64) as usize, 0);
|
||||
let read = kvm.get(slot.slot, &mut s.log);
|
||||
let first_page = lo / 64 * 64;
|
||||
let num_pages = (hi.div_ceil(64) * 64).min(pages) - first_page;
|
||||
s.clear.clear();
|
||||
s.clear.resize(num_pages.div_ceil(64) as usize, 0);
|
||||
let mut cleared = false;
|
||||
for (i, part) in &parts {
|
||||
let run_start = s.watched[*i].start;
|
||||
let mut g = (part.start - run_start) / GRANULE * GRANULE + run_start;
|
||||
while g < part.end {
|
||||
let (a, b) = (g.max(part.start), (g + GRANULE).min(part.end));
|
||||
let n = (b - a) / PAGE_SIZE;
|
||||
let at = (a - base) / PAGE_SIZE;
|
||||
let shift = (a - g) / PAGE_SIZE;
|
||||
let mask = if n >= 64 {
|
||||
!0
|
||||
} else {
|
||||
((1u64 << n) - 1) << shift
|
||||
};
|
||||
let word = s.firsts[*i] + ((g - run_start) / GRANULE) as usize;
|
||||
if read {
|
||||
let dirty = bits(&s.log, at, n);
|
||||
s.written[word] |= dirty << shift;
|
||||
if primary {
|
||||
s.known[word] |= mask;
|
||||
}
|
||||
if dirty != 0 {
|
||||
set_bits(&mut s.clear, at - first_page, dirty);
|
||||
cleared = true;
|
||||
}
|
||||
} else {
|
||||
s.written[word] |= mask;
|
||||
}
|
||||
g += GRANULE;
|
||||
}
|
||||
}
|
||||
if cleared && !kvm.clear(slot.slot, first_page, num_pages as u32, &s.clear) {
|
||||
log::warn!(
|
||||
"reims-vgpu: KVM refused a clear of its dirty log for slot {:#x}",
|
||||
slot.slot
|
||||
);
|
||||
}
|
||||
if !primary || !read {
|
||||
return;
|
||||
}
|
||||
// The host's own writes, from its record a word a granule: where a granule lies whole in
|
||||
// the slot and keeps its offset in the record; elsewhere its pages read as written.
|
||||
for (i, part) in &parts {
|
||||
let run_start = s.watched[*i].start;
|
||||
let mut g = (part.start - run_start) / GRANULE * GRANULE + run_start;
|
||||
while g < part.end {
|
||||
let word = s.firsts[*i] + ((g - run_start) / GRANULE) as usize;
|
||||
let offset = slot.host_offset.wrapping_add(g.wrapping_sub(base));
|
||||
let whole = g >= base && g + GRANULE <= end && offset.is_multiple_of(GRANULE);
|
||||
if whole {
|
||||
// Every whole granule from here on in this part, in one take.
|
||||
let mut e = g;
|
||||
while e + GRANULE <= part.end.min(end) {
|
||||
e += GRANULE;
|
||||
}
|
||||
let words = ((e - g) / GRANULE) as usize;
|
||||
if let Some(out) = s.written.get_mut(word..word + words) {
|
||||
host.take_host_writes(offset, e - g, out);
|
||||
}
|
||||
g = e;
|
||||
} else {
|
||||
s.known[word] = 0;
|
||||
g += GRANULE;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The log's side of a harvest: [`DirtyLog`]'s, or a test's.
|
||||
pub(crate) trait HarvestLog {
|
||||
/// [`DirtyLog::begin`].
|
||||
fn begin(&self, watched: &mut Vec<Range<u64>>) -> Option<DirtyStamp>;
|
||||
/// [`DirtyLog::end`].
|
||||
fn end(&self, stamp: DirtyStamp, written: &[u64]) -> bool;
|
||||
}
|
||||
|
||||
impl HarvestLog for DirtyLog {
|
||||
fn begin(&self, watched: &mut Vec<Range<u64>>) -> Option<DirtyStamp> {
|
||||
DirtyLog::begin(self, watched)
|
||||
}
|
||||
|
||||
fn end(&self, stamp: DirtyStamp, written: &[u64]) -> bool {
|
||||
DirtyLog::end(self, stamp, written)
|
||||
}
|
||||
}
|
||||
|
||||
/// One harvest of `log` (the module docs).
|
||||
pub(crate) fn harvest(
|
||||
log: &dyn HarvestLog,
|
||||
host: &dyn DirtyHost,
|
||||
kvm: &dyn KvmLog,
|
||||
flush: bool,
|
||||
s: &mut Scratch,
|
||||
) -> Option<DirtyStamp> {
|
||||
let stamp = log.begin(&mut s.watched)?;
|
||||
s.firsts.clear();
|
||||
let mut granules = 0usize;
|
||||
for run in &s.watched {
|
||||
s.firsts.push(granules);
|
||||
granules += ((run.end - run.start) / GRANULE) as usize;
|
||||
}
|
||||
s.written.clear();
|
||||
s.written.resize(granules, 0);
|
||||
s.known.clear();
|
||||
s.known.resize(granules, 0);
|
||||
if !flush || host.flush_vcpus(FLUSH_TIMEOUT) {
|
||||
let mut scratch = std::mem::take(s);
|
||||
if !host.for_each_slot(&mut |slot| harvest_slot(host, kvm, &mut scratch, slot)) {
|
||||
scratch.known.fill(0);
|
||||
}
|
||||
*s = scratch;
|
||||
}
|
||||
for (w, k) in s.written.iter_mut().zip(&s.known) {
|
||||
*w |= !k;
|
||||
}
|
||||
log.end(stamp, &s.written);
|
||||
Some(stamp)
|
||||
}
|
||||
|
||||
/// What the harvest thread and the log's hook share.
|
||||
struct Wake {
|
||||
wanted: AtomicBool,
|
||||
stop: AtomicBool,
|
||||
thread: std::sync::OnceLock<Thread>,
|
||||
}
|
||||
|
||||
impl Wake {
|
||||
fn wake(&self) {
|
||||
if let Some(t) = self.thread.get() {
|
||||
t.unpark();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The device's harvest of a host's dirty source: its log and the thread that harvests it. Its
|
||||
/// drop retires the log and ends the thread.
|
||||
pub(crate) struct Harvester {
|
||||
log: Arc<DirtyLog>,
|
||||
wake: Arc<Wake>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl Harvester {
|
||||
/// The log of the guest's RAM `ram` (guest physical ranges), harvested from `source`.
|
||||
pub(crate) fn new(ram: &[Range<u64>], source: DirtySource) -> Harvester {
|
||||
let kvm = VmFd(source.kvm_vm_fd);
|
||||
Harvester::with_kvm(ram, source.host, Box::new(kvm), cpu_buffers_writes())
|
||||
}
|
||||
|
||||
/// As [`Harvester::new`], over `kvm`, flushing the vCPUs where `flush` (tests).
|
||||
pub(crate) fn with_kvm(
|
||||
ram: &[Range<u64>],
|
||||
host: Arc<dyn DirtyHost>,
|
||||
kvm: Box<dyn KvmLog>,
|
||||
flush: bool,
|
||||
) -> Harvester {
|
||||
let wake = Arc::new(Wake {
|
||||
wanted: AtomicBool::new(false),
|
||||
stop: AtomicBool::new(false),
|
||||
thread: std::sync::OnceLock::new(),
|
||||
});
|
||||
let hook = wake.clone();
|
||||
let log = Arc::new(DirtyLog::new(
|
||||
ram,
|
||||
Box::new(move || {
|
||||
hook.wanted.store(true, Ordering::SeqCst);
|
||||
hook.wake();
|
||||
}),
|
||||
));
|
||||
let (l, w) = (log.clone(), wake.clone());
|
||||
let thread = thread::Builder::new()
|
||||
.name("reims-vgpu.dirty".into())
|
||||
.spawn(move || {
|
||||
let mut scratch = Scratch::default();
|
||||
let mut started = false;
|
||||
loop {
|
||||
if w.stop.load(Ordering::SeqCst) {
|
||||
return;
|
||||
}
|
||||
if !w.wanted.swap(false, Ordering::SeqCst) {
|
||||
thread::park();
|
||||
continue;
|
||||
}
|
||||
if !started {
|
||||
host.start();
|
||||
started = true;
|
||||
}
|
||||
harvest(&*l, &*host, &*kvm, flush, &mut scratch);
|
||||
}
|
||||
});
|
||||
let thread = match thread {
|
||||
Ok(t) => {
|
||||
let _ = wake.thread.set(t.thread().clone());
|
||||
wake.wake();
|
||||
Some(t)
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(
|
||||
"reims-vgpu: no dirty-log harvest thread ({e}); every page reads as written"
|
||||
);
|
||||
None
|
||||
}
|
||||
};
|
||||
Harvester { log, wake, thread }
|
||||
}
|
||||
|
||||
/// The log.
|
||||
pub(crate) fn log(&self) -> &Arc<DirtyLog> {
|
||||
&self.log
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Harvester {
|
||||
fn drop(&mut self) {
|
||||
self.log.retire();
|
||||
self.wake.stop.store(true, Ordering::SeqCst);
|
||||
self.wake.wake();
|
||||
if let Some(t) = self.thread.take() {
|
||||
let _ = t.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,325 +0,0 @@
|
||||
#![expect(
|
||||
clippy::single_range_in_vec_init,
|
||||
reason = "a list of one range is the argument the log and the harvest take"
|
||||
)]
|
||||
#![allow(clippy::disallowed_methods)] // test scaffolding: real-time waits for the device's thread
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use reims_vgpu_core::memory::dirty::{DirtyLog, DirtyStamp, GRANULE, PAGE_SIZE};
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
|
||||
const G: u64 = GRANULE;
|
||||
const P: u64 = PAGE_SIZE;
|
||||
|
||||
/// A log that hands out fixed runs and keeps what the harvest published.
|
||||
struct FakeLog {
|
||||
runs: Vec<Range<u64>>,
|
||||
ended: Mutex<Option<(DirtyStamp, Vec<u64>)>>,
|
||||
}
|
||||
|
||||
impl FakeLog {
|
||||
fn new(runs: Vec<Range<u64>>) -> FakeLog {
|
||||
FakeLog {
|
||||
runs,
|
||||
ended: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn words(&self) -> Vec<u64> {
|
||||
self.ended
|
||||
.lock()
|
||||
.as_ref()
|
||||
.map(|(_, w)| w.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl HarvestLog for FakeLog {
|
||||
fn begin(&self, watched: &mut Vec<Range<u64>>) -> Option<DirtyStamp> {
|
||||
watched.clone_from(&self.runs);
|
||||
Some(7)
|
||||
}
|
||||
|
||||
fn end(&self, stamp: DirtyStamp, written: &[u64]) -> bool {
|
||||
*self.ended.lock() = Some((stamp, written.to_vec()));
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// A clear KVM was asked for: the slot, the first page, the pages and the bitmap.
|
||||
type Clear = (u32, u64, u32, Vec<u64>);
|
||||
|
||||
/// KVM's log of each slot, a set of dirty pages, and the clears it was asked for.
|
||||
#[derive(Default)]
|
||||
struct FakeKvm {
|
||||
dirty: Mutex<Vec<(u32, Vec<u64>)>>,
|
||||
refuse_get: Vec<u32>,
|
||||
clears: Arc<Mutex<Vec<Clear>>>,
|
||||
gets: Arc<AtomicU32>,
|
||||
}
|
||||
|
||||
impl FakeKvm {
|
||||
fn with(dirty: &[(u32, &[u64])]) -> FakeKvm {
|
||||
FakeKvm {
|
||||
dirty: Mutex::new(dirty.iter().map(|(s, p)| (*s, p.to_vec())).collect()),
|
||||
..FakeKvm::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl KvmLog for FakeKvm {
|
||||
fn get(&self, slot: u32, bitmap: &mut [u64]) -> bool {
|
||||
self.gets.fetch_add(1, Ordering::SeqCst);
|
||||
if self.refuse_get.contains(&slot) {
|
||||
return false;
|
||||
}
|
||||
bitmap.fill(0);
|
||||
for (s, pages) in self.dirty.lock().iter() {
|
||||
if *s == slot {
|
||||
for &p in pages {
|
||||
bitmap[(p / 64) as usize] |= 1 << (p % 64);
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn clear(&self, slot: u32, first_page: u64, num_pages: u32, bitmap: &[u64]) -> bool {
|
||||
assert_eq!(first_page % 64, 0);
|
||||
self.clears
|
||||
.lock()
|
||||
.push((slot, first_page, num_pages, bitmap.to_vec()));
|
||||
let mut d = self.dirty.lock();
|
||||
for (s, pages) in d.iter_mut() {
|
||||
if *s == slot {
|
||||
pages.retain(|&p| {
|
||||
let i = p.wrapping_sub(first_page);
|
||||
!(p >= first_page && i < u64::from(num_pages) && bits(bitmap, i, 1) == 1)
|
||||
});
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's slots, its own writes (pages of its record) and what it was asked.
|
||||
#[derive(Default)]
|
||||
struct FakeHost {
|
||||
slots: Vec<KvmSlot>,
|
||||
own: Mutex<Vec<u64>>,
|
||||
reads_itself: bool,
|
||||
flush_fails: bool,
|
||||
starts: AtomicU32,
|
||||
flushes: AtomicU32,
|
||||
takes: Mutex<Vec<(u64, u64)>>,
|
||||
}
|
||||
|
||||
impl DirtyHost for FakeHost {
|
||||
fn start(&self) {
|
||||
self.starts.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
fn flush_vcpus(&self, timeout: Duration) -> bool {
|
||||
assert_eq!(timeout, Duration::from_millis(4));
|
||||
self.flushes.fetch_add(1, Ordering::SeqCst);
|
||||
!self.flush_fails
|
||||
}
|
||||
|
||||
fn for_each_slot(&self, slot: &mut dyn FnMut(KvmSlot)) -> bool {
|
||||
if self.reads_itself {
|
||||
return false;
|
||||
}
|
||||
self.slots.iter().for_each(|s| slot(*s));
|
||||
true
|
||||
}
|
||||
|
||||
fn take_host_writes(&self, host_offset: u64, length: u64, words: &mut [u64]) {
|
||||
assert_eq!(host_offset % G, 0);
|
||||
assert_eq!(length % G, 0);
|
||||
assert_eq!(words.len() as u64, length / G);
|
||||
self.takes.lock().push((host_offset, length));
|
||||
let first = host_offset / P;
|
||||
self.own.lock().retain(|&p| {
|
||||
let i = p.wrapping_sub(first);
|
||||
if p >= first && i < length / P {
|
||||
words[(i / 64) as usize] |= 1 << (i % 64);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn slot(slot: u32, gpa: u64, length: u64, host_offset: u64) -> KvmSlot {
|
||||
KvmSlot {
|
||||
slot,
|
||||
guest_physical_address: gpa,
|
||||
length,
|
||||
host_offset,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(runs: Vec<Range<u64>>, host: &FakeHost, kvm: &FakeKvm, flush: bool) -> Vec<u64> {
|
||||
let log = FakeLog::new(runs);
|
||||
assert_eq!(
|
||||
harvest(&log, host, kvm, flush, &mut Scratch::default()),
|
||||
Some(7)
|
||||
);
|
||||
log.words()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bits_read_and_set_across_words() {
|
||||
let mut b = vec![0u64; 3];
|
||||
set_bits(&mut b, 60, 0b1_0110);
|
||||
assert_eq!(b, vec![0x6000_0000_0000_0000, 0b1, 0]);
|
||||
assert_eq!(bits(&b, 60, 5), 0b1_0110);
|
||||
assert_eq!(bits(&b, 61, 1), 1);
|
||||
assert_eq!(bits(&b, 0, 64), 0x6000_0000_0000_0000);
|
||||
assert_eq!(bits(&b, 64, 64), 1);
|
||||
assert_eq!(bits(&b, 190, 64), 0, "past the end reads as zero");
|
||||
}
|
||||
|
||||
/// A slot's watched pages KVM shows written are published, cleared and no others, and the
|
||||
/// host's own writes join them; the unwatched page keeps its bit in KVM's log.
|
||||
#[test]
|
||||
fn a_harvest_takes_exactly_the_watched_pages_written() {
|
||||
let kvm = FakeKvm::with(&[(0, &[5, 128, 200, 703])]);
|
||||
let host = FakeHost {
|
||||
slots: vec![slot(0, 0, 1 << 30, 1 << 20)],
|
||||
own: Mutex::new(vec![(1 << 20) / P + 640 + 3]),
|
||||
..FakeHost::default()
|
||||
};
|
||||
let words = run(vec![2 * G..4 * G, 10 * G..11 * G], &host, &kvm, false);
|
||||
assert_eq!(words, vec![1, 1 << 8, (1 << 3) | (1 << 63)]);
|
||||
let clears = kvm.clears.lock().clone();
|
||||
assert_eq!(clears.len(), 1, "one clear a slot");
|
||||
let (s, first, num, bitmap) = &clears[0];
|
||||
assert_eq!((*s, *first, *num), (0, 128, 704 - 128));
|
||||
assert_eq!(bitmap[0], 1);
|
||||
assert_eq!(bitmap[1], 1 << 8);
|
||||
assert_eq!(bitmap[8], 1 << 63);
|
||||
assert_eq!(*kvm.dirty.lock(), vec![(0, vec![5])]);
|
||||
assert_eq!(
|
||||
*host.takes.lock(),
|
||||
vec![((1 << 20) + 2 * G, 2 * G), ((1 << 20) + 10 * G, G)]
|
||||
);
|
||||
assert_eq!(host.flushes.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
/// What no logged slot of address space 0 answers for reads as written: a page outside every
|
||||
/// slot, and SMM's address space only adds its writes.
|
||||
#[test]
|
||||
fn unanswered_pages_read_as_written() {
|
||||
let kvm = FakeKvm::with(&[(1 << 16, &[64 + 2])]);
|
||||
let host = FakeHost {
|
||||
slots: vec![slot(0, 0, G * 2, 0), slot(1 << 16, 0, G * 2, 0)],
|
||||
..FakeHost::default()
|
||||
};
|
||||
let words = run(vec![0..3 * G], &host, &kvm, false);
|
||||
assert_eq!(words, vec![0, 1 << 2, !0]);
|
||||
assert_eq!(
|
||||
host.takes.lock().len(),
|
||||
1,
|
||||
"the host's writes are taken once, for space 0"
|
||||
);
|
||||
}
|
||||
|
||||
/// A slot that starts inside a granule answers for its pages, and its granule's host writes
|
||||
/// cannot be taken a word at a time, so that granule reads as written; so does one whose host
|
||||
/// offset is out of step with its guest address.
|
||||
#[test]
|
||||
fn granules_the_host_cannot_take_whole_read_as_written() {
|
||||
let kvm = FakeKvm::default();
|
||||
let host = FakeHost {
|
||||
slots: vec![
|
||||
slot(0, 0, 160 * P, 0),
|
||||
slot(1, 192 * P, 64 * P, 192 * P),
|
||||
slot(2, 5 * G, G, 5 * G + P),
|
||||
],
|
||||
..FakeHost::default()
|
||||
};
|
||||
let words = run(vec![0..4 * G, 5 * G..6 * G], &host, &kvm, false);
|
||||
assert_eq!(words, vec![0, 0, !0, 0, !0]);
|
||||
let clears = kvm.clears.lock().clone();
|
||||
assert!(clears.is_empty(), "nothing written, nothing cleared");
|
||||
}
|
||||
|
||||
/// A host that reads its log itself, a flush past its time and a read KVM refuses give every
|
||||
/// page as written, and a refused read clears nothing.
|
||||
#[test]
|
||||
fn a_harvest_that_cannot_answer_gives_every_page() {
|
||||
let one = || FakeHost {
|
||||
slots: vec![slot(0, 0, 4 * G, 0)],
|
||||
..FakeHost::default()
|
||||
};
|
||||
let host = FakeHost {
|
||||
reads_itself: true,
|
||||
..one()
|
||||
};
|
||||
assert_eq!(
|
||||
run(vec![0..2 * G], &host, &FakeKvm::default(), false),
|
||||
vec![!0, !0]
|
||||
);
|
||||
|
||||
let host = FakeHost {
|
||||
flush_fails: true,
|
||||
..one()
|
||||
};
|
||||
let kvm = FakeKvm::default();
|
||||
assert_eq!(run(vec![0..2 * G], &host, &kvm, true), vec![!0, !0]);
|
||||
assert_eq!(host.flushes.load(Ordering::SeqCst), 1);
|
||||
assert_eq!(
|
||||
kvm.gets.load(Ordering::SeqCst),
|
||||
0,
|
||||
"no read after a failed flush"
|
||||
);
|
||||
|
||||
let kvm = FakeKvm {
|
||||
refuse_get: vec![0],
|
||||
..FakeKvm::with(&[(0, &[1])])
|
||||
};
|
||||
assert_eq!(run(vec![0..2 * G], &one(), &kvm, true), vec![!0, !0]);
|
||||
assert!(kvm.clears.lock().is_empty());
|
||||
}
|
||||
|
||||
/// The device's thread starts the log at the first harvest it is asked for, and publishes each.
|
||||
#[test]
|
||||
fn the_thread_harvests_what_the_log_requests() {
|
||||
let host = Arc::new(FakeHost {
|
||||
slots: vec![slot(0, 0, 4 * G, 0)],
|
||||
..FakeHost::default()
|
||||
});
|
||||
let kvm = FakeKvm::with(&[(0, &[3])]);
|
||||
let gets = kvm.gets.clone();
|
||||
let h = Harvester::with_kvm(&[0..4 * G], host.clone(), Box::new(kvm), false);
|
||||
h.log().watch(&[0..G]);
|
||||
for _ in 0..2 {
|
||||
let stamp = h.log().request();
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
while h.log().published() < stamp {
|
||||
assert!(Instant::now() < deadline, "harvest {stamp} never published");
|
||||
std::thread::sleep(Duration::from_millis(1));
|
||||
}
|
||||
}
|
||||
assert_eq!(host.starts.load(Ordering::SeqCst), 1);
|
||||
assert!(gets.load(Ordering::SeqCst) >= 2);
|
||||
drop(h);
|
||||
}
|
||||
|
||||
/// A log the harvester never started still drops cleanly.
|
||||
#[test]
|
||||
fn a_harvester_drops_without_a_harvest() {
|
||||
let host = Arc::new(FakeHost::default());
|
||||
let h = Harvester::with_kvm(&[0..G], host.clone(), Box::new(FakeKvm::default()), false);
|
||||
let _: &Arc<DirtyLog> = h.log();
|
||||
drop(h);
|
||||
assert_eq!(host.starts.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
@@ -1,497 +0,0 @@
|
||||
//! [`Display`]: a display on one of a device's ports, made from a [`DisplayConfig`].
|
||||
//!
|
||||
//! A display's callbacks run on the process's display thread ([`crate::platform`]), one at a
|
||||
//! time across every display of the process, in the order core queued them. A job still reads
|
||||
//! its callback when it runs, as it did on the host's queue: a display released with a job
|
||||
//! queued dies at that job. The last drop of a display is its unplug, run on the releasing
|
||||
//! thread; it may also be the device's last reference.
|
||||
//!
|
||||
//! A display created with a window ([`DisplayConfig::window`]) has all five callbacks as the
|
||||
//! guest reads them, each telling the window before it calls the host's; its last reference
|
||||
//! closes the window before it lets the display go ([`crate::window`]). Without a window, the
|
||||
//! display is as its config says.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::display::descriptor::DisplayDescriptor as CoreDescriptor;
|
||||
use reims_vgpu_core::display::host_calls::CursorGlyph as CoreGlyph;
|
||||
use reims_vgpu_core::display::mode::DisplayMode as CoreMode;
|
||||
use reims_vgpu_core::display::{DisplayCoord, DisplayHandle, DisplayName};
|
||||
use reims_vgpu_core::platform::os::Preferences;
|
||||
use reims_vgpu_core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
|
||||
use reims_vgpu_core::platform::{Handle as _, Platform};
|
||||
use reims_vgpu_core::raise::{OnFault, RaiseResult};
|
||||
use reims_vgpu_core::rt::Hold;
|
||||
use reims_vgpu_window::{Window, WindowConfig};
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::device::{Device, GuestMemoryLease};
|
||||
use crate::entry;
|
||||
use crate::error::Error;
|
||||
use crate::frame::{Frame, FrameTarget, Region};
|
||||
use crate::platform::{ApiPlatform, api_state};
|
||||
use crate::retained::Ours;
|
||||
use crate::stats;
|
||||
use crate::window::{self, WindowLink};
|
||||
|
||||
/// The settings [`DisplayConfig::apply_preferences`] asks its reader for.
|
||||
const MIN_NITS_KEY: &str = "PGDisplayMinNits";
|
||||
const MAX_NITS_KEY: &str = "PGDisplayMaxNits";
|
||||
const MAX_SDR_NITS_KEY: &str = "PGDisplayMaxSDRNits";
|
||||
/// The settings [`DisplayMode::with_preferences`] asks its reader for.
|
||||
const SUPPORTS_EDR_KEY: &str = "PGDisplaySupportsEDR";
|
||||
const SUPPORTS_10BPC_KEY: &str = "PGDisplaySupports10bpc";
|
||||
|
||||
/// A raise that reaches an entry point: nothing catches it there, so it ends the process.
|
||||
pub(crate) fn no_catch<T>(r: RaiseResult<T>) -> T {
|
||||
r.unwrap_or_else(|raised| raised.fatal())
|
||||
}
|
||||
|
||||
/// A display mode offered to the guest.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DisplayMode {
|
||||
/// Pixels wide.
|
||||
pub width: u16,
|
||||
/// Pixels high.
|
||||
pub height: u16,
|
||||
/// The refresh rate, as the guest reads it.
|
||||
pub refresh_rate_hz: f64,
|
||||
/// The guest reads that the mode supports EDR.
|
||||
pub supports_edr: bool,
|
||||
/// The guest reads that the mode supports 10 bits per channel.
|
||||
pub supports_10bpc: bool,
|
||||
}
|
||||
|
||||
impl DisplayMode {
|
||||
/// The size and rate, both flags off.
|
||||
pub fn new(width: u16, height: u16, refresh_rate_hz: f64) -> DisplayMode {
|
||||
DisplayMode {
|
||||
width,
|
||||
height,
|
||||
refresh_rate_hz,
|
||||
supports_edr: false,
|
||||
supports_10bpc: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The size and rate, then the flags `prefs` answers when the mode is made:
|
||||
/// `PGDisplaySupportsEDR`, then `PGDisplaySupports10bpc`, each set when the key exists and
|
||||
/// is true.
|
||||
pub fn with_preferences(
|
||||
prefs: &dyn Preferences,
|
||||
width: u16,
|
||||
height: u16,
|
||||
refresh_rate_hz: f64,
|
||||
) -> DisplayMode {
|
||||
let set = |key| prefs.app_bool(key) == (true, true);
|
||||
DisplayMode {
|
||||
supports_edr: set(SUPPORTS_EDR_KEY),
|
||||
supports_10bpc: set(SUPPORTS_10BPC_KEY),
|
||||
..DisplayMode::new(width, height, refresh_rate_hz)
|
||||
}
|
||||
}
|
||||
|
||||
/// Core's mode.
|
||||
fn to_core(self) -> CoreMode {
|
||||
CoreMode {
|
||||
size_in_pixels: DisplayCoord {
|
||||
x: self.width,
|
||||
y: self.height,
|
||||
},
|
||||
refresh_rate_in_hz: self.refresh_rate_hz,
|
||||
supports_edr: self.supports_edr,
|
||||
supports_10bpc: self.supports_10bpc,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The cursor glyph, borrowed for the callback.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct CursorGlyph<'a> {
|
||||
/// Pixels wide.
|
||||
pub width: u32,
|
||||
/// Pixels high.
|
||||
pub height: u32,
|
||||
/// The hot spot, in pixels from the top left.
|
||||
pub hot_spot: (u16, u16),
|
||||
/// `width * 4` bytes a row, `height` rows: the guest's BGRA with red and blue swapped.
|
||||
pub rgba: &'a [u8],
|
||||
}
|
||||
|
||||
/// `(width, height, pixel_format)`: the guest set a mode.
|
||||
pub type ModeChangeFn = Arc<dyn Fn(u16, u16, u32) + Send + Sync>;
|
||||
/// The guest presented a frame since the last call (calls coalesce).
|
||||
pub type NewFrameFn = Arc<dyn Fn() + Send + Sync>;
|
||||
/// The guest set a cursor glyph.
|
||||
pub type CursorGlyphFn = Arc<dyn Fn(&CursorGlyph<'_>) + Send + Sync>;
|
||||
/// The guest showed or hid the cursor: the guest's byte as written (0 hides).
|
||||
pub type CursorShowFn = Arc<dyn Fn(u8) + Send + Sync>;
|
||||
/// The guest moved the cursor.
|
||||
pub type CursorMoveFn = Arc<dyn Fn() + Send + Sync>;
|
||||
|
||||
/// A display's callbacks, each on the display thread. `None` is a callback the host does not
|
||||
/// give (each C typedef's comment says what the guest then sees).
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DisplayCallbacks {
|
||||
/// The guest set a mode.
|
||||
pub mode_change: Option<ModeChangeFn>,
|
||||
/// The guest presented a frame. Without it, the display's first present ends the process.
|
||||
pub new_frame: Option<NewFrameFn>,
|
||||
/// The guest set a cursor glyph. Without it, the guest reads a glyph size limit of 0.
|
||||
pub cursor_glyph: Option<CursorGlyphFn>,
|
||||
/// The guest showed or hid the cursor.
|
||||
pub cursor_show: Option<CursorShowFn>,
|
||||
/// The guest moved the cursor.
|
||||
pub cursor_move: Option<CursorMoveFn>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DisplayCallbacks {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DisplayCallbacks")
|
||||
.field("mode_change", &self.mode_change.is_some())
|
||||
.field("new_frame", &self.new_frame.is_some())
|
||||
.field("cursor_glyph", &self.cursor_glyph.is_some())
|
||||
.field("cursor_show", &self.cursor_show.is_some())
|
||||
.field("cursor_move", &self.cursor_move.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// A display's config.
|
||||
#[derive(Clone)]
|
||||
pub struct DisplayConfig {
|
||||
/// The port, below the device's port count.
|
||||
pub port: u64,
|
||||
/// The guest's serial number for the display, unique in the process.
|
||||
pub serial_number: u32,
|
||||
/// `None` is "Apple Virtual".
|
||||
pub name: Option<String>,
|
||||
/// Width, then height.
|
||||
pub size_in_millimeters: (f64, f64),
|
||||
/// The callbacks.
|
||||
pub callbacks: DisplayCallbacks,
|
||||
/// `None` is no window. Otherwise the library opens a window for the display, draws each
|
||||
/// new frame into it and sends its input to the config's callbacks. The display then has
|
||||
/// every callback as the guest reads them, and calls those of `callbacks` it has. With
|
||||
/// `match_host_screen`, the display offers the modes, size and scale factor of the window's
|
||||
/// host screen, where the platform names one, in place of `size_in_millimeters`.
|
||||
pub window: Option<WindowConfig>,
|
||||
/// What core's descriptor holds beyond the fields above, at its defaults (the colour
|
||||
/// space, the origin, the nits).
|
||||
hidden: CoreDescriptor,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for DisplayConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("DisplayConfig")
|
||||
.field("port", &self.port)
|
||||
.field("serial_number", &self.serial_number)
|
||||
.field("name", &self.name)
|
||||
.field("size_in_millimeters", &self.size_in_millimeters)
|
||||
.field("callbacks", &self.callbacks)
|
||||
.field("window", &self.window)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayConfig {
|
||||
/// A display on `port` with `serial_number`, no name ("Apple Virtual"), a zero size, no
|
||||
/// callbacks and no window.
|
||||
pub fn new(port: u64, serial_number: u32) -> DisplayConfig {
|
||||
DisplayConfig {
|
||||
port,
|
||||
serial_number,
|
||||
name: None,
|
||||
size_in_millimeters: (0.0, 0.0),
|
||||
callbacks: DisplayCallbacks::default(),
|
||||
window: None,
|
||||
hidden: CoreDescriptor::sdk_defaults(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the nits settings `prefs` answers now: `PGDisplayMinNits`, `PGDisplayMaxNits` and
|
||||
/// `PGDisplayMaxSDRNits`, in that order, each stored when it is a number.
|
||||
pub fn apply_preferences(&mut self, prefs: &dyn Preferences) {
|
||||
let h = &mut self.hidden;
|
||||
for (key, nits) in [
|
||||
(MIN_NITS_KEY, &mut h.min_nits),
|
||||
(MAX_NITS_KEY, &mut h.max_nits),
|
||||
(MAX_SDR_NITS_KEY, &mut h.max_sdr_nits),
|
||||
] {
|
||||
if let Some(value) = prefs.any_user_f32(key) {
|
||||
*nits = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Core's descriptor, with `queue` as the display's queue: closures that call the host's.
|
||||
fn into_core(self, queue: Arc<dyn reims_vgpu_core::host::HostQueue>) -> CoreDescriptor {
|
||||
let DisplayCallbacks {
|
||||
mode_change,
|
||||
new_frame,
|
||||
cursor_glyph,
|
||||
cursor_show,
|
||||
cursor_move,
|
||||
} = self.callbacks;
|
||||
let mut d = self.hidden;
|
||||
if let Some(name) = self.name {
|
||||
d.name = Some(DisplayName::new(name));
|
||||
}
|
||||
d.size_in_millimeters = self.size_in_millimeters;
|
||||
d.queue = Some(queue);
|
||||
d.mode_change_handler = mode_change.map(|f| {
|
||||
let h: reims_vgpu_core::display::host_calls::ModeChangeHandler =
|
||||
Arc::new(move |size: DisplayCoord, format: u32| f(size.x, size.y, format));
|
||||
h
|
||||
});
|
||||
d.new_frame_event_handler = new_frame;
|
||||
d.cursor_glyph_handler = cursor_glyph.map(|f| {
|
||||
let h: reims_vgpu_core::display::host_calls::CursorGlyphHandler =
|
||||
Arc::new(move |g: &CoreGlyph, hot: DisplayCoord| {
|
||||
f(&CursorGlyph {
|
||||
width: g.width,
|
||||
height: g.height,
|
||||
hot_spot: (hot.x, hot.y),
|
||||
rgba: &g.rgba,
|
||||
});
|
||||
});
|
||||
h
|
||||
});
|
||||
d.cursor_glyph_image_maker = None;
|
||||
d.cursor_show_handler = cursor_show;
|
||||
d.cursor_move_handler = cursor_move;
|
||||
d
|
||||
}
|
||||
}
|
||||
|
||||
/// One reference to a display.
|
||||
pub struct Display<P: Platform = DefaultPlatform> {
|
||||
/// The display's window, which every reference shares: the last reference's drop closes it
|
||||
/// before that reference's hold on the display goes (the `Drop` below).
|
||||
window: Option<Arc<WindowLink>>,
|
||||
inner: Ours<DisplayHandle<P>>,
|
||||
/// The frame queue of the device's Metal device.
|
||||
frame_queue: Option<P::CommandQueue>,
|
||||
/// The device's lease on the guest's RAM ([`Device::guest_memory_lease`]): core's display
|
||||
/// keeps core's device alive, so the lease goes after `inner`.
|
||||
guest_memory: Option<GuestMemoryLease>,
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for Display<P> {
|
||||
/// The window's share first, so that the display's last reference closes the window before
|
||||
/// it releases the display; then the reference itself, then the frame queue, then the
|
||||
/// device's lease on the guest's RAM.
|
||||
fn drop(&mut self) {
|
||||
drop(self.window.take());
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> std::fmt::Debug for Display<P> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Display")
|
||||
.field("port", &self.inner.port())
|
||||
.field("serial_number", &self.inner.serial_num())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> Display<P> {
|
||||
/// A new display on `device` ([`Device::new_display`]). The display thread is made at the
|
||||
/// process's first display. The config's closures are dropped before a refusal returns,
|
||||
/// except the new-frame closure of a display refused after its source was made, which the
|
||||
/// source's cancel frees on the display thread.
|
||||
///
|
||||
/// With a window, the callbacks are the window's tee ([`window::tee`]). Matching the host
|
||||
/// screen the platform names for the port, the scale factor and the size in millimetres are
|
||||
/// its density, and the display is made with its modes, as [`Display::set_modes`] sets them;
|
||||
/// the window opens sized for the first. The window is given the display's sink once the
|
||||
/// display exists, and a refusal closes it before it returns. Where the platform names no
|
||||
/// screen, the density and the modes are those [`window::host_matched`] gives without one.
|
||||
///
|
||||
/// With the frame statistics on (`REIMS_VGPU_STATS`, [`stats`]), the new-frame callback, the
|
||||
/// tee's for a window display, counts each of the guest's presents before it runs, and the
|
||||
/// display's stats are registered once it exists, before its window gets its sink.
|
||||
pub(crate) fn new(device: &Device<P>, mut config: DisplayConfig) -> Result<Display<P>, Error> {
|
||||
let platform = device.platform();
|
||||
entry::run(|_| {
|
||||
let state = api_state(platform);
|
||||
let queue = state.display_thread(platform);
|
||||
let frame_queue = state.frame_queue(device.handle.mtl_device_ref());
|
||||
let port = config.port;
|
||||
let serial = config.serial_number;
|
||||
let mut offered = Vec::new();
|
||||
let link = match config.window.take() {
|
||||
None => None,
|
||||
Some(wcfg) => {
|
||||
let w = Window::new(wcfg, port, reims_vgpu_window::handle::title(port));
|
||||
config.callbacks = window::tee(&w, std::mem::take(&mut config.callbacks));
|
||||
if w.match_host_screen()
|
||||
&& let Some((modes, density)) = window::host_matched(
|
||||
window::host_screen::<P>(port).as_ref(),
|
||||
w.chosen_mode(),
|
||||
w.chosen_ppi(),
|
||||
reims_vgpu_window::env::settings().refresh_hz,
|
||||
)
|
||||
{
|
||||
config.hidden.scale_factor = density.scale_factor;
|
||||
config.size_in_millimeters = density.size_in_millimeters;
|
||||
if let Some(first) = modes.first() {
|
||||
w.offered_mode(first.width, first.height);
|
||||
}
|
||||
offered = modes;
|
||||
}
|
||||
w.told_size(config.size_in_millimeters);
|
||||
Some(Arc::new(WindowLink::new(w)))
|
||||
}
|
||||
};
|
||||
let stats = stats::observe(
|
||||
platform.threads(),
|
||||
port,
|
||||
link.is_some(),
|
||||
&mut config.callbacks.new_frame,
|
||||
);
|
||||
let core = config.into_core(queue);
|
||||
let made = device.handle.new_display(&core, port, serial);
|
||||
drop(core);
|
||||
let made = match made {
|
||||
Ok(made) => made,
|
||||
Err(refusal) => {
|
||||
drop(link);
|
||||
return Err(refusal.into());
|
||||
}
|
||||
};
|
||||
if let Some(stats) = &stats {
|
||||
stats::register(stats, &made.downgrade());
|
||||
}
|
||||
if !offered.is_empty() {
|
||||
let modes: Vec<CoreMode> = offered
|
||||
.iter()
|
||||
.map(|m| DisplayMode::new(m.width, m.height, m.refresh_hz).to_core())
|
||||
.collect();
|
||||
no_catch(made.set_mode_list(&modes));
|
||||
}
|
||||
if let Some(link) = &link
|
||||
&& let Some(sink) = window::window_sink(
|
||||
platform,
|
||||
made.downgrade(),
|
||||
frame_queue.as_ref().map(|q| q.clone_ref()),
|
||||
)
|
||||
{
|
||||
link.window().attach(sink);
|
||||
}
|
||||
Ok(Display {
|
||||
window: link,
|
||||
inner: Ours::new(made),
|
||||
frame_queue,
|
||||
guest_memory: device.guest_memory_lease(),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Display<P> {
|
||||
/// Another reference to this display. It is unplugged when the last one drops, and its
|
||||
/// window, if it has one, closes then.
|
||||
#[must_use]
|
||||
pub fn clone_ref(&self) -> Display<P> {
|
||||
Display {
|
||||
window: self.window.clone(),
|
||||
inner: Ours::new(self.inner.clone_ref()),
|
||||
frame_queue: self
|
||||
.frame_queue
|
||||
.as_ref()
|
||||
.map(reims_vgpu_core::platform::Handle::clone_ref),
|
||||
guest_memory: self.guest_memory.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether both are references to one display.
|
||||
pub fn ptr_eq(&self, other: &Display<P>) -> bool {
|
||||
self.inner.ptr_eq(&other.inner)
|
||||
}
|
||||
|
||||
/// Core's display (tests).
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub fn core(&self) -> &DisplayHandle<P> {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
/// The display's window (tests).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn window(&self) -> Option<&Arc<Window>> {
|
||||
self.window.as_deref().map(WindowLink::window)
|
||||
}
|
||||
|
||||
/// Runs `body` as an entry ([`entry::run`]), with a hold of the entry's holder.
|
||||
fn entry<T>(&self, body: impl for<'u> FnOnce(Hold<'u>, &DisplayHandle<P>) -> T) -> T {
|
||||
entry::run(|hold| body(hold, &self.inner))
|
||||
}
|
||||
|
||||
/// Offers the guest `modes`, in order (copied). An empty list changes nothing. The change may
|
||||
/// plug the display in and queue a mode change. A raise from the display ends the process.
|
||||
/// The display's window, if it has one and has not opened yet, opens sized for the first.
|
||||
pub fn set_modes(&self, modes: &[DisplayMode]) {
|
||||
if let (Some(link), Some(first)) = (&self.window, modes.first()) {
|
||||
link.window().offered_mode(first.width, first.height);
|
||||
}
|
||||
self.entry(|_, d| {
|
||||
let modes: Vec<CoreMode> = modes.iter().map(|m| m.to_core()).collect();
|
||||
no_catch(d.set_mode_list(&modes));
|
||||
});
|
||||
}
|
||||
|
||||
/// The cursor's position; `(65535, 65535)` before the guest has linked the display.
|
||||
pub fn cursor_position(&self) -> (u16, u16) {
|
||||
let c = self.entry(|_, d| d.cursor_position());
|
||||
(c.x, c.y)
|
||||
}
|
||||
|
||||
/// The guest's presents counted so far.
|
||||
pub fn guest_present_count(&self) -> u64 {
|
||||
self.inner.guest_present_count()
|
||||
}
|
||||
|
||||
/// The host's encodes of a new frame counted so far.
|
||||
pub fn host_present_count(&self) -> u64 {
|
||||
self.inner.host_present_count()
|
||||
}
|
||||
|
||||
/// Encodes the current frame into `target` over `region` (`None`: the whole target), in a
|
||||
/// command buffer of the process's frame queue, and answers the uncommitted frame. The
|
||||
/// display counts the frame in flight until it completes; its presents wait for frames in
|
||||
/// flight. The first encode after each new guest frame counts one host present.
|
||||
/// [`Error::InvalidArgument`] for a target on another Metal device.
|
||||
pub fn encode_frame(
|
||||
&self,
|
||||
target: &FrameTarget<P>,
|
||||
region: Option<Region>,
|
||||
) -> Result<Frame<P>, Error> {
|
||||
self.entry(|_, d| {
|
||||
let Some(queue) = &self.frame_queue else {
|
||||
return Err(Error::Metal);
|
||||
};
|
||||
let region = region.unwrap_or(Region {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: u64::from(target.width()),
|
||||
height: u64::from(target.height()),
|
||||
});
|
||||
let region = MtlRegion::new(
|
||||
MtlOrigin::new(region.x, region.y, 0),
|
||||
MtlSize::new(region.width, region.height, 1),
|
||||
);
|
||||
// Metal's autorelease of the command buffer goes at the entry's pool, popped before
|
||||
// the return: only the frame's own reference is left.
|
||||
use reims_vgpu_core::platform::command::CommandQueue as _;
|
||||
let Some(command_buffer) = no_catch(queue.command_buffer(OnFault::Die)) else {
|
||||
return Err(Error::Metal);
|
||||
};
|
||||
let encoded =
|
||||
no_catch(d.encode_current_frame(&command_buffer, target.texture(), region));
|
||||
if !encoded {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
Ok(Frame::new(command_buffer, target.clone_ref()))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -12,8 +12,14 @@
|
||||
//! buffer) goes at the pool's pop, so no uncommitted buffer outlives the call and holds one of
|
||||
//! its queue's 64 slots.
|
||||
|
||||
use reims_vgpu_core::raise::RaiseResult;
|
||||
use reims_vgpu_core::rt::{Held, Hold, Pool, enter_ours};
|
||||
|
||||
/// A raise that reaches an entry point: nothing catches it there, so it ends the process.
|
||||
pub(crate) fn no_catch<T>(r: RaiseResult<T>) -> T {
|
||||
r.unwrap_or_else(|raised| raised.fatal())
|
||||
}
|
||||
|
||||
/// Runs one entry's `body` marked as ours, inside a real pool and with a holder; `body` gets a
|
||||
/// hold of that holder. The holder releases what it holds when `body` returns, then the pool pops
|
||||
/// (module doc). An entry reached inside another (a release of the last reference inside a call)
|
||||
|
||||
@@ -1,44 +1,15 @@
|
||||
//! [`Error`]: why a call refused, and [`ResumeError`]: why a resume refused its state.
|
||||
//! [`Error`]: why a call refused.
|
||||
|
||||
use reims_vgpu_core::device::DeviceRefusal;
|
||||
use reims_vgpu_core::display::DisplayRefusal;
|
||||
use reims_vgpu_core::iosurface::IoSurfaceRefusal;
|
||||
|
||||
/// Why a call refused. Each create checks in core's order (docs/api.md section 1): the
|
||||
/// variant names the check that failed.
|
||||
/// Why a call refused.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// A value outside its range, or `add_trace_range` without `remove_trace_range`.
|
||||
/// A value outside its range.
|
||||
InvalidArgument,
|
||||
/// A display port count of 0, or above [`crate::MAX_DISPLAY_PORTS`].
|
||||
DisplayPortCount,
|
||||
/// No Metal device has the registry ID, or the system has none.
|
||||
NoMetalDevice,
|
||||
/// A memory map together with a task or memory callback.
|
||||
MemoryConflict,
|
||||
/// The memory map was refused: ranges that overlap or overflow.
|
||||
MemoryMap,
|
||||
/// Process isolation without a memory map.
|
||||
IsolationWithoutMap,
|
||||
/// Metal refused an object the device or display needs.
|
||||
/// The platform refused an object the call needs.
|
||||
Metal,
|
||||
/// The display's port is not below the device's port count.
|
||||
PortOutOfRange,
|
||||
/// Another display holds the port.
|
||||
PortInUse,
|
||||
/// A display of the process holds the serial number.
|
||||
SerialInUse,
|
||||
/// An IOSurface device without a memory map.
|
||||
NoMemoryMap,
|
||||
/// The device has no suspend state to give.
|
||||
Suspend,
|
||||
/// The device refused the resume state, with its reason when it stored one.
|
||||
Resume(Option<ResumeError>),
|
||||
/// The frame's GPU work ended with an error.
|
||||
/// The call's GPU work ended with an error.
|
||||
Gpu,
|
||||
/// A frame committed twice, or waited on before its commit.
|
||||
FrameState,
|
||||
/// The host refused the memory, a pipe or a thread a device needs: the graphics device's
|
||||
/// region, or its threads.
|
||||
HostResources,
|
||||
@@ -48,128 +19,11 @@ impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Error::InvalidArgument => "invalid argument",
|
||||
Error::DisplayPortCount => "display port count out of range",
|
||||
Error::NoMetalDevice => "no such Metal device",
|
||||
Error::MemoryConflict => "a memory map together with a task or memory callback",
|
||||
Error::MemoryMap => "the memory map was refused",
|
||||
Error::IsolationWithoutMap => "process isolation needs a memory map",
|
||||
Error::Metal => "Metal refused an object",
|
||||
Error::PortOutOfRange => "the port is out of range",
|
||||
Error::PortInUse => "the port is in use",
|
||||
Error::SerialInUse => "the serial number is in use",
|
||||
Error::NoMemoryMap => "the IOSurface device needs a memory map",
|
||||
Error::Suspend => "no suspend state",
|
||||
Error::Resume(_) => "the resume state was refused",
|
||||
Error::Gpu => "the frame's GPU work failed",
|
||||
Error::FrameState => "the frame is not in a state for this call",
|
||||
Error::Metal => "the platform refused an object",
|
||||
Error::Gpu => "the GPU work failed",
|
||||
Error::HostResources => "the host refused memory, a pipe or a thread",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
impl From<DeviceRefusal> for Error {
|
||||
fn from(r: DeviceRefusal) -> Error {
|
||||
match r {
|
||||
DeviceRefusal::DisplayPortCount => Error::DisplayPortCount,
|
||||
DeviceRefusal::NoMetalDevice => Error::NoMetalDevice,
|
||||
DeviceRefusal::MemoryConflict => Error::MemoryConflict,
|
||||
DeviceRefusal::MemoryMap => Error::MemoryMap,
|
||||
DeviceRefusal::TraceWithoutRemove => Error::InvalidArgument,
|
||||
DeviceRefusal::Metal => Error::Metal,
|
||||
DeviceRefusal::IsolationWithoutMap => Error::IsolationWithoutMap,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<DisplayRefusal> for Error {
|
||||
fn from(r: DisplayRefusal) -> Error {
|
||||
match r {
|
||||
DisplayRefusal::PortOutOfRange => Error::PortOutOfRange,
|
||||
DisplayRefusal::Metal => Error::Metal,
|
||||
DisplayRefusal::SerialInUse => Error::SerialInUse,
|
||||
DisplayRefusal::PortInUse => Error::PortInUse,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<IoSurfaceRefusal> for Error {
|
||||
fn from(r: IoSurfaceRefusal) -> Error {
|
||||
match r {
|
||||
IoSurfaceRefusal::NoMemoryMap => Error::NoMemoryMap,
|
||||
IoSurfaceRefusal::MemoryMap => Error::MemoryMap,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a resume refused its state: the codes the device stores, which the guest ABI fixes.
|
||||
#[repr(u32)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum ResumeError {
|
||||
/// An internal fault.
|
||||
InternalFault = 0,
|
||||
/// The state's version is not one the device reads.
|
||||
InvalidSuspendStateVersion = 1,
|
||||
/// The state is malformed, or absent.
|
||||
InvalidContent = 2,
|
||||
/// The guest's binary version in the state is not one the device supports.
|
||||
InvalidGuestVersion = 3,
|
||||
/// The state was taken on a device this one cannot stand in for.
|
||||
IncompatibleDevice = 4,
|
||||
/// The state's display port count differs from the device's.
|
||||
InvalidDisplayPortCount = 5,
|
||||
}
|
||||
|
||||
impl ResumeError {
|
||||
/// The reason a device stored as `code`, or `None` for a code it never stores.
|
||||
pub fn from_code(code: u64) -> Option<ResumeError> {
|
||||
Some(match code {
|
||||
0 => ResumeError::InternalFault,
|
||||
1 => ResumeError::InvalidSuspendStateVersion,
|
||||
2 => ResumeError::InvalidContent,
|
||||
3 => ResumeError::InvalidGuestVersion,
|
||||
4 => ResumeError::IncompatibleDevice,
|
||||
5 => ResumeError::InvalidDisplayPortCount,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The code.
|
||||
pub fn code(self) -> u32 {
|
||||
self as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Each core refusal names its variant; `add_trace_range` alone is an invalid argument
|
||||
#[test]
|
||||
fn refusals_map_to_their_variant() {
|
||||
assert_eq!(
|
||||
Error::from(DeviceRefusal::TraceWithoutRemove),
|
||||
Error::InvalidArgument
|
||||
);
|
||||
assert_eq!(
|
||||
Error::from(DeviceRefusal::DisplayPortCount),
|
||||
Error::DisplayPortCount
|
||||
);
|
||||
assert_eq!(Error::from(DisplayRefusal::PortInUse), Error::PortInUse);
|
||||
assert_eq!(Error::from(IoSurfaceRefusal::MemoryMap), Error::MemoryMap);
|
||||
assert!(!Error::Resume(None).to_string().is_empty());
|
||||
}
|
||||
|
||||
/// The six codes round-trip; any other is no reason
|
||||
#[test]
|
||||
fn resume_codes() {
|
||||
for code in 0..6u32 {
|
||||
assert_eq!(
|
||||
ResumeError::from_code(u64::from(code)).map(ResumeError::code),
|
||||
Some(code)
|
||||
);
|
||||
}
|
||||
assert_eq!(ResumeError::from_code(6), None);
|
||||
}
|
||||
}
|
||||
@@ -1,296 +0,0 @@
|
||||
//! Frames copied into host memory (docs/api.md section 2): a [`FrameTarget`] the library draws
|
||||
//! into, and a [`Frame`], one encode of a display's current frame into a target.
|
||||
//!
|
||||
//! A frame target is a shared-storage 2D texture, not mipmapped, whose usage is render target
|
||||
//! and shader read. A frame is a command buffer of the process's frame queue: encoded
|
||||
//! uncommitted, then committed, then waited on, as separate calls, so a host can hold a frame
|
||||
//! in flight. Its completion handler holds the display until it has run; a frame released
|
||||
//! uncommitted lets the display go with its command buffer, and stays counted in flight for the
|
||||
//! display's life, as a host's dropped command buffer did (docs/api.md section 10, question 8).
|
||||
//!
|
||||
//! Each call, and each release of a frame or a target, runs as an entry ([`crate::entry`]).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::platform::command::CommandBuffer as _;
|
||||
use reims_vgpu_core::platform::descriptor::TextureDescriptor as _;
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::types::CommandBufferStatus;
|
||||
use reims_vgpu_core::platform::{Handle as _, Platform};
|
||||
use reims_vgpu_core::raise::{OnFault, RaiseResult};
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::entry;
|
||||
use crate::error::Error;
|
||||
use crate::platform::ApiPlatform;
|
||||
use crate::retained::Ours;
|
||||
|
||||
/// The largest width or height of a frame target.
|
||||
pub const MAX_FRAME_TARGET_SIZE: u32 = 16384;
|
||||
|
||||
/// `MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget`.
|
||||
const TARGET_USAGE: u64 = 0x1 | 0x4;
|
||||
/// `MTLResourceStorageModeShared`, with the default CPU cache and hazard tracking modes.
|
||||
const TARGET_RESOURCE_OPTIONS: u64 = 0;
|
||||
|
||||
/// A raise that reaches an entry point: nothing catches it there, so it ends the process.
|
||||
fn no_catch<T>(r: RaiseResult<T>) -> T {
|
||||
r.unwrap_or_else(|raised| raised.fatal())
|
||||
}
|
||||
|
||||
/// A frame target's pixel format: 8 bits a channel, 4 bytes a pixel.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PixelFormat {
|
||||
/// `MTLPixelFormatRGBA8Unorm` (70).
|
||||
Rgba8Unorm,
|
||||
/// `MTLPixelFormatRGBA8Unorm_sRGB` (71).
|
||||
Rgba8UnormSrgb,
|
||||
/// `MTLPixelFormatBGRA8Unorm` (80): the byte order of a pixman x8r8g8b8 surface.
|
||||
Bgra8Unorm,
|
||||
/// `MTLPixelFormatBGRA8Unorm_sRGB` (81).
|
||||
Bgra8UnormSrgb,
|
||||
}
|
||||
|
||||
impl PixelFormat {
|
||||
/// The format of Metal's number, or `None` for any other.
|
||||
pub fn from_metal(format: u32) -> Option<PixelFormat> {
|
||||
Some(match format {
|
||||
70 => PixelFormat::Rgba8Unorm,
|
||||
71 => PixelFormat::Rgba8UnormSrgb,
|
||||
80 => PixelFormat::Bgra8Unorm,
|
||||
81 => PixelFormat::Bgra8UnormSrgb,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Metal's number for the format.
|
||||
pub fn metal(self) -> u32 {
|
||||
match self {
|
||||
PixelFormat::Rgba8Unorm => 70,
|
||||
PixelFormat::Rgba8UnormSrgb => 71,
|
||||
PixelFormat::Bgra8Unorm => 80,
|
||||
PixelFormat::Bgra8UnormSrgb => 81,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a frame is drawn in its target, in pixels. The whole target is cleared first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct Region {
|
||||
/// Left.
|
||||
pub x: u64,
|
||||
/// Top.
|
||||
pub y: u64,
|
||||
/// Width.
|
||||
pub width: u64,
|
||||
/// Height.
|
||||
pub height: u64,
|
||||
}
|
||||
|
||||
/// What a frame target holds.
|
||||
struct Target<P: Platform> {
|
||||
texture: P::Texture,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: PixelFormat,
|
||||
/// The platform it was made on.
|
||||
platform: Arc<P>,
|
||||
}
|
||||
|
||||
/// A 2D texture the library draws frames into and reads pixels back from: one counted
|
||||
/// reference. It keeps only its texture, and may outlive the device it was made on.
|
||||
pub struct FrameTarget<P: Platform = DefaultPlatform> {
|
||||
inner: Ours<Arc<Target<P>>>,
|
||||
}
|
||||
|
||||
impl<P: Platform> std::fmt::Debug for FrameTarget<P> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("FrameTarget")
|
||||
.field("width", &self.inner.width)
|
||||
.field("height", &self.inner.height)
|
||||
.field("format", &self.inner.format)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> FrameTarget<P> {
|
||||
/// A target on `device`, the Metal device of a device of this platform.
|
||||
pub(crate) fn new(
|
||||
platform: &Arc<P>,
|
||||
device: &P::Device,
|
||||
width: u32,
|
||||
height: u32,
|
||||
format: PixelFormat,
|
||||
) -> Result<FrameTarget<P>, Error> {
|
||||
entry::run(|_| {
|
||||
let size = 1..=MAX_FRAME_TARGET_SIZE;
|
||||
if !size.contains(&width) || !size.contains(&height) {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
// Metal's `+0` descriptor goes at the entry's pool.
|
||||
let td = no_catch(platform.texture_2d_descriptor(
|
||||
OnFault::Die,
|
||||
u64::from(format.metal()),
|
||||
u64::from(width),
|
||||
u64::from(height),
|
||||
false,
|
||||
));
|
||||
td.set_usage(TARGET_USAGE);
|
||||
td.set_resource_options(TARGET_RESOURCE_OPTIONS);
|
||||
let texture = no_catch(device.new_texture(OnFault::Die, &td));
|
||||
drop(td);
|
||||
let texture = texture.ok_or(Error::Metal)?;
|
||||
let target = Target {
|
||||
texture,
|
||||
width,
|
||||
height,
|
||||
format,
|
||||
platform: platform.clone(),
|
||||
};
|
||||
Ok(FrameTarget {
|
||||
inner: Ours::new(Arc::new(target)),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Another reference to this target.
|
||||
#[must_use]
|
||||
pub fn clone_ref(&self) -> FrameTarget<P> {
|
||||
FrameTarget {
|
||||
inner: Ours::new(Arc::clone(&self.inner)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pixels wide.
|
||||
pub fn width(&self) -> u32 {
|
||||
self.inner.width
|
||||
}
|
||||
|
||||
/// Pixels high.
|
||||
pub fn height(&self) -> u32 {
|
||||
self.inner.height
|
||||
}
|
||||
|
||||
/// The pixel format.
|
||||
pub fn format(&self) -> PixelFormat {
|
||||
self.inner.format
|
||||
}
|
||||
|
||||
/// The texture.
|
||||
pub(crate) fn texture(&self) -> &P::Texture {
|
||||
&self.inner.texture
|
||||
}
|
||||
|
||||
/// Whether both are references to one target.
|
||||
pub fn ptr_eq(&self, other: &FrameTarget<P>) -> bool {
|
||||
Arc::ptr_eq(&self.inner, &other.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> FrameTarget<P> {
|
||||
/// Copies the whole target into `dst`: `height` rows of `width * 4` bytes, each
|
||||
/// `bytes_per_row` after the last, in the target's format. It reads what the GPU has
|
||||
/// written so far: wait for the frames that draw into it first. [`Error::InvalidArgument`]
|
||||
/// when `bytes_per_row` is below `width * 4` or `dst` is shorter than the copy's extent.
|
||||
pub fn read_pixels(&self, dst: &mut [u8], bytes_per_row: usize) -> Result<(), Error> {
|
||||
entry::run(|_| {
|
||||
let row = usize::try_from(self.inner.width)
|
||||
.ok()
|
||||
.and_then(|w| w.checked_mul(4))
|
||||
.ok_or(Error::InvalidArgument)?;
|
||||
let rows = usize::try_from(self.inner.height).map_err(|_| Error::InvalidArgument)?;
|
||||
let extent = bytes_per_row
|
||||
.checked_mul(rows.saturating_sub(1))
|
||||
.and_then(|e| e.checked_add(row))
|
||||
.ok_or(Error::InvalidArgument)?;
|
||||
if bytes_per_row < row || dst.len() < extent {
|
||||
return Err(Error::InvalidArgument);
|
||||
}
|
||||
let dst = dst.get_mut(..extent).ok_or(Error::InvalidArgument)?;
|
||||
self.inner
|
||||
.platform
|
||||
.read_pixels(&self.inner.texture, dst, bytes_per_row);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// One encode of a display's current frame into a target: uncommitted, committed, or complete.
|
||||
pub struct Frame<P: Platform = DefaultPlatform> {
|
||||
/// Its last release may be the display's: the command buffer's completion handler holds it.
|
||||
command_buffer: Ours<P::CommandBuffer>,
|
||||
/// The target it draws into, kept while the frame is.
|
||||
_target: FrameTarget<P>,
|
||||
committed: bool,
|
||||
}
|
||||
|
||||
impl<P: Platform> std::fmt::Debug for Frame<P> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Frame")
|
||||
.field("command_buffer", &self.command_buffer.id())
|
||||
.field("committed", &self.committed)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Frame<P> {
|
||||
/// An encoded, uncommitted frame.
|
||||
pub(crate) fn new(command_buffer: P::CommandBuffer, target: FrameTarget<P>) -> Frame<P> {
|
||||
Frame {
|
||||
command_buffer: Ours::new(command_buffer),
|
||||
_target: target,
|
||||
committed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Submits the frame to the GPU. [`Error::FrameState`] if it was committed already.
|
||||
pub fn commit(&mut self) -> Result<(), Error> {
|
||||
entry::run(|_| {
|
||||
if self.committed {
|
||||
return Err(Error::FrameState);
|
||||
}
|
||||
self.committed = true;
|
||||
no_catch(self.command_buffer.commit(OnFault::Die));
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether [`Frame::commit`] has run.
|
||||
pub fn is_committed(&self) -> bool {
|
||||
self.committed
|
||||
}
|
||||
|
||||
/// Waits until the committed frame completes: [`Error::Gpu`] when its GPU work ended with
|
||||
/// an error, [`Error::FrameState`] before [`Frame::commit`].
|
||||
pub fn wait(&self) -> Result<(), Error> {
|
||||
entry::run(|_| {
|
||||
if !self.committed {
|
||||
return Err(Error::FrameState);
|
||||
}
|
||||
no_catch(self.command_buffer.wait_until_completed(OnFault::Die));
|
||||
if self.command_buffer.status() == CommandBufferStatus::ERROR {
|
||||
return Err(Error::Gpu);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Metal's four numbers, and no other
|
||||
#[test]
|
||||
fn formats() {
|
||||
for f in [
|
||||
PixelFormat::Rgba8Unorm,
|
||||
PixelFormat::Rgba8UnormSrgb,
|
||||
PixelFormat::Bgra8Unorm,
|
||||
PixelFormat::Bgra8UnormSrgb,
|
||||
] {
|
||||
assert_eq!(PixelFormat::from_metal(f.metal()), Some(f));
|
||||
}
|
||||
assert_eq!(PixelFormat::from_metal(73), None);
|
||||
}
|
||||
}
|
||||
@@ -85,9 +85,9 @@ use reims_vgpu_window::{FrameSink, Window, WindowConfig, geometry};
|
||||
use zerocopy::{FromBytes, IntoBytes};
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::device::{GuestMemoryLease, MemoryMap};
|
||||
use crate::display::{CursorGlyph, CursorGlyphFn, CursorMoveFn, CursorShowFn, no_catch};
|
||||
use crate::cursor::{CursorGlyph, CursorGlyphFn, CursorMoveFn, CursorShowFn};
|
||||
use crate::entry;
|
||||
use crate::entry::no_catch;
|
||||
use crate::error::Error;
|
||||
use crate::graphics::color::{ColorChange, ColorStaging, DisplayColor};
|
||||
use crate::graphics::compile::{CompileKind, CompileOf, CompilePool, Pending};
|
||||
@@ -103,6 +103,7 @@ use crate::graphics::decode::{
|
||||
use crate::graphics::device_info::device_info;
|
||||
use crate::graphics::present::{Drawing, PresentAnswers, PresentQueue};
|
||||
use crate::graphics::read::DisplayRead;
|
||||
use crate::memory::{GuestMemoryLease, MemoryMap};
|
||||
use crate::platform::{ApiPlatform, api_state};
|
||||
use crate::window::WindowLink;
|
||||
|
||||
@@ -280,7 +281,7 @@ impl<P: ApiPlatform> GraphicsDevice<P> {
|
||||
// The platform's lease on the guest's RAM, held by the views of the surfaces' pages
|
||||
// made through the map, so it outlives the last of them.
|
||||
if let Some(map) = &config.memory_map {
|
||||
let lease: GuestMemoryLease = Arc::from(platform.guest_memory(map, None));
|
||||
let lease: GuestMemoryLease = Arc::from(platform.guest_memory(map));
|
||||
let memory = CoreMemoryMap::new(Arc::clone(&platform), &map.to_core())
|
||||
.ok_or(Error::InvalidArgument)?;
|
||||
decoder.set_guest_memory(memory, lease);
|
||||
|
||||
@@ -74,7 +74,7 @@
|
||||
//! waits for it on the GPU, on the cache's own event ([`Caches`]): no begin of a buffer, no
|
||||
//! present and no ring-0 copy waits on the CPU for another queue's walk.
|
||||
//! - **The host's own writes.** A device of the host that writes a surface's pages itself (a
|
||||
//! video device's frame, [`crate::device_writes`]) moves no generation, so each cache's pages
|
||||
//! video arm's frame, [`crate::device_writes`]) moves no generation, so each cache's pages
|
||||
//! are watched: a write over them makes the cache's next use fill it whatever its generation,
|
||||
//! and a download or a release before that copies nothing, the pages being newer than the
|
||||
//! cache.
|
||||
|
||||
@@ -64,7 +64,7 @@ use zerocopy::IntoBytes;
|
||||
|
||||
use super::super::{GraphicsDecoder, no_raise};
|
||||
use super::{GUEST_PAGE, Lease, SurfaceView, buffer_over};
|
||||
use crate::device::MemoryMap;
|
||||
use crate::memory::MemoryMap;
|
||||
use crate::platform::ApiPlatform;
|
||||
|
||||
/// The block every surface's messages name, one at a time.
|
||||
@@ -253,7 +253,7 @@ fn guest_ram(length: u64, touched: bool) -> Ram {
|
||||
// SAFETY: advice on the mapping just made.
|
||||
unsafe { libc::madvise(at, length.to_usize(), libc::MADV_HUGEPAGE) };
|
||||
}
|
||||
let file = crate::device::MemoryFile { fd, offset: 0 };
|
||||
let file = crate::memory::MemoryFile { fd, offset: 0 };
|
||||
(at.cast::<u8>(), file)
|
||||
};
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
@@ -316,7 +316,7 @@ fn measure<P: ApiPlatform>(label: &str) {
|
||||
let iters = env_u64("RGK_BENCH_ITERS", 40);
|
||||
let only = std::env::var("RGK_BENCH_CASES").ok();
|
||||
let ram = guest_ram(ram_bytes, true);
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map, None));
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map));
|
||||
let core = CoreMemoryMap::new(Arc::clone(&platform), &ram.map.to_core()).expect("a memory map");
|
||||
let size = BLOCK + 0x10_0000 + RGFX_CURSOR_SPAN;
|
||||
let region = Arc::new(Region::new(size.to_usize()).expect("a region"));
|
||||
@@ -510,7 +510,7 @@ fn measure_takes<P: ApiPlatform>(label: &str) {
|
||||
}
|
||||
// Fresh RAM, a lease and a decoder of their own an order, as a booted guest's.
|
||||
let ram = guest_ram(ram_bytes, false);
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map, None));
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map));
|
||||
let core =
|
||||
CoreMemoryMap::new(Arc::clone(&platform), &ram.map.to_core()).expect("a memory map");
|
||||
let size = BLOCK + takes * block_size + 0x10_0000 + RGFX_CURSOR_SPAN;
|
||||
@@ -660,7 +660,7 @@ fn measure_large_takes<P: ApiPlatform>(label: &str) {
|
||||
continue;
|
||||
}
|
||||
let ram = guest_ram(ram_bytes, false);
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map, None));
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map));
|
||||
let core =
|
||||
CoreMemoryMap::new(Arc::clone(&platform), &ram.map.to_core()).expect("a memory map");
|
||||
let size = BLOCK + takes * block_size + 0x10_0000 + RGFX_CURSOR_SPAN;
|
||||
@@ -752,7 +752,7 @@ fn map_only<P: ApiPlatform>(label: &str) {
|
||||
let iters = env_u64("RGK_BENCH_ITERS", 40);
|
||||
let only = std::env::var("RGK_BENCH_CASES").ok();
|
||||
let ram = guest_ram(ram_bytes, true);
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map, None));
|
||||
let lease: Lease = Arc::from(platform.guest_memory(&ram.map));
|
||||
let core = CoreMemoryMap::new(Arc::clone(&platform), &ram.map.to_core()).expect("a memory map");
|
||||
let mut rng = XorShift(0x9e37_79b9_7f4a_7c15);
|
||||
for case in cases(page) {
|
||||
|
||||
@@ -18,8 +18,8 @@ use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect};
|
||||
|
||||
use super::sink::ScanoutDraw;
|
||||
use super::{Presented, Shown};
|
||||
use crate::display::no_catch;
|
||||
use crate::entry;
|
||||
use crate::entry::no_catch;
|
||||
|
||||
/// The sink of a graphics display on Metal, over `region`; `None` where Metal refuses a queue.
|
||||
pub(super) fn sink(
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! texture of the display's mode, the size the guest is told (the window's size in pixels, or
|
||||
//! 1920 × 1080 without a window), placed and clipped as in a drawable of that size. Where the
|
||||
//! guest has no scanout and presents no surface the display shows black, and so does the read.
|
||||
//! The texture is BGRA8, shared, a render target, as a frame target is (`frame`), and is read
|
||||
//! The texture is BGRA8, shared, a render target, and is read
|
||||
//! once the draw has finished on the GPU: rows of `width * 4` bytes, B, G, R and A in memory.
|
||||
//!
|
||||
//! **What it touches.** Nothing the guest or the window sees. Its draws go on a queue of their
|
||||
@@ -32,11 +32,13 @@ use reims_vgpu_window::PixelRect;
|
||||
|
||||
use super::sink::ScanoutDraw;
|
||||
use super::{Presented, Shown};
|
||||
use crate::display::no_catch;
|
||||
use crate::entry::no_catch;
|
||||
use crate::error::Error;
|
||||
use crate::frame::MAX_FRAME_TARGET_SIZE;
|
||||
use crate::platform::ApiPlatform;
|
||||
|
||||
/// The largest width or height of a read's texture.
|
||||
const MAX_READ_SIZE: u32 = 16384;
|
||||
|
||||
/// `MTLPixelFormatBGRA8Unorm`.
|
||||
const BGRA8_UNORM: u64 = 80;
|
||||
/// `MTLTextureUsageShaderRead | MTLTextureUsageRenderTarget`, a frame target's.
|
||||
@@ -123,9 +125,7 @@ impl<P: ApiPlatform> DisplayRead<P> {
|
||||
.and_then(|h| h.checked_mul(row))
|
||||
.ok_or(Error::InvalidArgument)?;
|
||||
let dst = dst.get_mut(..length).ok_or(Error::InvalidArgument)?;
|
||||
if !(1..=MAX_FRAME_TARGET_SIZE).contains(&width)
|
||||
|| !(1..=MAX_FRAME_TARGET_SIZE).contains(&height)
|
||||
{
|
||||
if !(1..=MAX_READ_SIZE).contains(&width) || !(1..=MAX_READ_SIZE).contains(&height) {
|
||||
return Err(Error::Metal);
|
||||
}
|
||||
let draw = self
|
||||
|
||||
@@ -92,7 +92,7 @@ use reims_vgpu_core::platform::types::MtlViewport;
|
||||
|
||||
use super::color::DisplayColor;
|
||||
use super::{DisplayHold, DrawnPresents, Presented, Shown};
|
||||
use crate::display::no_catch;
|
||||
use crate::entry::no_catch;
|
||||
use crate::platform::ApiPlatform;
|
||||
use reims_graphics::wire::{
|
||||
RGFX_COLOR_MATRIX, RGFX_COLOR_PLANE_GAMMA, RGFX_COLOR_POST_GAMMA, RGFX_COLOR_PRE_GAMMA,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
//! A graphics display's window sink on the Vulkan platform, on either OS: [`VulkanScanoutSink`]
|
||||
//! makes a presenter over a swapchain of the window's surface, as the Vulkan platform's display
|
||||
//! sink does (`crate::window`'s `vulkan`), and each draw blits the scanout into the swapchain's
|
||||
//! next image (its usage takes transfers) and presents it. What each OS's window asks of the
|
||||
//! sink is its own (`linux.rs`, `macos.rs`).
|
||||
//! makes a presenter over a swapchain of the window's surface, and each draw blits the scanout
|
||||
//! into the swapchain's next image (its usage takes transfers) and presents it. What each OS's
|
||||
//! window asks of the sink is its own (`linux.rs`, `macos.rs`).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -15,8 +14,8 @@ use reims_vgpu_window::{Drawn, DrawnCursor, FrameSink, PixelRect, Presenter, Vul
|
||||
|
||||
use super::sink::ScanoutDraw;
|
||||
use super::{Presented, Shown};
|
||||
use crate::display::no_catch;
|
||||
use crate::entry;
|
||||
use crate::entry::no_catch;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
//! What macOS's window asks of the graphics display's Vulkan sink ([`FrameSink`]): it presents
|
||||
//! itself, through a presenter over a swapchain of the window's `CAMetalLayer`, as the Vulkan
|
||||
//! platform's display sink does (`crate::window`'s `vulkan/macos.rs`).
|
||||
//! itself, through a presenter over a swapchain of the window's `CAMetalLayer`.
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
//! [`IoSurfaceDevice`]: vmapple's second MMIO region, made from an [`IoSurfaceDeviceConfig`].
|
||||
//!
|
||||
//! The device registers itself as the process's latest IOSurface device, which a device made
|
||||
//! with `use_iosurface_mapper` finds at its first use. Its interrupt runs on its own serial
|
||||
//! worker; releasing the device from inside that callback ends the process, since its teardown
|
||||
//! waits for that worker.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::host::RaiseInterrupt;
|
||||
use reims_vgpu_core::iosurface::HostDeviceHandle;
|
||||
use reims_vgpu_core::iosurface::IoSurfaceHostDevice as CoreHostDevice;
|
||||
use reims_vgpu_core::iosurface::descriptor::IoSurfaceHostDeviceDescriptor as CoreDescriptor;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::device::MemoryMap;
|
||||
use crate::entry;
|
||||
use crate::error::Error;
|
||||
use crate::platform::ApiPlatform;
|
||||
use crate::retained::Ours;
|
||||
|
||||
/// An IOSurface device's config.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct IoSurfaceDeviceConfig {
|
||||
/// Required.
|
||||
pub memory_map: Option<MemoryMap>,
|
||||
/// `(vector)`, on the device's own worker. Without it, the device's first interrupt ends
|
||||
/// the process.
|
||||
pub raise_interrupt: Option<RaiseInterrupt>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for IoSurfaceDeviceConfig {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("IoSurfaceDeviceConfig")
|
||||
.field("memory_map", &self.memory_map)
|
||||
.field("raise_interrupt", &self.raise_interrupt.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// One reference to an IOSurface device: the last drop is its teardown, which waits for its
|
||||
/// worker. Each call, and the last drop, runs as an entry (the crate's `entry` module).
|
||||
pub struct IoSurfaceDevice<P: Platform = DefaultPlatform> {
|
||||
inner: Ours<HostDeviceHandle<P>>,
|
||||
}
|
||||
|
||||
impl<P: Platform> std::fmt::Debug for IoSurfaceDevice<P> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("IoSurfaceDevice")
|
||||
.field(&std::ptr::from_ref::<CoreHostDevice<P>>(&self.inner))
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl IoSurfaceDevice {
|
||||
/// A new IOSurface device on the process's platform ([`IoSurfaceDevice::with_platform`]).
|
||||
pub fn new(config: IoSurfaceDeviceConfig) -> Result<IoSurfaceDevice, Error> {
|
||||
IoSurfaceDevice::with_platform(DefaultPlatform::process(), config)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> IoSurfaceDevice<P> {
|
||||
/// A new IOSurface device on `platform`, the process's latest. Refusals, in order:
|
||||
/// [`Error::NoMemoryMap`], [`Error::MemoryMap`]; the closure is dropped before a refusal
|
||||
/// returns.
|
||||
pub fn with_platform(
|
||||
platform: Arc<P>,
|
||||
config: IoSurfaceDeviceConfig,
|
||||
) -> Result<IoSurfaceDevice<P>, Error> {
|
||||
entry::run(|_| {
|
||||
let mut d = CoreDescriptor::new();
|
||||
d.memory_map_descriptor = config.memory_map.as_ref().map(MemoryMap::to_core);
|
||||
d.raise_interrupt = config.raise_interrupt;
|
||||
let made = CoreHostDevice::new(&platform, &d);
|
||||
drop(d);
|
||||
Ok(IoSurfaceDevice {
|
||||
inner: Ours::new(made?),
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> IoSurfaceDevice<P> {
|
||||
/// Another reference to this device.
|
||||
#[must_use]
|
||||
pub fn clone_ref(&self) -> IoSurfaceDevice<P> {
|
||||
IoSurfaceDevice {
|
||||
inner: Ours::new(self.inner.clone_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether both are references to one device.
|
||||
pub fn ptr_eq(&self, other: &IoSurfaceDevice<P>) -> bool {
|
||||
self.inner.ptr_eq(&other.inner)
|
||||
}
|
||||
|
||||
/// Core's device state, unretained: what a video device resolves the guest's mapping IDs
|
||||
/// through, so that its lookups never keep this device alive or run its teardown, as the
|
||||
/// graphics device's mapper service holds it.
|
||||
pub(crate) fn core_weak(
|
||||
&self,
|
||||
) -> std::sync::Weak<reims_vgpu_core::iosurface::HostDeviceCore<P>> {
|
||||
self.inner.core_weak()
|
||||
}
|
||||
|
||||
/// Core's device (tests).
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub fn core(&self) -> &HostDeviceHandle<P> {
|
||||
&self.inner
|
||||
}
|
||||
|
||||
/// A 64-bit read at `offset` in the device's registers (0x1000 to 0x1030); an offset that
|
||||
/// names no register reads all ones.
|
||||
pub fn mmio_read(&self, offset: u64) -> u64 {
|
||||
entry::run(|_| self.inner.mmio_read(offset))
|
||||
}
|
||||
|
||||
/// A 64-bit write at `offset`; other offsets are ignored. May block on the device's worker.
|
||||
pub fn mmio_write(&self, offset: u64, value: u64) {
|
||||
entry::run(|_| {
|
||||
self.inner.mmio_write(offset, value);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use reims_vgpu_core::testkit::FakePlatform;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// No memory map refuses, and the closure goes with the refusal
|
||||
#[test]
|
||||
fn no_memory_map_refuses() {
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let raise: RaiseInterrupt = Arc::new(|_| {});
|
||||
let c = IoSurfaceDeviceConfig {
|
||||
memory_map: None,
|
||||
raise_interrupt: Some(raise.clone()),
|
||||
};
|
||||
assert_eq!(
|
||||
IoSurfaceDevice::with_platform(p, c).err(),
|
||||
Some(Error::NoMemoryMap)
|
||||
);
|
||||
assert_eq!(Arc::strong_count(&raise), 1);
|
||||
}
|
||||
|
||||
/// Made over one page of host memory, it registers as the process's latest and answers
|
||||
/// core's registers
|
||||
#[test]
|
||||
fn made_over_a_memory_map() {
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let vm = reims_vgpu_core::platform::Platform::vm(&*p);
|
||||
let page = vm.page_size();
|
||||
let host = vm.allocate_anywhere(page).unwrap();
|
||||
let mut m = MemoryMap::new();
|
||||
// SAFETY: the fake VM's region lives as long as the platform.
|
||||
unsafe { m.push(0, page, host.as_ptr()) };
|
||||
let c = IoSurfaceDeviceConfig {
|
||||
memory_map: Some(m),
|
||||
raise_interrupt: None,
|
||||
};
|
||||
let d = IoSurfaceDevice::with_platform(p.clone(), c).unwrap();
|
||||
let found = CoreHostDevice::latest_handle(&*p).unwrap();
|
||||
assert!(found.ptr_eq(d.core()));
|
||||
for off in (0x1000..0x1038).step_by(8) {
|
||||
assert_eq!(d.mmio_read(off), d.core().mmio_read(off), "{off:#x}");
|
||||
}
|
||||
let d2 = d.clone_ref();
|
||||
assert!(d.ptr_eq(&d2));
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,16 @@
|
||||
//! The library's Rust API (docs/api.md section 3): owned Rust types over core, which the C API
|
||||
//! (`reims-vgpu-c`) wraps one to one.
|
||||
//! The library's Rust API (docs/api.md section 3): the reims-graphics device ([`GraphicsDevice`]),
|
||||
//! which the C API (`reims-vgpu-c`) wraps one to one.
|
||||
//!
|
||||
//! Each object is made from one config ([`DeviceConfig`], [`DisplayConfig`],
|
||||
//! [`IoSurfaceDeviceConfig`]) holding closures for its callbacks, and answers a [`Result`] with
|
||||
//! the check that refused it ([`Error`]). [`Device`], [`Display`], [`FrameTarget`] and
|
||||
//! [`IoSurfaceDevice`] are counted references with `clone_ref()` and no `Clone`: the last drop
|
||||
//! of a device, display or IOSurface device is its end, run on the releasing thread. They are
|
||||
//! generic over the platform with [`DefaultPlatform`] as the default, so their forwarding is
|
||||
//! unit-tested on core's fake platform. The Vulkan platform, `VulkanPlatform`, over
|
||||
//! metal2vulkan's runtime, draws each frame of a window display into a swapchain of its window,
|
||||
//! on macOS one over the window's `CAMetalLayer`.
|
||||
//! A device is made from one config ([`GraphicsConfig`]) holding closures for its callbacks, and
|
||||
//! answers a [`Result`] with what refused it ([`Error`]). It is generic over the platform with
|
||||
//! [`DefaultPlatform`] as the default, so its forwarding is unit-tested on core's fake platform.
|
||||
//! The Vulkan platform, `VulkanPlatform`, over metal2vulkan's runtime, draws the device's window
|
||||
//! into a swapchain of its window, on macOS one over the window's `CAMetalLayer`.
|
||||
//!
|
||||
//! **By OS.** On macOS the default platform is `MetalPlatform`, the product, and the `vulkan`
|
||||
//! feature adds `VulkanPlatform` beside it. On Linux the library is the Vulkan platform's, with or
|
||||
//! without the feature, and `VulkanPlatform` is the default. The build script sets
|
||||
//! `cfg(vulkan_platform)` wherever the library has `VulkanPlatform`, and the code is gated on it.
|
||||
//!
|
||||
//! Behaviour is core's; this crate adds none. Its closures are called synchronously on the
|
||||
//! thread core calls them on, in core's order, which is the order of VM-memory operations and
|
||||
//! releases the host saw before. What it adds is where callbacks run: a display's on the
|
||||
//! process's display thread ([`platform`]), in place of the host's dispatch queue; and a
|
||||
//! display's own window, for a display created with one ([`DisplayConfig::window`]), which has
|
||||
//! every display callback as the guest reads them (`window.rs`).
|
||||
//! **By OS.** On macOS the default platform is `MetalPlatform`, and the `vulkan` feature adds
|
||||
//! `VulkanPlatform` beside it. On Linux the library is the Vulkan platform's, with or without the
|
||||
//! feature, and `VulkanPlatform` is the default. The build script sets `cfg(vulkan_platform)`
|
||||
//! wherever the library has `VulkanPlatform`, and the code is gated on it.
|
||||
//!
|
||||
//! The library logs through the `log` crate: a Rust host installs its own logger.
|
||||
|
||||
@@ -37,56 +26,29 @@ mod counted;
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: counted::Counted = counted::Counted;
|
||||
|
||||
mod device;
|
||||
mod cursor;
|
||||
mod device_writes;
|
||||
pub mod dirty;
|
||||
mod display;
|
||||
mod entry;
|
||||
mod error;
|
||||
mod frame;
|
||||
mod graphics;
|
||||
mod iosurface;
|
||||
mod memory;
|
||||
pub mod platform;
|
||||
mod retained;
|
||||
mod scaler;
|
||||
pub mod singleton;
|
||||
mod stats;
|
||||
mod video;
|
||||
mod window;
|
||||
|
||||
pub use device::{Device, DeviceConfig, HostCallbacks, MemoryFile, MemoryMap};
|
||||
pub use dirty::{DirtyHost, DirtySource, KvmSlot};
|
||||
pub use display::{
|
||||
CursorGlyph, CursorGlyphFn, CursorMoveFn, CursorShowFn, Display, DisplayCallbacks,
|
||||
DisplayConfig, DisplayMode, ModeChangeFn, NewFrameFn,
|
||||
};
|
||||
pub use error::{Error, ResumeError};
|
||||
pub use frame::{Frame, FrameTarget, MAX_FRAME_TARGET_SIZE, PixelFormat, Region};
|
||||
pub use cursor::{CursorGlyph, CursorGlyphFn, CursorMoveFn, CursorShowFn};
|
||||
pub use error::Error;
|
||||
pub use graphics::{
|
||||
GraphicsCallbacks, GraphicsConfig, GraphicsDevice, GraphicsRaiseFn, GraphicsVideo,
|
||||
GraphicsVideoSession, ScanoutWrittenFn, VideoDecode, VideoPlane,
|
||||
};
|
||||
pub use iosurface::{IoSurfaceDevice, IoSurfaceDeviceConfig};
|
||||
pub use memory::{MemoryFile, MemoryMap};
|
||||
pub use platform::ApiPlatform;
|
||||
pub use reims_vgpu_core::host::{
|
||||
AddTraceRange, CreateTask, DestroyTask, HostPtr, HostTask, HostTraceRange, MapMemory,
|
||||
PhysicalMemoryRange, RaiseInterrupt, ReadMemory, RemoveTraceRange, TraceRangeHandler,
|
||||
UnmapMemory,
|
||||
};
|
||||
pub use reims_vgpu_core::platform::os::Preferences;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use reims_vgpu_metal::MetalPlatform;
|
||||
/// reims-vgpu-video-core, for the tests of crates above this one: the scaler's CPU stand-in and
|
||||
/// its capabilities, which they make devices on.
|
||||
#[cfg(feature = "testkit")]
|
||||
pub use reims_vgpu_video_core;
|
||||
#[cfg(vulkan_platform)]
|
||||
pub use reims_vgpu_vulkan::VulkanPlatform;
|
||||
pub use scaler::{GuestMemory, ScalerDevice, ScalerDeviceConfig, ScalerOutcome};
|
||||
pub use video::{
|
||||
ALLOCATION_FAILED, INVALID_SESSION, MAX_MESSAGE_SIZE, SendToGuest, SurfacePlane, VideoDevice,
|
||||
VideoDeviceConfig,
|
||||
};
|
||||
|
||||
/// The platform every handle is made on by default: `MetalPlatform` on macOS.
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -99,12 +61,3 @@ pub use reims_vgpu_window::{
|
||||
MomentumPhase, PointerFn, ScrollEvent, ScrollFn, ScrollPhase, WheelFn, WindowCallbacks,
|
||||
WindowConfig,
|
||||
};
|
||||
|
||||
/// The most display ports a device has.
|
||||
pub const MAX_DISPLAY_PORTS: u32 = reims_vgpu_core::device::config::MAX_DISPLAY_PORT_COUNT;
|
||||
/// The size of the device's MMIO region: the PCI BAR, or vmapple's first region.
|
||||
pub const DEVICE_MMIO_SIZE: u64 = reims_vgpu_core::device::config::DEFAULT_MMIO_LENGTH;
|
||||
/// The PCI vendor ID of the device.
|
||||
pub const PCI_VENDOR_ID: u16 = 0x106b;
|
||||
/// The PCI device ID of the device.
|
||||
pub const PCI_DEVICE_ID: u16 = 0xeeee;
|
||||
@@ -0,0 +1,95 @@
|
||||
//! [`MemoryMap`]: the guest's RAM as the host maps it, which a graphics device is made over
|
||||
//! ([`GraphicsConfig::memory_map`](crate::GraphicsConfig::memory_map)), with the file behind each
|
||||
//! range where the host names one, and the platform's lease on it ([`GuestMemoryLease`]).
|
||||
|
||||
use std::any::Any;
|
||||
use std::os::fd::OwnedFd;
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::host::HostPtr;
|
||||
use reims_vgpu_core::memory::descriptor::{
|
||||
GuestPhysicalRange, MemoryMapDescriptor as CoreMemoryMap,
|
||||
};
|
||||
|
||||
/// Guest RAM and the host memory behind it, in order, with the file behind each range where the
|
||||
/// host names one. The ranges are copied into the device at its creation; nothing is checked
|
||||
/// until then.
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct MemoryMap {
|
||||
ranges: Vec<GuestPhysicalRange>,
|
||||
/// One entry per range, in the ranges' order.
|
||||
files: Vec<Option<MemoryFile>>,
|
||||
}
|
||||
|
||||
/// The file behind one range of a [`MemoryMap`]: the range's host memory is a shared mapping
|
||||
/// (`MAP_SHARED`) of `fd` from byte `offset`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemoryFile {
|
||||
/// The file, held open while any map or device holds it.
|
||||
pub fd: Arc<OwnedFd>,
|
||||
/// The file offset of the range's first byte, a multiple of the host's page size.
|
||||
pub offset: u64,
|
||||
}
|
||||
|
||||
impl MemoryMap {
|
||||
/// An empty map.
|
||||
pub fn new() -> MemoryMap {
|
||||
MemoryMap::default()
|
||||
}
|
||||
|
||||
/// Appends one range with no file, as given (no check, no merge).
|
||||
///
|
||||
/// # Safety
|
||||
/// As [`MemoryMap::push_with_file`].
|
||||
pub unsafe fn push(&mut self, guest_physical_address: u64, length: u64, host: *mut u8) {
|
||||
// SAFETY: the caller's contract.
|
||||
unsafe { self.push_with_file(guest_physical_address, length, host, None) }
|
||||
}
|
||||
|
||||
/// Appends one range and the file behind it, if any, as given (no check, no merge).
|
||||
///
|
||||
/// # Safety
|
||||
/// `host .. host + length` is host memory (`mach_vm_allocate`d or equivalent) that stays
|
||||
/// mapped while any graphics device made over the map lives: the device remaps it and reads
|
||||
/// and writes the guest's memory through it. With `file`, that memory is a
|
||||
/// shared mapping of `file.fd` from `file.offset`, and the file holds at least `length`
|
||||
/// bytes from there.
|
||||
pub unsafe fn push_with_file(
|
||||
&mut self,
|
||||
guest_physical_address: u64,
|
||||
length: u64,
|
||||
host: *mut u8,
|
||||
file: Option<MemoryFile>,
|
||||
) {
|
||||
self.ranges.push(GuestPhysicalRange {
|
||||
physical_address: guest_physical_address,
|
||||
physical_length: length,
|
||||
host_address: HostPtr::from_ptr(host),
|
||||
});
|
||||
self.files.push(file);
|
||||
}
|
||||
|
||||
/// The ranges, in order.
|
||||
pub fn ranges(&self) -> &[GuestPhysicalRange] {
|
||||
&self.ranges
|
||||
}
|
||||
|
||||
/// The file behind each range, in the ranges' order: `None` for a range with no file.
|
||||
pub fn files(&self) -> &[Option<MemoryFile>] {
|
||||
&self.files
|
||||
}
|
||||
|
||||
/// Core's descriptor of the map.
|
||||
pub(crate) fn to_core(&self) -> CoreMemoryMap {
|
||||
let mut m = CoreMemoryMap::new();
|
||||
for r in &self.ranges {
|
||||
m.add_range(*r);
|
||||
}
|
||||
m
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform's lease on the guest's RAM for one graphics device
|
||||
/// ([`ApiPlatform::guest_memory`](crate::ApiPlatform::guest_memory)), held by the views of the
|
||||
/// surfaces' pages made through the map.
|
||||
pub(crate) type GuestMemoryLease = Arc<dyn Any + Send + Sync>;
|
||||
@@ -1,29 +1,12 @@
|
||||
//! What the API needs of a platform beyond core's [`Platform`] ([`ApiPlatform`]), and the state
|
||||
//! it keeps once per platform instance, which in the product is once per process: the display
|
||||
//! thread and the frame queues.
|
||||
//! thread.
|
||||
//!
|
||||
//! **The display thread.** Every display is given one executor in place of a host's dispatch
|
||||
//! queue: a core [`SerialQueue`] made at the process's first display (docs/api.md section 5).
|
||||
//! Core queues onto it exactly the jobs it queued onto the host's queue, at the same points, so
|
||||
//! every display callback of the process runs one at a time in the order they were queued, as
|
||||
//! they did on the main queue QEMU and the runner gave every display. A graphics device queues
|
||||
//! its host's cursor callbacks onto it too (`graphics`' `HostCursor`), made at the first device
|
||||
//! whose host takes them where no display made it. The queue's worker exits
|
||||
//! after [`reims_vgpu_core::rt::queue::IDLE_EXIT`] idle and the next job starts another. It is
|
||||
//! not a dispatch queue, so core models the new-frame source with its `CoalescingSignal`. The
|
||||
//! library never waits for it: no core path `sync`s onto a display's queue, and a queue's drop
|
||||
//! joins nothing.
|
||||
//!
|
||||
//! **The frame queues.** One command queue per Metal device, made the first time a device is
|
||||
//! created on that Metal device, before core builds the device, and kept for the life of the
|
||||
//! process. Every frame's command buffer comes from it, a window's among them.
|
||||
//!
|
||||
//! **Windows.** A window display's host screen and what draws its frames are chosen by the
|
||||
//! platform's type (`window::host_screen`, `window::window_sink`): `MetalPlatform` answers from
|
||||
//! the host's screens and with a sink over Metal; the Vulkan platform (`cfg(vulkan_platform)`),
|
||||
//! from the host's screens and, on macOS, with a sink that has Metal copy the runtime's frames
|
||||
//! into the window; the testkit's platform, a fixed screen (`FAKE_HOST_SCREEN`) and no sink, so
|
||||
//! its window displays never open a window. So the trait below names no Objective-C type.
|
||||
//! **The display thread.** A graphics device queues its host's cursor callbacks onto one core
|
||||
//! [`SerialQueue`], made at the process's first device whose host takes them (`graphics`'
|
||||
//! `HostCursor`), so every display callback of the process runs one at a time in the order it
|
||||
//! was queued. The queue's worker exits after [`reims_vgpu_core::rt::queue::IDLE_EXIT`] idle and
|
||||
//! the next job starts another. The library never waits for it, and a queue's drop joins nothing.
|
||||
//!
|
||||
//! **By platform.** Each platform's `ApiPlatform` is a file of its own: `platform/metal.rs`
|
||||
//! (macOS) and `platform/vulkan.rs` (Linux, and macOS with the `vulkan` feature).
|
||||
@@ -32,17 +15,14 @@ use std::any::Any;
|
||||
use std::sync::{Arc, OnceLock, Weak};
|
||||
|
||||
use reims_vgpu_core::host::HostQueue;
|
||||
use reims_vgpu_core::memory::dirty::DirtyLog;
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::{Handle, ObjId, Platform};
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::rt::{Executor, Job, SerialQueue};
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_video_core::device_memory::DeviceMemory;
|
||||
|
||||
use crate::device::MemoryMap;
|
||||
use crate::memory::MemoryMap;
|
||||
|
||||
/// What the API asks of a platform beyond core's: the process's instance, the Metal device a
|
||||
/// config names, a frame target's pixels, and what it holds of the guest's RAM.
|
||||
/// What the API asks of a platform beyond core's: the process's instance, its GPU device, a
|
||||
/// texture's pixels, what it holds of the guest's RAM, a graphics device's region and its video.
|
||||
pub trait ApiPlatform: Platform {
|
||||
/// The process's platform, made on first use.
|
||||
fn process() -> Arc<Self>;
|
||||
@@ -55,17 +35,10 @@ pub trait ApiPlatform: Platform {
|
||||
/// `bytes_per_row` after the last. The caller has checked that `dst` holds them.
|
||||
fn read_pixels(&self, texture: &Self::Texture, dst: &mut [u8], bytes_per_row: usize);
|
||||
|
||||
/// What the platform holds of the guest's RAM while a device made over `map` lives: the
|
||||
/// device takes it as it is created and drops it after core's teardown. `dirty` is the
|
||||
/// device's dirty log, for a device with a dirty source: where the platform keeps copies of
|
||||
/// guest memory of its own, it asks the log which pages changed, and stamps there what it
|
||||
/// writes into the guest's RAM itself. Nothing by default.
|
||||
fn guest_memory(
|
||||
&self,
|
||||
map: &MemoryMap,
|
||||
dirty: Option<Arc<DirtyLog>>,
|
||||
) -> Box<dyn Any + Send + Sync> {
|
||||
let _ = (map, dirty);
|
||||
/// What the platform holds of the guest's RAM while a graphics device made over `map` lives:
|
||||
/// the views of the surfaces' pages made through the map hold it. Nothing by default.
|
||||
fn guest_memory(&self, map: &MemoryMap) -> Box<dyn Any + Send + Sync> {
|
||||
let _ = map;
|
||||
Box::new(())
|
||||
}
|
||||
|
||||
@@ -83,68 +56,14 @@ pub trait ApiPlatform: Platform {
|
||||
let _ = device;
|
||||
None
|
||||
}
|
||||
|
||||
/// The planes of `surface`, in order: what a video device's codecs read of a guest pixel
|
||||
/// buffer's layout beyond core's `Surface`. Empty for a surface without planes, whose layout
|
||||
/// is the surface's own, and by default, for a platform that does not say.
|
||||
fn surface_planes(&self, surface: &Self::Surface) -> Vec<crate::video::SurfacePlane> {
|
||||
let _ = surface;
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Lends `surface`'s bytes, from its first byte to the end of its allocation, to `write`:
|
||||
/// what a video device's decoders write a guest pixel buffer's frames through, in place where
|
||||
/// they can be. `Err` with why where they cannot be lent, and by default, for a platform that
|
||||
/// lends none.
|
||||
fn lend_surface_bytes(
|
||||
&self,
|
||||
surface: &Self::Surface,
|
||||
write: &mut dyn FnMut(&mut [u8]),
|
||||
) -> Result<(), &'static str> {
|
||||
let _ = (surface, write);
|
||||
Err("this platform lends no surface's bytes")
|
||||
}
|
||||
|
||||
/// Lends `surface`'s bytes, laid out as [`ApiPlatform::lend_surface_bytes`] lends them, to
|
||||
/// `read`: what a video device's scaler and encoders read a guest pixel buffer through,
|
||||
/// writing nothing back, so a surface the guest made read-only for its clients is lent too.
|
||||
/// `Err` with why where they cannot be lent, and by default, for a platform that lends none.
|
||||
fn lend_surface_bytes_for_reading(
|
||||
&self,
|
||||
surface: &Self::Surface,
|
||||
read: &mut dyn FnMut(&[u8]),
|
||||
) -> Result<(), &'static str> {
|
||||
let _ = (surface, read);
|
||||
Err("this platform lends no surface's bytes")
|
||||
}
|
||||
|
||||
/// What a video device's decoders lend a device of `surface`'s memory, so that the device
|
||||
/// writes a guest pixel buffer's frames into it with no copy by the CPU: the bytes
|
||||
/// [`ApiPlatform::lend_surface_bytes`] lends, on Linux as a dma-buf of their pages and as a
|
||||
/// view of them in the host's memory, on macOS as the surface's own IOSurface, and an
|
||||
/// identity that lives as long as the surface does, so that a device's imports of them go
|
||||
/// with it. The caller holds the surface while it uses them. `Err` with why where none is
|
||||
/// lent: a protected surface, one the guest made read-only for its clients, and by default,
|
||||
/// for a platform that lends none.
|
||||
fn surface_device_memory(
|
||||
&self,
|
||||
surface: &Self::Surface,
|
||||
) -> Result<Box<dyn DeviceMemory>, &'static str> {
|
||||
let _ = surface;
|
||||
Err("this platform lends no surface's memory to devices")
|
||||
}
|
||||
}
|
||||
|
||||
/// The API's state for one platform instance.
|
||||
pub(crate) struct ApiState<P: Platform> {
|
||||
/// The display thread, made at the first display.
|
||||
/// The display thread, made at the first device whose host takes the cursor.
|
||||
display_thread: Mutex<Option<DisplayThread>>,
|
||||
/// The frame queue of each Metal device a device was created on, by the device's identity
|
||||
/// (`None`: Metal made none). Unshared ([`new_command_queue_unshared`]): it draws the
|
||||
/// displays' frames, a host's and a window's, so no other queue's work holds them back.
|
||||
///
|
||||
/// [`new_command_queue_unshared`]: reims_vgpu_core::platform::device::GpuDevice::new_command_queue_unshared
|
||||
frame_queues: Mutex<Vec<(ObjId, Option<P::CommandQueue>)>>,
|
||||
/// The platform the state is of.
|
||||
platform: std::marker::PhantomData<fn() -> P>,
|
||||
}
|
||||
|
||||
/// A platform instance's state, found by the platform's identity: the platform, held weakly,
|
||||
@@ -170,7 +89,7 @@ pub(crate) fn api_state<P: Platform>(platform: &Arc<P>) -> Arc<ApiState<P>> {
|
||||
}
|
||||
let state = Arc::new(ApiState::<P> {
|
||||
display_thread: Mutex::new(None),
|
||||
frame_queues: Mutex::new(Vec::new()),
|
||||
platform: std::marker::PhantomData,
|
||||
});
|
||||
let weak: Weak<dyn Any + Send + Sync> = Arc::downgrade(platform) as Weak<dyn Any + Send + Sync>;
|
||||
states.push((weak, state.clone() as Arc<dyn Any + Send + Sync>));
|
||||
@@ -178,8 +97,8 @@ pub(crate) fn api_state<P: Platform>(platform: &Arc<P>) -> Arc<ApiState<P>> {
|
||||
}
|
||||
|
||||
impl<P: Platform> ApiState<P> {
|
||||
/// The display thread, made now if this is the process's first display, or its first
|
||||
/// graphics device whose host takes the cursor.
|
||||
/// The display thread, made now if this is the process's first graphics device whose host
|
||||
/// takes the cursor.
|
||||
pub(crate) fn display_thread(&self, platform: &P) -> Arc<dyn HostQueue> {
|
||||
let mut slot = self.display_thread.lock();
|
||||
let thread = slot.get_or_insert_with(|| {
|
||||
@@ -187,26 +106,13 @@ impl<P: Platform> ApiState<P> {
|
||||
});
|
||||
Arc::new(thread.clone())
|
||||
}
|
||||
|
||||
/// The frame queue for `device`, made now if none was made for it.
|
||||
pub(crate) fn frame_queue(&self, device: &P::Device) -> Option<P::CommandQueue> {
|
||||
let id = device.id();
|
||||
let mut queues = self.frame_queues.lock();
|
||||
if let Some((_, q)) = queues.iter().find(|(d, _)| *d == id) {
|
||||
return q.as_ref().map(Handle::clone_ref);
|
||||
}
|
||||
let queue = device.new_command_queue_unshared();
|
||||
let found = queue.as_ref().map(Handle::clone_ref);
|
||||
queues.push((id, queue));
|
||||
found
|
||||
}
|
||||
}
|
||||
|
||||
/// The display thread's label: a diagnostic.
|
||||
pub const DISPLAY_THREAD_LABEL: &str = "reims-vgpu.display";
|
||||
|
||||
/// The executor every display is given in place of a host's queue: one serial queue for the
|
||||
/// process. Another handle is the same queue.
|
||||
/// The executor the cursor callbacks run on: one serial queue for the process. Another handle is
|
||||
/// the same queue.
|
||||
#[derive(Clone, Debug)]
|
||||
struct DisplayThread(SerialQueue);
|
||||
|
||||
@@ -217,7 +123,7 @@ impl Executor for DisplayThread {
|
||||
}
|
||||
|
||||
impl HostQueue for DisplayThread {
|
||||
/// Another handle to the same queue: a display holds it until its unplug.
|
||||
/// Another handle to the same queue.
|
||||
fn dispatch_retain(&self) -> Arc<dyn HostQueue> {
|
||||
Arc::new(self.clone())
|
||||
}
|
||||
@@ -240,18 +146,8 @@ mod fake {
|
||||
static PLATFORM: Arc<FakePlatform> = Arc::new(FakePlatform::new());
|
||||
}
|
||||
|
||||
/// The host screen of the testkit's platform, whatever the port: a Retina screen of 3024 by
|
||||
/// 1964 pixels at 2 pixels a point, at 120 Hz.
|
||||
pub const FAKE_HOST_SCREEN: reims_vgpu_window::HostScreen = reims_vgpu_window::HostScreen {
|
||||
id: 1,
|
||||
pixels: (3024, 1964),
|
||||
scale: 2.0,
|
||||
refresh_hz: 120.0,
|
||||
};
|
||||
|
||||
/// The testkit's platform: a process per test thread, its one device (registry ID
|
||||
/// [`FAKE_REGISTRY_ID`]), pixels that read as zero, one host screen
|
||||
/// ([`FAKE_HOST_SCREEN`]) and no window sink, so a window display's window is never opened.
|
||||
/// [`FAKE_REGISTRY_ID`]), and pixels that read as zero.
|
||||
impl ApiPlatform for FakePlatform {
|
||||
fn process() -> Arc<FakePlatform> {
|
||||
PLATFORM.with(Arc::clone)
|
||||
@@ -275,9 +171,6 @@ mod fake {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub use fake::FAKE_HOST_SCREEN;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::mpsc;
|
||||
@@ -322,6 +215,7 @@ mod tests {
|
||||
#[cfg(vulkan_platform)]
|
||||
#[test]
|
||||
fn vulkan_devices_by_registry_id() {
|
||||
use reims_vgpu_core::platform::Handle as _;
|
||||
use reims_vgpu_core::tasks::isolation::TaskThreads;
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
|
||||
@@ -346,7 +240,7 @@ mod tests {
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
use reims_vgpu_vulkan::os::OsVm;
|
||||
|
||||
use crate::device::MemoryFile;
|
||||
use crate::memory::MemoryFile;
|
||||
|
||||
const LEN: u64 = 0x4000;
|
||||
let p = VulkanPlatform::new(Box::new(TaskThreads::new()));
|
||||
@@ -399,7 +293,7 @@ mod tests {
|
||||
// SAFETY: the guest's RAM, mapped writable above.
|
||||
unsafe { ram.as_ptr::<u8>().add(0x10).write_volatile(0x5a) };
|
||||
assert_eq!(view(ram), None, "no file is known before the lease");
|
||||
let lease = p.guest_memory(&map, None);
|
||||
let lease = p.guest_memory(&map);
|
||||
assert_eq!(view(ram), Some(0x5a));
|
||||
assert_eq!(view(plain), None, "a range without a file");
|
||||
drop(lease);
|
||||
@@ -409,21 +303,4 @@ mod tests {
|
||||
assert_eq!(unsafe { libc::munmap(ram.as_ptr(), LEN as usize) }, 0);
|
||||
assert!(vm.deallocate(plain, LEN).is_success());
|
||||
}
|
||||
|
||||
/// One frame queue per Metal device, made once, and unshared
|
||||
#[test]
|
||||
fn one_frame_queue_per_device() {
|
||||
use reims_vgpu_core::testkit::impls::device::UNSHARED_QUEUE;
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let s = api_state(&p);
|
||||
let d = p.device();
|
||||
let q1 = s.frame_queue(&d).unwrap();
|
||||
let q2 = s.frame_queue(&d).unwrap();
|
||||
assert_eq!(q1.id(), q2.id());
|
||||
let log = p.call_log();
|
||||
assert_eq!(log.count(UNSHARED_QUEUE), 1);
|
||||
assert_eq!(log.count("newCommandQueue"), 0);
|
||||
assert_eq!(p.metal_device(Some(0)).map(|d| d.id()), None);
|
||||
assert_eq!(p.metal_device(None).map(|d| d.id()), Some(d.id()));
|
||||
}
|
||||
}
|
||||
@@ -5,13 +5,10 @@ use objc2_metal::{MTLCreateSystemDefaultDevice, MTLOrigin, MTLRegion, MTLSize, M
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_metal::MetalPlatform;
|
||||
use reims_vgpu_metal::msg;
|
||||
use reims_vgpu_metal::os::surface_bytes;
|
||||
use reims_vgpu_metal::platform::Obj;
|
||||
|
||||
use super::*;
|
||||
|
||||
mod lent_memory;
|
||||
|
||||
impl ApiPlatform for MetalPlatform {
|
||||
fn process() -> Arc<MetalPlatform> {
|
||||
crate::singleton::platform()
|
||||
@@ -57,154 +54,4 @@ impl ApiPlatform for MetalPlatform {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Each plane the surface was made with, from IOSurface's per-plane getters
|
||||
/// (`reims_vgpu_metal::os::surface_bytes::plane_layout`).
|
||||
fn surface_planes(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
) -> Vec<crate::video::SurfacePlane> {
|
||||
use reims_vgpu_core::platform::os::surface::Surface as _;
|
||||
(0..surface.plane_count())
|
||||
.map_while(|i| surface_bytes::plane_layout(surface, i))
|
||||
.map(|p| crate::video::SurfacePlane {
|
||||
offset: p.offset,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
bytes_per_element: p.bytes_per_element,
|
||||
bytes_per_row: p.bytes_per_row,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Through the surface's base address under `IOSurfaceLock`
|
||||
/// (`reims_vgpu_metal::os::surface_bytes`).
|
||||
fn lend_surface_bytes(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
write: &mut dyn FnMut(&mut [u8]),
|
||||
) -> Result<(), &'static str> {
|
||||
surface_bytes::lend_surface_bytes(surface, write)
|
||||
}
|
||||
|
||||
/// Through the surface's base address under a read-only `IOSurfaceLock`
|
||||
/// (`reims_vgpu_metal::os::surface_bytes`).
|
||||
fn lend_surface_bytes_for_reading(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
read: &mut dyn FnMut(&[u8]),
|
||||
) -> Result<(), &'static str> {
|
||||
surface_bytes::lend_surface_bytes_for_reading(surface, read)
|
||||
}
|
||||
|
||||
/// The surface's own IOSurface, which a device writes through VideoToolbox, with an identity
|
||||
/// attached to the surface (`platform/metal/lent_memory.rs`). Refused as `lend_surface_bytes`
|
||||
/// refuses a writer, and besides for any surface the guest made read-only for its clients,
|
||||
/// over its pages or its own memory (`reims_vgpu_metal::os::device_lend`).
|
||||
fn surface_device_memory(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
) -> Result<Box<dyn DeviceMemory>, &'static str> {
|
||||
lent_memory::lent_memory(surface).map(|lent| Box::new(lent) as Box<dyn DeviceMemory>)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use reims_vgpu_core::platform::os::surface::{IoSurfaces as _, SurfacePlaneSpec, SurfaceSpec};
|
||||
use reims_vgpu_metal::os::iosurface::MetalSurfaces;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The video devices reach a surface's planes and bytes through the process's platform: each
|
||||
/// plane as it was made, a write lend's bytes in what a read lend sees
|
||||
#[test]
|
||||
fn a_surfaces_planes_and_bytes_reach_the_video_devices() {
|
||||
let plane = |offset, width, height, bytes_per_element| SurfacePlaneSpec {
|
||||
base: offset,
|
||||
offset,
|
||||
width,
|
||||
height,
|
||||
size: 64 * height,
|
||||
bytes_per_row: 64,
|
||||
bytes_per_element,
|
||||
element_width: 1,
|
||||
element_height: 1,
|
||||
..SurfacePlaneSpec::default()
|
||||
};
|
||||
let spec = SurfaceSpec {
|
||||
planes: Some(vec![plane(0, 64, 32, 1), plane(4096, 32, 16, 2)]),
|
||||
pixel_format: u32::from_be_bytes(*b"420v"),
|
||||
alloc_size: 16384,
|
||||
width: 64,
|
||||
height: 32,
|
||||
bytes_per_element: 1,
|
||||
bytes_per_row: 64,
|
||||
element_width: 1,
|
||||
element_height: 1,
|
||||
..SurfaceSpec::default()
|
||||
};
|
||||
let surface = MetalSurfaces::new().create(&spec).unwrap();
|
||||
let platform = MetalPlatform::process();
|
||||
let planes = platform.surface_planes(&surface);
|
||||
let offsets: Vec<_> = planes
|
||||
.iter()
|
||||
.map(|p| (p.offset, p.width, p.height))
|
||||
.collect();
|
||||
assert_eq!(offsets, [(0, 64, 32), (4096, 32, 16)]);
|
||||
assert_eq!(planes[1].bytes_per_element, 2);
|
||||
platform
|
||||
.lend_surface_bytes(&surface, &mut |bytes| bytes[4096] = 0x80)
|
||||
.unwrap();
|
||||
let mut seen = 0;
|
||||
platform
|
||||
.lend_surface_bytes_for_reading(&surface, &mut |bytes| seen = bytes[4096])
|
||||
.unwrap();
|
||||
assert_eq!(seen, 0x80);
|
||||
}
|
||||
|
||||
/// A surface's memory is lent to a device as its own IOSurface, writable, with one identity
|
||||
/// for every lend of it; the lend's reference of the IOSurface goes with it. One the guest made
|
||||
/// read-only for its clients is lent to none. Both are of their own memory: no test here makes
|
||||
/// a surface over client memory
|
||||
#[test]
|
||||
fn a_surface_is_lent_to_a_device_as_its_own_iosurface() {
|
||||
use reims_vgpu_core::platform::Handle as _;
|
||||
use reims_vgpu_core::platform::os::surface::Surface as _;
|
||||
|
||||
let spec = |client_direction| SurfaceSpec {
|
||||
pixel_format: u32::from_be_bytes(*b"BGRA"),
|
||||
alloc_size: 16384,
|
||||
width: 64,
|
||||
height: 64,
|
||||
bytes_per_element: 4,
|
||||
bytes_per_row: 256,
|
||||
element_width: 1,
|
||||
element_height: 1,
|
||||
client_direction,
|
||||
..SurfaceSpec::default()
|
||||
};
|
||||
let surface = MetalSurfaces::new().create(&spec(None)).unwrap();
|
||||
let platform = MetalPlatform::process();
|
||||
let before = surface.retain_count();
|
||||
let lent = platform.surface_device_memory(&surface).unwrap();
|
||||
let again = platform.surface_device_memory(&surface).unwrap();
|
||||
assert_eq!(lent.identity().key(), again.identity().key());
|
||||
assert_eq!(
|
||||
lent.length(),
|
||||
usize::try_from(surface.alloc_size()).unwrap()
|
||||
);
|
||||
let io_surface = lent.io_surface().unwrap();
|
||||
assert!(io_surface.writable());
|
||||
// A Metal surface's ID is its IOSurfaceRef's address (`Handle::id`).
|
||||
assert_eq!(io_surface.as_ptr().addr().get() as u64, surface.id().0);
|
||||
assert_eq!(surface.retain_count(), before + 2);
|
||||
drop((lent, again));
|
||||
assert_eq!(surface.retain_count(), before);
|
||||
let read_only = MetalSurfaces::new().create(&spec(Some(2))).unwrap();
|
||||
assert_eq!(
|
||||
platform.surface_device_memory(&read_only).err(),
|
||||
Some("a surface the guest made read-only for its clients")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
//! A Metal surface's memory as a video device's decoders lend it to a device
|
||||
//! ([`ApiPlatform::surface_device_memory`](crate::platform::ApiPlatform::surface_device_memory)):
|
||||
//! the Metal crate's lend of its IOSurface (`reims_vgpu_metal::os::device_lend`), and an identity
|
||||
//! attached to the surface (`reims_vgpu_metal::os::surface_bytes::attachment`). The identity is
|
||||
//! one for every object over the surface, and goes when a surface made later takes its
|
||||
//! `IOSurfaceID`, so the same pages mapped again are another surface with another identity, and no
|
||||
//! import of the one before is ever written again.
|
||||
//!
|
||||
//! The IOSurface is borrowed for the lend's life, which is the holder's hold: anything a device
|
||||
//! makes of it, a pixel buffer over it among them, is released before its write returns, as a
|
||||
//! reference of it is a hold the guest sees (the mapper's unmap answers Busy while one lives).
|
||||
|
||||
use reims_vgpu_metal::os::device_lend::{DeviceLend, lend_to_devices};
|
||||
use reims_vgpu_metal::os::iosurface::MetalSurface;
|
||||
use reims_vgpu_metal::os::surface_bytes::attachment;
|
||||
use reims_vgpu_video_core::device_memory::{
|
||||
DeviceMemory, LentIoSurface, MemoryIdentity, MemoryLife,
|
||||
};
|
||||
use reims_vgpu_video_core::surfaces::SurfaceError;
|
||||
|
||||
/// A surface's memory lent to a device (module docs).
|
||||
pub(super) struct LentMemory {
|
||||
identity: MemoryIdentity,
|
||||
lend: DeviceLend,
|
||||
}
|
||||
|
||||
/// `surface`'s memory lent to a device; `Err` with why where it is not lent: a protected surface,
|
||||
/// and one the guest made read-only for its clients.
|
||||
pub(super) fn lent_memory(surface: &MetalSurface) -> Result<LentMemory, &'static str> {
|
||||
let lend = lend_to_devices(surface)?;
|
||||
let identity = attachment(surface, MemoryLife::new, MemoryLife::identity)
|
||||
.ok_or("a surface the host attached another value to")?;
|
||||
Ok(LentMemory { identity, lend })
|
||||
}
|
||||
|
||||
impl DeviceMemory for LentMemory {
|
||||
fn identity(&self) -> MemoryIdentity {
|
||||
self.identity.clone()
|
||||
}
|
||||
|
||||
fn length(&self) -> usize {
|
||||
usize::try_from(self.lend.length()).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// The surface's own IOSurface, and whether a device may write it, asked again now
|
||||
/// (`DeviceLend::writable`).
|
||||
fn io_surface(&self) -> Result<LentIoSurface<'_>, SurfaceError> {
|
||||
// SAFETY: the lend holds a reference of the IOSurface for as long as it, and so this
|
||||
// borrow, lives.
|
||||
Ok(unsafe { LentIoSurface::new(self.lend.io_surface(), self.lend.writable()) })
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! `VulkanPlatform` as an `ApiPlatform` (`cfg(vulkan_platform)`): the runtime's devices, on macOS
|
||||
//! over MoltenVK, with the `vulkan` feature, and on Linux natively, always.
|
||||
|
||||
use reims_vgpu_core::memory::dirty::DirtyLog;
|
||||
use reims_vgpu_core::num::ToU64 as _;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
@@ -9,11 +8,7 @@ use reims_vgpu_vulkan::os::GuestRamFile;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod lent_memory;
|
||||
|
||||
/// The platform over metal2vulkan's runtime (architecture 2.2): the runtime's devices, and on
|
||||
/// macOS windows whose frames Metal copies from the runtime's (`window::window_sink`).
|
||||
/// The platform over metal2vulkan's runtime (architecture 2.2): the runtime's devices.
|
||||
impl ApiPlatform for VulkanPlatform {
|
||||
fn process() -> Arc<VulkanPlatform> {
|
||||
crate::singleton::vulkan_platform()
|
||||
@@ -59,14 +54,8 @@ impl ApiPlatform for VulkanPlatform {
|
||||
/// (`reims_vgpu_vulkan::os::lease_guest_memory`): on Linux the platform makes its views of the
|
||||
/// guest's pages of them. A range without a file is not registered, and a view of its pages
|
||||
/// is refused as a failed remap is. On macOS nothing is registered, since Mach makes a view
|
||||
/// by remapping addresses. Each range carries its guest physical address, and with the
|
||||
/// device's dirty log the platform finds the guest pages behind an import and the log they
|
||||
/// stamp (`reims_vgpu_vulkan::os::dirty`).
|
||||
fn guest_memory(
|
||||
&self,
|
||||
map: &MemoryMap,
|
||||
dirty: Option<Arc<DirtyLog>>,
|
||||
) -> Box<dyn Any + Send + Sync> {
|
||||
/// by remapping addresses.
|
||||
fn guest_memory(&self, map: &MemoryMap) -> Box<dyn Any + Send + Sync> {
|
||||
let ranges = map.ranges().iter().zip(map.files());
|
||||
let files = ranges.filter_map(|(range, file)| {
|
||||
let file = file.as_ref()?;
|
||||
@@ -78,26 +67,7 @@ impl ApiPlatform for VulkanPlatform {
|
||||
offset: file.offset,
|
||||
})
|
||||
});
|
||||
Box::new(reims_vgpu_vulkan::os::lease_guest_memory(files, dirty))
|
||||
}
|
||||
|
||||
/// Each plane the surface was made with (`reims_vgpu_vulkan::os::plane_layout`): on Linux
|
||||
/// the stand-in's record of its spec, on macOS IOSurface's per-plane getters.
|
||||
fn surface_planes(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
) -> Vec<crate::video::SurfacePlane> {
|
||||
use reims_vgpu_core::platform::os::surface::Surface as _;
|
||||
(0..surface.plane_count())
|
||||
.map_while(|i| reims_vgpu_vulkan::os::plane_layout(surface, i))
|
||||
.map(|p| crate::video::SurfacePlane {
|
||||
offset: p.offset,
|
||||
width: p.width,
|
||||
height: p.height,
|
||||
bytes_per_element: p.bytes_per_element,
|
||||
bytes_per_row: p.bytes_per_row,
|
||||
})
|
||||
.collect()
|
||||
Box::new(reims_vgpu_vulkan::os::lease_guest_memory(files, None))
|
||||
}
|
||||
|
||||
/// Vulkan Video on the device's video-decode queue (`graphics::vulkan::video`).
|
||||
@@ -107,32 +77,4 @@ impl ApiPlatform for VulkanPlatform {
|
||||
) -> Option<Arc<dyn crate::GraphicsVideo<Self>>> {
|
||||
crate::graphics::vulkan_graphics_video(device)
|
||||
}
|
||||
|
||||
fn lend_surface_bytes(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
write: &mut dyn FnMut(&mut [u8]),
|
||||
) -> Result<(), &'static str> {
|
||||
reims_vgpu_vulkan::os::lend_surface_bytes(surface, write)
|
||||
}
|
||||
|
||||
fn lend_surface_bytes_for_reading(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
read: &mut dyn FnMut(&[u8]),
|
||||
) -> Result<(), &'static str> {
|
||||
reims_vgpu_vulkan::os::lend_surface_bytes_for_reading(surface, read)
|
||||
}
|
||||
|
||||
/// On Linux, the bytes `lend_surface_bytes` lends, as a dma-buf of their pages made by
|
||||
/// udmabuf and as the surface's view of them, with an identity attached to the surface
|
||||
/// (`platform/vulkan/lent_memory.rs`). On macOS none: there the Metal platform lends a
|
||||
/// surface's IOSurface to VideoToolbox (`platform/metal/lent_memory.rs`).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn surface_device_memory(
|
||||
&self,
|
||||
surface: &<Self as Platform>::Surface,
|
||||
) -> Result<Box<dyn DeviceMemory>, &'static str> {
|
||||
lent_memory::lent_memory(surface).map(|lent| Box::new(lent) as Box<dyn DeviceMemory>)
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
//! A Linux surface's memory as a video device's decoders lend it to a device
|
||||
//! ([`ApiPlatform::surface_device_memory`](crate::platform::ApiPlatform::surface_device_memory)):
|
||||
//! the Vulkan crate's lend of its bytes (`reims_vgpu_vulkan::os::lend_to_devices`), and an
|
||||
//! identity attached to the surface for as long as it lives (`reims_vgpu_vulkan::os::attachment`).
|
||||
//! The identity goes with the surface's last object, when the guest has unmapped it and nothing
|
||||
//! holds it, and a device's imports of its memory with it (reims-vgpu-video-core's
|
||||
//! `DeviceImports`); the same pages mapped again are another surface, with another identity, so
|
||||
//! no import of the one before is ever written again.
|
||||
//!
|
||||
//! The device writes into the guest's pages while the lend lives, so the lend brackets its bytes
|
||||
//! as one lasting write for the dirty log (`reims_vgpu_core::memory::dirty::host_write`): a GPU
|
||||
//! runtime's copy of them takes them as written while it lives, and by their stamp after.
|
||||
|
||||
use reims_vgpu_core::memory::dirty::{HostWrite, host_write};
|
||||
use reims_vgpu_core::num::ToU64 as _;
|
||||
use reims_vgpu_video_core::device_memory::{
|
||||
DeviceMemory, DmaBufError, HostView, MemoryIdentity, MemoryLife, SurfaceDmaBuf,
|
||||
};
|
||||
use reims_vgpu_video_core::surfaces::SurfaceError;
|
||||
use reims_vgpu_vulkan::os::{DeviceLend, LendRefusal, OsSurface, attachment, lend_to_devices};
|
||||
|
||||
/// A surface's memory lent to a device (module docs).
|
||||
pub(super) struct LentMemory {
|
||||
identity: MemoryIdentity,
|
||||
lend: DeviceLend,
|
||||
/// The dirty log's bracket of the lent bytes (module docs), ended after the lend's drop.
|
||||
_written: HostWrite,
|
||||
}
|
||||
|
||||
/// `surface`'s memory lent to a device; `Err` with why where it is not lent.
|
||||
pub(super) fn lent_memory(surface: &OsSurface) -> Result<LentMemory, &'static str> {
|
||||
let lend = lend_to_devices(surface)?;
|
||||
let identity = attachment(surface, MemoryLife::new, MemoryLife::identity)
|
||||
.ok_or("a surface the host attached another value to")?;
|
||||
let written = host_write(lend.first().as_ptr().addr().to_u64(), lend.length());
|
||||
Ok(LentMemory {
|
||||
identity,
|
||||
lend,
|
||||
_written: written,
|
||||
})
|
||||
}
|
||||
|
||||
impl DeviceMemory for LentMemory {
|
||||
fn identity(&self) -> MemoryIdentity {
|
||||
self.identity.clone()
|
||||
}
|
||||
|
||||
fn length(&self) -> usize {
|
||||
usize::try_from(self.lend.length()).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
fn dma_buf_of(&self, ranges: &[(usize, usize)]) -> Result<SurfaceDmaBuf, DmaBufError> {
|
||||
let ranges: Vec<(u64, u64)> = (ranges.iter())
|
||||
.map(|&(at, bytes)| (at.to_u64(), bytes.to_u64()))
|
||||
.collect();
|
||||
match self.lend.dma_buf_of(&ranges) {
|
||||
Ok(made) => Ok(SurfaceDmaBuf {
|
||||
fd: made.fd,
|
||||
size: made.size,
|
||||
offsets: made.offsets,
|
||||
}),
|
||||
Err(LendRefusal::TooLarge {
|
||||
pieces,
|
||||
bytes,
|
||||
most_pieces,
|
||||
most_bytes,
|
||||
why,
|
||||
}) => Err(DmaBufError::TooLarge {
|
||||
pieces,
|
||||
bytes,
|
||||
most_pieces,
|
||||
most_bytes,
|
||||
why,
|
||||
}),
|
||||
Err(LendRefusal::Refused(why)) => Err(DmaBufError::Refused(why)),
|
||||
}
|
||||
}
|
||||
|
||||
fn host_view(&self) -> Result<HostView, SurfaceError> {
|
||||
let (first, size, offset) = self.lend.pages();
|
||||
let too_large = || SurfaceError::Unreachable("a view past the address space".to_owned());
|
||||
Ok(HostView {
|
||||
first,
|
||||
size: usize::try_from(size).map_err(|_| too_large())?,
|
||||
offset: usize::try_from(offset).map_err(|_| too_large())?,
|
||||
hold: self.lend.hold(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
//! The reference the public device, display, IOSurface host device, frame and frame target types
|
||||
//! hold.
|
||||
//!
|
||||
//! Every public entry point runs inside [`entry::run`] (6.5). A release is
|
||||
//! one too: the last one runs core's whole teardown (the device's stop, the root page cleared, the
|
||||
//! host's `destroyTask`, the display's unplug, the IOSurface queue's `dispatch_sync`) on the
|
||||
//! caller's thread, so [`Ours`] drops its handle inside an entry of its own: marked as ours, so a
|
||||
//! Rust panic in that teardown aborts at its op (D9) instead of unwinding into the host, and with
|
||||
//! what the teardown autoreleases released before the release returns. A drop has no caller's
|
||||
//! hold: the teardown runs under [`Hold::NONE`](reims_vgpu_core::rt::Hold::NONE).
|
||||
|
||||
use std::mem::ManuallyDrop;
|
||||
use std::ops::Deref;
|
||||
|
||||
use crate::entry;
|
||||
|
||||
/// A counted reference (one of core's handles) whose release runs as an entry of its own.
|
||||
pub(crate) struct Ours<T>(ManuallyDrop<T>);
|
||||
|
||||
impl<T> Ours<T> {
|
||||
/// Takes over `handle`'s reference.
|
||||
pub(crate) fn new(handle: T) -> Ours<T> {
|
||||
Ours(ManuallyDrop::new(handle))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Deref for Ours<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for Ours<T> {
|
||||
/// A release; the last one is the object's teardown, run as an entry.
|
||||
fn drop(&mut self) {
|
||||
let handle = &mut self.0;
|
||||
entry::run(|_| {
|
||||
// SAFETY: `handle` is dropped exactly once, here, and never touched again.
|
||||
unsafe { ManuallyDrop::drop(handle) };
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
|
||||
use reims_vgpu_core::rt::{enter_ours, is_our_thread};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Records, when dropped, whether its thread was marked as ours (1) or not (2).
|
||||
struct Probe(Arc<AtomicU8>);
|
||||
|
||||
impl Drop for Probe {
|
||||
fn drop(&mut self) {
|
||||
self.0
|
||||
.store(if is_our_thread() { 1 } else { 2 }, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// The last release runs marked as ours (the teardown of the device, the display and the
|
||||
/// IOSurface host device); an earlier one drops nothing; the mark is restored
|
||||
#[test]
|
||||
fn last_release_is_ours() {
|
||||
let seen = Arc::new(AtomicU8::new(0));
|
||||
let a = Ours::new(Arc::new(Probe(seen.clone())));
|
||||
let b = Ours::new(Arc::clone(&a));
|
||||
assert!(Arc::ptr_eq(&a, &b));
|
||||
drop(a);
|
||||
assert_eq!(seen.load(Ordering::SeqCst), 0);
|
||||
assert!(!is_our_thread());
|
||||
drop(b);
|
||||
assert_eq!(seen.load(Ordering::SeqCst), 1);
|
||||
assert!(!is_our_thread());
|
||||
// Nested inside an entry point, the caller's mark survives.
|
||||
let c = Ours::new(Arc::new(Probe(seen.clone())));
|
||||
let outer = enter_ours();
|
||||
drop(c);
|
||||
assert!(is_our_thread());
|
||||
drop(outer);
|
||||
assert!(!is_our_thread());
|
||||
}
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
//! [`ScalerDevice`]: the host side of the paravirtualized M2 scaler device that a macOS guest's
|
||||
//! AppleM2ScalerParavirtDriver drives (virtio-PCI `106b:1a0b`), made from a
|
||||
//! [`ScalerDeviceConfig`]: reims-vgpu-video-core's scaler device, over this library's IOSurface
|
||||
//! mapper and a backend that transforms on the host's GPU.
|
||||
//!
|
||||
//! The device has no transport of its own. Its host (QEMU's `apple-m2scaler-pci`) owns the one
|
||||
//! virtqueue: it hands each element's readable bytes to [`ScalerDevice::process`], with the size
|
||||
//! of its writable part and the guest's memory, and does what the [`ScalerOutcome`] says: write
|
||||
//! the reply, set DEVICE_NEEDS_RESET, or end the VM, as Apple's host does each.
|
||||
//!
|
||||
//! - **Lifecycle**, as Apple's host runs it: [`ScalerDevice::start`], at the guest's DRIVER_OK,
|
||||
//! makes the backend's accelerator, and [`ScalerDevice::reset`] drops it. A start that cannot
|
||||
//! make one is a needs-reset.
|
||||
//! - **Requests.** Type 1 writes the capabilities into the guest's memory; type 2 transforms one
|
||||
//! guest IOSurface into another, the two named by mapping ID and held for the transform through
|
||||
//! the IOSurface device the config names, as the video device holds its surfaces. The source is
|
||||
//! read through [`ApiPlatform::lend_surface_bytes_for_reading`], the destination written
|
||||
//! through [`ApiPlatform::lend_surface_bytes`].
|
||||
//! - **The backend** is our own kernel on the GPU the library draws with ([`gpu`]): Metal on
|
||||
//! macOS, the Vulkan platform's runtime elsewhere, on the device the library's GPU device runs
|
||||
//! on, the loader's pin included, whichever GPU that is. It computes core's reference transform
|
||||
//! (`reims_vgpu_video_core::scaler::reference`), reading and writing the guest's surfaces in
|
||||
//! place where the host lends their memory to devices.
|
||||
//! - **A host without that GPU** has the device all the same, so that a VM given it always
|
||||
//! starts: [`ScalerDevice::scales`] says false, and the host refuses the guest's features,
|
||||
//! leaving FEATURES_OK unset. That is a host where Metal or the Vulkan runtime finds no device,
|
||||
//! or refuses the kernel. The guest's driver reads back every status bit it sets, so its start
|
||||
//! fails before DRIVER_OK: it writes FAILED and registers no service, and the guest's
|
||||
//! IOSurfaceAccelerator does without it, as in a VM without the device. A guest that went on
|
||||
//! would find the start a needs-reset, as Apple's host answers where it cannot make an
|
||||
//! accelerator, and every request before it a needs-reset.
|
||||
//!
|
||||
//! Every call runs as an entry ([`crate::entry`]).
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::{Arc, Once};
|
||||
|
||||
use reims_vgpu_video_core::runtime::Runtime;
|
||||
use reims_vgpu_video_core::scaler::ScalerDevice as CoreScalerDevice;
|
||||
use reims_vgpu_video_core::scaler::backend::{Accelerator, ScalerBackend};
|
||||
pub use reims_vgpu_video_core::scaler::{GuestMemory, Outcome as ScalerOutcome};
|
||||
use reims_vgpu_video_core::surfaces::Surfaces;
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::entry;
|
||||
use crate::iosurface::IoSurfaceDevice;
|
||||
use crate::platform::ApiPlatform;
|
||||
use crate::video::MapperSurfaces;
|
||||
use crate::video::runtime::PlatformRuntime;
|
||||
|
||||
mod gpu;
|
||||
|
||||
use gpu::{Gpu as _, GpuScalerBackend};
|
||||
|
||||
/// A scaler device's config.
|
||||
pub struct ScalerDeviceConfig<P: ApiPlatform = DefaultPlatform> {
|
||||
/// The IOSurface device whose mapping IDs the guest's transforms name, held unretained;
|
||||
/// `None` is the process's latest at each lookup.
|
||||
pub iosurface_device: Option<IoSurfaceDevice<P>>,
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> Default for ScalerDeviceConfig<P> {
|
||||
fn default() -> Self {
|
||||
ScalerDeviceConfig {
|
||||
iosurface_device: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> fmt::Debug for ScalerDeviceConfig<P> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ScalerDeviceConfig")
|
||||
.field("iosurface_device", &self.iosurface_device)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The host side of one M2 scaler device (module doc).
|
||||
pub struct ScalerDevice<P: ApiPlatform = DefaultPlatform> {
|
||||
device: CoreScalerDevice,
|
||||
/// The guest's surfaces, kept for the mapper's description.
|
||||
surfaces: Arc<MapperSurfaces<P>>,
|
||||
/// Why the host has no GPU for the device; `None` where it has.
|
||||
unscaled: Option<String>,
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> fmt::Debug for ScalerDevice<P> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ScalerDevice")
|
||||
.field("mapper", &self.surfaces.names_its_mapper())
|
||||
.field("unscaled", &self.unscaled)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl ScalerDevice {
|
||||
/// A new scaler device on the process's platform ([`ScalerDevice::with_platform`]).
|
||||
pub fn new(config: ScalerDeviceConfig) -> ScalerDevice {
|
||||
ScalerDevice::with_platform(DefaultPlatform::process(), config)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> ScalerDevice<P> {
|
||||
/// A new scaler device on `platform`, transforming on the host's GPU (module doc), with no
|
||||
/// accelerator until [`Self::start`]. Made on every host: where there is no GPU it is one
|
||||
/// that does not scale ([`Self::scales`]).
|
||||
pub fn with_platform(platform: Arc<P>, config: ScalerDeviceConfig<P>) -> ScalerDevice<P> {
|
||||
let runtime = PlatformRuntime::of(&platform);
|
||||
ScalerDevice::on_host_gpu(platform, &runtime, config)
|
||||
}
|
||||
|
||||
/// [`Self::with_platform`], its transforms' waits for the GPU on `runtime`'s clock: the
|
||||
/// platform's, or, in a test of the host's GPU, std's, since such a wait ends only on a clock
|
||||
/// that runs.
|
||||
pub(crate) fn on_host_gpu(
|
||||
platform: Arc<P>,
|
||||
runtime: &Arc<dyn Runtime>,
|
||||
config: ScalerDeviceConfig<P>,
|
||||
) -> ScalerDevice<P> {
|
||||
entry::run(|_| match gpu_backend(runtime) {
|
||||
Ok(backend) => ScalerDevice::make(platform, config, backend, None),
|
||||
Err(why) => ScalerDevice::unscaled(platform, config, why),
|
||||
})
|
||||
}
|
||||
|
||||
/// A new scaler device on `platform` whose transforms run on `backend`: for a host that
|
||||
/// brings its own, and for the tests.
|
||||
pub fn with_backend(
|
||||
platform: Arc<P>,
|
||||
config: ScalerDeviceConfig<P>,
|
||||
backend: Arc<dyn ScalerBackend>,
|
||||
) -> ScalerDevice<P> {
|
||||
entry::run(|_| ScalerDevice::make(platform, config, backend, None))
|
||||
}
|
||||
|
||||
/// A new scaler device on `platform` with no GPU to transform on, `why` in words: one that
|
||||
/// does not scale ([`Self::scales`]), for a host that has none, and for the tests.
|
||||
pub fn without_gpu(
|
||||
platform: Arc<P>,
|
||||
config: ScalerDeviceConfig<P>,
|
||||
why: String,
|
||||
) -> ScalerDevice<P> {
|
||||
entry::run(|_| ScalerDevice::unscaled(platform, config, why))
|
||||
}
|
||||
|
||||
/// Whether the device transforms: false where the host has no GPU for it, and the host
|
||||
/// refuses the guest's features (module doc).
|
||||
pub fn scales(&self) -> bool {
|
||||
self.unscaled.is_none()
|
||||
}
|
||||
|
||||
fn unscaled(platform: Arc<P>, config: ScalerDeviceConfig<P>, why: String) -> ScalerDevice<P> {
|
||||
log::info!(
|
||||
"scaler device: {why}: it refuses the guest's features, so the guest's driver does \
|
||||
without it"
|
||||
);
|
||||
let backend = Arc::new(NoGpu(why.clone()));
|
||||
ScalerDevice::make(platform, config, backend, Some(why))
|
||||
}
|
||||
|
||||
fn make(
|
||||
platform: Arc<P>,
|
||||
config: ScalerDeviceConfig<P>,
|
||||
backend: Arc<dyn ScalerBackend>,
|
||||
unscaled: Option<String>,
|
||||
) -> ScalerDevice<P> {
|
||||
let surfaces = Arc::new(MapperSurfaces::new(
|
||||
"scaler device",
|
||||
platform,
|
||||
config.iosurface_device.as_ref(),
|
||||
));
|
||||
ScalerDevice {
|
||||
device: CoreScalerDevice::new(Arc::clone(&surfaces) as Arc<dyn Surfaces>, backend),
|
||||
surfaces,
|
||||
unscaled,
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's DRIVER_OK: a new accelerator, replacing the one there was. `Err` with
|
||||
/// Apple's reason where the backend cannot make one: the host sets DEVICE_NEEDS_RESET.
|
||||
pub fn start(&self) -> Result<(), &'static str> {
|
||||
entry::run(|_| {
|
||||
let started = self.device.start();
|
||||
match started {
|
||||
Ok(()) => log::info!("scaler device started"),
|
||||
Err(why) => log::warn!("scaler device did not start: {why}"),
|
||||
}
|
||||
started
|
||||
})
|
||||
}
|
||||
|
||||
/// One element of the queue: `request` its readable bytes, `writable` the size of its
|
||||
/// writable part, `memory` the guest's, through which type 1 writes the capabilities and
|
||||
/// type 2 gathers and scatters its side buffers. What the host does with the element
|
||||
/// ([`ScalerOutcome`]). May block on the IOSurface device's thread and on the GPU.
|
||||
pub fn process(
|
||||
&self,
|
||||
request: &[u8],
|
||||
writable: usize,
|
||||
memory: &dyn GuestMemory,
|
||||
) -> ScalerOutcome {
|
||||
entry::run(|_| {
|
||||
let outcome = self.device.process(request, writable, memory);
|
||||
let word = |bytes: &[u8], at: usize| {
|
||||
bytes.get(at..at + 4).map_or_else(
|
||||
|| "none".to_owned(),
|
||||
|b| format!("{:#x}", u32::from_le_bytes([b[0], b[1], b[2], b[3]])),
|
||||
)
|
||||
};
|
||||
let (kind, n) = (word(request, 0), request.len());
|
||||
match &outcome {
|
||||
ScalerOutcome::Reply(reply) => log::debug!(
|
||||
"scaler request type {kind}, {n} bytes: status {}",
|
||||
word(reply, 4)
|
||||
),
|
||||
ScalerOutcome::NeedsReset(why) => {
|
||||
log::warn!("scaler request type {kind}, {n} bytes: needs reset: {why}");
|
||||
}
|
||||
ScalerOutcome::EndVm(why) => {
|
||||
log::error!("scaler request type {kind}, {n} bytes: ends the VM: {why}");
|
||||
}
|
||||
}
|
||||
outcome
|
||||
})
|
||||
}
|
||||
|
||||
/// A reset or a stop: the accelerator goes.
|
||||
pub fn reset(&self) {
|
||||
entry::run(|_| {
|
||||
self.device.reset();
|
||||
log::info!("scaler device reset");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend on the process's GPU, opened at its first use: Metal on macOS, the Vulkan
|
||||
/// platform's runtime elsewhere. `Err` with why where there is none, or it refuses the kernel.
|
||||
/// The first open of a process starts the making of the kernels' pipelines ahead of the guest's
|
||||
/// first transform, on a thread of `runtime`'s, which nothing waits for ([`gpu::make_ahead`]).
|
||||
fn gpu_backend(runtime: &Arc<dyn Runtime>) -> Result<Arc<dyn ScalerBackend>, String> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let gpu = gpu::metal::MetalGpu::process()?;
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let gpu = gpu::vulkan::VulkanGpu::process(runtime)?;
|
||||
log::info!("scaler device: transforms on {}", gpu.name());
|
||||
static AHEAD: Once = Once::new();
|
||||
AHEAD.call_once(|| {
|
||||
if let Err(why) = gpu::make_ahead(&gpu, runtime) {
|
||||
log::warn!("scaler: {why}: each kernel is made at its first transform");
|
||||
}
|
||||
});
|
||||
Ok(Arc::new(GpuScalerBackend::new(gpu, Arc::clone(runtime))))
|
||||
}
|
||||
|
||||
/// The backend of a device without a GPU: it makes no accelerator, so its start is a
|
||||
/// needs-reset, as Apple's host answers where it cannot make one.
|
||||
struct NoGpu(String);
|
||||
|
||||
impl ScalerBackend for NoGpu {
|
||||
fn create_accelerator(&self) -> Result<Box<dyn Accelerator>, String> {
|
||||
Err(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,805 +0,0 @@
|
||||
//! The scaler device's backend: core's transform (`reims_vgpu_video_core::scaler::reference`)
|
||||
//! as kernels of our own, `scaler.metal`, on the GPU the library draws with: Metal on macOS
|
||||
//! (`gpu/metal.rs`), the Vulkan platform's runtime elsewhere (`gpu/vulkan.rs`), whichever GPU that
|
||||
//! is, a software rasterizer's included. Nothing chooses it: every host has it where it has that
|
||||
//! GPU.
|
||||
//!
|
||||
//! - **What the kernels compute.** The CPU works out from a transform's plan where each
|
||||
//! destination pixel samples and with what weights, the reference's own taps, and every number
|
||||
//! a format, a matrix or a window gives ([`params`]); the kernels apply them, a dispatch a plane
|
||||
//! of the destination, each thread one 32-bit word of it, after a dispatch that sums a reduction
|
||||
//! down into lines where the transform is separable (`scaler.metal`'s header). So the output is
|
||||
//! the reference's but for float rounding: the kernels compute in 32-bit floats, the reference
|
||||
//! in 64-bit doubles, each sum in the reference's order.
|
||||
//! - **Guest memory in place.** A surface whose memory the host lends a device
|
||||
//! ([`DeviceMemory`]) is bound where it is: its own IOSurface on macOS, the host's view of its
|
||||
//! pages on Linux, imported once a mapping and kept until the mapping goes. A destination is
|
||||
//! bound so only where its planes start on 4-byte boundaries and their rows are a multiple of 4
|
||||
//! bytes, the host lends it for writing (never a surface the guest made read-only for its
|
||||
//! clients), and it is not the source's own memory. Anything else is **staged**: the source
|
||||
//! copied in its lend into a buffer of the GPU's own, the destination written there and copied
|
||||
//! back in its lend, the bytes the reference writes alone ([`covered`]). A destination written
|
||||
//! in place is told so once the GPU is done with it
|
||||
//! ([`reims_vgpu_video_core::surfaces::GuestSurface::device_wrote`]), as a lend is a write of
|
||||
//! its own.
|
||||
//! - **Statuses**, in [`TransformJob::with_bytes`]'s order: a source that cannot be read, a
|
||||
//! destination that cannot be written, a surface too small for its layout
|
||||
//! (kIOReturnBadArgument), then the transform's own: kIOReturnUnsupported for a side outside
|
||||
//! the capabilities' or an offset past the kernel's 4 GiB, kIOReturnError where the GPU fails or
|
||||
//! is not done by its deadline.
|
||||
//! - **A bounded wait.** The GPU is waited for until core's deadline ([`device_wait`]); work not
|
||||
//! done by then is kept with everything it may still write and the device's hold on both
|
||||
//! surfaces ([`Lingering`]), and the accelerator answers kIOReturnError to every transform after
|
||||
//! it, until the guest resets the device. A destination written in place is told written at the
|
||||
//! deadline, as far as the GPU ran, and again once the kept work is done and lets the hold go
|
||||
//! (core's `GuestHold::report_late_write`).
|
||||
//! - **Made ahead.** A Vulkan driver makes a kernel's pipeline at its first dispatch of each
|
||||
//! threadgroup size, not where the runtime makes its pipeline state, and with the shader caches
|
||||
//! cold the making of the costliest took 2.5 s on MoltenVK on the M3 Max and 1.5 s on an RTX
|
||||
//! 5080 Laptop GPU (2026-10-26), within the 5 s a transform is given. So once a process,
|
||||
//! when the first scaler device opens, a thread of the runtime's dispatches each kernel at each
|
||||
//! threadgroup size the transforms dispatch it at ([`make_ahead`], [`params::DISPATCHED`]), one
|
||||
//! after another, with parameters of zeros, so that every thread returns at its bounds check, on
|
||||
//! a queue apart from the transforms' ([`Gpu::submit_apart`]), binding only a buffer of its own.
|
||||
//! Nothing waits for it: neither the device's opening nor a transform, which takes a pipeline
|
||||
//! made or in the making as it stands, and makes its own where the making ahead has not reached
|
||||
//! it. And it gives way to the transforms: it starts no making while one runs, so that the
|
||||
//! driver's making of what a transform waits for shares the CPU with no more than the one it
|
||||
//! has in hand. The guest sees nothing of it (docs/video/scaler.md, "Made ahead").
|
||||
//! - **Speed.** A source pixel is decoded once a line of a reduction, not once a destination pixel
|
||||
//! ([`params`]). Two facts the kernels' shapes rest on, of an RTX 5080 Laptop GPU (driver
|
||||
//! 615.71.09) through the Vulkan platform, 2026-10-25:
|
||||
//! - it writes guest memory where the host lends it, in host-cached system memory, across the
|
||||
//! bus, and stores with gaps between them crawl there (**measured**): a 4K 420v copy into
|
||||
//! BGRA in place took 320 ms with each thread writing its own two by two pixels, so that each
|
||||
//! store's words lay 8 bytes apart, about 0.1 GB/s, and 2.8 ms with a threadgroup's words
|
||||
//! written side by side, as `scaler_quads` writes them;
|
||||
//! - a buffer of the GPU's own in the default CPU cache mode lies in that memory too, and a
|
||||
//! write-combined one in the GPU's (**read** in the runtime's notice of it,
|
||||
//! `metal2vulkan-degrade-shared-in-system-memory`), so the taps, which every thread reads,
|
||||
//! are in a write-combined one ([`Gpu::table`]), and the lines in a private one
|
||||
//! ([`Gpu::scratch`]).
|
||||
//!
|
||||
//! Each host's GPU against its native scaler is docs/video/scaler.md, "Speed".
|
||||
//!
|
||||
//! [`device_wait`]: reims_vgpu_video_core::device_wait
|
||||
|
||||
mod params;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) mod metal;
|
||||
#[cfg(vulkan_platform)]
|
||||
#[cfg_attr(
|
||||
target_os = "macos",
|
||||
allow(
|
||||
dead_code,
|
||||
reason = "Linux's; on macOS only the tests run it, on MoltenVK"
|
||||
)
|
||||
)]
|
||||
pub(crate) mod vulkan;
|
||||
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_core::num::ToUsize as _;
|
||||
use reims_vgpu_video_core::device_memory::DeviceMemory;
|
||||
use reims_vgpu_video_core::device_wait::{self, GuestHold, Lingering, Unfinished};
|
||||
use reims_vgpu_video_core::runtime::{self, Answer, Bell, Runtime};
|
||||
use reims_vgpu_video_core::scaler::backend::{Accelerator, ScalerBackend, TransformJob};
|
||||
use reims_vgpu_video_core::scaler::capabilities::{Capabilities, FormatClass};
|
||||
use reims_vgpu_video_core::scaler::coverage::{Window, covered};
|
||||
use reims_vgpu_video_core::scaler::format::PlaneSpan;
|
||||
use reims_vgpu_video_core::scaler::io_return::{self, IoReturn};
|
||||
use reims_vgpu_video_core::scaler::plan::{FormatOf, Plan};
|
||||
use reims_vgpu_video_core::surfaces::SurfaceError;
|
||||
|
||||
pub(crate) use params::Kernel;
|
||||
use params::{BoundPlane, TooLarge};
|
||||
|
||||
/// The smallest side of a surface the scaler takes, either way: Apple's scaler's on the M3 Max
|
||||
/// (docs/video/devices.md, "The capabilities").
|
||||
pub(crate) const SMALLEST_SIDE: u32 = 4;
|
||||
|
||||
/// The largest: Apple's scaler's.
|
||||
pub(crate) const LARGEST_SIDE: u32 = 65536;
|
||||
|
||||
/// The largest ratios, `MaxHUpscale`, `MaxHDownscale`, `MaxVUpscale` and `MaxVDownscale`:
|
||||
/// Apple's scaler's.
|
||||
pub(crate) const MAX_SCALE: [u32; 4] = [8, 8, 8, 4];
|
||||
|
||||
/// What the backend asks of a GPU: buffers, the kernels' dispatches, and when they are done.
|
||||
pub(crate) trait Gpu: Send + Sync + 'static {
|
||||
/// A buffer the kernels bind.
|
||||
type Buffer: Send + Sync + 'static;
|
||||
/// A submission of dispatches.
|
||||
type Run: Send + 'static;
|
||||
|
||||
/// The GPU's name, for the log.
|
||||
fn name(&self) -> &str;
|
||||
|
||||
/// A buffer of `length` bytes of the GPU's own memory, zeroed, which the CPU reaches.
|
||||
fn shared(&self, length: usize) -> Result<Self::Buffer, String>;
|
||||
|
||||
/// A buffer of the GPU's own memory holding `bytes`, which the CPU writes once and never
|
||||
/// reads: the taps.
|
||||
fn table(&self, bytes: &[u8]) -> Result<Self::Buffer, String>;
|
||||
|
||||
/// A buffer of `length` bytes of the GPU's own memory, which only the GPU reaches: the lines.
|
||||
fn scratch(&self, length: usize) -> Result<Self::Buffer, String>;
|
||||
|
||||
/// `buffer`'s bytes as the CPU reaches them: a buffer [`Gpu::shared`] made's.
|
||||
fn contents(buffer: &mut Self::Buffer) -> Option<&mut [u8]>;
|
||||
|
||||
/// A buffer over `memory`, and where the surface's first byte lies in it; `Ok(None)` where
|
||||
/// this GPU reaches none of it, or none it may write where `writes` says it will.
|
||||
fn memory(
|
||||
&self,
|
||||
memory: &dyn DeviceMemory,
|
||||
writes: bool,
|
||||
) -> Result<Option<(Self::Buffer, usize)>, String>;
|
||||
|
||||
/// Encodes `dispatches` in one submission, in order, and submits it; `done` runs once the GPU
|
||||
/// is done with it, on a thread of the GPU's.
|
||||
fn submit(
|
||||
&self,
|
||||
dispatches: &[Dispatch<'_, Self::Buffer>],
|
||||
done: Box<dyn FnOnce() + Send>,
|
||||
) -> Result<Self::Run, String>;
|
||||
|
||||
/// [`Gpu::submit`], on a queue apart from the transforms', after whose work nothing of
|
||||
/// theirs waits: the making ahead's ([`make_ahead`]).
|
||||
fn submit_apart(
|
||||
&self,
|
||||
dispatches: &[Dispatch<'_, Self::Buffer>],
|
||||
done: Box<dyn FnOnce() + Send>,
|
||||
) -> Result<Self::Run, String>;
|
||||
|
||||
/// `None` while the GPU runs `run`; then `Ok`, or why it failed.
|
||||
fn finished(run: &Self::Run) -> Option<Result<(), String>>;
|
||||
|
||||
/// How long the GPU took for `run`, once it is done, where the GPU says.
|
||||
fn gpu_time(run: &Self::Run) -> Option<Duration>;
|
||||
}
|
||||
|
||||
/// How long the GPU took for each transform the process ran, where it said, which the tests'
|
||||
/// benches read.
|
||||
#[cfg(test)]
|
||||
static GPU_TIMES: reims_vgpu_core::sync::Mutex<Vec<Duration>> =
|
||||
reims_vgpu_core::sync::Mutex::new(Vec::new());
|
||||
|
||||
/// One dispatch of the kernel: its kernel, buffers, parameters and threads.
|
||||
pub(crate) struct Dispatch<'a, B> {
|
||||
pub(crate) kernel: Kernel,
|
||||
pub(crate) source: &'a B,
|
||||
pub(crate) destination: &'a B,
|
||||
pub(crate) taps: &'a B,
|
||||
pub(crate) params: &'a [u8],
|
||||
pub(crate) lines: &'a B,
|
||||
pub(crate) threads: (u32, u32),
|
||||
pub(crate) group: (u32, u32),
|
||||
}
|
||||
|
||||
/// The backend: an accelerator a DRIVER_OK, each on the one GPU.
|
||||
pub(crate) struct GpuScalerBackend<G: Gpu> {
|
||||
gpu: Arc<G>,
|
||||
runtime: Arc<dyn Runtime>,
|
||||
smallest: u32,
|
||||
}
|
||||
|
||||
impl<G: Gpu> GpuScalerBackend<G> {
|
||||
/// The backend on `gpu`, waiting on `runtime`'s clock.
|
||||
pub(crate) fn new(gpu: Arc<G>, runtime: Arc<dyn Runtime>) -> Self {
|
||||
Self {
|
||||
gpu,
|
||||
runtime,
|
||||
smallest: SMALLEST_SIDE,
|
||||
}
|
||||
}
|
||||
|
||||
/// The same, taking sides from `smallest`: for the tests, which run pictures under Apple's
|
||||
/// smallest against the reference too.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn with_smallest_side(mut self, smallest: u32) -> Self {
|
||||
self.smallest = smallest;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<G: Gpu> ScalerBackend for GpuScalerBackend<G> {
|
||||
fn create_accelerator(&self) -> Result<Box<dyn Accelerator>, String> {
|
||||
Ok(Box::new(GpuAccelerator {
|
||||
gpu: Arc::clone(&self.gpu),
|
||||
runtime: Arc::clone(&self.runtime),
|
||||
smallest: self.smallest,
|
||||
stuck: false,
|
||||
lines: None,
|
||||
prepared: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/// The capabilities: the four classes of [`ScalerFormat`], each both ways, Apple's sides from
|
||||
/// `smallest`, and Apple's ratios.
|
||||
///
|
||||
/// [`ScalerFormat`]: reims_vgpu_video_core::scaler::format::ScalerFormat
|
||||
fn capabilities(smallest: u32) -> Capabilities {
|
||||
Capabilities {
|
||||
// No hardware revision of Apple's describes this scaler, and nothing reads it: 0, ours.
|
||||
scaler_version: 0,
|
||||
formats: vec![
|
||||
FormatClass::TwoPlanes420,
|
||||
FormatClass::Argb8888,
|
||||
FormatClass::Interleaved422,
|
||||
FormatClass::TwoPlanes42010,
|
||||
],
|
||||
min_source: smallest,
|
||||
max_source: (LARGEST_SIDE, LARGEST_SIDE),
|
||||
min_destination: smallest,
|
||||
max_destination: (LARGEST_SIDE, LARGEST_SIDE),
|
||||
max_scale: MAX_SCALE,
|
||||
// Windows go anywhere in a surface.
|
||||
xy_offsets_with_tiling: (true, true),
|
||||
}
|
||||
}
|
||||
|
||||
/// One accelerator: the device's from DRIVER_OK to its reset.
|
||||
struct GpuAccelerator<G: Gpu> {
|
||||
gpu: Arc<G>,
|
||||
runtime: Arc<dyn Runtime>,
|
||||
smallest: u32,
|
||||
/// Whether a transform's work was not done by its deadline: every later one fails.
|
||||
stuck: bool,
|
||||
/// The lines buffer of the separable transforms, and its bytes: made at the first that needs
|
||||
/// it, and again larger where one needs more.
|
||||
lines: Option<(G::Buffer, usize)>,
|
||||
/// The last transform's work, which the next takes where its plan and planes are the same.
|
||||
prepared: Option<Prepared<G>>,
|
||||
}
|
||||
|
||||
/// One dispatch of a transform: its kernel, its parameters' bytes, its threads and its
|
||||
/// threadgroup's, across and down.
|
||||
type Pass = (Kernel, Vec<u8>, (u32, u32), (u32, u32));
|
||||
|
||||
/// A transform's work, ready to dispatch: what it is for, each pass's kernel, parameters' bytes
|
||||
/// and threads, and the taps in a buffer of the GPU's.
|
||||
struct Prepared<G: Gpu> {
|
||||
plan: Plan,
|
||||
source: Vec<BoundPlane>,
|
||||
destination: Vec<BoundPlane>,
|
||||
passes: Vec<Pass>,
|
||||
taps: G::Buffer,
|
||||
}
|
||||
|
||||
/// How long a wait for the GPU goes before it asks whether the GPU is done, where nothing rang:
|
||||
/// a backstop to the GPU's ring.
|
||||
const ASK_AGAIN: Duration = Duration::from_millis(2);
|
||||
|
||||
/// How long the making ahead waits for one kernel's dispatch, its pipeline's making included,
|
||||
/// before it leaves the rest to their first transforms: many times the 2.5 s the costliest took
|
||||
/// (module docs).
|
||||
const AHEAD_WAIT: Duration = Duration::from_secs(60);
|
||||
|
||||
/// The making ahead's thread.
|
||||
const AHEAD_THREAD_NAME: &str = "reims-vgpu-video.scaler-ahead";
|
||||
|
||||
/// The transforms running in the process, which the making ahead gives way to, and the bell their
|
||||
/// ends ring.
|
||||
static RUNNING: AtomicUsize = AtomicUsize::new(0);
|
||||
static RUNNING_ENDED: LazyLock<Bell> = LazyLock::new(Bell::new);
|
||||
|
||||
/// One transform running, counted in [`RUNNING`] while it lives.
|
||||
struct Running;
|
||||
|
||||
impl Running {
|
||||
fn start() -> Running {
|
||||
RUNNING.fetch_add(1, Ordering::AcqRel);
|
||||
Running
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Running {
|
||||
fn drop(&mut self) {
|
||||
if RUNNING.fetch_sub(1, Ordering::AcqRel) == 1 {
|
||||
RUNNING_ENDED.ring();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Makes each kernel's pipeline ahead of a guest's first transform, on a thread of `runtime`'s
|
||||
/// (module docs, "Made ahead"): a dispatch of each of [`params::DISPATCHED`] in turn, each of one
|
||||
/// threadgroup, on the queue apart, its buffers all one buffer of the making's own, made here, and
|
||||
/// its parameters zeros, so that no thread reads or writes a buffer. Each waits until no transform
|
||||
/// runs ([`RUNNING`]), or for [`AHEAD_WAIT`] at most. The answer is given once the
|
||||
/// last is done, or the making stopped: where the GPU refused or failed a dispatch, or did not
|
||||
/// finish one within [`AHEAD_WAIT`], the kernels after it are made at their first transforms, as
|
||||
/// they would be without it. `Err` with why where it could not start.
|
||||
pub(crate) fn make_ahead<G: Gpu>(
|
||||
gpu: &Arc<G>,
|
||||
runtime: &Arc<dyn Runtime>,
|
||||
) -> Result<Answer<()>, String> {
|
||||
let buffer = gpu.scratch(16)?;
|
||||
let (answerer, answer) = runtime::answer();
|
||||
let (gpu, clock) = (Arc::clone(gpu), Arc::clone(runtime));
|
||||
let body = move || {
|
||||
let params = params::Params::default().bytes();
|
||||
let started = clock.now();
|
||||
for (kernel, group) in params::DISPATCHED {
|
||||
let dispatch = Dispatch {
|
||||
kernel,
|
||||
source: &buffer,
|
||||
destination: &buffer,
|
||||
taps: &buffer,
|
||||
params: ¶ms,
|
||||
lines: &buffer,
|
||||
threads: group,
|
||||
group,
|
||||
};
|
||||
// Way given to the transforms running, for as long as a making may take.
|
||||
let way = clock.deadline_in(AHEAD_WAIT);
|
||||
let _ = RUNNING_ENDED.wait_until(&*clock, way, || {
|
||||
(RUNNING.load(Ordering::Acquire) == 0).then_some(())
|
||||
});
|
||||
let bell = Arc::new(Bell::new());
|
||||
let ring = Arc::clone(&bell);
|
||||
let one = clock.now();
|
||||
let run = match gpu.submit_apart(&[dispatch], Box::new(move || ring.ring())) {
|
||||
Ok(run) => run,
|
||||
Err(why) => {
|
||||
log::warn!(
|
||||
"scaler: {} refused a kernel's making ahead: {why}",
|
||||
gpu.name()
|
||||
);
|
||||
break;
|
||||
}
|
||||
};
|
||||
let deadline = clock.deadline_in(AHEAD_WAIT);
|
||||
match bell.wait_until(&*clock, deadline, || G::finished(&run)) {
|
||||
Some(Ok(())) => log::debug!(
|
||||
"scaler: {kernel:?} at {group:?} made ahead in {:.1} ms, {:.0} ms after the \
|
||||
making ahead started",
|
||||
clock.elapsed_since(one).as_secs_f64() * 1000.0,
|
||||
clock.elapsed_since(started).as_secs_f64() * 1000.0
|
||||
),
|
||||
Some(Err(why)) => {
|
||||
log::warn!("scaler: the making ahead of {kernel:?} failed: {why}");
|
||||
break;
|
||||
}
|
||||
None => {
|
||||
// The run's command buffer holds the buffer until the GPU is done with it.
|
||||
log::warn!(
|
||||
"scaler: the making ahead of {kernel:?} did not end within {} s: the \
|
||||
kernels left are made at their first transforms",
|
||||
AHEAD_WAIT.as_secs()
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
log::info!(
|
||||
"scaler device: kernels made ahead in {:.0} ms",
|
||||
clock.elapsed_since(started).as_secs_f64() * 1000.0
|
||||
);
|
||||
answerer.give(());
|
||||
};
|
||||
runtime
|
||||
.spawn(AHEAD_THREAD_NAME, Box::new(body))
|
||||
.map_err(|e| format!("no thread makes the kernels ahead: {e}"))?;
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
/// A surface as the kernel reaches it: a buffer, its planes in it, and whether it is staged.
|
||||
struct Bound<B> {
|
||||
buffer: B,
|
||||
planes: Vec<BoundPlane>,
|
||||
staged: bool,
|
||||
}
|
||||
|
||||
/// Work the GPU did not finish by its deadline, with everything it may still read or write,
|
||||
/// kept until it is done: the buffers go before the hold on the surfaces, as a buffer over a
|
||||
/// surface's IOSurface retains it.
|
||||
struct Kept<G: Gpu> {
|
||||
run: G::Run,
|
||||
_buffers: Vec<G::Buffer>,
|
||||
_hold: GuestHold,
|
||||
}
|
||||
|
||||
impl<G: Gpu> Unfinished for Kept<G> {
|
||||
fn finished(&mut self) -> bool {
|
||||
G::finished(&self.run).is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// `planes` at `base`, as the kernel reaches them; `None` past the address space.
|
||||
fn at_base(planes: &[PlaneSpan], base: usize) -> Option<Vec<BoundPlane>> {
|
||||
planes.iter().map(|p| BoundPlane::at(p, base)).collect()
|
||||
}
|
||||
|
||||
/// The bytes the planes of `of` span from its first byte, as a lend must hold them.
|
||||
fn extent(of: &FormatOf) -> Option<usize> {
|
||||
of.planes
|
||||
.iter()
|
||||
.map(|p| p.extent()?.checked_add(p.offset))
|
||||
.try_fold(0usize, |most, end| Some(most.max(end?)))
|
||||
}
|
||||
|
||||
/// The planes a staged destination of `of` is written in: each from a 4-byte boundary, its rows
|
||||
/// a multiple of 4 bytes, one after another; and the bytes they take.
|
||||
fn staged_planes(of: &FormatOf) -> Option<(Vec<BoundPlane>, usize)> {
|
||||
let mut at = 0usize;
|
||||
let mut planes = Vec::with_capacity(of.planes.len());
|
||||
for span in &of.planes {
|
||||
let pitch = span.row_bytes.checked_next_multiple_of(4)?;
|
||||
planes.push(BoundPlane {
|
||||
offset: at,
|
||||
pitch,
|
||||
row_bytes: span.row_bytes,
|
||||
rows: span.rows,
|
||||
});
|
||||
at = at.checked_add(pitch.checked_mul(span.rows)?)?;
|
||||
}
|
||||
Some((planes, at))
|
||||
}
|
||||
|
||||
impl<G: Gpu> GpuAccelerator<G> {
|
||||
/// The source, bound where it is, or staged: copied in its lend.
|
||||
fn source(&self, job: &TransformJob<'_>) -> Result<Bound<G::Buffer>, IoReturn> {
|
||||
let src = &job.plan.source_format;
|
||||
if let Some(memory) = job.source.device_memory() {
|
||||
match self.gpu.memory(memory, false) {
|
||||
Ok(Some((buffer, base))) => {
|
||||
if !src.fits(memory.length()) {
|
||||
return Err(io_return::BAD_ARGUMENT);
|
||||
}
|
||||
let planes = at_base(&src.planes, base).ok_or(io_return::UNSUPPORTED)?;
|
||||
return Ok(Bound {
|
||||
buffer,
|
||||
planes,
|
||||
staged: false,
|
||||
});
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(why) => log::debug!("scaler: the source is staged: {why}"),
|
||||
}
|
||||
}
|
||||
let length = extent(src).ok_or(io_return::UNSUPPORTED)?;
|
||||
let mut buffer = self.gpu.shared(length).map_err(|why| {
|
||||
log::warn!("scaler: no staging buffer of {length} bytes: {why}");
|
||||
io_return::NO_MEMORY
|
||||
})?;
|
||||
let staging = G::contents(&mut buffer).ok_or(io_return::ERROR)?;
|
||||
let mut fits = false;
|
||||
let read = job.source.read(&mut |bytes| {
|
||||
fits = src.fits(bytes.len());
|
||||
if let (true, Some(to), Some(from)) =
|
||||
(fits, staging.get_mut(..length), bytes.get(..length))
|
||||
{
|
||||
to.copy_from_slice(from);
|
||||
}
|
||||
});
|
||||
if let Err(error) = read {
|
||||
log::warn!("scaler: the source surface cannot be read: {error}");
|
||||
return Err(io_return::NOT_READABLE);
|
||||
}
|
||||
if !fits {
|
||||
return Err(io_return::BAD_ARGUMENT);
|
||||
}
|
||||
Ok(Bound {
|
||||
buffer,
|
||||
planes: at_base(&src.planes, 0).ok_or(io_return::UNSUPPORTED)?,
|
||||
staged: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// The destination, bound where it is, or staged: written in a buffer of the GPU's own and
|
||||
/// copied back in its lend.
|
||||
fn destination(
|
||||
&self,
|
||||
job: &TransformJob<'_>,
|
||||
source_in_place: bool,
|
||||
) -> Result<Bound<G::Buffer>, IoReturn> {
|
||||
let dst = &job.plan.destination_format;
|
||||
let same = |memory: &dyn DeviceMemory| {
|
||||
source_in_place
|
||||
&& job
|
||||
.source
|
||||
.device_memory()
|
||||
.is_some_and(|source| source.identity().key() == memory.identity().key())
|
||||
};
|
||||
if let Some(memory) = job.destination.device_memory().filter(|m| !same(*m)) {
|
||||
match self.gpu.memory(memory, true) {
|
||||
Ok(Some((buffer, base))) => {
|
||||
if !dst.fits(memory.length()) {
|
||||
return Err(io_return::BAD_ARGUMENT);
|
||||
}
|
||||
let planes = at_base(&dst.planes, base).ok_or(io_return::UNSUPPORTED)?;
|
||||
if planes.iter().all(BoundPlane::word_aligned) {
|
||||
return Ok(Bound {
|
||||
buffer,
|
||||
planes,
|
||||
staged: false,
|
||||
});
|
||||
}
|
||||
log::debug!("scaler: the destination's planes are not word-aligned: staged");
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(why) => log::debug!("scaler: the destination is staged: {why}"),
|
||||
}
|
||||
}
|
||||
let (planes, length) = staged_planes(dst).ok_or(io_return::UNSUPPORTED)?;
|
||||
let buffer = self.gpu.shared(length).map_err(|why| {
|
||||
log::warn!("scaler: no staging buffer of {length} bytes: {why}");
|
||||
io_return::NO_MEMORY
|
||||
})?;
|
||||
Ok(Bound {
|
||||
buffer,
|
||||
planes,
|
||||
staged: true,
|
||||
})
|
||||
}
|
||||
|
||||
/// The transform's work for `plan` with its surfaces' planes bound as they are, from the last
|
||||
/// transform's where they are the same, as a guest's frames of one stream are: its passes'
|
||||
/// parameters, and its taps in a buffer of the GPU's.
|
||||
fn prepare(
|
||||
&mut self,
|
||||
plan: &Plan,
|
||||
source: &[BoundPlane],
|
||||
destination: &[BoundPlane],
|
||||
) -> Result<(), IoReturn> {
|
||||
let same = self
|
||||
.prepared
|
||||
.as_ref()
|
||||
.is_some_and(|p| p.plan == *plan && p.source == source && p.destination == destination);
|
||||
if same {
|
||||
return Ok(());
|
||||
}
|
||||
self.prepared = None;
|
||||
let work = match params::work(plan, source, destination) {
|
||||
Ok(work) => work,
|
||||
Err(TooLarge) => {
|
||||
log::warn!("scaler: refused, as a surface lies past the kernel's 4 GiB");
|
||||
return Err(io_return::UNSUPPORTED);
|
||||
}
|
||||
};
|
||||
let table: Vec<u8> = params::taps_bytes(&work.taps).collect();
|
||||
let taps = self.gpu.table(&table).map_err(|why| {
|
||||
log::warn!("scaler: no buffer of {} bytes of taps: {why}", table.len());
|
||||
io_return::NO_MEMORY
|
||||
})?;
|
||||
if work.lines > self.lines.as_ref().map_or(0, |(_, bytes)| *bytes) {
|
||||
self.lines = None;
|
||||
let buffer = self.gpu.scratch(work.lines).map_err(|why| {
|
||||
log::warn!("scaler: no buffer of {} bytes of lines: {why}", work.lines);
|
||||
io_return::NO_MEMORY
|
||||
})?;
|
||||
self.lines = Some((buffer, work.lines));
|
||||
}
|
||||
self.prepared = Some(Prepared {
|
||||
plan: plan.clone(),
|
||||
source: source.to_vec(),
|
||||
destination: destination.to_vec(),
|
||||
passes: (work.passes.iter())
|
||||
.map(|(kernel, p, threads, group)| (*kernel, p.bytes(), *threads, *group))
|
||||
.collect(),
|
||||
taps,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Runs the kernel from `source` into `destination` and waits for it; `Err` with the
|
||||
/// transform's status where it fails. Past the deadline, what the GPU may still use is kept.
|
||||
fn run(
|
||||
&mut self,
|
||||
job: &TransformJob<'_>,
|
||||
source: Bound<G::Buffer>,
|
||||
destination: Bound<G::Buffer>,
|
||||
) -> Result<Bound<G::Buffer>, IoReturn> {
|
||||
let _running = Running::start();
|
||||
self.prepare(&job.plan, &source.planes, &destination.planes)?;
|
||||
let prepared = self.prepared.as_ref().ok_or(io_return::ERROR)?;
|
||||
let lines = self
|
||||
.lines
|
||||
.as_ref()
|
||||
.map_or(&prepared.taps, |(buffer, _)| buffer);
|
||||
let dispatches: Vec<Dispatch<'_, G::Buffer>> = (prepared.passes.iter())
|
||||
.map(|(kernel, params, threads, group)| Dispatch {
|
||||
kernel: *kernel,
|
||||
source: &source.buffer,
|
||||
destination: &destination.buffer,
|
||||
taps: &prepared.taps,
|
||||
params,
|
||||
lines,
|
||||
threads: *threads,
|
||||
group: *group,
|
||||
})
|
||||
.collect();
|
||||
// The GPU rings the bell once it is done, which ends the wait at once; the wait asks
|
||||
// again at least every `ASK_AGAIN` all the same.
|
||||
let bell = Arc::new(Bell::new());
|
||||
let ring = Arc::clone(&bell);
|
||||
let run = self
|
||||
.gpu
|
||||
.submit(&dispatches, Box::new(move || ring.ring()))
|
||||
.map_err(|why| {
|
||||
log::warn!("scaler: {} refused the transform: {why}", self.gpu.name());
|
||||
io_return::ERROR
|
||||
})?;
|
||||
drop(dispatches);
|
||||
let deadline = device_wait::deadline(&*self.runtime);
|
||||
let finished = loop {
|
||||
let ask = self.runtime.now().saturating_add(ASK_AGAIN).min(deadline);
|
||||
if let Some(done) = bell.wait_until(&*self.runtime, ask, || G::finished(&run)) {
|
||||
break Some(done);
|
||||
}
|
||||
if self.runtime.now() >= deadline {
|
||||
break G::finished(&run);
|
||||
}
|
||||
};
|
||||
match finished {
|
||||
Some(Ok(())) => {
|
||||
if let Some(time) = G::gpu_time(&run) {
|
||||
#[cfg(test)]
|
||||
GPU_TIMES.lock().push(time);
|
||||
log::debug!(
|
||||
"scaler: {} {}x{} to {} {}x{}: {:.3} ms on the GPU",
|
||||
job.plan.source_format.format.fourcc(),
|
||||
job.plan.source_format.width,
|
||||
job.plan.source_format.height,
|
||||
job.plan.destination_format.format.fourcc(),
|
||||
job.plan.destination_format.width,
|
||||
job.plan.destination_format.height,
|
||||
time.as_secs_f64() * 1000.0
|
||||
);
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
Some(Err(why)) => {
|
||||
log::warn!("scaler: the transform failed on {}: {why}", self.gpu.name());
|
||||
Err(io_return::ERROR)
|
||||
}
|
||||
None => {
|
||||
self.stuck = true;
|
||||
let mut buffers = vec![source.buffer, destination.buffer];
|
||||
buffers.extend(self.prepared.take().map(|p| p.taps));
|
||||
buffers.extend(self.lines.take().map(|(buffer, _)| buffer));
|
||||
let kept = Kept::<G> {
|
||||
run,
|
||||
_buffers: buffers,
|
||||
_hold: job.hold.clone(),
|
||||
};
|
||||
Lingering::process(&self.runtime).keep(
|
||||
format!("a scaler transform on {}", self.gpu.name()),
|
||||
Box::new(kept),
|
||||
);
|
||||
Err(io_return::ERROR)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Copies what the reference writes of a destination of `of` into `window` from `staged`, laid
|
||||
/// out as `planes`, into the destination's `bytes`. Each run lies within both, as the staged
|
||||
/// planes hold every row and byte of the format's and the caller checked that `bytes` holds the
|
||||
/// destination's planes; one that would not is skipped.
|
||||
fn copy_back(
|
||||
of: &FormatOf,
|
||||
window: Window,
|
||||
planes: &[BoundPlane],
|
||||
staged: &[u8],
|
||||
bytes: &mut [u8],
|
||||
) {
|
||||
let at = |offset: usize, pitch: usize, row: usize, start: usize, length: usize| {
|
||||
let first = row
|
||||
.checked_mul(pitch)?
|
||||
.checked_add(offset)?
|
||||
.checked_add(start)?;
|
||||
Some(first..first.checked_add(length)?)
|
||||
};
|
||||
for run in covered(of.format, window) {
|
||||
let (Some(from), Some(to)) = (planes.get(run.plane), of.planes.get(run.plane)) else {
|
||||
continue;
|
||||
};
|
||||
let source = at(from.offset, from.pitch, run.row, run.start, run.length);
|
||||
let target = at(to.offset, to.bytes_per_row, run.row, run.start, run.length);
|
||||
if let (Some(from), Some(to)) = (
|
||||
source.and_then(|r| staged.get(r)),
|
||||
target.and_then(|r| bytes.get_mut(r)),
|
||||
) {
|
||||
to.copy_from_slice(from);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The status of a transform whose source does not hold its layout: kIOReturnNotWritable where
|
||||
/// the destination cannot be lent for writing, kIOReturnBadArgument where it can, as
|
||||
/// [`TransformJob::with_bytes`] answers.
|
||||
fn too_small(job: &TransformJob<'_>) -> IoReturn {
|
||||
match job.destination.write(&mut |_| {}) {
|
||||
Ok(()) | Err(SurfaceError::Layout) => io_return::BAD_ARGUMENT,
|
||||
Err(error) => {
|
||||
log::warn!("scaler: the destination surface cannot be written: {error}");
|
||||
io_return::NOT_WRITABLE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<G: Gpu> Accelerator for GpuAccelerator<G> {
|
||||
fn capabilities(&self) -> Capabilities {
|
||||
capabilities(self.smallest)
|
||||
}
|
||||
|
||||
fn transform(&mut self, job: &mut TransformJob<'_>) -> IoReturn {
|
||||
if self.stuck {
|
||||
log::warn!(
|
||||
"scaler: refused, as {} did not finish an earlier transform",
|
||||
self.gpu.name()
|
||||
);
|
||||
return io_return::ERROR;
|
||||
}
|
||||
let plan = &job.plan;
|
||||
let sides = |of: &FormatOf| {
|
||||
let within = |side: u32| (self.smallest..=LARGEST_SIDE).contains(&side);
|
||||
within(of.width) && within(of.height)
|
||||
};
|
||||
if !sides(&plan.source_format) || !sides(&plan.destination_format) {
|
||||
return io_return::UNSUPPORTED;
|
||||
}
|
||||
let source = match self.source(job) {
|
||||
Ok(source) => source,
|
||||
Err(io_return::BAD_ARGUMENT) => return too_small(job),
|
||||
Err(status) => return status,
|
||||
};
|
||||
let destination = match self.destination(job, !source.staged) {
|
||||
Ok(destination) => destination,
|
||||
Err(status) => return status,
|
||||
};
|
||||
let staged = destination.staged;
|
||||
let ran = self.run(job, source, destination);
|
||||
if !staged {
|
||||
// Written in place, by the GPU, as far as it ran.
|
||||
job.destination.device_wrote();
|
||||
return ran.err().unwrap_or(io_return::SUCCESS);
|
||||
}
|
||||
// Staged: the destination's lend says whether it can be written, then what the kernel
|
||||
// wrote is copied into it.
|
||||
let mut output = ran;
|
||||
let dst = &job.plan.destination_format;
|
||||
let d = job.plan.destination_rect;
|
||||
let window = Window {
|
||||
x: d.x.to_usize(),
|
||||
y: d.y.to_usize(),
|
||||
width: d.width.to_usize(),
|
||||
height: d.height.to_usize(),
|
||||
};
|
||||
let mut status = io_return::SUCCESS;
|
||||
let written = job.destination.write(&mut |bytes| {
|
||||
status = if !dst.fits(bytes.len()) {
|
||||
io_return::BAD_ARGUMENT
|
||||
} else {
|
||||
match &mut output {
|
||||
Ok(bound) => match G::contents(&mut bound.buffer) {
|
||||
Some(staged) => {
|
||||
copy_back(dst, window, &bound.planes, staged, bytes);
|
||||
io_return::SUCCESS
|
||||
}
|
||||
None => io_return::ERROR,
|
||||
},
|
||||
Err(status) => *status,
|
||||
}
|
||||
};
|
||||
});
|
||||
drop(output);
|
||||
match written {
|
||||
Ok(()) => status,
|
||||
Err(SurfaceError::Layout) => io_return::BAD_ARGUMENT,
|
||||
Err(error) => {
|
||||
log::warn!("scaler: the destination surface cannot be written: {error}");
|
||||
io_return::NOT_WRITABLE
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,138 +0,0 @@
|
||||
//! The scaler's kernel on Metal (`reims_vgpu_metal::gpu::scaler`), on the system's default
|
||||
//! device, the one the library's GPU device draws on.
|
||||
//!
|
||||
//! A surface is reached in place through the IOSurface the host lends
|
||||
//! ([`DeviceMemory::io_surface`]): a buffer over it starts at the surface's first byte, as the
|
||||
//! lend's bytes do, and runs past them to the allocation's size (`reims_vgpu_metal::gpu::scaler`),
|
||||
//! so the planes are bound at their own offsets and only the lend's bytes are reached. The buffer
|
||||
//! retains the IOSurface, a hold the guest sees, so it is made for one transform and dropped
|
||||
//! before the transform returns, or kept with the device's hold on the surfaces where the GPU is
|
||||
//! not done by the deadline. A surface the host says it may not write is not bound as a
|
||||
//! destination: it is staged, and its lend refuses the write. Where Metal makes no buffer over an
|
||||
//! IOSurface, the surface is staged too; over a guest's pages, which the host's IOSurfaces of a
|
||||
//! VM lie in, no such buffer has been made yet, as no VM with the device has run on a Mac.
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_metal::gpu::scaler::{GpuBuffer, Kernel as GpuKernel, Pass, ScalerGpu, Submitted};
|
||||
use reims_vgpu_video_core::device_memory::DeviceMemory;
|
||||
|
||||
use super::{Dispatch, Gpu, Kernel};
|
||||
|
||||
/// The kernel on Metal.
|
||||
pub(crate) struct MetalGpu(ScalerGpu);
|
||||
|
||||
impl MetalGpu {
|
||||
/// The process's, made at its first use: `Err` with why where Metal has no device or refuses
|
||||
/// the kernel, which every later ask answers the same.
|
||||
pub(crate) fn process() -> Result<Arc<MetalGpu>, String> {
|
||||
static GPU: OnceLock<Result<Arc<MetalGpu>, String>> = OnceLock::new();
|
||||
GPU.get_or_init(|| ScalerGpu::new().map(|gpu| Arc::new(MetalGpu(gpu))))
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Gpu for MetalGpu {
|
||||
type Buffer = GpuBuffer;
|
||||
type Run = Submitted;
|
||||
|
||||
fn name(&self) -> &str {
|
||||
self.0.name()
|
||||
}
|
||||
|
||||
fn shared(&self, length: usize) -> Result<GpuBuffer, String> {
|
||||
self.0.shared_buffer(length)
|
||||
}
|
||||
|
||||
fn table(&self, bytes: &[u8]) -> Result<Self::Buffer, String> {
|
||||
self.0.table_buffer(bytes)
|
||||
}
|
||||
|
||||
fn scratch(&self, length: usize) -> Result<GpuBuffer, String> {
|
||||
self.0.private_buffer(length)
|
||||
}
|
||||
|
||||
fn contents(buffer: &mut GpuBuffer) -> Option<&mut [u8]> {
|
||||
buffer.contents()
|
||||
}
|
||||
|
||||
fn memory(
|
||||
&self,
|
||||
memory: &dyn DeviceMemory,
|
||||
writes: bool,
|
||||
) -> Result<Option<(GpuBuffer, usize)>, String> {
|
||||
let Ok(lent) = memory.io_surface() else {
|
||||
return Ok(None);
|
||||
};
|
||||
if writes && !lent.writable() {
|
||||
return Ok(None);
|
||||
}
|
||||
// SAFETY: the lend keeps the IOSurface live while `memory` lives, which the caller's hold
|
||||
// on the surface outlives, and the buffer goes before that hold (module docs); the host
|
||||
// lends it for writing where it is bound as a destination.
|
||||
let buffer = unsafe { self.0.surface_buffer(lent.as_ptr()) }?;
|
||||
if buffer.length() < memory.length() {
|
||||
return Err(format!(
|
||||
"a buffer of {} bytes over a surface of {}",
|
||||
buffer.length(),
|
||||
memory.length()
|
||||
));
|
||||
}
|
||||
Ok(Some((buffer, 0)))
|
||||
}
|
||||
|
||||
fn submit(
|
||||
&self,
|
||||
dispatches: &[Dispatch<'_, GpuBuffer>],
|
||||
done: Box<dyn FnOnce() + Send>,
|
||||
) -> Result<Submitted, String> {
|
||||
self.0.submit(&passes(dispatches), done)
|
||||
}
|
||||
|
||||
fn submit_apart(
|
||||
&self,
|
||||
dispatches: &[Dispatch<'_, GpuBuffer>],
|
||||
done: Box<dyn FnOnce() + Send>,
|
||||
) -> Result<Submitted, String> {
|
||||
self.0.submit_apart(&passes(dispatches), done)
|
||||
}
|
||||
|
||||
fn finished(run: &Submitted) -> Option<Result<(), String>> {
|
||||
run.finished()
|
||||
}
|
||||
|
||||
fn gpu_time(run: &Submitted) -> Option<Duration> {
|
||||
run.gpu_time()
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform's passes of `dispatches`.
|
||||
fn passes<'a>(dispatches: &[Dispatch<'a, GpuBuffer>]) -> Vec<Pass<'a>> {
|
||||
dispatches
|
||||
.iter()
|
||||
.map(|d| Pass {
|
||||
kernel: kernel(d.kernel),
|
||||
source: d.source,
|
||||
destination: d.destination,
|
||||
taps: d.taps,
|
||||
params: d.params,
|
||||
lines: d.lines,
|
||||
threads: d.threads,
|
||||
group: d.group,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The platform's kernel of `kernel`.
|
||||
fn kernel(kernel: Kernel) -> GpuKernel {
|
||||
match kernel {
|
||||
Kernel::Lines => GpuKernel::Lines,
|
||||
Kernel::Transform => GpuKernel::Transform,
|
||||
Kernel::Across => GpuKernel::Across,
|
||||
Kernel::Shared => GpuKernel::Shared,
|
||||
Kernel::Quads => GpuKernel::Quads,
|
||||
Kernel::TransformAdaptive => GpuKernel::TransformAdaptive,
|
||||
Kernel::TransformBothPlanes => GpuKernel::TransformBothPlanes,
|
||||
}
|
||||
}
|
||||
@@ -1,934 +0,0 @@
|
||||
//! What the scaler's kernel is told for one transform: each dispatch's parameters, laid out as
|
||||
//! `ScalerParams` in `scaler.metal` (reims-vgpu-metal's `src/gpu/scaler.metal`), and the taps,
|
||||
//! all worked out from the plan as core's reference works its transform out (`reference::run`):
|
||||
//! - the source's formats and planes, how its pixels and chroma samples turn, how its codes
|
||||
//! read, and the chroma samples the source window covers, which its chroma is interpolated
|
||||
//! from;
|
||||
//! - the matrix, where RGB and Y'CbCr meet, and whether the scale is in linear light;
|
||||
//! - where each destination pixel samples, and with what weights: the reference's own taps
|
||||
//! ([`reference::taps`]), each axis's weights divided by their sum, so that a change to where
|
||||
//! the reference samples reaches the kernel as it is;
|
||||
//! - the destination window, its chroma's siting, how its codes are written, and one dispatch
|
||||
//! per plane of the destination, over the words the window covers: of `scaler_transform`
|
||||
//! (`scaler_transform_adaptive` where the adaptive filter moves a pass, and
|
||||
//! `scaler_transform_both_planes` for both planes of a 4:2:0 window where it moves none), or of
|
||||
//! `scaler_quads` for the RGB plane of a copy of a Y'CbCr source;
|
||||
//! - where a destination pixel takes more than one pixel of the turned source each way, the lines:
|
||||
//! bands of the window's rows, each a dispatch of `scaler_lines` over the columns of the turned
|
||||
//! source the window's across taps take and the band's rows, then its planes' dispatches, which
|
||||
//! sum those lines across ([`LINES_BUDGET`]): of `scaler_across`, or of `scaler_across_shared`
|
||||
//! for a reduction across of a plane whose words hold more than one pixel.
|
||||
//!
|
||||
//! Each number the reference's functions give is taken from them (`reference::luma_of`,
|
||||
//! `code_chroma`, `chroma_window` and the rest), not worked out again here.
|
||||
|
||||
use reims_vgpu_core::num::ToUsize as _;
|
||||
use reims_vgpu_video_core::scaler::format::{Packing, PlaneSpan, ScalerFormat};
|
||||
use reims_vgpu_video_core::scaler::plan::{Orientation, Plan, Site};
|
||||
use reims_vgpu_video_core::scaler::reference::{self, Space};
|
||||
|
||||
/// What a dispatch's plane holds: `KIND_*` in `scaler.metal`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[repr(u32)]
|
||||
pub(super) enum PlaneKind {
|
||||
Luma8 = 0,
|
||||
Luma16 = 1,
|
||||
Chroma8 = 2,
|
||||
Chroma16 = 3,
|
||||
Packed422 = 4,
|
||||
Rgb32 = 5,
|
||||
Biplanar8 = 6,
|
||||
Biplanar16 = 7,
|
||||
}
|
||||
|
||||
/// One dispatch's parameters: `ScalerParams` in `scaler.metal`, field for field, each four
|
||||
/// bytes, in its order ([`Params::bytes`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
pub(super) struct Params {
|
||||
pub(super) source_packing: u32,
|
||||
pub(super) source_sample_bytes: u32,
|
||||
pub(super) source_order: [u32; 4],
|
||||
pub(super) source_luma_offset: u32,
|
||||
pub(super) source_luma_pitch: u32,
|
||||
pub(super) source_chroma_offset: u32,
|
||||
pub(super) source_chroma_pitch: u32,
|
||||
pub(super) source_luma_low: f32,
|
||||
pub(super) source_luma_scale: f32,
|
||||
pub(super) source_chroma_middle: f32,
|
||||
pub(super) source_chroma_scale: f32,
|
||||
pub(super) luma_map: [i32; 6],
|
||||
pub(super) turned_last_x: u32,
|
||||
pub(super) turned_last_y: u32,
|
||||
pub(super) source_subsample_x: u32,
|
||||
pub(super) source_subsample_y: u32,
|
||||
pub(super) chroma_step_x: u32,
|
||||
pub(super) chroma_step_y: u32,
|
||||
pub(super) chroma_origin_x: u32,
|
||||
pub(super) chroma_origin_y: u32,
|
||||
pub(super) chroma_last_x: u32,
|
||||
pub(super) chroma_last_y: u32,
|
||||
pub(super) rgb: u32,
|
||||
pub(super) linear: u32,
|
||||
pub(super) kr: f32,
|
||||
pub(super) kg: f32,
|
||||
pub(super) kb: f32,
|
||||
pub(super) cb_scale: f32,
|
||||
pub(super) cr_scale: f32,
|
||||
pub(super) b_of_cb: f32,
|
||||
pub(super) r_of_cr: f32,
|
||||
pub(super) g_scale: f32,
|
||||
pub(super) across_first: u32,
|
||||
pub(super) across_count: u32,
|
||||
pub(super) down_first: u32,
|
||||
pub(super) down_count: u32,
|
||||
pub(super) window_x: u32,
|
||||
pub(super) window_y: u32,
|
||||
pub(super) window_width: u32,
|
||||
pub(super) window_height: u32,
|
||||
pub(super) site_x: u32,
|
||||
pub(super) site_y: u32,
|
||||
pub(super) subsample_x: u32,
|
||||
pub(super) subsample_y: u32,
|
||||
pub(super) plane_kind: u32,
|
||||
pub(super) plane_order: [u32; 4],
|
||||
pub(super) plane_offset: u32,
|
||||
pub(super) plane_pitch: u32,
|
||||
pub(super) first_row: u32,
|
||||
pub(super) rows: u32,
|
||||
pub(super) first_byte: u32,
|
||||
pub(super) end_byte: u32,
|
||||
pub(super) words: u32,
|
||||
pub(super) luma_low: f32,
|
||||
pub(super) luma_span: f32,
|
||||
pub(super) chroma_middle: f32,
|
||||
pub(super) chroma_span: f32,
|
||||
pub(super) code_max: f32,
|
||||
pub(super) lines_first: u32,
|
||||
pub(super) lines_pitch: u32,
|
||||
pub(super) lines_row: u32,
|
||||
pub(super) lines_rows: u32,
|
||||
pub(super) chroma_plane_offset: u32,
|
||||
pub(super) chroma_plane_pitch: u32,
|
||||
pub(super) chroma_across_first: u32,
|
||||
pub(super) chroma_across_count: u32,
|
||||
pub(super) chroma_down_first: u32,
|
||||
pub(super) chroma_down_count: u32,
|
||||
pub(super) ycbcr_to_rgb: u32,
|
||||
pub(super) across_points_first: u32,
|
||||
pub(super) down_points_first: u32,
|
||||
pub(super) across_span_first: u32,
|
||||
pub(super) across_span_last: u32,
|
||||
pub(super) down_span_first: u32,
|
||||
pub(super) down_span_last: u32,
|
||||
pub(super) across_reduces: u32,
|
||||
pub(super) down_reduces: u32,
|
||||
pub(super) adapt_across: u32,
|
||||
pub(super) adapt_down: u32,
|
||||
pub(super) adaptive_channels: u32,
|
||||
pub(super) adaptive_scale: f32,
|
||||
}
|
||||
|
||||
/// The words of `ScalerParams`.
|
||||
pub(super) const PARAMS_WORDS: usize = 92;
|
||||
|
||||
impl Params {
|
||||
/// Its bytes, as the kernel reads them: each field in order, little-endian.
|
||||
pub(super) fn bytes(&self) -> Vec<u8> {
|
||||
let mut words: Vec<u32> = Vec::with_capacity(PARAMS_WORDS);
|
||||
let mut u = |v: u32| words.push(v);
|
||||
u(self.source_packing);
|
||||
u(self.source_sample_bytes);
|
||||
self.source_order.into_iter().for_each(&mut u);
|
||||
u(self.source_luma_offset);
|
||||
u(self.source_luma_pitch);
|
||||
u(self.source_chroma_offset);
|
||||
u(self.source_chroma_pitch);
|
||||
for f in [
|
||||
self.source_luma_low,
|
||||
self.source_luma_scale,
|
||||
self.source_chroma_middle,
|
||||
self.source_chroma_scale,
|
||||
] {
|
||||
u(f.to_bits());
|
||||
}
|
||||
self.luma_map.into_iter().for_each(|v| u(v.cast_unsigned()));
|
||||
for v in [
|
||||
self.turned_last_x,
|
||||
self.turned_last_y,
|
||||
self.source_subsample_x,
|
||||
self.source_subsample_y,
|
||||
self.chroma_step_x,
|
||||
self.chroma_step_y,
|
||||
self.chroma_origin_x,
|
||||
self.chroma_origin_y,
|
||||
self.chroma_last_x,
|
||||
self.chroma_last_y,
|
||||
self.rgb,
|
||||
self.linear,
|
||||
] {
|
||||
u(v);
|
||||
}
|
||||
for f in [
|
||||
self.kr,
|
||||
self.kg,
|
||||
self.kb,
|
||||
self.cb_scale,
|
||||
self.cr_scale,
|
||||
self.b_of_cb,
|
||||
self.r_of_cr,
|
||||
self.g_scale,
|
||||
] {
|
||||
u(f.to_bits());
|
||||
}
|
||||
for v in [
|
||||
self.across_first,
|
||||
self.across_count,
|
||||
self.down_first,
|
||||
self.down_count,
|
||||
self.window_x,
|
||||
self.window_y,
|
||||
self.window_width,
|
||||
self.window_height,
|
||||
self.site_x,
|
||||
self.site_y,
|
||||
self.subsample_x,
|
||||
self.subsample_y,
|
||||
self.plane_kind,
|
||||
] {
|
||||
u(v);
|
||||
}
|
||||
self.plane_order.into_iter().for_each(&mut u);
|
||||
for v in [
|
||||
self.plane_offset,
|
||||
self.plane_pitch,
|
||||
self.first_row,
|
||||
self.rows,
|
||||
self.first_byte,
|
||||
self.end_byte,
|
||||
self.words,
|
||||
] {
|
||||
u(v);
|
||||
}
|
||||
for f in [
|
||||
self.luma_low,
|
||||
self.luma_span,
|
||||
self.chroma_middle,
|
||||
self.chroma_span,
|
||||
self.code_max,
|
||||
] {
|
||||
u(f.to_bits());
|
||||
}
|
||||
for v in [
|
||||
self.lines_first,
|
||||
self.lines_pitch,
|
||||
self.lines_row,
|
||||
self.lines_rows,
|
||||
self.chroma_plane_offset,
|
||||
self.chroma_plane_pitch,
|
||||
self.chroma_across_first,
|
||||
self.chroma_across_count,
|
||||
self.chroma_down_first,
|
||||
self.chroma_down_count,
|
||||
self.ycbcr_to_rgb,
|
||||
self.across_points_first,
|
||||
self.down_points_first,
|
||||
self.across_span_first,
|
||||
self.across_span_last,
|
||||
self.down_span_first,
|
||||
self.down_span_last,
|
||||
self.across_reduces,
|
||||
self.down_reduces,
|
||||
self.adapt_across,
|
||||
self.adapt_down,
|
||||
self.adaptive_channels,
|
||||
] {
|
||||
u(v);
|
||||
}
|
||||
u(self.adaptive_scale.to_bits());
|
||||
words.into_iter().flat_map(u32::to_le_bytes).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// One plane of a surface as the kernel reaches it, in the buffer it is bound in: where it
|
||||
/// starts and its row pitch, and the bytes of each row its samples fill.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct BoundPlane {
|
||||
pub(super) offset: usize,
|
||||
pub(super) pitch: usize,
|
||||
pub(super) row_bytes: usize,
|
||||
pub(super) rows: usize,
|
||||
}
|
||||
|
||||
impl BoundPlane {
|
||||
/// `span` of a surface whose first byte lies at `base` in its buffer.
|
||||
pub(super) fn at(span: &PlaneSpan, base: usize) -> Option<BoundPlane> {
|
||||
Some(BoundPlane {
|
||||
offset: span.offset.checked_add(base)?,
|
||||
pitch: span.bytes_per_row,
|
||||
row_bytes: span.row_bytes,
|
||||
rows: span.rows,
|
||||
})
|
||||
}
|
||||
|
||||
/// Where its last row's samples end, from the buffer's first byte.
|
||||
pub(super) fn end(&self) -> Option<usize> {
|
||||
let rows = self.rows.checked_sub(1)?;
|
||||
rows.checked_mul(self.pitch)?
|
||||
.checked_add(self.row_bytes)?
|
||||
.checked_add(self.offset)
|
||||
}
|
||||
|
||||
/// Whether the kernel can write it word by word: its rows start on 4-byte boundaries.
|
||||
pub(super) fn word_aligned(&self) -> bool {
|
||||
self.offset.is_multiple_of(4) && self.pitch.is_multiple_of(4)
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernel a dispatch runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Kernel {
|
||||
/// `scaler_lines`: columns of the turned source down a band of the window's rows, into the
|
||||
/// lines buffer.
|
||||
Lines,
|
||||
/// `scaler_transform`: a plane of the destination, of a transform that is not separable.
|
||||
Transform,
|
||||
/// `scaler_across`: a plane of the destination, over a band of the window's rows, from the
|
||||
/// lines `scaler_lines` wrote, a thread a word.
|
||||
Across,
|
||||
/// `scaler_across_shared`: the same, a threadgroup's pixels worked out a thread a pixel into
|
||||
/// threadgroup memory first.
|
||||
Shared,
|
||||
/// `scaler_quads`: the RGB plane of a copy of a Y'CbCr source, a thread two by two pixels, in
|
||||
/// whole threadgroups.
|
||||
Quads,
|
||||
/// `scaler_transform_adaptive`: `scaler_transform` for a transform whose passes the adaptive
|
||||
/// filter moves, a kernel of its own so that the transforms it does not move run, and are
|
||||
/// made, without its code.
|
||||
TransformAdaptive,
|
||||
/// `scaler_transform_both_planes`: `scaler_transform` for both planes of a 4:2:0 window whose
|
||||
/// every edge is even, which the adaptive filter does not move, a kernel of its own so that the
|
||||
/// others are made without its unrolled code.
|
||||
TransformBothPlanes,
|
||||
}
|
||||
|
||||
/// One dispatch: its kernel, its parameters, its threads across and down, and those of a
|
||||
/// threadgroup.
|
||||
pub(super) type Pass = (Kernel, Params, (u32, u32), (u32, u32));
|
||||
|
||||
/// The threads of a threadgroup of every kernel but `scaler_lines`: 64, which every GPU runs.
|
||||
pub(super) const GROUP: (u32, u32) = (16, 4);
|
||||
|
||||
/// The columns of a threadgroup of `scaler_lines`, its `LINES_COLUMNS`.
|
||||
const LINES_COLUMNS: u32 = 16;
|
||||
|
||||
/// The rows of a threadgroup of `scaler_lines` ([`lines_rows`]): 16, or 8 where the source's rows
|
||||
/// that 16 rows of the window read do not fit the pixels it decodes once.
|
||||
const LINES_ROWS: [u32; 2] = [16, 8];
|
||||
|
||||
/// Every kernel and threadgroup [`work`] dispatches, as a Vulkan driver makes a pipeline for
|
||||
/// each at the first dispatch of its threadgroup's size: the dispatches that make them ahead of a
|
||||
/// guest's first transform (`gpu.rs`, `make_ahead`), in their order, the cheapest to make first
|
||||
/// (docs/video/scaler.md, "Made ahead").
|
||||
pub(super) const DISPATCHED: [(Kernel, (u32, u32)); 8] = [
|
||||
(Kernel::Shared, GROUP),
|
||||
(Kernel::Quads, GROUP),
|
||||
(Kernel::Lines, (LINES_COLUMNS, LINES_ROWS[0])),
|
||||
(Kernel::Lines, (LINES_COLUMNS, LINES_ROWS[1])),
|
||||
(Kernel::Across, GROUP),
|
||||
(Kernel::TransformBothPlanes, GROUP),
|
||||
(Kernel::Transform, GROUP),
|
||||
(Kernel::TransformAdaptive, GROUP),
|
||||
];
|
||||
|
||||
/// The pixels of the turned source a threadgroup of `scaler_lines` decodes once each, its
|
||||
/// `SHARED_PIXELS`.
|
||||
const SHARED_PIXELS: u32 = 768;
|
||||
|
||||
/// A transform as the kernel runs it: its dispatches, in order; the taps, as `(index, weight)`
|
||||
/// pairs; and the bytes of lines its largest band takes, 0 where it is not separable.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct Work {
|
||||
pub(super) passes: Vec<Pass>,
|
||||
pub(super) taps: Vec<(u32, f32)>,
|
||||
pub(super) lines: usize,
|
||||
}
|
||||
|
||||
/// The bytes of lines a band takes at most, unless one pair of the window's rows takes more: 16
|
||||
/// MiB.
|
||||
pub(super) const LINES_BUDGET: usize = 16 << 20;
|
||||
|
||||
/// Why a transform cannot run on the kernel: an offset past what the kernel addresses.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) struct TooLarge;
|
||||
|
||||
fn small(v: usize) -> Result<u32, TooLarge> {
|
||||
u32::try_from(v).map_err(|_| TooLarge)
|
||||
}
|
||||
|
||||
/// A count of the source's, which a `u32` holds, as an index.
|
||||
fn index(v: u32) -> usize {
|
||||
usize::try_from(v).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// `values`' four bytes' offsets, as the kernel takes them.
|
||||
fn order(values: [usize; 4]) -> Result<[u32; 4], TooLarge> {
|
||||
let mut out = [0; 4];
|
||||
for (o, v) in out.iter_mut().zip(values) {
|
||||
*o = small(v)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The turned picture's pixel `(x, y)` as the pixel of a `width` by `height` picture it is
|
||||
/// ([`Orientation::source_point`] at its centre, as the reference turns a picture): the map's
|
||||
/// six coefficients, `(m0 x + m1 y + m2, m3 x + m4 y + m5)`. A turn is a signed permutation, so
|
||||
/// three points give it.
|
||||
fn turn_map(orientation: Orientation, width: u32, height: u32) -> Result<[i32; 6], TooLarge> {
|
||||
let (w, h) = (f64::from(width), f64::from(height));
|
||||
let at = |x: f64, y: f64| {
|
||||
let (sx, sy) = orientation.source_point(x + 0.5, y + 0.5, w, h);
|
||||
(sx.floor(), sy.floor())
|
||||
};
|
||||
let (o, a, d) = (at(0.0, 0.0), at(1.0, 0.0), at(0.0, 1.0));
|
||||
let int = |v: f64| {
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "a whole number within a side, checked below"
|
||||
)]
|
||||
let i = v as i64;
|
||||
i32::try_from(i).map_err(|_| TooLarge)
|
||||
};
|
||||
Ok([
|
||||
int(a.0 - o.0)?,
|
||||
int(d.0 - o.0)?,
|
||||
int(o.0)?,
|
||||
int(a.1 - o.1)?,
|
||||
int(d.1 - o.1)?,
|
||||
int(o.1)?,
|
||||
])
|
||||
}
|
||||
|
||||
/// An affine map of `v` as `(f(0), f(1) - f(0))`: its value at 0, and its slope.
|
||||
fn affine(f: impl Fn(f64) -> f64) -> (f64, f64) {
|
||||
let at_zero = f(0.0);
|
||||
(at_zero, f(1.0) - at_zero)
|
||||
}
|
||||
|
||||
/// How the kernel reads a code of `format`'s in `space`, as the reference's `luma_of` and
|
||||
/// `chroma_of` read it, each affine in the code: `(low, scale)` for a luma code's value,
|
||||
/// `(code - low) * scale`, and `(middle, scale)` for a chroma code's.
|
||||
fn decoding(format: ScalerFormat, space: Space) -> ((f64, f64), (f64, f64)) {
|
||||
let inverse = |(at_zero, slope): (f64, f64)| (-at_zero / slope, slope);
|
||||
(
|
||||
inverse(affine(|v| reference::luma_of(format, v, space))),
|
||||
inverse(affine(|v| reference::chroma_of(format, v, space))),
|
||||
)
|
||||
}
|
||||
|
||||
/// How the kernel writes `format`'s codes, as the reference's `code_luma` and `code_chroma`
|
||||
/// write them, each affine in the value: `(low, span)` for a luma code, `low + span * value`,
|
||||
/// and `(middle, span)` for a chroma code.
|
||||
fn encoding(format: ScalerFormat) -> ((f64, f64), (f64, f64)) {
|
||||
(
|
||||
affine(|y| reference::code_luma(format, y)),
|
||||
affine(|c| reference::code_chroma(format, c)),
|
||||
)
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_possible_truncation,
|
||||
reason = "the kernel works in floats"
|
||||
)]
|
||||
fn float(v: f64) -> f32 {
|
||||
v as f32
|
||||
}
|
||||
|
||||
/// The taps of one axis, as the kernel takes them: each pixel's merged by index, with no zero
|
||||
/// weight, divided by their sum, and padded with zero weights to the most any pixel has; laid out
|
||||
/// a tap at a time, that tap of every pixel in turn, so that neighbouring threads read
|
||||
/// neighbouring taps. The count a pixel, and the table.
|
||||
fn axis(taps: &[Vec<(usize, f64)>]) -> Result<(u32, Vec<(u32, f32)>), TooLarge> {
|
||||
let merged: Vec<Vec<(usize, f64)>> = taps
|
||||
.iter()
|
||||
.map(|pixel| {
|
||||
let total: f64 = pixel.iter().map(|(_, w)| w).sum();
|
||||
let mut out: Vec<(usize, f64)> = Vec::with_capacity(pixel.len());
|
||||
for &(i, w) in pixel {
|
||||
match out.iter_mut().find(|(j, _)| *j == i) {
|
||||
Some((_, sum)) => *sum += w,
|
||||
None => out.push((i, w)),
|
||||
}
|
||||
}
|
||||
out.retain(|(_, w)| *w != 0.0);
|
||||
if total != 0.0 {
|
||||
out.iter_mut().for_each(|(_, w)| *w /= total);
|
||||
}
|
||||
out
|
||||
})
|
||||
.collect();
|
||||
let count = merged.iter().map(Vec::len).max().unwrap_or(0).max(1);
|
||||
let mut table = Vec::with_capacity(count * merged.len());
|
||||
for k in 0..count {
|
||||
for pixel in &merged {
|
||||
let pad = pixel.first().map_or(0, |(i, _)| *i);
|
||||
let (i, w) = pixel.get(k).copied().unwrap_or((pad, 0.0));
|
||||
table.push((small(i)?, float(w)));
|
||||
}
|
||||
}
|
||||
Ok((small(count)?, table))
|
||||
}
|
||||
|
||||
const fn site(site: Site) -> u32 {
|
||||
match site {
|
||||
Site::First => 0,
|
||||
Site::Between => 1,
|
||||
Site::Second => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// A destination plane's dispatch before its parameters: its kind, its index among the
|
||||
/// destination's planes and that of the chroma plane it writes too, the rows and the bytes of a
|
||||
/// row the window covers, each first and end, and its components' order.
|
||||
type PlaneWork = (
|
||||
PlaneKind,
|
||||
usize,
|
||||
Option<usize>,
|
||||
(u32, u32),
|
||||
(u32, u32),
|
||||
[usize; 4],
|
||||
);
|
||||
|
||||
/// The kernel's work for `plan`, its source's planes at `source` and its destination's at
|
||||
/// `destination` in the buffers they are bound in. Every plane of the destination must be
|
||||
/// [`BoundPlane::word_aligned`]; `Err` where an offset or a count is past what the kernel
|
||||
/// addresses.
|
||||
pub(super) fn work(
|
||||
plan: &Plan,
|
||||
source: &[BoundPlane],
|
||||
destination: &[BoundPlane],
|
||||
) -> Result<Work, TooLarge> {
|
||||
let src = &plan.source_format;
|
||||
let dst = &plan.destination_format;
|
||||
let mut p = Params::default();
|
||||
// The source.
|
||||
let luma = source.first().ok_or(TooLarge)?;
|
||||
let chroma = source.get(1).unwrap_or(luma);
|
||||
p.source_packing = match src.format.packing() {
|
||||
Packing::Biplanar420 => 0,
|
||||
Packing::Packed422(order_of) => {
|
||||
p.source_order = order(order_of)?;
|
||||
1
|
||||
}
|
||||
Packing::Rgb32(order_of) => {
|
||||
p.source_order = order(order_of)?;
|
||||
2
|
||||
}
|
||||
};
|
||||
p.source_sample_bytes = small(src.format.bytes_per_sample())?;
|
||||
p.source_luma_offset = small(luma.offset)?;
|
||||
p.source_luma_pitch = small(luma.pitch)?;
|
||||
p.source_chroma_offset = small(chroma.offset)?;
|
||||
p.source_chroma_pitch = small(chroma.pitch)?;
|
||||
// Each plane's last byte the kernel reads lies inside the buffer's first 4 GiB.
|
||||
for plane in source {
|
||||
small(plane.end().ok_or(TooLarge)?)?;
|
||||
}
|
||||
let space = Space::between(src.format, dst.format);
|
||||
let ((luma_low, luma_scale), (chroma_middle, chroma_scale)) = decoding(src.format, space);
|
||||
p.source_luma_low = float(luma_low);
|
||||
p.source_luma_scale = float(luma_scale);
|
||||
p.source_chroma_middle = float(chroma_middle);
|
||||
p.source_chroma_scale = float(chroma_scale);
|
||||
let (sx, sy) = src.format.subsampling();
|
||||
(p.source_subsample_x, p.source_subsample_y) = (sx, sy);
|
||||
p.luma_map = turn_map(plan.orientation, src.width, src.height)?;
|
||||
let step = if plan.orientation.rotates() {
|
||||
(sy, sx)
|
||||
} else {
|
||||
(sx, sy)
|
||||
};
|
||||
(p.chroma_step_x, p.chroma_step_y) = step;
|
||||
// The taps, and the turned window's chroma samples: where the first sits, and the last.
|
||||
let taps = reference::taps(plan);
|
||||
let (origin_x, origin_y, last_x, last_y) =
|
||||
reference::chroma_window(taps.window, (index(step.0), index(step.1)));
|
||||
p.chroma_origin_x = small(origin_x)?;
|
||||
p.chroma_origin_y = small(origin_y)?;
|
||||
p.chroma_last_x = small(last_x)?;
|
||||
p.chroma_last_y = small(last_y)?;
|
||||
p.turned_last_x = small(taps.turned.0.saturating_sub(1))?;
|
||||
p.turned_last_y = small(taps.turned.1.saturating_sub(1))?;
|
||||
// The working space.
|
||||
p.rgb = u32::from(space == Space::Rgb);
|
||||
p.linear = u32::from(reference::in_linear_light(src.format, dst.format));
|
||||
let (kr, kb) = plan.matrix.weights();
|
||||
p.kr = float(kr);
|
||||
p.kg = float(1.0 - kr - kb);
|
||||
p.kb = float(kb);
|
||||
p.cb_scale = float(1.0 / (2.0 * (1.0 - kb)));
|
||||
p.cr_scale = float(1.0 / (2.0 * (1.0 - kr)));
|
||||
p.b_of_cb = float(2.0 * (1.0 - kb));
|
||||
p.r_of_cr = float(2.0 * (1.0 - kr));
|
||||
p.g_scale = float(1.0 / (1.0 - kr - kb));
|
||||
// A Y'CbCr source into RGB converts after the scale, as the reference converts it.
|
||||
p.ycbcr_to_rgb = u32::from(src.format.is_ycbcr() && space == Space::Rgb);
|
||||
let (across_count, across) = axis(&taps.across)?;
|
||||
let (down_count, down) = axis(&taps.down)?;
|
||||
// A Y'CbCr source's chroma's taps, along an axis where they are not its luma's.
|
||||
let chroma_across = taps.chroma_across.as_deref().map(axis).transpose()?;
|
||||
let chroma_down = taps.chroma_down.as_deref().map(axis).transpose()?;
|
||||
// A pixel of one source pixel each way is that pixel: into linear light and back out of it
|
||||
// is no change, so it goes neither way.
|
||||
if across_count == 1 && down_count == 1 {
|
||||
p.linear = 0;
|
||||
}
|
||||
p.across_first = 0;
|
||||
p.across_count = across_count;
|
||||
p.down_first = small(across.len())?;
|
||||
p.down_count = down_count;
|
||||
// The chroma's taps after the luma's, or the luma's where they are the same.
|
||||
let mut end = across.len() + down.len();
|
||||
let mut placed = |taps: &Option<(u32, Vec<(u32, f32)>)>, (first, count): (u32, u32)| {
|
||||
let Some((count, table)) = taps else {
|
||||
return Ok((first, count));
|
||||
};
|
||||
let at = small(end)?;
|
||||
end += table.len();
|
||||
Ok::<_, TooLarge>((at, *count))
|
||||
};
|
||||
(p.chroma_across_first, p.chroma_across_count) =
|
||||
placed(&chroma_across, (p.across_first, across_count))?;
|
||||
(p.chroma_down_first, p.chroma_down_count) = placed(&chroma_down, (p.down_first, down_count))?;
|
||||
// The adaptive filter: each column's and row's sample point after the taps, as the pixel it
|
||||
// lies in (an int's bits) and its fraction past it, and where each axis's pixels end. An
|
||||
// axis whose every pixel takes one source pixel moves none: its point lies on that pixel.
|
||||
let point = |&(pixel, fraction): &(i64, f64)| {
|
||||
let pixel = i32::try_from(pixel).map_err(|_| TooLarge)?;
|
||||
Ok::<_, TooLarge>((pixel.cast_unsigned(), float(fraction)))
|
||||
};
|
||||
let across_points = taps
|
||||
.across_points
|
||||
.iter()
|
||||
.map(point)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
let down_points = taps
|
||||
.down_points
|
||||
.iter()
|
||||
.map(point)
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
p.across_points_first = small(end)?;
|
||||
p.down_points_first = small(end + across_points.len())?;
|
||||
(p.across_span_first, p.across_span_last) =
|
||||
(small(taps.across_span.0)?, small(taps.across_span.1)?);
|
||||
(p.down_span_first, p.down_span_last) = (small(taps.down_span.0)?, small(taps.down_span.1)?);
|
||||
p.across_reduces = u32::from(taps.reduces[0]);
|
||||
p.down_reduces = u32::from(taps.reduces[1]);
|
||||
let adaptive = reference::adaptive(src.format, space);
|
||||
p.adaptive_channels = small(adaptive.channels)?;
|
||||
p.adaptive_scale = float(adaptive.scale);
|
||||
p.adapt_across = u32::from(adaptive.channels > 0 && across_count > 1);
|
||||
p.adapt_down = u32::from(adaptive.channels > 0 && down_count > 1);
|
||||
let chroma_across_table = chroma_across.map(|(_, table)| table);
|
||||
let chroma_down_table = chroma_down.map(|(_, table)| table);
|
||||
// The window.
|
||||
let rect = plan.destination_rect;
|
||||
(p.window_x, p.window_y, p.window_width, p.window_height) =
|
||||
(rect.x, rect.y, rect.width, rect.height);
|
||||
p.site_x = site(plan.destination_siting.horizontal);
|
||||
p.site_y = site(plan.destination_siting.vertical);
|
||||
let (dx, dy) = dst.format.subsampling();
|
||||
(p.subsample_x, p.subsample_y) = (dx, dy);
|
||||
let ((luma_low, luma_span), (chroma_middle, chroma_span)) = encoding(dst.format);
|
||||
p.luma_low = float(luma_low);
|
||||
p.luma_span = float(luma_span);
|
||||
p.chroma_middle = float(chroma_middle);
|
||||
p.chroma_span = float(chroma_span);
|
||||
p.code_max = float(f64::from((1u32 << dst.format.bits()) - 1));
|
||||
// A dispatch a plane: its rows and bytes the window covers, as `coverage::covered` has them.
|
||||
let (x0, y0) = (rect.x, rect.y);
|
||||
let (x1, y1) = (rect.x + rect.width, rect.y + rect.height);
|
||||
let s = small(dst.format.bytes_per_sample())?;
|
||||
let even = [x0, x1, y0, y1].iter().all(|v| v % 2 == 0);
|
||||
let planes: Vec<PlaneWork> = match dst.format.packing() {
|
||||
// A window of even edges, as the plan takes 4:2:0 windows of two pixels or more: one
|
||||
// dispatch for both planes, each chroma word with the luma words of its pixels.
|
||||
Packing::Biplanar420 if even => {
|
||||
let kind = if s == 1 {
|
||||
PlaneKind::Biplanar8
|
||||
} else {
|
||||
PlaneKind::Biplanar16
|
||||
};
|
||||
vec![(kind, 0, Some(1), (y0 / 2, y1 / 2), (x0 * s, x1 * s), [0; 4])]
|
||||
}
|
||||
Packing::Biplanar420 => {
|
||||
let (luma_kind, chroma_kind) = if s == 1 {
|
||||
(PlaneKind::Luma8, PlaneKind::Chroma8)
|
||||
} else {
|
||||
(PlaneKind::Luma16, PlaneKind::Chroma16)
|
||||
};
|
||||
vec![
|
||||
(luma_kind, 0, None, (y0, y1), (x0 * s, x1 * s), [0; 4]),
|
||||
(
|
||||
chroma_kind,
|
||||
1,
|
||||
None,
|
||||
(y0 / 2, y1.div_ceil(2)),
|
||||
(x0 / 2 * 2 * s, x1.div_ceil(2) * 2 * s),
|
||||
[0; 4],
|
||||
),
|
||||
]
|
||||
}
|
||||
Packing::Packed422(order_of) => vec![(
|
||||
PlaneKind::Packed422,
|
||||
0,
|
||||
None,
|
||||
(y0, y1),
|
||||
(x0 / 2 * 4, x1.div_ceil(2) * 4),
|
||||
order_of,
|
||||
)],
|
||||
Packing::Rgb32(order_of) => {
|
||||
vec![(
|
||||
PlaneKind::Rgb32,
|
||||
0,
|
||||
None,
|
||||
(y0, y1),
|
||||
(x0 * 4, x1 * 4),
|
||||
order_of,
|
||||
)]
|
||||
}
|
||||
};
|
||||
let mut plane_passes = Vec::with_capacity(planes.len());
|
||||
for (kind, index, chroma, rows, (first_byte, end_byte), order_of) in planes {
|
||||
let plane = destination.get(index).ok_or(TooLarge)?;
|
||||
small(plane.end().ok_or(TooLarge)?)?;
|
||||
let mut pass = p;
|
||||
pass.plane_kind = kind as u32;
|
||||
pass.plane_order = order(order_of)?;
|
||||
pass.plane_offset = small(plane.offset)?;
|
||||
pass.plane_pitch = small(plane.pitch)?;
|
||||
if let Some(index) = chroma {
|
||||
let plane = destination.get(index).ok_or(TooLarge)?;
|
||||
small(plane.end().ok_or(TooLarge)?)?;
|
||||
pass.chroma_plane_offset = small(plane.offset)?;
|
||||
pass.chroma_plane_pitch = small(plane.pitch)?;
|
||||
}
|
||||
pass.first_byte = first_byte;
|
||||
pass.end_byte = end_byte;
|
||||
pass.words = (end_byte - (first_byte & !3)).div_ceil(4);
|
||||
plane_passes.push((pass, rows));
|
||||
}
|
||||
// A plane's rows `rows` of a band of the window's `[y0, y1)`: the window's for a luma or RGB
|
||||
// plane, the chroma rows a 4:2:0 plane's luma rows share. A band past the first starts on an
|
||||
// even row, so a chroma row lies in one band.
|
||||
let halved = [
|
||||
PlaneKind::Chroma8,
|
||||
PlaneKind::Chroma16,
|
||||
PlaneKind::Biplanar8,
|
||||
PlaneKind::Biplanar16,
|
||||
]
|
||||
.map(|kind| kind as u32);
|
||||
let band_rows = |kind: u32, (first, end): (u32, u32), (b0, b1): (u32, u32)| {
|
||||
if halved.contains(&kind) {
|
||||
(first.max(b0 / 2), end.min(b1.div_ceil(2)))
|
||||
} else {
|
||||
(first.max(b0), end.min(b1))
|
||||
}
|
||||
};
|
||||
// Separable where a pixel takes more than one pixel each way: the lines span the columns the
|
||||
// across taps take, the chroma's among them, and the pixels the adaptive filter reads.
|
||||
let taken = (across.iter().chain(chroma_across_table.iter().flatten()))
|
||||
.filter(|(_, w)| *w != 0.0)
|
||||
.map(|(i, _)| *i);
|
||||
let read = (p.adapt_across != 0).then_some([p.across_span_first, p.across_span_last]);
|
||||
let taken = taken.chain(read.into_iter().flatten());
|
||||
let columns = taken.clone().min().zip(taken.max());
|
||||
let separable = (across_count.max(p.chroma_across_count) > 1
|
||||
&& down_count.max(p.chroma_down_count) > 1)
|
||||
.then_some(columns)
|
||||
.flatten()
|
||||
.filter(|_| p.window_width > 0);
|
||||
// The bytes of one line: a float4 for an RGB source, three floats for a Y'CbCr source,
|
||||
// whose pixels are opaque.
|
||||
let line_bytes = if p.source_packing == 2 { 16 } else { 12 };
|
||||
let (bands, first, pitch) = match separable {
|
||||
Some((first, last)) => {
|
||||
let pitch = last - first + 1;
|
||||
let rows = LINES_BUDGET / line_bytes / pitch.to_usize();
|
||||
(
|
||||
bands((y0, y1), u32::try_from(rows).unwrap_or(u32::MAX), dy),
|
||||
first,
|
||||
pitch,
|
||||
)
|
||||
}
|
||||
None => (vec![(y0, y1)], 0, 0),
|
||||
};
|
||||
// The source rows each row of the window reads down: its taps' first and last, the chroma's
|
||||
// among them, and the six about its point where the pass down moves its sums.
|
||||
let row_runs: Vec<Option<(u32, u32)>> = (0..p.window_height)
|
||||
.map(|dy| {
|
||||
let mut rows: Vec<u32> = [&down, chroma_down_table.as_deref().unwrap_or(&[])]
|
||||
.iter()
|
||||
.flat_map(|table| {
|
||||
let count = table.len() / p.window_height.max(1).to_usize();
|
||||
(0..count).filter_map(move |k| {
|
||||
table
|
||||
.get(k * p.window_height.to_usize() + dy.to_usize())
|
||||
.filter(|(_, w)| *w != 0.0)
|
||||
.map(|(i, _)| *i)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
if p.adapt_down != 0 {
|
||||
let b = i64::from(down_points[dy.to_usize()].0.cast_signed());
|
||||
let six = |k: i64| {
|
||||
let row = (b - 2 + k)
|
||||
.clamp(i64::from(p.down_span_first), i64::from(p.down_span_last));
|
||||
u32::try_from(row).unwrap_or(0)
|
||||
};
|
||||
rows.extend([six(0), six(5)]);
|
||||
}
|
||||
rows.iter().copied().min().zip(rows.iter().copied().max())
|
||||
})
|
||||
.collect();
|
||||
let mut passes = Vec::new();
|
||||
let mut lines = 0usize;
|
||||
for band in bands {
|
||||
let mut lined = p;
|
||||
if separable.is_some() {
|
||||
lined.lines_first = first;
|
||||
lined.lines_pitch = pitch;
|
||||
lined.lines_row = band.0 - y0;
|
||||
lined.lines_rows = band.1 - band.0;
|
||||
let bytes = (lined.lines_rows.to_usize())
|
||||
.checked_mul(pitch.to_usize())
|
||||
.and_then(|n| n.checked_mul(line_bytes))
|
||||
.ok_or(TooLarge)?;
|
||||
small(bytes)?;
|
||||
lines = lines.max(bytes);
|
||||
let rows = lines_rows(&row_runs, (band.0 - y0, band.1 - y0));
|
||||
passes.push((
|
||||
Kernel::Lines,
|
||||
lined,
|
||||
(pitch, lined.lines_rows),
|
||||
(LINES_COLUMNS, rows),
|
||||
));
|
||||
}
|
||||
for (plane, rows) in &plane_passes {
|
||||
let (first_row, end_row) = band_rows(plane.plane_kind, *rows, band);
|
||||
if first_row >= end_row {
|
||||
continue;
|
||||
}
|
||||
let mut pass = *plane;
|
||||
(
|
||||
pass.lines_first,
|
||||
pass.lines_pitch,
|
||||
pass.lines_row,
|
||||
pass.lines_rows,
|
||||
) = (
|
||||
lined.lines_first,
|
||||
lined.lines_pitch,
|
||||
lined.lines_row,
|
||||
lined.lines_rows,
|
||||
);
|
||||
pass.first_row = first_row;
|
||||
pass.rows = end_row - first_row;
|
||||
let kernel = if separable.is_some() {
|
||||
// A reduction across of a plane whose words hold more than a pixel: each word's
|
||||
// pixels take lines far apart, which its threads read side by side a pixel each.
|
||||
if pitch > p.window_width && pass.plane_kind != PlaneKind::Rgb32 as u32 {
|
||||
Kernel::Shared
|
||||
} else {
|
||||
Kernel::Across
|
||||
}
|
||||
} else if across_count == 1
|
||||
&& down_count == 1
|
||||
&& pass.plane_kind == PlaneKind::Rgb32 as u32
|
||||
&& p.source_packing != 2
|
||||
{
|
||||
// A copy of a Y'CbCr source into RGB: two by two pixels share chroma samples.
|
||||
Kernel::Quads
|
||||
} else if p.adapt_across != 0 || p.adapt_down != 0 {
|
||||
Kernel::TransformAdaptive
|
||||
} else if pass.plane_kind == PlaneKind::Biplanar8 as u32
|
||||
|| pass.plane_kind == PlaneKind::Biplanar16 as u32
|
||||
{
|
||||
Kernel::TransformBothPlanes
|
||||
} else {
|
||||
Kernel::Transform
|
||||
};
|
||||
let threads = if kernel == Kernel::Quads {
|
||||
// Whole threadgroups: every thread of one reaches its barrier.
|
||||
(
|
||||
pass.words.div_ceil(2).next_multiple_of(GROUP.0),
|
||||
pass.rows.div_ceil(2).next_multiple_of(GROUP.1),
|
||||
)
|
||||
} else {
|
||||
(pass.words, pass.rows)
|
||||
};
|
||||
passes.push((kernel, pass, threads, GROUP));
|
||||
}
|
||||
}
|
||||
let mut table = across;
|
||||
table.extend(down);
|
||||
table.extend(chroma_across_table.into_iter().flatten());
|
||||
table.extend(chroma_down_table.into_iter().flatten());
|
||||
table.extend(across_points);
|
||||
table.extend(down_points);
|
||||
Ok(Work {
|
||||
passes,
|
||||
taps: table,
|
||||
lines,
|
||||
})
|
||||
}
|
||||
|
||||
/// The rows of a threadgroup of `scaler_lines` for the band `[b0, b1)` of the window's rows,
|
||||
/// each of which reads the source's rows `runs` gives, first and last: 16, where the run of the
|
||||
/// source's rows each 16 rows of the band read fits the pixels it decodes once
|
||||
/// ([`SHARED_PIXELS`]), as at a reduction of up to 2.5; else 8 ([`LINES_ROWS`]).
|
||||
fn lines_rows(runs: &[Option<(u32, u32)>], (b0, b1): (u32, u32)) -> u32 {
|
||||
const ROWS: u32 = LINES_ROWS[0];
|
||||
let run = |dy: u32| runs.get(dy.to_usize()).copied().flatten();
|
||||
let fits = (b0..b1).step_by(ROWS.to_usize()).all(|top| {
|
||||
let bottom = (top + ROWS).min(b1) - 1;
|
||||
let first = run(top).map(|(first, _)| first);
|
||||
let last = run(bottom).map(|(_, last)| last);
|
||||
match first.zip(last) {
|
||||
Some((first, last)) if first <= last => {
|
||||
(last - first + 1) * LINES_COLUMNS <= SHARED_PIXELS
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
});
|
||||
if fits { ROWS } else { LINES_ROWS[1] }
|
||||
}
|
||||
|
||||
/// The bands of the window's rows `[y0, y1)` of a separable transform: `rows` rows each at most,
|
||||
/// or `step` where `rows` is fewer, each past the first starting on a multiple of `step` (the
|
||||
/// destination's chroma rows), so that no chroma row spans two bands.
|
||||
pub(super) fn bands((y0, y1): (u32, u32), rows: u32, step: u32) -> Vec<(u32, u32)> {
|
||||
let step = step.max(1);
|
||||
let rows = (rows / step * step).max(step);
|
||||
let mut out = Vec::new();
|
||||
let mut start = y0;
|
||||
while start < y1 {
|
||||
// To the multiple of `step` `rows` past the band's first group's start.
|
||||
let end = (start / step)
|
||||
.saturating_mul(step)
|
||||
.saturating_add(rows)
|
||||
.min(y1);
|
||||
out.push((start, end));
|
||||
start = end;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The taps' bytes, as the kernel reads them: each an index and a weight, little-endian.
|
||||
pub(super) fn taps_bytes(taps: &[(u32, f32)]) -> impl Iterator<Item = u8> + '_ {
|
||||
taps.iter()
|
||||
.flat_map(|(i, w)| i.to_le_bytes().into_iter().chain(w.to_bits().to_le_bytes()))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,473 +0,0 @@
|
||||
use reims_vgpu_video_core::scaler::format::ScalerFormat;
|
||||
use reims_vgpu_video_core::scaler::plan::{FormatOf, Orientation, Plan};
|
||||
use reims_vgpu_video_core::scaler::request::{
|
||||
FIXED_ONE, FixedRect, Rect, Transform, TransformFlags,
|
||||
};
|
||||
use reims_vgpu_video_core::surfaces::{PlaneLayout, SurfaceLayout};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A surface's layout of `format`, `width` by `height`, its rows `pitch` bytes apart and a
|
||||
/// biplanar format's chroma at `chroma`.
|
||||
fn layout(
|
||||
format: ScalerFormat,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pitch: usize,
|
||||
chroma: usize,
|
||||
) -> SurfaceLayout {
|
||||
let planes = match format.packing() {
|
||||
Packing::Biplanar420 => vec![
|
||||
PlaneLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: pitch,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
PlaneLayout {
|
||||
offset: chroma,
|
||||
bytes_per_row: pitch,
|
||||
width: width.div_ceil(2),
|
||||
height: height.div_ceil(2),
|
||||
},
|
||||
],
|
||||
_ => Vec::new(),
|
||||
};
|
||||
SurfaceLayout {
|
||||
pixel_format: format.fourcc(),
|
||||
width,
|
||||
height,
|
||||
planes,
|
||||
bytes_per_row: pitch,
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan of a transform into `rect` with `flags`, from the source window of `rect`'s size at
|
||||
/// the source's origin.
|
||||
fn plan(source: &SurfaceLayout, destination: &SurfaceLayout, flags: u64, rect: Rect) -> Plan {
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(flags),
|
||||
source_rect: FixedRect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: u64::from(rect.width) * FIXED_ONE,
|
||||
height: u64::from(rect.height) * FIXED_ONE,
|
||||
},
|
||||
destination_rect: rect,
|
||||
..Transform::default()
|
||||
};
|
||||
Plan::new(&transform, source, destination).unwrap()
|
||||
}
|
||||
|
||||
fn bound(plan_of: &FormatOf) -> Vec<BoundPlane> {
|
||||
plan_of
|
||||
.planes
|
||||
.iter()
|
||||
.map(|p| BoundPlane::at(p, 0).unwrap())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The parameters are the shader's `ScalerParams`, word for word: 92 words, each field where
|
||||
/// the shader reads it
|
||||
#[test]
|
||||
fn the_parameters_are_the_shaders_words() {
|
||||
let p = Params {
|
||||
source_packing: 1,
|
||||
source_order: [2, 3, 4, 5],
|
||||
luma_map: [-1, 0, 7, 0, 1, 0],
|
||||
source_subsample_y: 21,
|
||||
chroma_origin_x: 6,
|
||||
chroma_last_y: 8,
|
||||
rgb: 9,
|
||||
linear: 17,
|
||||
across_first: 10,
|
||||
plane_kind: 11,
|
||||
plane_order: [12, 13, 14, 15],
|
||||
words: 16,
|
||||
code_max: 1023.0,
|
||||
lines_first: 18,
|
||||
lines_rows: 19,
|
||||
chroma_plane_pitch: 20,
|
||||
chroma_across_first: 22,
|
||||
ycbcr_to_rgb: 23,
|
||||
across_points_first: 24,
|
||||
adaptive_channels: 25,
|
||||
adaptive_scale: 0.5,
|
||||
..Params::default()
|
||||
};
|
||||
let bytes = p.bytes();
|
||||
assert_eq!(bytes.len(), PARAMS_WORDS * 4);
|
||||
let word = |at: usize| u32::from_le_bytes(bytes[at * 4..at * 4 + 4].try_into().unwrap());
|
||||
assert_eq!(word(0), 1);
|
||||
assert_eq!([word(2), word(3), word(4), word(5)], [2, 3, 4, 5]);
|
||||
assert_eq!(word(14), u32::MAX);
|
||||
assert_eq!(word(16), 7);
|
||||
assert_eq!(word(23), 21);
|
||||
assert_eq!((word(26), word(29)), (6, 8));
|
||||
assert_eq!((word(30), word(31)), (9, 17));
|
||||
assert_eq!(word(40), 10);
|
||||
assert_eq!(word(52), 11);
|
||||
assert_eq!([word(53), word(54), word(55), word(56)], [12, 13, 14, 15]);
|
||||
assert_eq!(word(63), 16);
|
||||
assert_eq!(f32::from_bits(word(68)), 1023.0);
|
||||
assert_eq!((word(69), word(72), word(74)), (18, 19, 20));
|
||||
assert_eq!((word(75), word(79)), (22, 23));
|
||||
assert_eq!((word(80), word(90)), (24, 25));
|
||||
assert_eq!(f32::from_bits(word(91)), 0.5);
|
||||
}
|
||||
|
||||
/// A format's codes read and are written as the reference's: 420v's luma from 16, 219 codes to
|
||||
/// 1, and its chroma about 128.125, 224 codes of 255 to 1 in 256; x420's luma into RGB from 64,
|
||||
/// 876 codes to 1
|
||||
#[test]
|
||||
fn codes_read_and_are_written_as_the_references() {
|
||||
let close = |a: f64, b: f64| (a - b).abs() < 1e-6;
|
||||
let v = ScalerFormat::Nv12VideoRange;
|
||||
let ((low, scale), (middle, chroma_scale)) = decoding(v, Space::YCbCr);
|
||||
assert!(
|
||||
close(low, 16.0) && close(scale, 1.0 / 219.0),
|
||||
"{low} {scale}"
|
||||
);
|
||||
assert!(
|
||||
close(middle, 128.125) && close(chroma_scale, 255.0 / (224.0 * 256.0)),
|
||||
"{middle} {chroma_scale}"
|
||||
);
|
||||
let ((low, span), (middle, chroma_span)) = encoding(v);
|
||||
assert!(close(low, 16.0) && close(span, 219.0), "{low} {span}");
|
||||
assert!(close(middle, 128.125) && close(chroma_span, 224.0 * 256.0 / 255.0));
|
||||
let ((low, scale), _) = decoding(ScalerFormat::P010VideoRange, Space::Rgb);
|
||||
assert!(
|
||||
close(low, 64.0) && close(scale, 1.0 / 876.0),
|
||||
"{low} {scale}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Each orientation's map takes the turned picture's pixels to the source's as the reference
|
||||
/// turns it: `source_point` at each pixel's centre
|
||||
#[test]
|
||||
fn a_turn_maps_each_pixel_as_the_reference_turns_it() {
|
||||
let (w, h) = (5u32, 3u32);
|
||||
for bits in 0..8 {
|
||||
let o = Orientation::from_bits(bits);
|
||||
let m = turn_map(o, w, h).unwrap();
|
||||
let (tw, th) = if o.rotates() { (h, w) } else { (w, h) };
|
||||
for y in 0..th {
|
||||
for x in 0..tw {
|
||||
let (sx, sy) = o.source_point(
|
||||
f64::from(x) + 0.5,
|
||||
f64::from(y) + 0.5,
|
||||
f64::from(w),
|
||||
f64::from(h),
|
||||
);
|
||||
let (x, y) = (i64::from(x), i64::from(y));
|
||||
let mapped = (
|
||||
i64::from(m[0]) * x + i64::from(m[1]) * y + i64::from(m[2]),
|
||||
i64::from(m[3]) * x + i64::from(m[4]) * y + i64::from(m[5]),
|
||||
);
|
||||
#[expect(clippy::as_conversions, clippy::cast_possible_truncation)]
|
||||
let expected = (sx.floor() as i64, sy.floor() as i64);
|
||||
assert_eq!(mapped, expected, "orientation {bits} at ({x}, {y})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An axis's taps are merged by pixel, without zero weights, divided by their sum, and padded
|
||||
/// with zero weights to the most a pixel has
|
||||
#[test]
|
||||
fn an_axis_s_taps_are_merged_normalized_and_padded() {
|
||||
let (count, table) =
|
||||
axis(&[vec![(0, 1.0), (0, 1.0), (1, 2.0)], vec![(3, 0.0), (4, 4.0)]]).unwrap();
|
||||
assert_eq!(count, 2);
|
||||
assert_eq!(table, [(0, 0.5), (4, 1.0), (1, 0.5), (4, 0.0)]);
|
||||
}
|
||||
|
||||
/// A 4:2:0 window is one dispatch for both planes, over the chroma rows and the words of its
|
||||
/// coverage, the luma words of the same pixels with them. The plan starts it on an even pixel and
|
||||
/// spans even pixels, so (3, 5) 10x7 is (2, 4) 10x6, its first word in part
|
||||
#[test]
|
||||
fn a_biplanar_window_is_a_dispatch_over_its_coverage() {
|
||||
let n = ScalerFormat::Nv12VideoRange;
|
||||
let source = layout(n, 64, 32, 64, 2048);
|
||||
let destination = layout(n, 64, 32, 64, 2048);
|
||||
let rect = Rect {
|
||||
x: 3,
|
||||
y: 5,
|
||||
width: 10,
|
||||
height: 7,
|
||||
};
|
||||
let plan = plan(&source, &destination, 0, rect);
|
||||
let work = work(
|
||||
&plan,
|
||||
&bound(&plan.source_format),
|
||||
&bound(&plan.destination_format),
|
||||
)
|
||||
.unwrap();
|
||||
let [(Kernel::TransformBothPlanes, both, threads, _)] = work.passes.as_slice() else {
|
||||
panic!("one pass: {:?}", work.passes.len());
|
||||
};
|
||||
assert_eq!(both.plane_kind, PlaneKind::Biplanar8 as u32);
|
||||
assert_eq!((both.first_row, both.rows), (2, 3), "chroma rows 2 to 4");
|
||||
assert_eq!((both.first_byte, both.end_byte), (2, 12), "pixels 2 to 11");
|
||||
assert_eq!(both.words, 3, "bytes 0 to 11");
|
||||
assert_eq!(*threads, (3, 3));
|
||||
assert_eq!((both.plane_offset, both.chroma_plane_offset), (0, 2048));
|
||||
assert_eq!((both.plane_pitch, both.chroma_plane_pitch), (64, 64));
|
||||
assert_eq!(work.lines, 0, "a copy takes a pixel a pixel");
|
||||
// The taps of a copy: one a pixel, of weight 1; then each pixel's sample point, on a
|
||||
// pixel, which the adaptive filter, with no pass to move, does not read.
|
||||
assert_eq!(both.across_count, 1);
|
||||
assert_eq!(both.down_first, 10);
|
||||
assert!(work.taps[..16].iter().all(|&(_, w)| w == 1.0));
|
||||
assert_eq!((both.across_points_first, both.down_points_first), (16, 26));
|
||||
assert!(work.taps[16..].iter().all(|&(_, f)| f == 0.0));
|
||||
assert_eq!((both.adapt_across, both.adapt_down), (0, 0));
|
||||
}
|
||||
|
||||
/// A transform the adaptive filter moves and that is not separable, here a halving across alone,
|
||||
/// runs `scaler_transform_adaptive`, and one it does not move `scaler_transform`
|
||||
#[test]
|
||||
fn a_moved_transform_runs_the_adaptive_kernel() {
|
||||
let bgra = ScalerFormat::Bgra;
|
||||
let (source, half, whole) = (
|
||||
layout(bgra, 64, 32, 256, 0),
|
||||
layout(bgra, 32, 32, 128, 0),
|
||||
layout(bgra, 64, 32, 256, 0),
|
||||
);
|
||||
let kernels = |destination: &SurfaceLayout| {
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(0x1000),
|
||||
..Transform::default()
|
||||
};
|
||||
let plan = Plan::new(&transform, &source, destination).unwrap();
|
||||
let work = work(
|
||||
&plan,
|
||||
&bound(&plan.source_format),
|
||||
&bound(&plan.destination_format),
|
||||
)
|
||||
.unwrap();
|
||||
work.passes
|
||||
.iter()
|
||||
.map(|(kernel, pass, _, _)| (*kernel, pass.adapt_across, pass.adapt_down))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(kernels(&half), [(Kernel::TransformAdaptive, 1, 0)]);
|
||||
assert_eq!(kernels(&whole), [(Kernel::Transform, 0, 0)]);
|
||||
}
|
||||
|
||||
/// A copy of a 4:2:0 source into BGRA is a dispatch of whole threadgroups of `scaler_quads`, a
|
||||
/// thread two by two of the window's pixels
|
||||
#[test]
|
||||
fn a_copy_into_rgb_is_whole_threadgroups_of_quads() {
|
||||
let source = layout(ScalerFormat::Nv12VideoRange, 64, 32, 64, 2048);
|
||||
let destination = layout(ScalerFormat::Bgra, 64, 32, 256, 0);
|
||||
let rect = Rect {
|
||||
x: 3,
|
||||
y: 5,
|
||||
width: 36,
|
||||
height: 10,
|
||||
};
|
||||
let plan = plan(&source, &destination, 0, rect);
|
||||
let work = work(
|
||||
&plan,
|
||||
&bound(&plan.source_format),
|
||||
&bound(&plan.destination_format),
|
||||
)
|
||||
.unwrap();
|
||||
let [(Kernel::Quads, rgb, threads, group)] = work.passes.as_slice() else {
|
||||
panic!("one pass of quads: {:?}", work.passes);
|
||||
};
|
||||
assert_eq!((rgb.first_row, rgb.rows), (5, 10));
|
||||
assert_eq!((rgb.first_byte, rgb.end_byte), (12, 156));
|
||||
assert_eq!(rgb.words, 36);
|
||||
// 18 quads across and 5 down, in threadgroups of 16 by 4.
|
||||
assert_eq!((*threads, *group), ((32, 8), GROUP));
|
||||
assert_eq!(work.lines, 0);
|
||||
}
|
||||
|
||||
/// A 4:2:0 window of an odd edge, one under two pixels, which the plan keeps as it is, is a
|
||||
/// dispatch a plane: its luma rows and bytes, and the chroma rows and pairs it shares
|
||||
#[test]
|
||||
fn an_odd_biplanar_window_is_a_dispatch_a_plane() {
|
||||
let n = ScalerFormat::Nv12VideoRange;
|
||||
let source = layout(n, 64, 32, 64, 2048);
|
||||
let destination = layout(n, 64, 32, 64, 2048);
|
||||
let rect = Rect {
|
||||
x: 3,
|
||||
y: 5,
|
||||
width: 1,
|
||||
height: 1,
|
||||
};
|
||||
let plan = plan(&source, &destination, 0, rect);
|
||||
let work = work(
|
||||
&plan,
|
||||
&bound(&plan.source_format),
|
||||
&bound(&plan.destination_format),
|
||||
)
|
||||
.unwrap();
|
||||
let [
|
||||
(Kernel::Transform, luma, luma_threads, _),
|
||||
(Kernel::Transform, chroma, chroma_threads, _),
|
||||
] = work.passes.as_slice()
|
||||
else {
|
||||
panic!("two passes: {:?}", work.passes.len());
|
||||
};
|
||||
assert_eq!(luma.plane_kind, PlaneKind::Luma8 as u32);
|
||||
assert_eq!((luma.first_row, luma.rows), (5, 1));
|
||||
assert_eq!((luma.first_byte, luma.end_byte), (3, 4));
|
||||
assert_eq!(*luma_threads, (1, 1));
|
||||
assert_eq!(chroma.plane_kind, PlaneKind::Chroma8 as u32);
|
||||
assert_eq!((chroma.first_row, chroma.rows), (2, 1));
|
||||
assert_eq!((chroma.first_byte, chroma.end_byte), (2, 4), "pair 1");
|
||||
assert_eq!(*chroma_threads, (1, 1));
|
||||
assert_eq!(chroma.plane_offset, 2048);
|
||||
}
|
||||
|
||||
/// An offset past 4 GiB, which the kernel's 32-bit offsets do not reach, is too large
|
||||
#[test]
|
||||
fn a_plane_past_the_kernels_offsets_is_too_large() {
|
||||
let b = ScalerFormat::Bgra;
|
||||
let source = layout(b, 64, 32, 256, 0);
|
||||
let plan = plan(&source, &source, 0, Rect::default());
|
||||
let far = |planes: Vec<BoundPlane>| {
|
||||
planes
|
||||
.into_iter()
|
||||
.map(|p| BoundPlane {
|
||||
offset: p.offset + (1 << 32),
|
||||
..p
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let near = bound(&plan.source_format);
|
||||
assert!(work(&plan, &near, &near).is_ok());
|
||||
assert_eq!(work(&plan, &far(near.clone()), &near), Err(TooLarge));
|
||||
assert_eq!(work(&plan, &near, &far(near.clone())), Err(TooLarge));
|
||||
}
|
||||
|
||||
/// A separable transform's bands cover the window's rows once each, in order, each of the rows
|
||||
/// the lines buffer holds at most, a band past the first from a multiple of the chroma's rows;
|
||||
/// where it holds fewer, a pair of rows a band
|
||||
#[test]
|
||||
fn a_tall_windows_bands_cover_its_rows() {
|
||||
for (rows, step) in [(0u32, 2u32), (1, 2), (7, 2), (10, 1), (1000, 2)] {
|
||||
let bands = bands((3, 42), rows, step);
|
||||
let mut next = 3;
|
||||
for &(b0, b1) in &bands {
|
||||
assert_eq!(b0, next, "{rows} {step}");
|
||||
assert!(b1 > b0);
|
||||
assert!(b0 == 3 || b0 % step == 0, "{rows} {step}: {b0}");
|
||||
assert!(b1 - b0 <= rows.max(step), "{rows} {step}: {b0}..{b1}");
|
||||
next = b1;
|
||||
}
|
||||
assert_eq!(next, 42, "{rows} {step}");
|
||||
}
|
||||
assert_eq!(bands((3, 42), 1, 2)[..2], [(3, 4), (4, 6)]);
|
||||
assert_eq!(bands((3, 42), 7, 2)[..2], [(3, 8), (8, 14)]);
|
||||
assert_eq!(bands((3, 42), 1000, 2), [(3, 42)]);
|
||||
}
|
||||
|
||||
/// A 4:2:0 reduction is separable: its lines' dispatch first, over the columns of the source the
|
||||
/// window's taps take and the window's rows, then its planes', which read the lines
|
||||
#[test]
|
||||
fn a_reduction_runs_its_lines_then_its_planes() {
|
||||
let n = ScalerFormat::Nv12VideoRange;
|
||||
let source = layout(n, 64, 32, 64, 2048);
|
||||
let destination = layout(n, 32, 16, 64, 2048);
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(0x1000),
|
||||
..Transform::default()
|
||||
};
|
||||
let plan = Plan::new(&transform, &source, &destination).unwrap();
|
||||
let work = work(
|
||||
&plan,
|
||||
&bound(&plan.source_format),
|
||||
&bound(&plan.destination_format),
|
||||
)
|
||||
.unwrap();
|
||||
let [
|
||||
(Kernel::Lines, lines, lines_threads, lines_group),
|
||||
(Kernel::Shared, both, _, group),
|
||||
] = work.passes.as_slice()
|
||||
else {
|
||||
panic!("two passes: {:?}", work.passes.len());
|
||||
};
|
||||
assert_eq!((lines.lines_first, lines.lines_pitch), (0, 64));
|
||||
assert_eq!(
|
||||
(lines.lines_row, lines.lines_rows),
|
||||
(0, 16),
|
||||
"every row of the window"
|
||||
);
|
||||
assert_eq!(*lines_threads, (64, 16));
|
||||
assert_eq!(
|
||||
work.lines,
|
||||
64 * 16 * 12,
|
||||
"three floats a line: a Y'CbCr source is opaque"
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
both.lines_first,
|
||||
both.lines_pitch,
|
||||
both.lines_row,
|
||||
both.lines_rows
|
||||
),
|
||||
(0, 64, 0, 16)
|
||||
);
|
||||
// The 32 rows of the source 16 rows of the window take fit what a threadgroup of the lines
|
||||
// decodes once.
|
||||
assert_eq!((*lines_group, *group), ((16, 16), (16, 4)));
|
||||
assert_eq!(both.plane_kind, PlaneKind::Biplanar8 as u32);
|
||||
assert_eq!((both.first_row, both.rows), (0, 8), "every chroma row");
|
||||
}
|
||||
|
||||
/// Every kernel and threadgroup a transform dispatches is one the making ahead dispatches
|
||||
/// ([`DISPATCHED`]), and each of those some transform dispatches: over every pair of formats,
|
||||
/// copies, turns, reductions and enlargements of each axis, by 2 and by 4
|
||||
#[test]
|
||||
fn every_dispatch_is_one_the_making_ahead_makes() {
|
||||
let mut taken = Vec::new();
|
||||
for from in ScalerFormat::ALL {
|
||||
for to in ScalerFormat::ALL {
|
||||
let source = layout(from, 96, 64, 512, 16384);
|
||||
for ((width, height), flags) in [
|
||||
((96, 64), 0x1000),
|
||||
((64, 96), 0x1004),
|
||||
((48, 32), 0x1000),
|
||||
((24, 16), 0x1000),
|
||||
((96, 32), 0x1000),
|
||||
((48, 64), 0x1000),
|
||||
((192, 128), 0x1000),
|
||||
((96, 128), 0x1000),
|
||||
((192, 64), 0x1000),
|
||||
((32, 48), 0x1004),
|
||||
] {
|
||||
let destination = layout(to, width, height, 1024, 32768);
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(flags),
|
||||
..Transform::default()
|
||||
};
|
||||
let Ok(plan) = Plan::new(&transform, &source, &destination) else {
|
||||
continue;
|
||||
};
|
||||
let work = work(
|
||||
&plan,
|
||||
&bound(&plan.source_format),
|
||||
&bound(&plan.destination_format),
|
||||
)
|
||||
.unwrap();
|
||||
for (kernel, _, _, group) in work.passes {
|
||||
assert!(
|
||||
DISPATCHED.contains(&(kernel, group)),
|
||||
"{kernel:?} at {group:?} is not made ahead"
|
||||
);
|
||||
taken.push((kernel, group));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for dispatched in DISPATCHED {
|
||||
assert!(
|
||||
taken.contains(&dispatched),
|
||||
"{dispatched:?} is made for none"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,792 +0,0 @@
|
||||
//! The kernel against core's reference, on every GPU the host's tests reach: Metal on macOS, the
|
||||
//! Vulkan platform's runtime where the crate has it (MoltenVK on macOS). Each GPU test says which
|
||||
//! GPU it ran on, and skips a GPU the host has none of, saying so.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use reims_vgpu_core::num::ToU64 as _;
|
||||
use reims_vgpu_core::platform::Platform as _;
|
||||
use reims_vgpu_core::platform::os::surface::{SurfacePlaneSpec, SurfaceSpec};
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_video_core::device_memory::DeviceMemory;
|
||||
use reims_vgpu_video_core::runtime::StdRuntime;
|
||||
use reims_vgpu_video_core::scaler::format::{Packing, ScalerFormat};
|
||||
use reims_vgpu_video_core::scaler::plan::{FormatOf, Matrix, Plan, Siting};
|
||||
use reims_vgpu_video_core::scaler::reference::{self, Space};
|
||||
use reims_vgpu_video_core::scaler::request::{
|
||||
FIXED_ONE, FixedRect, Rect, Transform, TransformFlags,
|
||||
};
|
||||
use reims_vgpu_video_core::surfaces::{GuestSurface, PlaneLayout, SurfaceLayout};
|
||||
|
||||
use super::*;
|
||||
use crate::platform::ApiPlatform as _;
|
||||
|
||||
/// The kernel on each GPU this host's tests reach, taking sides from 1, by name.
|
||||
fn gpus() -> Vec<(String, Arc<dyn ScalerBackend>)> {
|
||||
let runtime = StdRuntime::shared();
|
||||
let mut out: Vec<(String, Arc<dyn ScalerBackend>)> = Vec::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let gpu = metal::MetalGpu::process().expect("Metal opens the kernel");
|
||||
let name = format!("Metal, {}", gpu.name());
|
||||
let backend = GpuScalerBackend::new(gpu, Arc::clone(&runtime)).with_smallest_side(1);
|
||||
out.push((name, Arc::new(backend)));
|
||||
}
|
||||
#[cfg(vulkan_platform)]
|
||||
match vulkan::VulkanGpu::process(&runtime) {
|
||||
Ok(gpu) => {
|
||||
let name = format!("Vulkan, {}", gpu.name());
|
||||
let backend = GpuScalerBackend::new(gpu, Arc::clone(&runtime)).with_smallest_side(1);
|
||||
out.push((name, Arc::new(backend)));
|
||||
}
|
||||
Err(why) => eprintln!("no Vulkan GPU: {why}; skipped"),
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A surface of the test's own memory, which counts its lends.
|
||||
struct Memory {
|
||||
layout: SurfaceLayout,
|
||||
bytes: Mutex<Vec<u8>>,
|
||||
lends: AtomicUsize,
|
||||
}
|
||||
|
||||
impl GuestSurface for Memory {
|
||||
fn layout(&self) -> SurfaceLayout {
|
||||
self.layout.clone()
|
||||
}
|
||||
|
||||
fn write(&self, write: &mut dyn FnMut(&mut [u8])) -> Result<(), SurfaceError> {
|
||||
self.lends.fetch_add(1, Ordering::Relaxed);
|
||||
write(&mut self.bytes.lock());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read(&self, read: &mut dyn FnMut(&[u8])) -> Result<(), SurfaceError> {
|
||||
self.lends.fetch_add(1, Ordering::Relaxed);
|
||||
read(&self.bytes.lock());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A layout of `format`, `width` by `height`: rows rounded up to `align` bytes, a biplanar
|
||||
/// format's chroma after its luma, at a multiple of `align` plus `skew`.
|
||||
fn layout(
|
||||
format: ScalerFormat,
|
||||
width: u32,
|
||||
height: u32,
|
||||
align: usize,
|
||||
skew: usize,
|
||||
) -> SurfaceLayout {
|
||||
let row = |bytes: usize| bytes.div_ceil(align) * align;
|
||||
let (w, h) = (width.to_usize(), height.to_usize());
|
||||
let s = format.bytes_per_sample();
|
||||
match format.packing() {
|
||||
Packing::Biplanar420 => {
|
||||
let luma = row(w * s);
|
||||
let chroma = row(w.div_ceil(2) * 2 * s);
|
||||
SurfaceLayout {
|
||||
pixel_format: format.fourcc(),
|
||||
width,
|
||||
height,
|
||||
planes: vec![
|
||||
PlaneLayout {
|
||||
offset: 0,
|
||||
bytes_per_row: luma,
|
||||
width,
|
||||
height,
|
||||
},
|
||||
PlaneLayout {
|
||||
offset: row(luma * h) + skew,
|
||||
bytes_per_row: chroma,
|
||||
width: width.div_ceil(2),
|
||||
height: height.div_ceil(2),
|
||||
},
|
||||
],
|
||||
bytes_per_row: luma,
|
||||
}
|
||||
}
|
||||
Packing::Packed422(_) => SurfaceLayout {
|
||||
pixel_format: format.fourcc(),
|
||||
width,
|
||||
height,
|
||||
planes: Vec::new(),
|
||||
bytes_per_row: row(w.div_ceil(2) * 4),
|
||||
},
|
||||
Packing::Rgb32(_) => SurfaceLayout {
|
||||
pixel_format: format.fourcc(),
|
||||
width,
|
||||
height,
|
||||
planes: Vec::new(),
|
||||
bytes_per_row: row(w * 4),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes a layout's planes span.
|
||||
fn length(layout: &SurfaceLayout) -> usize {
|
||||
let of = FormatOf::of(layout).unwrap();
|
||||
extent(&of).unwrap().next_multiple_of(64)
|
||||
}
|
||||
|
||||
/// `layout`'s bytes holding the test picture, or `rgb` flat.
|
||||
fn picture_bytes(layout: &SurfaceLayout, rgb: Option<[f64; 4]>) -> Vec<u8> {
|
||||
let of = FormatOf::of(layout).unwrap();
|
||||
let mut bytes = vec![0u8; length(layout)];
|
||||
let (w, h) = (layout.width.to_usize(), layout.height.to_usize());
|
||||
let picture = match rgb {
|
||||
Some(rgb) => reference::flat_picture(w, h, rgb),
|
||||
None => reference::test_picture(w, h),
|
||||
};
|
||||
reference::encode(
|
||||
&of,
|
||||
&mut bytes,
|
||||
&picture,
|
||||
0,
|
||||
0,
|
||||
Space::Rgb,
|
||||
Matrix::Bt601,
|
||||
Siting::CENTRED,
|
||||
);
|
||||
bytes
|
||||
}
|
||||
|
||||
fn memory(layout: SurfaceLayout, rgb: Option<[f64; 4]>) -> Memory {
|
||||
let bytes = picture_bytes(&layout, rgb);
|
||||
Memory {
|
||||
layout,
|
||||
bytes: Mutex::new(bytes),
|
||||
lends: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest difference between two surfaces of `of`, a sample at a time over each plane's
|
||||
/// samples, and how many samples differ.
|
||||
fn difference(of: &FormatOf, a: &[u8], b: &[u8]) -> (u32, usize) {
|
||||
let (mut largest, mut count) = (0u32, 0usize);
|
||||
let s = of.format.bytes_per_sample();
|
||||
for span in &of.planes {
|
||||
for row in 0..span.rows {
|
||||
let at = span.offset + row * span.bytes_per_row;
|
||||
for k in (0..span.row_bytes).step_by(s) {
|
||||
let sample = |bytes: &[u8]| {
|
||||
if s == 2 {
|
||||
u32::from(u16::from_le_bytes([bytes[at + k], bytes[at + k + 1]]) >> 6)
|
||||
} else {
|
||||
u32::from(bytes[at + k])
|
||||
}
|
||||
};
|
||||
let d = sample(a).abs_diff(sample(b));
|
||||
largest = largest.max(d);
|
||||
count += usize::from(d != 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
(largest, count)
|
||||
}
|
||||
|
||||
/// One transform of a sweep: its name, the surfaces, and its flags and windows.
|
||||
struct Case {
|
||||
name: String,
|
||||
source: SurfaceLayout,
|
||||
destination: SurfaceLayout,
|
||||
flags: u64,
|
||||
crop: FixedRect,
|
||||
rect: Rect,
|
||||
}
|
||||
|
||||
/// The plan of `transform`, as the device makes it, but for a pair of formats Apple's scaler
|
||||
/// refuses, which the device refuses (`format::apple_refuses`) and the kernel does all the same.
|
||||
fn plan(
|
||||
transform: &Transform,
|
||||
source: &SurfaceLayout,
|
||||
destination: &SurfaceLayout,
|
||||
) -> Result<Plan, IoReturn> {
|
||||
let planned = Plan::new(transform, source, destination);
|
||||
match planned {
|
||||
Err(io_return::UNSUPPORTED) => Plan::of_any_pair(transform, source, destination),
|
||||
planned => planned,
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `case` on `backend`, from the test picture into a destination of mid grey; the largest
|
||||
/// difference from the reference and how many samples differ, or the status.
|
||||
fn run(accelerator: &mut dyn Accelerator, case: &Case) -> Result<(u32, usize, u64), IoReturn> {
|
||||
let source = memory(case.source.clone(), None);
|
||||
let destination = memory(case.destination.clone(), Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(case.flags),
|
||||
source_rect: case.crop,
|
||||
destination_rect: case.rect,
|
||||
..Transform::default()
|
||||
};
|
||||
let plan = plan(&transform, &source.layout, &destination.layout)?;
|
||||
let mut expected = destination.bytes.lock().clone();
|
||||
reference::run(&plan, &source.bytes.lock(), &mut expected)?;
|
||||
let mut job = TransformJob {
|
||||
transform: &transform,
|
||||
plan: plan.clone(),
|
||||
source: &source,
|
||||
destination: &destination,
|
||||
hold: GuestHold::nothing(),
|
||||
inputs: Default::default(),
|
||||
outputs: Default::default(),
|
||||
};
|
||||
match accelerator.transform(&mut job) {
|
||||
io_return::SUCCESS => {}
|
||||
status => return Err(status),
|
||||
}
|
||||
let out = destination.bytes.lock().clone();
|
||||
let (largest, count) = difference(&plan.destination_format, &out, &expected);
|
||||
Ok((largest, count, digest(&out)))
|
||||
}
|
||||
|
||||
/// A digest of `bytes`, FNV-1a's of 64 bits: two builds whose kernels write the same bytes print
|
||||
/// the same digests.
|
||||
fn digest(bytes: &[u8]) -> u64 {
|
||||
(bytes.iter()).fold(0xcbf2_9ce4_8422_2325, |h, &b| {
|
||||
(h ^ u64::from(b)).wrapping_mul(0x0100_0000_01b3)
|
||||
})
|
||||
}
|
||||
|
||||
/// Every pair of formats, through each kind of transform: copies at an odd size, scales down and
|
||||
/// up, a quarter turn, a flip, a crop at a fraction, an odd window, and the nearest filter (which
|
||||
/// filters as the smooth one, as Apple's scaler does), each within a code of the reference a
|
||||
/// sample, and exact where the reference only moves samples: copies and flips of a format into
|
||||
/// itself, its quarter turns but for 4:2:2's, whose chroma the turn resamples, and copies, flips
|
||||
/// and turns between RGB formats. The pairs the device refuses as Apple's scaler does run too, on
|
||||
/// plans made by hand. Prints each case's largest difference, how many samples differ and a
|
||||
/// digest of the destination's bytes, for the record, and to tell two builds' outputs apart.
|
||||
#[test]
|
||||
fn every_pair_of_formats_is_within_a_code_of_the_reference() {
|
||||
let fixed = |x: f64, y: f64, w: f64, h: f64| {
|
||||
let f = |v: f64| {
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss
|
||||
)]
|
||||
let v = (v * FIXED_ONE as f64).round() as u64;
|
||||
v
|
||||
};
|
||||
FixedRect {
|
||||
x: f(x),
|
||||
y: f(y),
|
||||
width: f(w),
|
||||
height: f(h),
|
||||
}
|
||||
};
|
||||
let whole = FixedRect::default();
|
||||
let all = Rect::default();
|
||||
let mut failures = Vec::new();
|
||||
for (gpu, backend) in gpus() {
|
||||
let mut accelerator = backend.create_accelerator().unwrap();
|
||||
let mut inexact = 0;
|
||||
for from in ScalerFormat::ALL {
|
||||
for to in ScalerFormat::ALL {
|
||||
let n = name;
|
||||
let l = |f, w, h| layout(f, w, h, 64, 0);
|
||||
let kinds: [(&str, SurfaceLayout, SurfaceLayout, u64, FixedRect, Rect); 9] = [
|
||||
("copy", l(from, 37, 23), l(to, 37, 23), 0, whole, all),
|
||||
("down", l(from, 96, 54), l(to, 40, 22), 0x1000, whole, all),
|
||||
("up", l(from, 24, 14), l(to, 60, 34), 0x1000, whole, all),
|
||||
("transfer-up", l(from, 24, 14), l(to, 61, 35), 0, whole, all),
|
||||
("turn", l(from, 38, 22), l(to, 22, 38), 4, whole, all),
|
||||
("flip", l(from, 37, 23), l(to, 37, 23), 3, whole, all),
|
||||
(
|
||||
"crop",
|
||||
l(from, 64, 48),
|
||||
l(to, 30, 20),
|
||||
0x1000,
|
||||
fixed(5.5, 3.25, 40.0, 30.0),
|
||||
all,
|
||||
),
|
||||
(
|
||||
"window",
|
||||
l(from, 32, 24),
|
||||
l(to, 48, 40),
|
||||
0x1000,
|
||||
whole,
|
||||
Rect {
|
||||
x: 7,
|
||||
y: 5,
|
||||
width: 31,
|
||||
height: 25,
|
||||
},
|
||||
),
|
||||
("nearest", l(from, 64, 40), l(to, 40, 24), 0x80, whole, all),
|
||||
];
|
||||
for (kind, source, destination, flags, crop, rect) in kinds {
|
||||
let case = Case {
|
||||
name: format!("{kind} {} to {}", n(from), n(to)),
|
||||
source,
|
||||
destination,
|
||||
flags,
|
||||
crop,
|
||||
rect,
|
||||
};
|
||||
match run(accelerator.as_mut(), &case) {
|
||||
Ok((largest, count, digest)) => {
|
||||
println!(
|
||||
"{gpu}: {}: largest {largest}, {count} differ, digest {digest:016x}",
|
||||
case.name
|
||||
);
|
||||
let rgb = !from.is_ycbcr() && !to.is_ycbcr();
|
||||
let moves = match kind {
|
||||
"copy" | "flip" => true,
|
||||
"turn" => !matches!(from.packing(), Packing::Packed422(_)),
|
||||
_ => false,
|
||||
};
|
||||
let exact = moves && (from == to || rgb);
|
||||
if largest > 1 || (exact && largest > 0) {
|
||||
failures.push(format!("{gpu}: {}: largest {largest}", case.name));
|
||||
}
|
||||
inexact += usize::from(largest > 0);
|
||||
}
|
||||
Err(status) => {
|
||||
failures.push(format!("{gpu}: {}: status {status:#x}", case.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("{gpu}: {inexact} of {} cases not exact", 64 * 9);
|
||||
}
|
||||
assert!(failures.is_empty(), "{failures:#?}");
|
||||
}
|
||||
|
||||
/// A format's name as the suite prints it.
|
||||
fn name(format: ScalerFormat) -> String {
|
||||
reims_vgpu_video_conformance::scaler::format_name(format)
|
||||
}
|
||||
|
||||
/// The conformance suite's cases of small surfaces pass, the ones under Apple's smallest side
|
||||
/// among them, with the siting and map lines it prints
|
||||
#[test]
|
||||
fn the_suites_small_cases_pass() {
|
||||
let only: Vec<String> = [
|
||||
"siting", "map", "tiny-", "odd-", "rect-odd", "rotate-", "nearest-",
|
||||
]
|
||||
.map(str::to_owned)
|
||||
.to_vec();
|
||||
for (gpu, backend) in gpus() {
|
||||
assert!(
|
||||
reims_vgpu_video_conformance::scaler::check(backend.as_ref(), &gpu, &only, false),
|
||||
"{gpu}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole conformance suite, with its benches: run alone, in release, on each GPU
|
||||
/// (`cargo nextest run --release -p reims-vgpu -E 'test(/whole_suite/)' --run-ignored only
|
||||
/// --no-capture`), for the record in docs/video/scaler.md.
|
||||
#[test]
|
||||
#[ignore = "the whole suite, for the record: run alone, in release"]
|
||||
fn the_whole_suite() {
|
||||
for (gpu, backend) in gpus() {
|
||||
assert!(
|
||||
reims_vgpu_video_conformance::scaler::check(backend.as_ref(), &gpu, &[], true),
|
||||
"{gpu}"
|
||||
);
|
||||
bench_in_place(&gpu, backend.as_ref());
|
||||
}
|
||||
}
|
||||
|
||||
/// The suite's benches on surfaces of the platform's, as a guest's reach the device: each
|
||||
/// transform's wall time through the accelerator and its GPU time, the median of 20 after a
|
||||
/// first, and whether the surfaces were reached in place.
|
||||
fn bench_in_place(gpu: &str, backend: &dyn ScalerBackend) {
|
||||
use ScalerFormat::{Bgra, Nv12VideoRange};
|
||||
|
||||
let mut accelerator = backend.create_accelerator().unwrap();
|
||||
let runtime = StdRuntime::shared();
|
||||
let benches = [
|
||||
(
|
||||
"1080p 420v to 720p BGRA",
|
||||
Nv12VideoRange,
|
||||
(1920, 1080),
|
||||
Bgra,
|
||||
(1280, 720),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"2160p 420v to 1080p 420v",
|
||||
Nv12VideoRange,
|
||||
(3840, 2160),
|
||||
Nv12VideoRange,
|
||||
(1920, 1080),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"720p BGRA to 720p 420v",
|
||||
Bgra,
|
||||
(1280, 720),
|
||||
Nv12VideoRange,
|
||||
(1280, 720),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"1080p BGRA turned 90",
|
||||
Bgra,
|
||||
(1920, 1080),
|
||||
Bgra,
|
||||
(1080, 1920),
|
||||
0x1004,
|
||||
),
|
||||
(
|
||||
"2160p 420v to 2160p BGRA",
|
||||
Nv12VideoRange,
|
||||
(3840, 2160),
|
||||
Bgra,
|
||||
(3840, 2160),
|
||||
0x1000,
|
||||
),
|
||||
];
|
||||
for (label, from, (sw, sh), to, (dw, dh), flags) in benches {
|
||||
let (sl, dl) = (layout(from, sw, sh, 64, 0), layout(to, dw, dh, 64, 0));
|
||||
let source = platform_surface(sl.clone(), &picture_bytes(&sl, None), None);
|
||||
let grey = picture_bytes(&dl, Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let destination = platform_surface(dl.clone(), &grey, None);
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(flags),
|
||||
..Transform::default()
|
||||
};
|
||||
let plan = Plan::new(&transform, &sl, &dl).unwrap();
|
||||
let (mut wall, mut on_gpu) = (Vec::new(), Vec::new());
|
||||
for _ in 0..21 {
|
||||
let mut job = TransformJob {
|
||||
transform: &transform,
|
||||
plan: plan.clone(),
|
||||
source: &source,
|
||||
destination: &destination,
|
||||
hold: GuestHold::nothing(),
|
||||
inputs: Default::default(),
|
||||
outputs: Default::default(),
|
||||
};
|
||||
GPU_TIMES.lock().clear();
|
||||
let started = runtime.now();
|
||||
assert_eq!(
|
||||
accelerator.transform(&mut job),
|
||||
io_return::SUCCESS,
|
||||
"{gpu}: {label}"
|
||||
);
|
||||
wall.push(runtime.elapsed_since(started).as_secs_f64() * 1000.0);
|
||||
on_gpu.extend(GPU_TIMES.lock().iter().map(|t| t.as_secs_f64() * 1000.0));
|
||||
}
|
||||
let median = |times: &[f64]| {
|
||||
let mut rest = times.get(1..).unwrap_or_default().to_vec();
|
||||
rest.sort_by(f64::total_cmp);
|
||||
rest.get(rest.len() / 2).copied().unwrap_or(f64::NAN)
|
||||
};
|
||||
let lends =
|
||||
source.lends.load(Ordering::Relaxed) + destination.lends.load(Ordering::Relaxed);
|
||||
println!(
|
||||
"bench in place {label}: {gpu}: first {:.1} ms, median of 20 {:.1} ms wall, \
|
||||
{:.2} ms on the GPU, {}",
|
||||
wall[0],
|
||||
median(&wall),
|
||||
median(&on_gpu),
|
||||
if lends == 0 {
|
||||
"in place".to_owned()
|
||||
} else {
|
||||
format!("{lends} lends")
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Apple's sides, from 4 to 65536 each way, and ratios; a surface outside the sides is refused
|
||||
#[test]
|
||||
fn a_side_outside_apples_is_refused() {
|
||||
let caps = capabilities(SMALLEST_SIDE);
|
||||
assert_eq!(caps.min_source, 4);
|
||||
assert_eq!(caps.max_source, (65536, 65536));
|
||||
assert_eq!(caps.max_scale, [8, 8, 8, 4]);
|
||||
let runtime = StdRuntime::shared();
|
||||
#[cfg(target_os = "macos")]
|
||||
let gpu = Some(metal::MetalGpu::process().unwrap());
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let gpu = vulkan::VulkanGpu::process(&runtime).ok();
|
||||
let Some(gpu) = gpu else {
|
||||
eprintln!("no GPU: skipped");
|
||||
return;
|
||||
};
|
||||
let mut accelerator = GpuScalerBackend::new(gpu, runtime)
|
||||
.create_accelerator()
|
||||
.unwrap();
|
||||
let b = ScalerFormat::Bgra;
|
||||
let case = |source: SurfaceLayout, destination: SurfaceLayout| Case {
|
||||
name: "small".to_owned(),
|
||||
source,
|
||||
destination,
|
||||
flags: 0,
|
||||
crop: FixedRect::default(),
|
||||
rect: Rect::default(),
|
||||
};
|
||||
let refused = case(layout(b, 3, 8, 64, 0), layout(b, 8, 8, 64, 0));
|
||||
assert_eq!(
|
||||
run(accelerator.as_mut(), &refused),
|
||||
Err(io_return::UNSUPPORTED)
|
||||
);
|
||||
let refused = case(layout(b, 8, 8, 64, 0), layout(b, 8, 3, 64, 0));
|
||||
assert_eq!(
|
||||
run(accelerator.as_mut(), &refused),
|
||||
Err(io_return::UNSUPPORTED)
|
||||
);
|
||||
let taken = case(layout(b, 4, 4, 64, 0), layout(b, 4, 4, 64, 0));
|
||||
assert_eq!(
|
||||
run(accelerator.as_mut(), &taken).map(|(largest, count, _)| (largest, count)),
|
||||
Ok((0, 0))
|
||||
);
|
||||
}
|
||||
|
||||
/// A destination whose planes do not start on 4-byte boundaries is staged, and the same: the
|
||||
/// bytes the reference writes, and nothing else
|
||||
#[test]
|
||||
fn a_misaligned_destination_is_staged_and_the_same() {
|
||||
for (gpu, backend) in gpus() {
|
||||
let mut accelerator = backend.create_accelerator().unwrap();
|
||||
for format in [ScalerFormat::Nv12VideoRange, ScalerFormat::P010FullRange] {
|
||||
let case = Case {
|
||||
name: format!("{} skewed", name(format)),
|
||||
source: layout(ScalerFormat::Bgra, 40, 30, 64, 0),
|
||||
destination: layout(format, 50, 34, 64, 2),
|
||||
flags: 0x1000,
|
||||
crop: FixedRect::default(),
|
||||
rect: Rect {
|
||||
x: 3,
|
||||
y: 1,
|
||||
width: 41,
|
||||
height: 31,
|
||||
},
|
||||
};
|
||||
let (largest, _, _) = run(accelerator.as_mut(), &case).unwrap();
|
||||
assert!(largest <= 1, "{gpu}: {}: {largest}", case.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform the library runs on.
|
||||
type P = crate::DefaultPlatform;
|
||||
|
||||
/// A surface of the platform's, as the mapper gives the guest's, its lends, and the writes of
|
||||
/// its memory by a device it was told of.
|
||||
struct Platform {
|
||||
platform: Arc<P>,
|
||||
surface: <P as reims_vgpu_core::platform::Platform>::Surface,
|
||||
layout: SurfaceLayout,
|
||||
memory: Option<Box<dyn DeviceMemory>>,
|
||||
lends: AtomicUsize,
|
||||
device_writes: AtomicUsize,
|
||||
}
|
||||
|
||||
impl GuestSurface for Platform {
|
||||
fn layout(&self) -> SurfaceLayout {
|
||||
self.layout.clone()
|
||||
}
|
||||
|
||||
fn write(&self, write: &mut dyn FnMut(&mut [u8])) -> Result<(), SurfaceError> {
|
||||
self.lends.fetch_add(1, Ordering::Relaxed);
|
||||
self.platform
|
||||
.lend_surface_bytes(&self.surface, write)
|
||||
.map_err(|e| SurfaceError::Unreachable(e.to_owned()))
|
||||
}
|
||||
|
||||
fn read(&self, read: &mut dyn FnMut(&[u8])) -> Result<(), SurfaceError> {
|
||||
self.lends.fetch_add(1, Ordering::Relaxed);
|
||||
self.platform
|
||||
.lend_surface_bytes_for_reading(&self.surface, read)
|
||||
.map_err(|e| SurfaceError::Unreachable(e.to_owned()))
|
||||
}
|
||||
|
||||
fn device_memory(&self) -> Option<&dyn DeviceMemory> {
|
||||
self.memory.as_deref()
|
||||
}
|
||||
|
||||
fn device_wrote(&self) {
|
||||
self.device_writes.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// A surface of the platform's of `layout`, holding `bytes`, read-only for its clients where
|
||||
/// `client_direction` says.
|
||||
fn platform_surface(
|
||||
layout: SurfaceLayout,
|
||||
bytes: &[u8],
|
||||
client_direction: Option<u32>,
|
||||
) -> Platform {
|
||||
let platform = P::process();
|
||||
let of = FormatOf::of(&layout).unwrap();
|
||||
let alloc = bytes.len().next_multiple_of(16384);
|
||||
let planes = (of.format.packing() == Packing::Biplanar420).then(|| {
|
||||
(of.planes.iter().zip(&layout.planes))
|
||||
.zip([1, 2])
|
||||
.map(|((span, plane), elements)| SurfacePlaneSpec {
|
||||
base: span.offset.to_u64(),
|
||||
offset: span.offset.to_u64(),
|
||||
width: u64::from(plane.width),
|
||||
height: u64::from(plane.height),
|
||||
size: (span.bytes_per_row * span.rows).to_u64(),
|
||||
bytes_per_row: span.bytes_per_row.to_u64(),
|
||||
bytes_per_element: (elements * of.format.bytes_per_sample()).to_u64(),
|
||||
element_width: 1,
|
||||
element_height: 1,
|
||||
..SurfacePlaneSpec::default()
|
||||
})
|
||||
.collect()
|
||||
});
|
||||
let spec = SurfaceSpec {
|
||||
planes,
|
||||
pixel_format: layout.pixel_format.0,
|
||||
alloc_size: alloc.to_u64(),
|
||||
width: u64::from(layout.width),
|
||||
height: u64::from(layout.height),
|
||||
bytes_per_element: match of.format.packing() {
|
||||
Packing::Rgb32(_) | Packing::Packed422(_) => 4,
|
||||
Packing::Biplanar420 => of.format.bytes_per_sample().to_u64(),
|
||||
},
|
||||
bytes_per_row: of.planes[0].bytes_per_row.to_u64(),
|
||||
element_width: match of.format.packing() {
|
||||
Packing::Packed422(_) => 2,
|
||||
_ => 1,
|
||||
},
|
||||
element_height: 1,
|
||||
client_direction,
|
||||
..SurfaceSpec::default()
|
||||
};
|
||||
let surface = platform.surfaces().create(&spec).unwrap();
|
||||
// Refused for a surface read-only for its clients where the platform refuses its CPU's
|
||||
// writes too: its bytes stay zeros.
|
||||
let _ =
|
||||
platform.lend_surface_bytes(&surface, &mut |to| to[..bytes.len()].copy_from_slice(bytes));
|
||||
let memory = platform.surface_device_memory(&surface).ok();
|
||||
Platform {
|
||||
platform,
|
||||
surface,
|
||||
layout,
|
||||
memory,
|
||||
lends: AtomicUsize::new(0),
|
||||
device_writes: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// A platform surface's bytes, through a lend.
|
||||
fn snapshot(s: &Platform) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
s.platform
|
||||
.lend_surface_bytes_for_reading(&s.surface, &mut |b| out.extend_from_slice(b))
|
||||
.unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
/// Surfaces the process's platform makes, whose memory it lends to devices, are reached in place:
|
||||
/// no lend of either, the reference's bytes, and the destination told its memory was written; one
|
||||
/// the guest made read-only for its clients is never written: staged, its write lend refused,
|
||||
/// kIOReturnNotWritable, its bytes as they were
|
||||
#[test]
|
||||
fn platform_surfaces_are_reached_in_place() {
|
||||
for (gpu, backend) in gpus() {
|
||||
let mut accelerator = backend.create_accelerator().unwrap();
|
||||
for (from, to) in [
|
||||
(ScalerFormat::Nv12VideoRange, ScalerFormat::Bgra),
|
||||
(ScalerFormat::Bgra, ScalerFormat::P010VideoRange),
|
||||
(ScalerFormat::Yuyv, ScalerFormat::Nv12FullRange),
|
||||
] {
|
||||
let (sl, dl) = (layout(from, 64, 48, 64, 0), layout(to, 96, 72, 64, 0));
|
||||
let source = platform_surface(sl.clone(), &picture_bytes(&sl, None), None);
|
||||
let grey = picture_bytes(&dl, Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let destination = platform_surface(dl.clone(), &grey, None);
|
||||
let in_place = source.memory.is_some() && destination.memory.is_some();
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(0x1000),
|
||||
..Transform::default()
|
||||
};
|
||||
let plan = Plan::new(&transform, &sl, &dl).unwrap();
|
||||
let mut expected = snapshot(&destination);
|
||||
reference::run(&plan, &snapshot(&source), &mut expected).unwrap();
|
||||
let mut job = TransformJob {
|
||||
transform: &transform,
|
||||
plan: plan.clone(),
|
||||
source: &source,
|
||||
destination: &destination,
|
||||
hold: GuestHold::nothing(),
|
||||
inputs: Default::default(),
|
||||
outputs: Default::default(),
|
||||
};
|
||||
assert_eq!(accelerator.transform(&mut job), io_return::SUCCESS, "{gpu}");
|
||||
let (largest, _) =
|
||||
difference(&plan.destination_format, &snapshot(&destination), &expected);
|
||||
let lends =
|
||||
source.lends.load(Ordering::Relaxed) + destination.lends.load(Ordering::Relaxed);
|
||||
println!(
|
||||
"{gpu}: {} to {} on surfaces of the platform's: largest {largest}, {lends} lends{}",
|
||||
name(from),
|
||||
name(to),
|
||||
if in_place { ", in place" } else { ", staged" }
|
||||
);
|
||||
assert!(largest <= 1, "{gpu}: {largest}");
|
||||
if in_place
|
||||
&& gpu.starts_with(if cfg!(target_os = "macos") {
|
||||
"Metal"
|
||||
} else {
|
||||
"Vulkan"
|
||||
})
|
||||
{
|
||||
assert_eq!(lends, 0, "{gpu}: in place, no lend");
|
||||
assert_eq!(
|
||||
destination.device_writes.load(Ordering::Relaxed),
|
||||
1,
|
||||
"{gpu}: told of the write"
|
||||
);
|
||||
}
|
||||
}
|
||||
// A destination the guest made read-only for its clients: lent to no device, so staged,
|
||||
// and written only where the platform's own lend takes the CPU's writes (a surface of its
|
||||
// own memory on macOS does; none over the guest's pages does). The Vulkan platform on
|
||||
// Linux takes the direction only for a surface over a guest's pages, whose lends to
|
||||
// devices and for writing it refuses (its own tests), so a surface of its own memory is
|
||||
// no such surface there.
|
||||
let b = ScalerFormat::Bgra;
|
||||
let (sl, dl) = (layout(b, 32, 32, 64, 0), layout(b, 32, 32, 64, 0));
|
||||
let source = platform_surface(sl.clone(), &picture_bytes(&sl, None), None);
|
||||
let grey = picture_bytes(&dl, Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let destination = platform_surface(dl.clone(), &grey, Some(2));
|
||||
if cfg!(target_os = "linux") && destination.memory.is_some() {
|
||||
println!("{gpu}: a read-only destination: no such surface of the platform's own");
|
||||
continue;
|
||||
}
|
||||
assert!(destination.memory.is_none(), "{gpu}: lent to no device");
|
||||
let writable = (destination.platform)
|
||||
.lend_surface_bytes(&destination.surface, &mut |_| {})
|
||||
.is_ok();
|
||||
let before = snapshot(&destination);
|
||||
let transform = Transform::default();
|
||||
let mut job = TransformJob {
|
||||
transform: &transform,
|
||||
plan: Plan::new(&transform, &sl, &dl).unwrap(),
|
||||
source: &source,
|
||||
destination: &destination,
|
||||
hold: GuestHold::nothing(),
|
||||
inputs: Default::default(),
|
||||
outputs: Default::default(),
|
||||
};
|
||||
let status = accelerator.transform(&mut job);
|
||||
if writable {
|
||||
assert_eq!(status, io_return::SUCCESS, "{gpu}");
|
||||
} else {
|
||||
assert_eq!(status, io_return::NOT_WRITABLE, "{gpu}");
|
||||
assert_eq!(snapshot(&destination), before, "{gpu}: as it was");
|
||||
}
|
||||
assert_eq!(
|
||||
destination.device_writes.load(Ordering::Relaxed),
|
||||
0,
|
||||
"{gpu}: staged, written in its lend alone"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
mod native;
|
||||
|
||||
mod firsts;
|
||||
@@ -1,294 +0,0 @@
|
||||
//! A process's first transforms on each kernel, as a guest's first transforms after its device
|
||||
//! opened meet them: with nothing made ahead, as the making ahead starts, and once it is done
|
||||
//! (`make_ahead`). Each prints, of each transform, its first wall time and the next, the
|
||||
//! dispatches' kernels, and on the Vulkan platform what the runtime counted meanwhile: functions
|
||||
//! translated and found translated, `VkPipeline`s made, and the driver's hits and misses in the
|
||||
//! caches the makings were handed (`ScalerGpu::cache_counts`), which tell a cold making from a
|
||||
//! cached one; as the making ahead starts, its own lines follow, which say when it made each
|
||||
//! kernel. Run each alone, in its own process, for the record in docs/video/scaler.md, "Making
|
||||
//! the kernels" (`--run-ignored only --no-capture`, in release), with the caches as the record
|
||||
//! says: a cold first transform wants the runtime's shader cache new, which lies under `HOME`, and
|
||||
//! the driver's off.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A first transform: its name, its source's format and size, its destination's, and its flags.
|
||||
type First = (
|
||||
&'static str,
|
||||
ScalerFormat,
|
||||
(u32, u32),
|
||||
ScalerFormat,
|
||||
(u32, u32),
|
||||
u64,
|
||||
);
|
||||
|
||||
/// One transform for each kernel and threadgroup size the transforms dispatch
|
||||
/// ([`params::DISPATCHED`]).
|
||||
const FIRSTS: [First; 7] = [
|
||||
(
|
||||
"2160p 420v to 2160p BGRA",
|
||||
ScalerFormat::Nv12VideoRange,
|
||||
(3840, 2160),
|
||||
ScalerFormat::Bgra,
|
||||
(3840, 2160),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"1080p 420v to 720p BGRA",
|
||||
ScalerFormat::Nv12VideoRange,
|
||||
(1920, 1080),
|
||||
ScalerFormat::Bgra,
|
||||
(1280, 720),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"2160p 420v to 1080p 420v",
|
||||
ScalerFormat::Nv12VideoRange,
|
||||
(3840, 2160),
|
||||
ScalerFormat::Nv12VideoRange,
|
||||
(1920, 1080),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"720p BGRA to 180p BGRA",
|
||||
ScalerFormat::Bgra,
|
||||
(1280, 720),
|
||||
ScalerFormat::Bgra,
|
||||
(320, 180),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"720p BGRA to 720p 420v",
|
||||
ScalerFormat::Bgra,
|
||||
(1280, 720),
|
||||
ScalerFormat::Nv12VideoRange,
|
||||
(1280, 720),
|
||||
0x1000,
|
||||
),
|
||||
(
|
||||
"1080p BGRA turned 90",
|
||||
ScalerFormat::Bgra,
|
||||
(1920, 1080),
|
||||
ScalerFormat::Bgra,
|
||||
(1080, 1920),
|
||||
0x1004,
|
||||
),
|
||||
(
|
||||
"240p BGRA turned 90 to 160p",
|
||||
ScalerFormat::Bgra,
|
||||
(320, 240),
|
||||
ScalerFormat::Bgra,
|
||||
(240, 160),
|
||||
0x1004,
|
||||
),
|
||||
];
|
||||
|
||||
/// How the probe meets the making ahead.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum Ahead {
|
||||
/// None runs.
|
||||
None,
|
||||
/// The transforms start as it starts.
|
||||
Starting,
|
||||
/// The transforms start once it is done.
|
||||
Done,
|
||||
}
|
||||
|
||||
/// The runtime's counts (module docs), where the GPU is the Vulkan platform's.
|
||||
type Counts<'a> = &'a dyn Fn() -> Option<[u64; 5]>;
|
||||
|
||||
/// A first transform's status, the kernels and threadgroups its dispatches take, and the
|
||||
/// `VkPipeline`s the runtime made while it ran, where it counts them.
|
||||
type Taken = (IoReturn, Vec<(Kernel, (u32, u32))>, Option<u64>);
|
||||
|
||||
/// What the runtime counted from `then` to `now`, in words; nothing where it counts nothing.
|
||||
fn counted(then: Option<[u64; 5]>, now: Option<[u64; 5]>) -> String {
|
||||
let (Some(then), Some(now)) = (then, now) else {
|
||||
return String::new();
|
||||
};
|
||||
let d: Vec<u64> = now.iter().zip(then).map(|(n, t)| n - t).collect();
|
||||
format!(
|
||||
"; translated +{}, found translated +{}, pipelines made +{}, driver hits +{}, misses +{}",
|
||||
d[0], d[1], d[2], d[3], d[4]
|
||||
)
|
||||
}
|
||||
|
||||
/// The first transforms on `gpu` (module docs), with the runtime's `counts`: what each took.
|
||||
fn firsts<G: Gpu>(name: &str, gpu: Arc<G>, ahead: Ahead, counts: Counts<'_>) -> Vec<Taken> {
|
||||
let mut out = Vec::new();
|
||||
let runtime = StdRuntime::shared();
|
||||
let opened = runtime.now();
|
||||
let before = counts();
|
||||
// As it starts, the making ahead's own lines say when it made each kernel, beside the
|
||||
// transforms'.
|
||||
let logs = (ahead == Ahead::Starting).then(|| {
|
||||
let logs = reims_vgpu_core::testkit::logs::capture();
|
||||
log::set_max_level(log::LevelFilter::Debug);
|
||||
logs
|
||||
});
|
||||
let answer = (ahead != Ahead::None).then(|| make_ahead(&gpu, &runtime).unwrap());
|
||||
if ahead == Ahead::Done {
|
||||
let deadline = runtime.deadline_in(Duration::from_secs(300));
|
||||
answer
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.wait_until(&*runtime, deadline)
|
||||
.unwrap();
|
||||
println!(
|
||||
"first transforms, {ahead:?}: {name}: made ahead in {:.0} ms{}",
|
||||
runtime.elapsed_since(opened).as_secs_f64() * 1000.0,
|
||||
counted(before, counts())
|
||||
);
|
||||
}
|
||||
let backend = GpuScalerBackend::new(gpu, Arc::clone(&runtime));
|
||||
let mut accelerator = backend.create_accelerator().unwrap();
|
||||
for (label, from, (sw, sh), to, (dw, dh), flags) in FIRSTS {
|
||||
let (sl, dl) = (layout(from, sw, sh, 64, 0), layout(to, dw, dh, 64, 0));
|
||||
let source = platform_surface(sl.clone(), &picture_bytes(&sl, None), None);
|
||||
let grey = picture_bytes(&dl, Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let destination = platform_surface(dl.clone(), &grey, None);
|
||||
let transform = Transform {
|
||||
flags: TransformFlags(flags),
|
||||
..Transform::default()
|
||||
};
|
||||
let plan = Plan::new(&transform, &sl, &dl).unwrap();
|
||||
let kernels: Vec<(Kernel, (u32, u32))> = params::work(
|
||||
&plan,
|
||||
&at_base(&plan.source_format.planes, 0).unwrap(),
|
||||
&at_base(&plan.destination_format.planes, 0).unwrap(),
|
||||
)
|
||||
.unwrap()
|
||||
.passes
|
||||
.iter()
|
||||
.map(|(kernel, _, _, group)| (*kernel, *group))
|
||||
.collect();
|
||||
let named: Vec<String> = (kernels.iter())
|
||||
.map(|(kernel, group)| format!("{kernel:?} {group:?}"))
|
||||
.collect();
|
||||
let mut times = Vec::new();
|
||||
let before = counts();
|
||||
for _ in 0..2 {
|
||||
let mut job = TransformJob {
|
||||
transform: &transform,
|
||||
plan: plan.clone(),
|
||||
source: &source,
|
||||
destination: &destination,
|
||||
hold: GuestHold::nothing(),
|
||||
inputs: Default::default(),
|
||||
outputs: Default::default(),
|
||||
};
|
||||
let started = runtime.now();
|
||||
let status = accelerator.transform(&mut job);
|
||||
times.push((
|
||||
runtime.elapsed_since(started).as_secs_f64() * 1000.0,
|
||||
status,
|
||||
));
|
||||
}
|
||||
println!(
|
||||
"first transforms, {ahead:?}: {name}: {label}: first {:.1} ms (status {:#x}), then \
|
||||
{:.1} ms; at {:.0} ms after the opening; {}{}",
|
||||
times[0].0,
|
||||
times[0].1,
|
||||
times[1].0,
|
||||
runtime.elapsed_since(opened).as_secs_f64() * 1000.0,
|
||||
named.join(", "),
|
||||
counted(before, counts())
|
||||
);
|
||||
let made = counts().zip(before).map(|(now, then)| now[2] - then[2]);
|
||||
out.push((times[0].1, kernels, made));
|
||||
}
|
||||
if let (Some(logs), Some(answer)) = (logs, answer) {
|
||||
let deadline = runtime.deadline_in(Duration::from_secs(300));
|
||||
answer.wait_until(&*runtime, deadline).unwrap();
|
||||
for (_, target, line) in logs.take() {
|
||||
if target.starts_with("reims_vgpu::scaler") {
|
||||
println!("first transforms, {ahead:?}: {name}: {line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The first transforms on each GPU, `ahead` as it says.
|
||||
fn each_gpu(ahead: Ahead) {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let runtime = StdRuntime::shared();
|
||||
let started = runtime.now();
|
||||
let gpu = metal::MetalGpu::process().expect("Metal opens the kernel");
|
||||
let name = format!("Metal, {}", gpu.name());
|
||||
println!(
|
||||
"first transforms, {ahead:?}: {name}: opened in {:.0} ms",
|
||||
runtime.elapsed_since(started).as_secs_f64() * 1000.0
|
||||
);
|
||||
firsts(&name, gpu, ahead, &|| None);
|
||||
}
|
||||
#[cfg(vulkan_platform)]
|
||||
{
|
||||
let runtime = StdRuntime::shared();
|
||||
let started = runtime.now();
|
||||
match vulkan::VulkanGpu::process(&runtime) {
|
||||
Ok(gpu) => {
|
||||
let name = format!("Vulkan, {}", gpu.name());
|
||||
let (opening, directory) = gpu.cache_counts();
|
||||
println!(
|
||||
"first transforms, {ahead:?}: {name}: opened in {:.0} ms, its shader cache in \
|
||||
{}{}",
|
||||
runtime.elapsed_since(started).as_secs_f64() * 1000.0,
|
||||
directory.display(),
|
||||
counted(Some([0; 5]), Some(opening))
|
||||
);
|
||||
let of = Arc::clone(&gpu);
|
||||
firsts(&name, gpu, ahead, &move || Some(of.cache_counts().0));
|
||||
}
|
||||
Err(why) => eprintln!("no Vulkan GPU: {why}; skipped"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Once the making ahead is done, a process's first transform on each kernel and threadgroup the
|
||||
/// transforms dispatch makes no `VkPipeline`: the making ahead made the one it takes, for the same
|
||||
/// bindings. On the Vulkan platform, which makes them at first dispatches; Metal makes them where
|
||||
/// it makes the pipeline states
|
||||
#[test]
|
||||
fn the_making_ahead_makes_what_the_first_transforms_take() {
|
||||
#[cfg(vulkan_platform)]
|
||||
match vulkan::VulkanGpu::process(&StdRuntime::shared()) {
|
||||
Ok(gpu) => {
|
||||
let name = format!("Vulkan, {}", gpu.name());
|
||||
let of = Arc::clone(&gpu);
|
||||
let firsts = firsts(&name, gpu, Ahead::Done, &move || Some(of.cache_counts().0));
|
||||
let mut taken: Vec<(Kernel, (u32, u32))> = Vec::new();
|
||||
for (status, kernels, made) in firsts {
|
||||
assert_eq!(status, io_return::SUCCESS, "{name}");
|
||||
assert_eq!(made, Some(0), "{name}: {kernels:?}");
|
||||
taken.extend(kernels);
|
||||
}
|
||||
for dispatched in params::DISPATCHED {
|
||||
assert!(taken.contains(&dispatched), "{dispatched:?} untried");
|
||||
}
|
||||
}
|
||||
Err(why) => eprintln!("no Vulkan GPU: {why}; skipped"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A process's first transforms with nothing made ahead (module docs)
|
||||
#[test]
|
||||
#[ignore = "a probe of a process's first transforms: run alone, for the record"]
|
||||
fn first_transforms_with_nothing_made_ahead() {
|
||||
each_gpu(Ahead::None);
|
||||
}
|
||||
|
||||
/// A process's first transforms as the making ahead starts (module docs)
|
||||
#[test]
|
||||
#[ignore = "a probe of a process's first transforms: run alone, for the record"]
|
||||
fn first_transforms_as_the_making_ahead_starts() {
|
||||
each_gpu(Ahead::Starting);
|
||||
}
|
||||
|
||||
/// A process's first transforms once the making ahead is done (module docs)
|
||||
#[test]
|
||||
#[ignore = "a probe of a process's first transforms: run alone, for the record"]
|
||||
fn first_transforms_once_made_ahead() {
|
||||
each_gpu(Ahead::Done);
|
||||
}
|
||||
@@ -1,815 +0,0 @@
|
||||
//! The scaler's kernels beside this Mac's own scalers, in one process, interleaved, on the same
|
||||
//! surfaces: Apple's scaler through IOSurfaceAccelerator's TransformSurface, VideoToolbox's
|
||||
//! VTPixelTransferSession, and MPS's MPSImageLanczosScale and MPSImageBilinearScale on textures
|
||||
//! over the surfaces' planes. Each case runs every engine once to warm it, then 8 rounds of 3
|
||||
//! transforms of each engine in turn, and prints each engine's median wall time and, where the
|
||||
//! GPU says, GPU time. Run alone, in release (`cargo nextest run --release -p reims-vgpu -E
|
||||
//! 'test(/against_the_macs/)' --run-ignored only --no-capture`).
|
||||
//!
|
||||
//! - **The surfaces** are the platform's own IOSurfaces of the process's memory, as
|
||||
//! CVPixelBuffers make them: never one over pages read-only for the scaler.
|
||||
//! - **What runs where**: MPS only scales, so it runs only where the formats are the same and
|
||||
//! nothing turns, each plane of a 4:2:0 surface a texture of its own; VideoToolbox only where
|
||||
//! nothing turns and both windows are whole; Apple's scaler everywhere.
|
||||
//! - **The staged kernel** runs on surfaces of the test's own memory, which the kernel reaches
|
||||
//! through buffers of the GPU's own: its GPU time beside the in-place one says what reading the
|
||||
//! surfaces where they are costs.
|
||||
|
||||
use std::ffi::{c_char, c_int, c_void};
|
||||
use std::ptr::{self, NonNull};
|
||||
|
||||
use objc2::encode::{Encode, Encoding, RefEncode};
|
||||
use objc2::msg_send;
|
||||
use objc2::rc::{Allocated, Retained};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ProtocolObject};
|
||||
use objc2_foundation::{NSMutableDictionary, NSNumber, NSString};
|
||||
use objc2_io_surface::IOSurfaceRef;
|
||||
use objc2_metal::{
|
||||
MTLCommandBuffer as _, MTLCommandQueue, MTLCreateSystemDefaultDevice, MTLDevice, MTLOrigin,
|
||||
MTLPixelFormat, MTLRegion, MTLSize, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn dlopen(path: *const c_char, mode: c_int) -> *mut c_void;
|
||||
fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
|
||||
}
|
||||
|
||||
const RTLD_NOW: c_int = 2;
|
||||
|
||||
#[link(name = "CoreFoundation", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CFRelease(cf: *const c_void);
|
||||
}
|
||||
|
||||
#[link(name = "CoreVideo", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CVPixelBufferCreateWithIOSurface(
|
||||
allocator: *const c_void,
|
||||
surface: *const c_void,
|
||||
attributes: *const c_void,
|
||||
out: *mut *mut c_void,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
#[link(name = "VideoToolbox", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn VTPixelTransferSessionCreate(allocator: *const c_void, session: *mut *mut c_void) -> i32;
|
||||
fn VTPixelTransferSessionTransferImage(
|
||||
session: *mut c_void,
|
||||
source: *mut c_void,
|
||||
destination: *mut c_void,
|
||||
) -> i32;
|
||||
}
|
||||
|
||||
/// TransformSurface's windows: the source's in 16.16, the destination's in pixels.
|
||||
#[repr(C)]
|
||||
struct Rects {
|
||||
src_x: u64,
|
||||
src_y: u64,
|
||||
src_width: u64,
|
||||
src_height: u64,
|
||||
dst_x: u32,
|
||||
dst_y: u32,
|
||||
dst_width: u32,
|
||||
dst_height: u32,
|
||||
}
|
||||
|
||||
type CreateFn = unsafe extern "C" fn(*const c_void, *const c_void, *mut *mut c_void) -> i32;
|
||||
type TransformFn = unsafe extern "C" fn(
|
||||
*mut c_void,
|
||||
*const c_void,
|
||||
*const c_void,
|
||||
*const c_void,
|
||||
*const Rects,
|
||||
*const c_void,
|
||||
) -> i32;
|
||||
|
||||
/// Apple's scaler, through IOSurfaceAccelerator.
|
||||
struct Apple {
|
||||
accelerator: *mut c_void,
|
||||
transform: TransformFn,
|
||||
}
|
||||
|
||||
impl Apple {
|
||||
fn open() -> Option<Apple> {
|
||||
let path =
|
||||
c"/System/Library/PrivateFrameworks/IOSurfaceAccelerator.framework/IOSurfaceAccelerator";
|
||||
// SAFETY: dlopen and dlsym of a system framework's exported functions, whose signatures
|
||||
// are as declared above.
|
||||
unsafe {
|
||||
let handle = dlopen(path.as_ptr(), RTLD_NOW);
|
||||
if handle.is_null() {
|
||||
return None;
|
||||
}
|
||||
let create = dlsym(handle, c"IOSurfaceAcceleratorCreate".as_ptr());
|
||||
let transform = dlsym(handle, c"IOSurfaceAcceleratorTransformSurface".as_ptr());
|
||||
if create.is_null() || transform.is_null() {
|
||||
return None;
|
||||
}
|
||||
let create: CreateFn = std::mem::transmute(create);
|
||||
let transform: TransformFn = std::mem::transmute(transform);
|
||||
let mut accelerator = ptr::null_mut();
|
||||
let status = create(ptr::null(), ptr::null(), &raw mut accelerator);
|
||||
(status == 0 && !accelerator.is_null()).then_some(Apple {
|
||||
accelerator,
|
||||
transform,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn run(
|
||||
&self,
|
||||
source: NonNull<c_void>,
|
||||
destination: NonNull<c_void>,
|
||||
case: &AbCase,
|
||||
plan: &Plan,
|
||||
) -> i32 {
|
||||
let options = NSMutableDictionary::<NSString, AnyObject>::new();
|
||||
let bits = case.flags & 7;
|
||||
if bits != 0 {
|
||||
options.insert(&*NSString::from_str("Transform"), &*NSNumber::new_u64(bits));
|
||||
}
|
||||
if case.flags & 0x80 != 0 {
|
||||
options.insert(
|
||||
&*NSString::from_str("UseNearestFilter"),
|
||||
&*NSNumber::new_bool(true),
|
||||
);
|
||||
}
|
||||
let (s, d) = (plan.source_rect, plan.destination_rect);
|
||||
let rects = Rects {
|
||||
src_x: s.x,
|
||||
src_y: s.y,
|
||||
src_width: s.width,
|
||||
src_height: s.height,
|
||||
dst_x: d.x,
|
||||
dst_y: d.y,
|
||||
dst_width: d.width,
|
||||
dst_height: d.height,
|
||||
};
|
||||
// SAFETY: live surfaces and dictionary for the call, which is synchronous.
|
||||
unsafe {
|
||||
(self.transform)(
|
||||
self.accelerator,
|
||||
source.as_ptr(),
|
||||
destination.as_ptr(),
|
||||
Retained::as_ptr(&options).cast(),
|
||||
&raw const rects,
|
||||
ptr::null(),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// MPS's scale transform.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy)]
|
||||
struct ScaleTransform {
|
||||
scale_x: f64,
|
||||
scale_y: f64,
|
||||
translate_x: f64,
|
||||
translate_y: f64,
|
||||
}
|
||||
|
||||
// SAFETY: MPSScaleTransform's layout, four doubles.
|
||||
unsafe impl Encode for ScaleTransform {
|
||||
const ENCODING: Encoding = Encoding::Struct(
|
||||
"MPSScaleTransform",
|
||||
&[f64::ENCODING, f64::ENCODING, f64::ENCODING, f64::ENCODING],
|
||||
);
|
||||
}
|
||||
// SAFETY: as above.
|
||||
unsafe impl RefEncode for ScaleTransform {
|
||||
const ENCODING_REF: Encoding = Encoding::Pointer(&<Self as Encode>::ENCODING);
|
||||
}
|
||||
|
||||
/// A texture over a plane of a surface, and its chroma step: 1, or 2 for a 4:2:0 chroma plane.
|
||||
type Plane = (Retained<ProtocolObject<dyn MTLTexture>>, u32);
|
||||
|
||||
/// MPS's two scales, on the system's default device.
|
||||
struct Mps {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
lanczos: Retained<AnyObject>,
|
||||
bilinear: Retained<AnyObject>,
|
||||
}
|
||||
|
||||
impl Mps {
|
||||
fn open() -> Option<Mps> {
|
||||
let path =
|
||||
c"/System/Library/Frameworks/MetalPerformanceShaders.framework/MetalPerformanceShaders";
|
||||
// SAFETY: loads a system framework.
|
||||
if unsafe { dlopen(path.as_ptr(), RTLD_NOW) }.is_null() {
|
||||
return None;
|
||||
}
|
||||
let device = MTLCreateSystemDefaultDevice()?;
|
||||
let queue = device.newCommandQueue()?;
|
||||
let make = |name: &std::ffi::CStr| -> Option<Retained<AnyObject>> {
|
||||
let class = AnyClass::get(name)?;
|
||||
// SAFETY: MPSImageScale's subclasses' initWithDevice:.
|
||||
unsafe {
|
||||
let allocated: Allocated<AnyObject> = msg_send![class, alloc];
|
||||
msg_send![allocated, initWithDevice: &*device]
|
||||
}
|
||||
};
|
||||
Some(Mps {
|
||||
lanczos: make(c"MPSImageLanczosScale")?,
|
||||
bilinear: make(c"MPSImageBilinearScale")?,
|
||||
device,
|
||||
queue,
|
||||
})
|
||||
}
|
||||
|
||||
/// Textures over `surface`'s planes of `format`, `width` by `height`; `None` for a format MPS
|
||||
/// scales no plane of.
|
||||
fn planes(
|
||||
&self,
|
||||
surface: &IOSurfaceRef,
|
||||
format: ScalerFormat,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Option<Vec<Plane>> {
|
||||
let (w, h) = (width.to_usize(), height.to_usize());
|
||||
let planes: Vec<(MTLPixelFormat, usize, usize, u32)> = match format {
|
||||
ScalerFormat::Bgra => vec![(MTLPixelFormat::BGRA8Unorm, w, h, 1)],
|
||||
ScalerFormat::Nv12VideoRange | ScalerFormat::Nv12FullRange => vec![
|
||||
(MTLPixelFormat::R8Unorm, w, h, 1),
|
||||
(MTLPixelFormat::RG8Unorm, w.div_ceil(2), h.div_ceil(2), 2),
|
||||
],
|
||||
ScalerFormat::P010VideoRange | ScalerFormat::P010FullRange => vec![
|
||||
(MTLPixelFormat::R16Unorm, w, h, 1),
|
||||
(MTLPixelFormat::RG16Unorm, w.div_ceil(2), h.div_ceil(2), 2),
|
||||
],
|
||||
_ => return None,
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for (plane, (pixel_format, pw, ph, step)) in planes.into_iter().enumerate() {
|
||||
// SAFETY: a descriptor of a 2D texture.
|
||||
let descriptor = unsafe {
|
||||
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
|
||||
pixel_format,
|
||||
pw,
|
||||
ph,
|
||||
false,
|
||||
)
|
||||
};
|
||||
descriptor.setUsage(MTLTextureUsage::ShaderRead | MTLTextureUsage::ShaderWrite);
|
||||
// SAFETY: a texture over a live surface's plane, which outlives it.
|
||||
let texture: Option<Retained<ProtocolObject<dyn MTLTexture>>> = unsafe {
|
||||
msg_send![
|
||||
&*self.device,
|
||||
newTextureWithDescriptor: &*descriptor,
|
||||
iosurface: surface,
|
||||
plane: plane
|
||||
]
|
||||
};
|
||||
let texture = texture?;
|
||||
out.push((texture, step));
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
/// Scales each plane of `source` into `destination`'s with `kernel`, the plan's windows a
|
||||
/// plane's subsampling smaller; its wall and GPU times in ms.
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_precision_loss,
|
||||
reason = "a bench's numbers"
|
||||
)]
|
||||
fn run(
|
||||
&self,
|
||||
kernel: &AnyObject,
|
||||
source: &[Plane],
|
||||
destination: &[Plane],
|
||||
plan: &Plan,
|
||||
runtime: &dyn Runtime,
|
||||
) -> (f64, Option<f64>) {
|
||||
let started = runtime.now();
|
||||
let cb = self.queue.commandBuffer().unwrap();
|
||||
let (s, d) = (plan.source_rect, plan.destination_rect);
|
||||
let fixed = |v: u64| v as f64 / FIXED_ONE as f64;
|
||||
for ((from, step), (to, _)) in source.iter().zip(destination) {
|
||||
let k = f64::from(*step);
|
||||
let (sx, sy, sw, sh) = (
|
||||
fixed(s.x) / k,
|
||||
fixed(s.y) / k,
|
||||
fixed(s.width) / k,
|
||||
fixed(s.height) / k,
|
||||
);
|
||||
let (dx, dy, dw, dh) = (
|
||||
f64::from(d.x) / k,
|
||||
f64::from(d.y) / k,
|
||||
f64::from(d.width) / k,
|
||||
f64::from(d.height) / k,
|
||||
);
|
||||
let transform = ScaleTransform {
|
||||
scale_x: dw / sw,
|
||||
scale_y: dh / sh,
|
||||
translate_x: dx - sx * dw / sw,
|
||||
translate_y: dy - sy * dh / sh,
|
||||
};
|
||||
let clip = MTLRegion {
|
||||
origin: MTLOrigin {
|
||||
x: dx.floor() as usize,
|
||||
y: dy.floor() as usize,
|
||||
z: 0,
|
||||
},
|
||||
size: MTLSize {
|
||||
width: dw.ceil() as usize,
|
||||
height: dh.ceil() as usize,
|
||||
depth: 1,
|
||||
},
|
||||
};
|
||||
// SAFETY: MPSImageScale's scaleTransform, clipRect and encode, each with live
|
||||
// objects; the transform is copied by the set.
|
||||
unsafe {
|
||||
let () = msg_send![kernel, setScaleTransform: &raw const transform];
|
||||
let () = msg_send![kernel, setClipRect: clip];
|
||||
let () = msg_send![
|
||||
kernel,
|
||||
encodeToCommandBuffer: &*cb,
|
||||
sourceTexture: &**from,
|
||||
destinationTexture: &**to
|
||||
];
|
||||
}
|
||||
}
|
||||
cb.commit();
|
||||
cb.waitUntilCompleted();
|
||||
let wall = runtime.elapsed_since(started).as_secs_f64() * 1000.0;
|
||||
let (start, end) = (cb.GPUStartTime(), cb.GPUEndTime());
|
||||
(
|
||||
wall,
|
||||
(end >= start && start > 0.0).then_some((end - start) * 1000.0),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// VideoToolbox's transfer session.
|
||||
struct Vt {
|
||||
session: *mut c_void,
|
||||
}
|
||||
|
||||
impl Vt {
|
||||
fn open() -> Option<Vt> {
|
||||
let mut session = ptr::null_mut();
|
||||
// SAFETY: an out-parameter.
|
||||
let status = unsafe { VTPixelTransferSessionCreate(ptr::null(), &raw mut session) };
|
||||
(status == 0 && !session.is_null()).then_some(Vt { session })
|
||||
}
|
||||
}
|
||||
|
||||
/// A CVPixelBuffer over an IOSurface, released when dropped.
|
||||
struct PixelBuffer(*mut c_void);
|
||||
|
||||
impl PixelBuffer {
|
||||
fn over(surface: NonNull<c_void>) -> Option<PixelBuffer> {
|
||||
let mut out = ptr::null_mut();
|
||||
// SAFETY: a live IOSurface, which the buffer retains.
|
||||
let status = unsafe {
|
||||
CVPixelBufferCreateWithIOSurface(
|
||||
ptr::null(),
|
||||
surface.as_ptr(),
|
||||
ptr::null(),
|
||||
&raw mut out,
|
||||
)
|
||||
};
|
||||
(status == 0 && !out.is_null()).then_some(PixelBuffer(out))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for PixelBuffer {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the buffer's +1.
|
||||
unsafe { CFRelease(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
/// One case: a name, the formats and sizes, the source window (`x, y, width, height`, zeros for
|
||||
/// the whole source), the destination window, and the transform's flags.
|
||||
struct AbCase {
|
||||
name: &'static str,
|
||||
from: ScalerFormat,
|
||||
source: (u32, u32),
|
||||
to: ScalerFormat,
|
||||
destination: (u32, u32),
|
||||
crop: (f64, f64, f64, f64),
|
||||
rect: (u32, u32, u32, u32),
|
||||
flags: u64,
|
||||
}
|
||||
|
||||
/// The kernel's bench cases, then every case of the conformance suite that scales.
|
||||
fn ab_cases() -> Vec<AbCase> {
|
||||
use ScalerFormat::{Bgra, Nv12VideoRange as N, P010VideoRange, Yuyv};
|
||||
const WHOLE: (f64, f64, f64, f64) = (0.0, 0.0, 0.0, 0.0);
|
||||
const ALL: (u32, u32, u32, u32) = (0, 0, 0, 0);
|
||||
let c = |name, from, source, to, destination, flags| AbCase {
|
||||
name,
|
||||
from,
|
||||
source,
|
||||
to,
|
||||
destination,
|
||||
crop: WHOLE,
|
||||
rect: ALL,
|
||||
flags,
|
||||
};
|
||||
let fix = 0x1000;
|
||||
vec![
|
||||
c(
|
||||
"1080p 420v to 720p BGRA",
|
||||
N,
|
||||
(1920, 1080),
|
||||
Bgra,
|
||||
(1280, 720),
|
||||
fix,
|
||||
),
|
||||
c(
|
||||
"2160p 420v to 1080p 420v",
|
||||
N,
|
||||
(3840, 2160),
|
||||
N,
|
||||
(1920, 1080),
|
||||
fix,
|
||||
),
|
||||
c(
|
||||
"720p BGRA to 720p 420v",
|
||||
Bgra,
|
||||
(1280, 720),
|
||||
N,
|
||||
(1280, 720),
|
||||
fix,
|
||||
),
|
||||
c(
|
||||
"1080p BGRA turned 90",
|
||||
Bgra,
|
||||
(1920, 1080),
|
||||
Bgra,
|
||||
(1080, 1920),
|
||||
fix | 4,
|
||||
),
|
||||
c(
|
||||
"2160p 420v to 2160p BGRA",
|
||||
N,
|
||||
(3840, 2160),
|
||||
Bgra,
|
||||
(3840, 2160),
|
||||
fix,
|
||||
),
|
||||
c("down2-420v", N, (1280, 720), N, (640, 360), fix),
|
||||
c("down4-BGRA", Bgra, (1280, 720), Bgra, (320, 180), fix),
|
||||
c("up4-420v", N, (320, 180), N, (1280, 720), fix),
|
||||
c("up8-BGRA", Bgra, (160, 90), Bgra, (1280, 720), fix),
|
||||
c(
|
||||
"scale-csc-420v-BGRA",
|
||||
N,
|
||||
(1920, 1080),
|
||||
Bgra,
|
||||
(1280, 720),
|
||||
fix,
|
||||
),
|
||||
c(
|
||||
"scale-csc-BGRA-420v",
|
||||
Bgra,
|
||||
(1920, 1080),
|
||||
N,
|
||||
(1280, 720),
|
||||
fix,
|
||||
),
|
||||
c(
|
||||
"scale-x420-420v",
|
||||
P010VideoRange,
|
||||
(1920, 1080),
|
||||
N,
|
||||
(960, 540),
|
||||
fix,
|
||||
),
|
||||
AbCase {
|
||||
crop: (160.0, 90.0, 640.0, 360.0),
|
||||
..c("crop-420v", N, (1280, 720), N, (320, 180), fix)
|
||||
},
|
||||
AbCase {
|
||||
crop: (80.5, 40.25, 320.0, 180.0),
|
||||
..c(
|
||||
"crop-fraction-BGRA",
|
||||
Bgra,
|
||||
(640, 360),
|
||||
Bgra,
|
||||
(320, 180),
|
||||
fix,
|
||||
)
|
||||
},
|
||||
AbCase {
|
||||
rect: (320, 180, 320, 180),
|
||||
..c("rect-scale-BGRA", Bgra, (640, 360), Bgra, (1280, 720), fix)
|
||||
},
|
||||
c(
|
||||
"nearest-up-BGRA",
|
||||
Bgra,
|
||||
(160, 120),
|
||||
Bgra,
|
||||
(480, 360),
|
||||
fix | 0x80,
|
||||
),
|
||||
c(
|
||||
"nearest-down-420v",
|
||||
N,
|
||||
(640, 480),
|
||||
N,
|
||||
(320, 240),
|
||||
fix | 0x80,
|
||||
),
|
||||
c("odd-420v", N, (321, 241), N, (161, 121), fix),
|
||||
c("odd-yuvs-BGRA", Yuyv, (321, 241), Bgra, (161, 121), fix),
|
||||
c(
|
||||
"turn-aniso-BGRA",
|
||||
Bgra,
|
||||
(320, 240),
|
||||
Bgra,
|
||||
(240, 160),
|
||||
fix | 4,
|
||||
),
|
||||
c(
|
||||
"turn-1080-half-420v",
|
||||
N,
|
||||
(1920, 1080),
|
||||
N,
|
||||
(540, 960),
|
||||
fix | 4,
|
||||
),
|
||||
AbCase {
|
||||
crop: (13.0, 7.0, 99.0, 101.0),
|
||||
..c(
|
||||
"odd-crop-rotate-BGRA",
|
||||
Bgra,
|
||||
(320, 240),
|
||||
Bgra,
|
||||
(101, 99),
|
||||
fix | 6,
|
||||
)
|
||||
},
|
||||
c(
|
||||
"rotate-scale-BGRA",
|
||||
Bgra,
|
||||
(320, 240),
|
||||
Bgra,
|
||||
(120, 160),
|
||||
fix | 4,
|
||||
),
|
||||
c("transfer-up2-420v", N, (320, 180), N, (640, 360), 0),
|
||||
c("transfer-up2-BGRA", Bgra, (160, 120), Bgra, (320, 240), 0),
|
||||
c("transfer-up1.5-BGRA", Bgra, (320, 240), Bgra, (480, 360), 0),
|
||||
c("transfer-up4-420v", N, (320, 180), N, (1280, 720), 0),
|
||||
c("transfer-up8-BGRA", Bgra, (160, 90), Bgra, (1280, 720), 0),
|
||||
c("transfer-down2-BGRA", Bgra, (640, 480), Bgra, (320, 240), 0),
|
||||
c(
|
||||
"transfer-csc-up-420v-BGRA",
|
||||
N,
|
||||
(640, 360),
|
||||
Bgra,
|
||||
(1280, 720),
|
||||
0,
|
||||
),
|
||||
c(
|
||||
"transfer-turn-up-BGRA",
|
||||
Bgra,
|
||||
(160, 120),
|
||||
Bgra,
|
||||
(240, 320),
|
||||
4,
|
||||
),
|
||||
c(
|
||||
"transfer-odd-up-BGRA",
|
||||
Bgra,
|
||||
(321, 241),
|
||||
Bgra,
|
||||
(642, 482),
|
||||
0,
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// The median of `times`; NaN for none.
|
||||
fn median(times: &[f64]) -> f64 {
|
||||
let mut sorted = times.to_vec();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
sorted.get(sorted.len() / 2).copied().unwrap_or(f64::NAN)
|
||||
}
|
||||
|
||||
/// What one engine took: wall times, and GPU times where the GPU says.
|
||||
#[derive(Default)]
|
||||
struct Times {
|
||||
wall: Vec<f64>,
|
||||
gpu: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Times {
|
||||
fn show(&self) -> String {
|
||||
if self.wall.is_empty() {
|
||||
return "-".to_owned();
|
||||
}
|
||||
// The median wall time, the quartiles about it, and the median GPU time.
|
||||
let mut sorted = self.wall.clone();
|
||||
sorted.sort_by(f64::total_cmp);
|
||||
let q = |f: usize| sorted[(sorted.len() - 1) * f / 4];
|
||||
let spread = format!("[{:.3}-{:.3}]", q(1), q(3));
|
||||
if self.gpu.is_empty() {
|
||||
format!("{:.3} {spread}", median(&self.wall))
|
||||
} else {
|
||||
format!(
|
||||
"{:.3} {spread} ({:.3})",
|
||||
median(&self.wall),
|
||||
median(&self.gpu)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The kernels beside this Mac's own scalers, interleaved, on the same surfaces (module docs)
|
||||
#[test]
|
||||
#[ignore = "an A/B bench against the Mac's own scalers: run alone, in release"]
|
||||
fn the_kernel_against_the_macs_scalers() {
|
||||
let runtime = StdRuntime::shared();
|
||||
let gpu = metal::MetalGpu::process().expect("Metal opens the kernel");
|
||||
let gpu_name = gpu.name().to_owned();
|
||||
let mut ours = GpuScalerBackend::new(gpu, Arc::clone(&runtime))
|
||||
.create_accelerator()
|
||||
.unwrap();
|
||||
let apple = Apple::open();
|
||||
let mps = Mps::open();
|
||||
let vt = Vt::open();
|
||||
println!(
|
||||
"ab: Metal, {gpu_name}; Apple's scaler {}, MPS {}, VideoToolbox {}",
|
||||
apple.is_some(),
|
||||
mps.is_some(),
|
||||
vt.is_some()
|
||||
);
|
||||
println!(
|
||||
"ab columns: case | ours in place, wall (GPU) ms | ours staged | Apple's scaler | \
|
||||
VTPixelTransferSession | MPS Lanczos | MPS bilinear | ours / fastest native but MPS bilinear, wall"
|
||||
);
|
||||
for case in ab_cases() {
|
||||
let (sw, sh) = case.source;
|
||||
let (dw, dh) = case.destination;
|
||||
let (sl, dl) = (
|
||||
layout(case.from, sw, sh, 64, 0),
|
||||
layout(case.to, dw, dh, 64, 0),
|
||||
);
|
||||
let source = platform_surface(sl.clone(), &picture_bytes(&sl, None), None);
|
||||
let grey = picture_bytes(&dl, Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let destination = platform_surface(dl.clone(), &grey, None);
|
||||
let staged_source = memory(sl.clone(), None);
|
||||
let staged_destination = memory(dl.clone(), Some([0.5, 0.5, 0.5, 1.0]));
|
||||
let fixed = |v: f64| {
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
clippy::cast_precision_loss,
|
||||
reason = "a window's 16.16"
|
||||
)]
|
||||
let f = (v * FIXED_ONE as f64).round() as u64;
|
||||
f
|
||||
};
|
||||
let transform = Transform {
|
||||
source_rect: FixedRect {
|
||||
x: fixed(case.crop.0),
|
||||
y: fixed(case.crop.1),
|
||||
width: fixed(case.crop.2),
|
||||
height: fixed(case.crop.3),
|
||||
},
|
||||
destination_rect: Rect {
|
||||
x: case.rect.0,
|
||||
y: case.rect.1,
|
||||
width: case.rect.2,
|
||||
height: case.rect.3,
|
||||
},
|
||||
flags: TransformFlags(case.flags),
|
||||
..Transform::default()
|
||||
};
|
||||
let Ok(plan) = Plan::new(&transform, &sl, &dl) else {
|
||||
println!("ab {}: no plan", case.name);
|
||||
continue;
|
||||
};
|
||||
let surface_of = |s: &Platform| {
|
||||
s.memory
|
||||
.as_ref()
|
||||
.and_then(|m| m.io_surface().ok())
|
||||
.map(|l| l.as_ptr())
|
||||
};
|
||||
let (Some(src_ref), Some(dst_ref)) = (surface_of(&source), surface_of(&destination)) else {
|
||||
println!("ab {}: no IOSurfaces", case.name);
|
||||
continue;
|
||||
};
|
||||
let turns = case.flags & 7 != 0;
|
||||
let whole = case.crop.2 == 0.0 && case.rect.2 == 0;
|
||||
// SAFETY: the surfaces outlive the textures and the pixel buffers made over them.
|
||||
let as_ref = |p: NonNull<c_void>| unsafe { p.cast::<IOSurfaceRef>().as_ref() };
|
||||
let textures = mps
|
||||
.as_ref()
|
||||
.filter(|_| case.from == case.to && !turns)
|
||||
.and_then(|m| {
|
||||
Some((
|
||||
m.planes(as_ref(src_ref), case.from, sw, sh)?,
|
||||
m.planes(as_ref(dst_ref), case.to, dw, dh)?,
|
||||
))
|
||||
});
|
||||
let buffers = vt
|
||||
.as_ref()
|
||||
.filter(|_| !turns && whole)
|
||||
.and_then(|_| Some((PixelBuffer::over(src_ref)?, PixelBuffer::over(dst_ref)?)));
|
||||
let mut times: [Times; 6] = Default::default();
|
||||
let mut once = |engine: usize, record: bool, times: &mut [Times; 6]| -> bool {
|
||||
let (wall, gpu_ms) = match engine {
|
||||
0 | 1 => {
|
||||
let (s, d): (&dyn GuestSurface, &dyn GuestSurface) = if engine == 0 {
|
||||
(&source, &destination)
|
||||
} else {
|
||||
(&staged_source, &staged_destination)
|
||||
};
|
||||
let mut job = TransformJob {
|
||||
transform: &transform,
|
||||
plan: plan.clone(),
|
||||
source: s,
|
||||
destination: d,
|
||||
hold: GuestHold::nothing(),
|
||||
inputs: Default::default(),
|
||||
outputs: Default::default(),
|
||||
};
|
||||
GPU_TIMES.lock().clear();
|
||||
let started = runtime.now();
|
||||
if ours.transform(&mut job) != io_return::SUCCESS {
|
||||
return false;
|
||||
}
|
||||
let wall = runtime.elapsed_since(started).as_secs_f64() * 1000.0;
|
||||
(
|
||||
wall,
|
||||
GPU_TIMES.lock().first().map(|t| t.as_secs_f64() * 1000.0),
|
||||
)
|
||||
}
|
||||
2 => {
|
||||
let Some(apple) = &apple else { return false };
|
||||
let started = runtime.now();
|
||||
if apple.run(src_ref, dst_ref, &case, &plan) != 0 {
|
||||
return false;
|
||||
}
|
||||
(runtime.elapsed_since(started).as_secs_f64() * 1000.0, None)
|
||||
}
|
||||
3 => {
|
||||
let (Some(vt), Some((s, d))) = (&vt, &buffers) else {
|
||||
return false;
|
||||
};
|
||||
let started = runtime.now();
|
||||
// SAFETY: live pixel buffers and session.
|
||||
if unsafe { VTPixelTransferSessionTransferImage(vt.session, s.0, d.0) } != 0 {
|
||||
return false;
|
||||
}
|
||||
(runtime.elapsed_since(started).as_secs_f64() * 1000.0, None)
|
||||
}
|
||||
_ => {
|
||||
let (Some(m), Some((s, d))) = (&mps, &textures) else {
|
||||
return false;
|
||||
};
|
||||
let kernel = if engine == 4 { &m.lanczos } else { &m.bilinear };
|
||||
m.run(kernel, s, d, &plan, runtime.as_ref())
|
||||
}
|
||||
};
|
||||
if record {
|
||||
times[engine].wall.push(wall);
|
||||
times[engine].gpu.extend(gpu_ms);
|
||||
}
|
||||
true
|
||||
};
|
||||
let mut runs = [false; 6];
|
||||
for (engine, ran) in runs.iter_mut().enumerate() {
|
||||
*ran = once(engine, false, &mut times);
|
||||
if *ran {
|
||||
once(engine, false, &mut times);
|
||||
}
|
||||
}
|
||||
for _ in 0..8 {
|
||||
for (engine, ran) in runs.iter().enumerate() {
|
||||
if *ran {
|
||||
for _ in 0..3 {
|
||||
once(engine, true, &mut times);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// MPS's bilinear scale is shown, as the floor of a submission, and not counted.
|
||||
let fastest = (2..5)
|
||||
.filter(|e| runs[*e])
|
||||
.map(|e| median(×[e].wall))
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
println!(
|
||||
"ab {}: {} | {} | {} | {} | {} | {} | {:.2}x",
|
||||
case.name,
|
||||
times[0].show(),
|
||||
times[1].show(),
|
||||
times[2].show(),
|
||||
times[3].show(),
|
||||
times[4].show(),
|
||||
times[5].show(),
|
||||
median(×[0].wall) / fastest
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,188 +0,0 @@
|
||||
//! The scaler's kernel on the Vulkan platform (`reims_vgpu_vulkan::gpu::scaler`), on the runtime's
|
||||
//! system default device, the one the library's GPU device draws on.
|
||||
//!
|
||||
//! A surface is reached in place through the host's view of its pages ([`DeviceMemory::host_view`],
|
||||
//! on Linux): imported once a mapping, with the view's hold as the import's keep-alive, and kept
|
||||
//! by the mapping's identity until the mapping goes ([`DeviceImports`]), so a transform after the
|
||||
//! first on the same surfaces imports nothing. Where the host lends no view, as on macOS, the
|
||||
//! surface is staged.
|
||||
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_video_core::device_memory::{DeviceImports, DeviceMemory};
|
||||
use reims_vgpu_video_core::runtime::Runtime;
|
||||
use reims_vgpu_vulkan::gpu::scaler::{GpuBuffer, Kernel as GpuKernel, Pass, ScalerGpu, Submitted};
|
||||
|
||||
use super::{Dispatch, Gpu, Kernel};
|
||||
|
||||
/// The most surfaces' imports kept at once.
|
||||
const IMPORTS_KEPT: usize = 32;
|
||||
|
||||
/// The kernel on the Vulkan platform, and its imports of surfaces' pages.
|
||||
pub(crate) struct VulkanGpu {
|
||||
gpu: ScalerGpu,
|
||||
imports: DeviceImports<Imported>,
|
||||
}
|
||||
|
||||
/// A surface's pages imported, and where its first byte lies in them.
|
||||
pub(crate) struct Imported {
|
||||
buffer: GpuBuffer,
|
||||
base: usize,
|
||||
}
|
||||
|
||||
/// A buffer the kernel binds: one of the GPU's own, or a surface's import, shared with the
|
||||
/// imports kept.
|
||||
pub(crate) enum VulkanBuffer {
|
||||
Own(GpuBuffer),
|
||||
Import(Arc<Imported>),
|
||||
}
|
||||
|
||||
impl VulkanBuffer {
|
||||
fn get(&self) -> &GpuBuffer {
|
||||
match self {
|
||||
VulkanBuffer::Own(buffer) => buffer,
|
||||
VulkanBuffer::Import(imported) => &imported.buffer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl VulkanGpu {
|
||||
/// The process's, made at its first use, its imports dropped on threads `runtime` starts:
|
||||
/// `Err` with why where the runtime finds no device or refuses the kernel, which every later
|
||||
/// ask answers the same.
|
||||
pub(crate) fn process(runtime: &Arc<dyn Runtime>) -> Result<Arc<VulkanGpu>, String> {
|
||||
static GPU: OnceLock<Result<Arc<VulkanGpu>, String>> = OnceLock::new();
|
||||
GPU.get_or_init(|| {
|
||||
ScalerGpu::new().map(|gpu| {
|
||||
Arc::new(VulkanGpu {
|
||||
gpu,
|
||||
imports: DeviceImports::new(runtime, "scaler", IMPORTS_KEPT),
|
||||
})
|
||||
})
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Gpu for VulkanGpu {
|
||||
type Buffer = VulkanBuffer;
|
||||
type Run = Submitted;
|
||||
|
||||
fn name(&self) -> &str {
|
||||
self.gpu.name()
|
||||
}
|
||||
|
||||
fn shared(&self, length: usize) -> Result<VulkanBuffer, String> {
|
||||
self.gpu.shared_buffer(length).map(VulkanBuffer::Own)
|
||||
}
|
||||
|
||||
fn table(&self, bytes: &[u8]) -> Result<Self::Buffer, String> {
|
||||
self.gpu.table_buffer(bytes).map(VulkanBuffer::Own)
|
||||
}
|
||||
|
||||
fn scratch(&self, length: usize) -> Result<VulkanBuffer, String> {
|
||||
self.gpu.private_buffer(length).map(VulkanBuffer::Own)
|
||||
}
|
||||
|
||||
fn contents(buffer: &mut VulkanBuffer) -> Option<&mut [u8]> {
|
||||
match buffer {
|
||||
VulkanBuffer::Own(buffer) => buffer.contents(),
|
||||
VulkanBuffer::Import(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn memory(
|
||||
&self,
|
||||
memory: &dyn DeviceMemory,
|
||||
_writes: bool,
|
||||
) -> Result<Option<(VulkanBuffer, usize)>, String> {
|
||||
let identity = memory.identity();
|
||||
let imported = self.imports.get_or_make(
|
||||
&identity,
|
||||
0,
|
||||
|| {
|
||||
let view = memory.host_view().map_err(|e| e.to_string())?;
|
||||
// SAFETY: the view is whole pages of the host's mapping of the surface, which
|
||||
// the host lends only where it may be written, kept mapped by its hold, which the
|
||||
// import keeps until the runtime lets go of it.
|
||||
let buffer = unsafe { self.gpu.memory_buffer(view.first, view.size, view.hold) }?;
|
||||
Ok(Imported {
|
||||
buffer,
|
||||
base: view.offset,
|
||||
})
|
||||
},
|
||||
|| "the surface's mapping is gone".to_owned(),
|
||||
);
|
||||
match imported {
|
||||
Ok(imported) => {
|
||||
let base = imported.base;
|
||||
Ok(Some((VulkanBuffer::Import(imported), base)))
|
||||
}
|
||||
Err(why) => Err(why),
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(
|
||||
&self,
|
||||
dispatches: &[Dispatch<'_, VulkanBuffer>],
|
||||
done: Box<dyn FnOnce() + Send>,
|
||||
) -> Result<Submitted, String> {
|
||||
self.gpu.submit(&passes(dispatches), done)
|
||||
}
|
||||
|
||||
fn submit_apart(
|
||||
&self,
|
||||
dispatches: &[Dispatch<'_, VulkanBuffer>],
|
||||
done: Box<dyn FnOnce() + Send>,
|
||||
) -> Result<Submitted, String> {
|
||||
self.gpu.submit_apart(&passes(dispatches), done)
|
||||
}
|
||||
|
||||
fn finished(run: &Submitted) -> Option<Result<(), String>> {
|
||||
run.finished()
|
||||
}
|
||||
|
||||
fn gpu_time(run: &Submitted) -> Option<Duration> {
|
||||
run.gpu_time()
|
||||
}
|
||||
}
|
||||
|
||||
impl VulkanGpu {
|
||||
/// The runtime's counts of translations, makings and the driver cache's hits and misses, and
|
||||
/// its shader cache's directory, for the probes (`ScalerGpu::cache_counts`).
|
||||
#[cfg(test)]
|
||||
pub(crate) fn cache_counts(&self) -> ([u64; 5], std::path::PathBuf) {
|
||||
self.gpu.cache_counts()
|
||||
}
|
||||
}
|
||||
|
||||
/// The platform's passes of `dispatches`.
|
||||
fn passes<'a>(dispatches: &[Dispatch<'a, VulkanBuffer>]) -> Vec<Pass<'a>> {
|
||||
dispatches
|
||||
.iter()
|
||||
.map(|d| Pass {
|
||||
kernel: kernel(d.kernel),
|
||||
source: d.source.get(),
|
||||
destination: d.destination.get(),
|
||||
taps: d.taps.get(),
|
||||
params: d.params,
|
||||
lines: d.lines.get(),
|
||||
threads: d.threads,
|
||||
group: d.group,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The platform's kernel of `kernel`.
|
||||
fn kernel(kernel: Kernel) -> GpuKernel {
|
||||
match kernel {
|
||||
Kernel::Lines => GpuKernel::Lines,
|
||||
Kernel::Transform => GpuKernel::Transform,
|
||||
Kernel::Across => GpuKernel::Across,
|
||||
Kernel::Shared => GpuKernel::Shared,
|
||||
Kernel::Quads => GpuKernel::Quads,
|
||||
Kernel::TransformAdaptive => GpuKernel::TransformAdaptive,
|
||||
Kernel::TransformBothPlanes => GpuKernel::TransformBothPlanes,
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_core::testkit::FakePlatform;
|
||||
use reims_vgpu_video_core::scaler::backend::ReferenceBackend;
|
||||
use reims_vgpu_video_core::scaler::capabilities::{Capabilities, FormatClass};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Where the fake guest's RAM starts, and its size.
|
||||
const RAM: u64 = 0x4000_0000;
|
||||
const RAM_SIZE: usize = 0x2000;
|
||||
|
||||
/// A guest's RAM: one run of bytes at [`RAM`].
|
||||
#[derive(Default)]
|
||||
struct Ram(Mutex<Vec<u8>>);
|
||||
|
||||
impl Ram {
|
||||
fn new() -> Ram {
|
||||
Ram(Mutex::new(vec![0; RAM_SIZE]))
|
||||
}
|
||||
|
||||
fn range(address: u64, length: usize) -> Option<std::ops::Range<usize>> {
|
||||
let start = usize::try_from(address.checked_sub(RAM)?).ok()?;
|
||||
let end = start.checked_add(length)?;
|
||||
(end <= RAM_SIZE).then_some(start..end)
|
||||
}
|
||||
}
|
||||
|
||||
impl GuestMemory for Ram {
|
||||
fn is_ram(&self, address: u64, length: u64) -> bool {
|
||||
Ram::range(
|
||||
address,
|
||||
usize::try_from(length.max(1)).unwrap_or(usize::MAX),
|
||||
)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn read(&self, address: u64, bytes: &mut [u8]) -> bool {
|
||||
let Some(r) = Ram::range(address, bytes.len()) else {
|
||||
return false;
|
||||
};
|
||||
bytes.copy_from_slice(&self.0.lock()[r]);
|
||||
true
|
||||
}
|
||||
|
||||
fn write(&self, address: u64, bytes: &[u8]) -> bool {
|
||||
let Some(r) = Ram::range(address, bytes.len()) else {
|
||||
return false;
|
||||
};
|
||||
self.0.lock()[r].copy_from_slice(bytes);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn capabilities() -> Capabilities {
|
||||
Capabilities {
|
||||
scaler_version: 1,
|
||||
formats: vec![FormatClass::TwoPlanes420, FormatClass::Argb8888],
|
||||
min_source: 4,
|
||||
max_source: (4096, 4096),
|
||||
min_destination: 4,
|
||||
max_destination: (4096, 4096),
|
||||
max_scale: [8, 8, 8, 4],
|
||||
xy_offsets_with_tiling: (false, false),
|
||||
}
|
||||
}
|
||||
|
||||
fn device() -> ScalerDevice<FakePlatform> {
|
||||
ScalerDevice::with_backend(
|
||||
Arc::new(FakePlatform::new()),
|
||||
ScalerDeviceConfig::default(),
|
||||
Arc::new(ReferenceBackend {
|
||||
capabilities: capabilities(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// The guest kext's type 1 request: its capabilities at `address`, 0x288 bytes.
|
||||
fn capabilities_request(address: u64) -> Vec<u8> {
|
||||
let mut r = vec![0u8; 0x20];
|
||||
r[0..4].copy_from_slice(&1u32.to_le_bytes());
|
||||
r[8..16].copy_from_slice(&address.to_le_bytes());
|
||||
r[0x18..0x20].copy_from_slice(&0x288u64.to_le_bytes());
|
||||
r
|
||||
}
|
||||
|
||||
/// A type 2 request from surface mapping ID `source` to `destination`, with no options.
|
||||
fn transform_request(source: u64, destination: u64) -> Vec<u8> {
|
||||
let mut r = vec![0u8; 0x610];
|
||||
r[0..4].copy_from_slice(&2u32.to_le_bytes());
|
||||
r[0x1b8..0x1c0].copy_from_slice(&source.to_le_bytes());
|
||||
r[0x1c0..0x1c8].copy_from_slice(&destination.to_le_bytes());
|
||||
r
|
||||
}
|
||||
|
||||
fn status(outcome: &ScalerOutcome) -> Option<u32> {
|
||||
match outcome {
|
||||
ScalerOutcome::Reply(r) => Some(u32::from_le_bytes([r[4], r[5], r[6], r[7]])),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Before the start a request is a needs-reset; once started, type 1 writes the backend's
|
||||
/// capabilities into the guest's RAM and puts the count it wrote at R+0x18; after a reset,
|
||||
/// needs-resets again
|
||||
#[test]
|
||||
fn a_device_answers_from_start_to_reset() {
|
||||
let d = device();
|
||||
let ram = Ram::new();
|
||||
let caps = capabilities_request(RAM + 0x100);
|
||||
assert!(matches!(
|
||||
d.process(&caps, caps.len(), &ram),
|
||||
ScalerOutcome::NeedsReset(_)
|
||||
));
|
||||
assert_eq!(d.start(), Ok(()));
|
||||
let outcome = d.process(&caps, caps.len(), &ram);
|
||||
assert_eq!(status(&outcome), Some(0));
|
||||
let ScalerOutcome::Reply(reply) = outcome else {
|
||||
unreachable!("a reply, by the status above");
|
||||
};
|
||||
assert_eq!(reply[0x18..0x20], 0x288u64.to_le_bytes());
|
||||
let written = ram.0.lock()[0x100..0x100 + 0x288].to_vec();
|
||||
assert_eq!(written, capabilities().to_bytes());
|
||||
d.reset();
|
||||
assert!(matches!(
|
||||
d.process(&caps, caps.len(), &ram),
|
||||
ScalerOutcome::NeedsReset(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// Capabilities outside the guest's RAM are a needs-reset, as Apple's host answers an address
|
||||
/// it cannot translate
|
||||
#[test]
|
||||
fn capabilities_outside_ram_are_a_needs_reset() {
|
||||
let d = device();
|
||||
let ram = Ram::new();
|
||||
d.start().unwrap();
|
||||
let caps = capabilities_request(RAM + RAM_SIZE as u64 - 0x100);
|
||||
assert!(matches!(
|
||||
d.process(&caps, caps.len(), &ram),
|
||||
ScalerOutcome::NeedsReset(_)
|
||||
));
|
||||
}
|
||||
|
||||
/// With no IOSurface device in the process, a transform's surfaces are not found: the request is
|
||||
/// answered, with kIOReturnNotFound
|
||||
#[test]
|
||||
fn surfaces_without_a_mapper_are_not_found() {
|
||||
let d = device();
|
||||
let ram = Ram::new();
|
||||
d.start().unwrap();
|
||||
let t = transform_request(3, 4);
|
||||
assert_eq!(
|
||||
status(&d.process(&t, t.len(), &ram)),
|
||||
Some(reims_vgpu_video_core::scaler::io_return::NOT_FOUND)
|
||||
);
|
||||
}
|
||||
|
||||
/// A Mac's device transforms on its GPU, Metal's default device, whatever the platform. Its waits
|
||||
/// for the GPU are on std's runtime, not the testkit platform's, whose virtual clock no such wait
|
||||
/// would pass.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn a_mac_transforms_on_its_gpu() {
|
||||
let made = ScalerDevice::on_host_gpu(
|
||||
Arc::new(FakePlatform::new()),
|
||||
&reims_vgpu_video_core::runtime::StdRuntime::shared(),
|
||||
ScalerDeviceConfig::default(),
|
||||
);
|
||||
assert!(made.scales(), "{made:?}");
|
||||
}
|
||||
|
||||
/// A host without a GPU has a device all the same, one that does not scale: its
|
||||
/// start is a needs-reset, as Apple's where it cannot make an accelerator, and so is a request
|
||||
/// before it and after
|
||||
#[test]
|
||||
fn a_host_without_a_gpu_has_a_device_that_does_not_scale() {
|
||||
let d = ScalerDevice::without_gpu(
|
||||
Arc::new(FakePlatform::new()),
|
||||
ScalerDeviceConfig::default(),
|
||||
"a stand-in host with none".to_owned(),
|
||||
);
|
||||
assert!(!d.scales());
|
||||
let ram = Ram::new();
|
||||
let caps = capabilities_request(RAM);
|
||||
assert!(matches!(
|
||||
d.process(&caps, caps.len(), &ram),
|
||||
ScalerOutcome::NeedsReset(_)
|
||||
));
|
||||
assert_eq!(d.start(), Err("IOSurfaceAcceleratorCreate failed"));
|
||||
assert!(matches!(
|
||||
d.process(&caps, caps.len(), &ram),
|
||||
ScalerOutcome::NeedsReset(_)
|
||||
));
|
||||
assert!(device().scales());
|
||||
}
|
||||
@@ -17,7 +17,6 @@
|
||||
|
||||
use std::sync::{Arc, Once, OnceLock};
|
||||
|
||||
use reims_vgpu_core::platform::os::Preferences;
|
||||
use reims_vgpu_core::rt::is_our_thread;
|
||||
use reims_vgpu_core::tasks::isolation::TaskThreads;
|
||||
#[cfg(target_os = "macos")]
|
||||
@@ -63,26 +62,6 @@ pub fn vulkan_platform() -> Arc<VulkanPlatform> {
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// The process's settings reader, for [`crate::DisplayConfig::apply_preferences`] and
|
||||
/// [`crate::DisplayMode::with_preferences`]: every key is absent, as the library reads no
|
||||
/// preferences domain.
|
||||
pub fn preferences() -> &'static dyn Preferences {
|
||||
&NoPreferences
|
||||
}
|
||||
|
||||
/// A reader with no settings.
|
||||
struct NoPreferences;
|
||||
|
||||
impl Preferences for NoPreferences {
|
||||
fn app_bool(&self, _key: &str) -> (bool, bool) {
|
||||
(false, false)
|
||||
}
|
||||
|
||||
fn any_user_f32(&self, _key: &str) -> Option<f32> {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The line the hook writes before it aborts.
|
||||
pub(crate) fn hook_message(info: &dyn std::fmt::Display) -> String {
|
||||
format!("reims-vgpu: panic: {info}\n")
|
||||
|
||||
@@ -1,391 +0,0 @@
|
||||
//! Frame statistics, a diagnostic. With `REIMS_VGPU_STATS` on (`1`, `true`, `yes` or `on`), each
|
||||
//! display gets a [`DisplayStats`], and the library's thread `reims-vgpu.stats` writes one line
|
||||
//! per live display to stderr every second, by port:
|
||||
//!
|
||||
//! ```text
|
||||
//! reims-vgpu stats: port 0: guest 59.9/s, max gap 17.2 ms; window 60.0/s, max gap 16.9 ms; window GPU 0.41 ms avg, 0.97 ms max
|
||||
//! ```
|
||||
//!
|
||||
//! - *guest*: the frames the guest presented, as the display's new-frame callback reports them,
|
||||
//! per second, and the longest time between two of them.
|
||||
//! - *window*, for a display made with a window: the frames its sink drew, per second, and the
|
||||
//! longest time between two.
|
||||
//! - *window GPU*: the GPU time of the sink's draws, as the sink measures it, the mean and the
|
||||
//! longest; `-` while the sink has reported none. The Vulkan platform's sink measures it (its
|
||||
//! command buffers' GPU end less their start, as the runtime answers them), on either OS; the
|
||||
//! Metal platform's does not.
|
||||
//!
|
||||
//! A rate is over the time since the display's last line. A gap still open when the line is
|
||||
//! written counts too, so a guest that stops presenting shows a gap that grows by a second each
|
||||
//! line; `-` until the first frame.
|
||||
//!
|
||||
//! The inputs are three hooks. [`DisplayStats::guest_present`] is called by the closure
|
||||
//! [`observe`] wraps around the display's new-frame callback (for a window display, the window's
|
||||
//! tee). A window's sink counts each frame it commits with [`DisplayStats::window_present`], and
|
||||
//! the Vulkan platform's sink reports each one's GPU time with [`DisplayStats::window_gpu_time`],
|
||||
//! through
|
||||
//! the stats [`of_display`] finds for its display (`window::SinkDisplay`). Each reads the platform's monotonic clock and updates atomics: no lock,
|
||||
//! no wait, nothing the guest or the host sees. With the switch off, no display has stats,
|
||||
//! nothing is wrapped and no thread is made.
|
||||
//!
|
||||
//! The lines go to stderr directly, not through the log, so that the switch alone shows them. A
|
||||
//! failed write is ignored.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::io::Write as _;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use std::sync::{Arc, OnceLock, Weak};
|
||||
use std::time::Duration;
|
||||
|
||||
use reims_vgpu_core::display::Display as CoreDisplay;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::os::{Deadline, MonoTime, Threads, TimerClock};
|
||||
use reims_vgpu_core::sync::{Condvar, Mutex};
|
||||
|
||||
use crate::NewFrameFn;
|
||||
|
||||
/// The switch.
|
||||
const STATS_VAR: &str = "REIMS_VGPU_STATS";
|
||||
|
||||
/// The time between two reports.
|
||||
const PERIOD: Duration = Duration::from_secs(1);
|
||||
|
||||
/// A [`Presents`] field's value before the first frame.
|
||||
const NONE: u64 = u64::MAX;
|
||||
|
||||
/// Whether the environment turns the statistics on, read once per process. A value that is not
|
||||
/// UTF-8 counts as unset.
|
||||
fn on() -> bool {
|
||||
static ON: OnceLock<bool> = OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var(STATS_VAR).is_ok_and(|v| switch(&v)))
|
||||
}
|
||||
|
||||
/// Whether a switch's value turns it on.
|
||||
fn switch(value: &str) -> bool {
|
||||
let value = value.trim();
|
||||
["1", "true", "yes", "on"]
|
||||
.iter()
|
||||
.any(|on| value.eq_ignore_ascii_case(on))
|
||||
}
|
||||
|
||||
/// The frames of one kind: how many since the last report, when the last was, and the longest
|
||||
/// time between two since the last report (nanoseconds on the monotonic clock).
|
||||
struct Presents {
|
||||
count: AtomicU64,
|
||||
last: AtomicU64,
|
||||
max_gap: AtomicU64,
|
||||
}
|
||||
|
||||
impl Presents {
|
||||
fn new() -> Presents {
|
||||
Presents {
|
||||
count: AtomicU64::new(0),
|
||||
last: AtomicU64::new(NONE),
|
||||
max_gap: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame at `now`.
|
||||
fn record(&self, now: u64) {
|
||||
self.count.fetch_add(1, Relaxed);
|
||||
let last = self.last.swap(now, Relaxed);
|
||||
if last != NONE {
|
||||
self.max_gap.fetch_max(now.saturating_sub(last), Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// The frames since the last report, and the longest gap among them and the one still open
|
||||
/// at `now` (`None` before the first frame); starts the next period.
|
||||
fn take(&self, now: u64) -> (u64, Option<u64>) {
|
||||
let count = self.count.swap(0, Relaxed);
|
||||
let ended = self.max_gap.swap(0, Relaxed);
|
||||
let last = self.last.load(Relaxed);
|
||||
let gap = (last != NONE).then(|| ended.max(now.saturating_sub(last)));
|
||||
(count, gap)
|
||||
}
|
||||
}
|
||||
|
||||
/// The GPU times of the window's draws since the last report: how many, their sum and the
|
||||
/// longest (nanoseconds).
|
||||
#[derive(Default)]
|
||||
struct GpuTimes {
|
||||
count: AtomicU64,
|
||||
total: AtomicU64,
|
||||
max: AtomicU64,
|
||||
}
|
||||
|
||||
/// One display's statistics (module doc).
|
||||
pub(crate) struct DisplayStats {
|
||||
/// The display's port.
|
||||
port: u64,
|
||||
/// Whether the display was made with a window.
|
||||
window: bool,
|
||||
/// The platform's clock.
|
||||
clock: Arc<dyn TimerClock>,
|
||||
/// The guest's presents.
|
||||
guest: Presents,
|
||||
/// The window's draws.
|
||||
drawn: Presents,
|
||||
/// The window's GPU times.
|
||||
gpu: GpuTimes,
|
||||
/// When the period of the next report started.
|
||||
since: AtomicU64,
|
||||
}
|
||||
|
||||
impl DisplayStats {
|
||||
/// The stats of the display on `port`, from `now` on `clock`.
|
||||
fn new(clock: Arc<dyn TimerClock>, port: u64, window: bool) -> DisplayStats {
|
||||
let since = AtomicU64::new(mono_now(&*clock));
|
||||
DisplayStats {
|
||||
port,
|
||||
window,
|
||||
clock,
|
||||
guest: Presents::new(),
|
||||
drawn: Presents::new(),
|
||||
gpu: GpuTimes::default(),
|
||||
since,
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest presented a frame.
|
||||
pub(crate) fn guest_present(&self) {
|
||||
self.guest.record(mono_now(&*self.clock));
|
||||
}
|
||||
|
||||
/// The window's sink drew a frame.
|
||||
pub(crate) fn window_present(&self) {
|
||||
self.drawn.record(mono_now(&*self.clock));
|
||||
}
|
||||
|
||||
/// One of the window's draws took `gpu` of GPU time.
|
||||
#[cfg_attr(
|
||||
not(any(test, vulkan_platform)),
|
||||
expect(
|
||||
dead_code,
|
||||
reason = "only the Vulkan platform's sink measures its frames' GPU time"
|
||||
)
|
||||
)]
|
||||
pub(crate) fn window_gpu_time(&self, gpu: Duration) {
|
||||
let ns = u64::try_from(gpu.as_nanos()).unwrap_or(u64::MAX);
|
||||
self.gpu.count.fetch_add(1, Relaxed);
|
||||
self.gpu.total.fetch_add(ns, Relaxed);
|
||||
self.gpu.max.fetch_max(ns, Relaxed);
|
||||
}
|
||||
|
||||
/// The line for the period up to now, which starts the next.
|
||||
fn report(&self) -> String {
|
||||
let now = mono_now(&*self.clock);
|
||||
let since = self.since.swap(now, Relaxed);
|
||||
let seconds = Duration::from_nanos(now.saturating_sub(since)).as_secs_f64();
|
||||
let mut line = format!("reims-vgpu stats: port {}: ", self.port);
|
||||
presents(&mut line, "guest", self.guest.take(now), seconds);
|
||||
if self.window {
|
||||
line.push_str("; ");
|
||||
presents(&mut line, "window", self.drawn.take(now), seconds);
|
||||
line.push_str("; window GPU ");
|
||||
let count = self.gpu.count.swap(0, Relaxed);
|
||||
let total = self.gpu.total.swap(0, Relaxed);
|
||||
let max = self.gpu.max.swap(0, Relaxed);
|
||||
match total.checked_div(count) {
|
||||
None => line.push('-'),
|
||||
Some(mean) => {
|
||||
let _ = write!(
|
||||
line,
|
||||
"{:.2} ms avg, {:.2} ms max",
|
||||
millis(mean),
|
||||
millis(max)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
}
|
||||
|
||||
/// `kind`'s rate over `seconds` and its longest gap, onto `line`.
|
||||
fn presents(line: &mut String, kind: &str, (count, gap): (u64, Option<u64>), seconds: f64) {
|
||||
let rate = if seconds > 0.0 {
|
||||
count as f64 / seconds
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let _ = write!(line, "{kind} {rate:.1}/s, max gap ");
|
||||
match gap {
|
||||
Some(gap) => {
|
||||
let _ = write!(line, "{:.1} ms", millis(gap));
|
||||
}
|
||||
None => line.push('-'),
|
||||
}
|
||||
}
|
||||
|
||||
/// Nanoseconds as milliseconds.
|
||||
fn millis(ns: u64) -> f64 {
|
||||
Duration::from_nanos(ns).as_secs_f64() * 1000.0
|
||||
}
|
||||
|
||||
/// Nanoseconds now on `clock`'s monotonic clock.
|
||||
fn mono_now(clock: &dyn TimerClock) -> u64 {
|
||||
clock.now_on(Deadline::Mono(MonoTime::from_nanos(0)))
|
||||
}
|
||||
|
||||
/// With the statistics on, the stats of a new display on `port`, made with a window or not, and
|
||||
/// `new_frame` wrapped to count the guest's presents before it runs: `None`, with `new_frame`
|
||||
/// untouched, when they are off, when there is no new-frame callback to count them by, or when
|
||||
/// the platform has no clock. The callback stays present or absent as it was, which the guest
|
||||
/// reads.
|
||||
pub(crate) fn observe(
|
||||
threads: &dyn Threads,
|
||||
port: u64,
|
||||
window: bool,
|
||||
new_frame: &mut Option<NewFrameFn>,
|
||||
) -> Option<Arc<DisplayStats>> {
|
||||
if !on() {
|
||||
return None;
|
||||
}
|
||||
wrap(threads.timer_clock(), port, window, new_frame)
|
||||
}
|
||||
|
||||
/// [`observe`] with the statistics on, on `clock`.
|
||||
fn wrap(
|
||||
clock: Option<Arc<dyn TimerClock>>,
|
||||
port: u64,
|
||||
window: bool,
|
||||
new_frame: &mut Option<NewFrameFn>,
|
||||
) -> Option<Arc<DisplayStats>> {
|
||||
let clock = clock?;
|
||||
let inner = new_frame.take()?;
|
||||
let stats = Arc::new(DisplayStats::new(clock, port, window));
|
||||
*new_frame = Some(counting(&stats, inner));
|
||||
Some(stats)
|
||||
}
|
||||
|
||||
/// `inner`, after counting each call as one of the guest's presents in `stats`.
|
||||
fn counting(stats: &Arc<DisplayStats>, inner: NewFrameFn) -> NewFrameFn {
|
||||
let stats = Arc::clone(stats);
|
||||
Arc::new(move || {
|
||||
stats.guest_present();
|
||||
inner();
|
||||
})
|
||||
}
|
||||
|
||||
/// The stats of each display made, by its core display's address, until they end.
|
||||
struct Registry {
|
||||
displays: Vec<(usize, Weak<DisplayStats>)>,
|
||||
/// Whether the reporting thread runs.
|
||||
reporting: bool,
|
||||
}
|
||||
|
||||
/// The process's registry.
|
||||
fn registry() -> &'static Mutex<Registry> {
|
||||
static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
|
||||
REGISTRY.get_or_init(|| {
|
||||
Mutex::new(Registry {
|
||||
displays: Vec::new(),
|
||||
reporting: false,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// A core display's address, its key in the registry.
|
||||
fn key<P: Platform>(display: &Weak<CoreDisplay<P>>) -> usize {
|
||||
display.as_ptr().cast::<()>().addr()
|
||||
}
|
||||
|
||||
/// Registers `stats` as `display`'s, once the display exists, for [`of_display`] and the
|
||||
/// reports; starts the reporting thread at the first. Entries whose stats have ended, or that
|
||||
/// another display at the same address left, are dropped here.
|
||||
pub(crate) fn register<P: Platform>(stats: &Arc<DisplayStats>, display: &Weak<CoreDisplay<P>>) {
|
||||
let mut registry = registry().lock();
|
||||
registry.add(key(display), stats);
|
||||
if !registry.reporting {
|
||||
registry.reporting = start(Arc::clone(&stats.clock));
|
||||
}
|
||||
}
|
||||
|
||||
impl Registry {
|
||||
/// `stats` at `key`, in place of any entry there and of the ended ones.
|
||||
fn add(&mut self, key: usize, stats: &Arc<DisplayStats>) {
|
||||
self.displays
|
||||
.retain(|(k, s)| *k != key && s.strong_count() > 0);
|
||||
self.displays.push((key, Arc::downgrade(stats)));
|
||||
}
|
||||
|
||||
/// The stats at `key`, while they live.
|
||||
fn find(&self, key: usize) -> Option<Arc<DisplayStats>> {
|
||||
self.displays
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.and_then(|(_, s)| s.upgrade())
|
||||
}
|
||||
|
||||
/// The live stats, by port; drops the ended ones.
|
||||
fn live(&mut self) -> Vec<Arc<DisplayStats>> {
|
||||
self.displays.retain(|(_, s)| s.strong_count() > 0);
|
||||
let mut live: Vec<Arc<DisplayStats>> = self
|
||||
.displays
|
||||
.iter()
|
||||
.filter_map(|(_, s)| s.upgrade())
|
||||
.collect();
|
||||
live.sort_by_key(|s| s.port);
|
||||
live
|
||||
}
|
||||
}
|
||||
|
||||
/// The stats of `display`, for its window's sink: `None` with the statistics off.
|
||||
pub(crate) fn of_display<P: Platform>(display: &Weak<CoreDisplay<P>>) -> Option<Arc<DisplayStats>> {
|
||||
registry().lock().find(key(display))
|
||||
}
|
||||
|
||||
/// The lines of `displays`, each ending in a newline. The stats are released after the
|
||||
/// registry's lock, which the caller no longer holds.
|
||||
fn lines(displays: &[Arc<DisplayStats>]) -> String {
|
||||
let mut lines = String::new();
|
||||
for stats in displays {
|
||||
lines.push_str(&stats.report());
|
||||
lines.push('\n');
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Starts the reporting thread, which waits on `clock`: whether it started. One that did not is
|
||||
/// tried again at the next display.
|
||||
fn start(clock: Arc<dyn TimerClock>) -> bool {
|
||||
let started = std::thread::Builder::new()
|
||||
.name("reims-vgpu.stats".into())
|
||||
.spawn(move || report_forever(&*clock));
|
||||
if let Err(e) = &started {
|
||||
log::warn!("frame statistics: no reporting thread: {e}");
|
||||
}
|
||||
started.is_ok()
|
||||
}
|
||||
|
||||
/// Every [`PERIOD`] on `clock`, the lines of every live display, written to stderr in one write.
|
||||
/// A late wake skips to the next point of the schedule.
|
||||
fn report_forever(clock: &dyn TimerClock) -> ! {
|
||||
let lock = Mutex::new(false);
|
||||
let cv = Condvar::new();
|
||||
let step = u64::try_from(PERIOD.as_nanos()).unwrap_or(u64::MAX);
|
||||
let mut next = mono_now(clock).saturating_add(step);
|
||||
loop {
|
||||
{
|
||||
let mut guard = lock.lock();
|
||||
while mono_now(clock) < next {
|
||||
clock.wait_until(&cv, &mut guard, Deadline::Mono(MonoTime::from_nanos(next)));
|
||||
}
|
||||
}
|
||||
let live = registry().lock().live();
|
||||
let lines = lines(&live);
|
||||
drop(live);
|
||||
if !lines.is_empty() {
|
||||
let _ = std::io::stderr().lock().write_all(lines.as_bytes());
|
||||
}
|
||||
let now = mono_now(clock);
|
||||
next = next.saturating_add(step);
|
||||
if next <= now {
|
||||
next = now.saturating_add(step);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,191 +0,0 @@
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use reims_vgpu_core::sync::MutexGuard;
|
||||
use reims_vgpu_core::testkit::FakePlatform;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A clock the test sets: `now_on` answers its time, and a wait returns at once.
|
||||
#[derive(Default)]
|
||||
struct SetClock(AtomicU64);
|
||||
|
||||
impl SetClock {
|
||||
fn at(&self, ms: u64) {
|
||||
self.0.store(ms * 1_000_000, Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl TimerClock for SetClock {
|
||||
fn now_on(&self, _: Deadline) -> u64 {
|
||||
self.0.load(Relaxed)
|
||||
}
|
||||
|
||||
fn wait_until(&self, _: &Condvar, _: &mut MutexGuard<'_, bool>, _: Deadline) {}
|
||||
}
|
||||
|
||||
/// Stats of a display on `port` over a clock at `start_ms`, and the clock.
|
||||
fn stats(port: u64, window: bool, start_ms: u64) -> (Arc<SetClock>, DisplayStats) {
|
||||
let clock = Arc::new(SetClock::default());
|
||||
clock.at(start_ms);
|
||||
let stats = DisplayStats::new(clock.clone(), port, window);
|
||||
(clock, stats)
|
||||
}
|
||||
|
||||
/// The usual words turn the switch on, around spaces and in any case; anything else is off
|
||||
#[test]
|
||||
fn the_switch_takes_the_usual_words() {
|
||||
for on in ["1", "true", "YES", " on "] {
|
||||
assert!(switch(on), "{on}");
|
||||
}
|
||||
for off in ["", "0", "off", "2", "enable"] {
|
||||
assert!(!switch(off), "{off}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line gives the guest's rate over the period and its longest gap; before the first frame
|
||||
/// the gap is `-`, and a display without a window has no window part
|
||||
#[test]
|
||||
fn a_line_without_a_window() {
|
||||
let (clock, s) = stats(3, false, 5);
|
||||
clock.at(1005);
|
||||
assert_eq!(
|
||||
s.report(),
|
||||
"reims-vgpu stats: port 3: guest 0.0/s, max gap -"
|
||||
);
|
||||
for ms in [1010, 1020, 1050, 1060] {
|
||||
clock.at(ms);
|
||||
s.guest_present();
|
||||
}
|
||||
clock.at(1505);
|
||||
assert_eq!(
|
||||
s.report(),
|
||||
"reims-vgpu stats: port 3: guest 8.0/s, max gap 445.0 ms"
|
||||
);
|
||||
}
|
||||
|
||||
/// The longest gap is the longest between two frames of the period, or the one still open
|
||||
/// when it is longer: a guest that stops presenting shows a gap that grows each line
|
||||
#[test]
|
||||
fn the_open_gap_counts() {
|
||||
let (clock, s) = stats(0, false, 0);
|
||||
for ms in [100, 130, 140] {
|
||||
clock.at(ms);
|
||||
s.guest_present();
|
||||
}
|
||||
clock.at(150);
|
||||
assert!(s.report().ends_with("max gap 30.0 ms"));
|
||||
clock.at(1150);
|
||||
assert!(s.report().ends_with("guest 0.0/s, max gap 1010.0 ms"));
|
||||
clock.at(2150);
|
||||
assert!(s.report().ends_with("max gap 2010.0 ms"));
|
||||
clock.at(2160);
|
||||
s.guest_present();
|
||||
clock.at(2170);
|
||||
assert!(s.report().ends_with("max gap 2020.0 ms"));
|
||||
clock.at(2180);
|
||||
assert!(s.report().ends_with("max gap 20.0 ms"));
|
||||
}
|
||||
|
||||
/// A window display's line adds the sink's draws and their GPU times, each period's own
|
||||
#[test]
|
||||
fn a_line_with_a_window() {
|
||||
let (clock, s) = stats(1, true, 0);
|
||||
for ms in [10, 26, 42] {
|
||||
clock.at(ms);
|
||||
s.guest_present();
|
||||
s.window_present();
|
||||
}
|
||||
s.window_gpu_time(Duration::from_micros(400));
|
||||
s.window_gpu_time(Duration::from_micros(1_000));
|
||||
s.window_gpu_time(Duration::from_micros(700));
|
||||
clock.at(500);
|
||||
assert_eq!(
|
||||
s.report(),
|
||||
"reims-vgpu stats: port 1: guest 6.0/s, max gap 458.0 ms; window 6.0/s, max gap 458.0 ms; \
|
||||
window GPU 0.70 ms avg, 1.00 ms max"
|
||||
);
|
||||
clock.at(1000);
|
||||
assert_eq!(
|
||||
s.report(),
|
||||
"reims-vgpu stats: port 1: guest 0.0/s, max gap 958.0 ms; window 0.0/s, max gap 958.0 ms; \
|
||||
window GPU -"
|
||||
);
|
||||
}
|
||||
|
||||
/// Wrapping counts each new frame before the callback runs; without a clock or a callback
|
||||
/// there are no stats and the callback is as it was
|
||||
#[test]
|
||||
fn wrapping_counts_each_new_frame() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let c = calls.clone();
|
||||
let inner: NewFrameFn = Arc::new(move || {
|
||||
c.fetch_add(1, Relaxed);
|
||||
});
|
||||
let clock: Arc<dyn TimerClock> = Arc::new(SetClock::default());
|
||||
|
||||
let mut none: Option<NewFrameFn> = None;
|
||||
assert!(wrap(Some(clock.clone()), 0, false, &mut none).is_none());
|
||||
assert!(none.is_none());
|
||||
let mut kept = Some(inner.clone());
|
||||
assert!(wrap(None, 0, false, &mut kept).is_none());
|
||||
assert!(Arc::ptr_eq(kept.as_ref().unwrap(), &inner));
|
||||
|
||||
let mut new_frame = Some(inner.clone());
|
||||
let s = wrap(Some(clock), 0, false, &mut new_frame).unwrap();
|
||||
assert!(!Arc::ptr_eq(new_frame.as_ref().unwrap(), &inner));
|
||||
new_frame.as_ref().unwrap()();
|
||||
new_frame.as_ref().unwrap()();
|
||||
assert_eq!(calls.load(Relaxed), 2);
|
||||
assert_eq!(s.guest.count.load(Relaxed), 2);
|
||||
// The wrapper holds the stats and the callback, and drops both with it.
|
||||
drop(new_frame);
|
||||
assert_eq!((Arc::strong_count(&s), Arc::strong_count(&inner)), (1, 2));
|
||||
}
|
||||
|
||||
/// The registry finds a display's stats while they live, keeps one entry per address, and
|
||||
/// gives the live ones by port
|
||||
#[test]
|
||||
fn the_registry_finds_live_stats_by_address() {
|
||||
let mut r = Registry {
|
||||
displays: Vec::new(),
|
||||
reporting: false,
|
||||
};
|
||||
let (_c2, two) = stats(2, false, 0);
|
||||
let (_c0, zero) = stats(0, false, 0);
|
||||
let (_c1, one) = stats(1, false, 0);
|
||||
let (two, zero, one) = (Arc::new(two), Arc::new(zero), Arc::new(one));
|
||||
r.add(0x20, &two);
|
||||
r.add(0x10, &zero);
|
||||
r.add(0x30, &one);
|
||||
assert!(Arc::ptr_eq(&r.find(0x10).unwrap(), &zero));
|
||||
assert!(r.find(0x40).is_none());
|
||||
let ports: Vec<u64> = r.live().iter().map(|s| s.port).collect();
|
||||
assert_eq!(ports, [0, 1, 2]);
|
||||
// An ended display's stats are not found, and its entry goes at the next live().
|
||||
drop(zero);
|
||||
assert!(r.find(0x10).is_none());
|
||||
assert_eq!(r.live().len(), 2);
|
||||
assert_eq!(r.displays.len(), 2);
|
||||
// A display at an address another left takes its entry.
|
||||
let (_c3, three) = stats(3, false, 0);
|
||||
let three = Arc::new(three);
|
||||
r.add(0x20, &three);
|
||||
assert!(Arc::ptr_eq(&r.find(0x20).unwrap(), &three));
|
||||
assert_eq!(r.displays.len(), 2);
|
||||
let text = lines(&r.live());
|
||||
assert_eq!(text.lines().count(), 2);
|
||||
assert!(text.starts_with("reims-vgpu stats: port 1: ") && text.ends_with('\n'));
|
||||
}
|
||||
|
||||
/// A sink finds its display's stats by its reference to the display, while they live
|
||||
#[test]
|
||||
fn a_sink_finds_its_display_s_stats() {
|
||||
let display = Weak::<CoreDisplay<FakePlatform>>::new();
|
||||
assert!(of_display(&display).is_none());
|
||||
let (_clock, s) = stats(5, true, 0);
|
||||
let s = Arc::new(s);
|
||||
registry().lock().add(key(&display), &s);
|
||||
assert!(Arc::ptr_eq(&of_display(&display).unwrap(), &s));
|
||||
drop(s);
|
||||
assert!(of_display(&display).is_none());
|
||||
}
|
||||
@@ -1,618 +1,4 @@
|
||||
//! [`VideoDevice`]: the host side of the paravirtualized VideoToolbox device that a macOS guest's
|
||||
//! AppleVideoToolboxParavirtualization drives (virtio-PCI `106b:1a03`), made from a
|
||||
//! [`VideoDeviceConfig`]: reims-vgpu-video-core's host session, over this library's IOSurface
|
||||
//! mapper and the host's callback.
|
||||
//!
|
||||
//! The device has no transport of its own. Its host (QEMU's `apple-videotoolbox-pci`) owns the
|
||||
//! two virtqueues: it hands each guest-to-host message of queue 0 to [`VideoDevice::deliver`] and
|
||||
//! writes the status that answers into the element, and it takes each host-to-guest message
|
||||
//! through [`VideoDeviceConfig::send_to_guest`] into the next buffer the guest posts on queue 1.
|
||||
//!
|
||||
//! - **Lifecycle**, as Apple's host runs it: [`VideoDevice::start`], at the guest's DRIVER_OK,
|
||||
//! makes the host session (core's `HostSession`). A reset or a stop ends it in two phases:
|
||||
//! [`VideoDevice::invalidate`], after which it sends the guest nothing more, then the
|
||||
//! completion, once the work it had started has drained ([`VideoDevice::reset`] runs both). A
|
||||
//! message delivered while there is no session answers [`INVALID_SESSION`].
|
||||
//! - **Messages.** The session reads each message as Apple's device does: a leading `subs` atom
|
||||
//! of 0x30 bytes names up to five IOSurfaces by mapping ID, then the `vtpv` message. It answers
|
||||
//! the status, and its replies and the messages of its decoders go to `send_to_guest`, from the
|
||||
//! delivering thread or from a session's own.
|
||||
//! - **Surfaces** are reached through the IOSurface device the config names, held unretained, as
|
||||
//! the graphics device's mapper service holds it: a lookup after its teardown finds no surface.
|
||||
//! With none, each lookup goes to the process's latest IOSurface device, as a device made with
|
||||
//! `use_iosurface_mapper` finds it, so the host need not make the two in any order. A surface
|
||||
//! the session holds is one reference to it ([`MappedSurface`]), a hold the guest sees: the
|
||||
//! mapper answers an unmap of it Busy while the hold lives. Its bytes are lent to the session's
|
||||
//! decoders through the platform ([`ApiPlatform::lend_surface_bytes`]), and to its encoders to
|
||||
//! read ([`ApiPlatform::lend_surface_bytes_for_reading`]). Its memory is lent to the decoders'
|
||||
//! device too, where the platform lends it ([`ApiPlatform::surface_device_memory`]), so that
|
||||
//! the device writes frames into it with no copy by the CPU, while the session holds it. Each
|
||||
//! write of it, in a lend or by a device, is reported with its guest pages
|
||||
//! ([`crate::device_writes`]), so a graphics device's cache of the surface does not hide it.
|
||||
//! - **Codecs.** The session decodes and encodes on the host's backend, which the device picks
|
||||
//! itself ([`backend_choice`]): VideoToolbox on macOS (reims-vgpu-video-videotoolbox); on
|
||||
//! Linux, on the GPU the library's GPU device runs on, NVIDIA's NVDEC and NVENC where it is an
|
||||
//! NVIDIA GPU that CUDA opens (reims-vgpu-video-nvidia), else VA-API on its render node
|
||||
//! (reims-vgpu-video-vaapi), and a hardware GPU of the host's where that GPU is a software
|
||||
//! rasterizer or offers no video. It offers what the driver decodes and encodes. The backend is
|
||||
//! opened once, at the device's creation, and the choice and its reason are logged; where none
|
||||
//! opens the session lists no codec, and a guest's VideoToolbox decodes and encodes in
|
||||
//! software. Its JPEG engine (`jcap`, `jdec`) decodes on the backend's JPEG decoder, VA-API's
|
||||
//! `VaapiJpegDecoder` on the decoders' display; where the backend has none (NVIDIA's and
|
||||
//! VideoToolbox's have none), the engine answers as Apple's host without JPEG hardware. Core
|
||||
//! copies a `jdec`'s source out of its read lend, decodes on a thread of its own with no surface
|
||||
//! lent, waiting 10 s at most for it, and copies the picture into the destination in a write
|
||||
//! lend after. The `jdec` is answered inside [`VideoDevice::deliver`], so QEMU's device delivers
|
||||
//! on a worker thread of its own, off the main loop.
|
||||
//!
|
||||
//! Every call runs as an entry ([`crate::entry`]); the device's last drop is a reset.
|
||||
//! The host's hardware video for the reims-graphics device: the platform as the video crates'
|
||||
//! runtime ([`runtime`]), which the device's video arms run their host sessions on.
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::Range;
|
||||
use std::sync::{Arc, OnceLock, Weak};
|
||||
|
||||
use reims_vgpu_core::iosurface::{HostDeviceCore, IoSurfaceHostDevice};
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::os::surface::Surface as _;
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_video_core::backend::{Backend, DecoderBackend};
|
||||
use reims_vgpu_video_core::device_memory::DeviceMemory;
|
||||
use reims_vgpu_video_core::encoder_backend::EncoderBackend;
|
||||
use reims_vgpu_video_core::host::{GuestSink, HostSession};
|
||||
use reims_vgpu_video_core::runtime::Runtime;
|
||||
use reims_vgpu_video_core::status::Status;
|
||||
use reims_vgpu_video_core::surfaces::{
|
||||
GuestSurface, MappingId, PlaneLayout, SurfaceError, SurfaceLayout, Surfaces,
|
||||
};
|
||||
use reims_vgpu_video_core::wire::message::read_header;
|
||||
|
||||
use crate::DefaultPlatform;
|
||||
use crate::entry;
|
||||
use crate::iosurface::IoSurfaceDevice;
|
||||
use crate::platform::ApiPlatform;
|
||||
use crate::retained::Ours;
|
||||
use backend_choice::OpenBackends;
|
||||
|
||||
pub(crate) mod backend_choice;
|
||||
mod logged;
|
||||
pub(crate) mod runtime;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
/// What [`VideoDevice::deliver`] answers while the device has no host session: VideoToolbox's
|
||||
/// `kVTInvalidSessionErr`. Apple's host has no such answer: it hands the message to a session it
|
||||
/// does not have.
|
||||
pub const INVALID_SESSION: i32 = -12903;
|
||||
|
||||
/// The longest guest-to-host message [`VideoDevice::deliver`] takes: 16 MiB, ours. A guest's
|
||||
/// descriptors may add up to many times the host's memory, which a host that gathers an element
|
||||
/// before it delivers it would allocate and copy. The guest's VideoToolbox cuts a value across
|
||||
/// messages at 0x200000 bytes ("Fragments", docs/video/devices.md), and the session gathers no
|
||||
/// reply past 16 MiB, so no message of a guest it drives comes near this. A host checks it
|
||||
/// before it copies an element out of the guest's memory, as QEMU's `apple-videotoolbox-pci`
|
||||
/// does, and answers a longer one [`ALLOCATION_FAILED`] itself.
|
||||
pub const MAX_MESSAGE_SIZE: usize = 16 << 20;
|
||||
|
||||
/// What [`VideoDevice::deliver`] answers a message longer than [`MAX_MESSAGE_SIZE`], unread:
|
||||
/// VideoToolbox's `kVTAllocationFailedErr`, as the session answers a delivery past what it
|
||||
/// holds of the guest's messages.
|
||||
pub const ALLOCATION_FAILED: i32 = Status::AllocationFailed.code();
|
||||
|
||||
/// `send_to_guest(message)`: one host-to-guest message, the whole `vtpv` container (or `rels`
|
||||
/// box), borrowed for the call. It arrives on a session's thread, or on the host's own inside
|
||||
/// [`VideoDevice::deliver`] when the session answers at once, so it must not wait for a thread
|
||||
/// that may be inside a call on the same device; it copies the message and queues it for the
|
||||
/// guest.
|
||||
pub type SendToGuest = Arc<dyn Fn(&[u8]) + Send + Sync>;
|
||||
|
||||
/// A video device's config.
|
||||
pub struct VideoDeviceConfig<P: Platform = DefaultPlatform> {
|
||||
/// The IOSurface device whose mapping IDs the guest's messages name, held unretained; `None`
|
||||
/// is the process's latest at each lookup.
|
||||
pub iosurface_device: Option<IoSurfaceDevice<P>>,
|
||||
/// Where host-to-guest messages go. Without it they are dropped, as Apple's host drops them
|
||||
/// with no reply queue.
|
||||
pub send_to_guest: Option<SendToGuest>,
|
||||
}
|
||||
|
||||
impl<P: Platform> Default for VideoDeviceConfig<P> {
|
||||
fn default() -> Self {
|
||||
VideoDeviceConfig {
|
||||
iosurface_device: None,
|
||||
send_to_guest: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> fmt::Debug for VideoDeviceConfig<P> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("VideoDeviceConfig")
|
||||
.field("iosurface_device", &self.iosurface_device)
|
||||
.field("send_to_guest", &self.send_to_guest.is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// One plane of a surface: its bytes' offset from the surface's base address, its size in
|
||||
/// elements, and its bytes per element and per row ([`ApiPlatform::surface_planes`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
pub struct SurfacePlane {
|
||||
/// Its bytes' offset from the surface's base address.
|
||||
pub offset: u64,
|
||||
/// Its width, in elements.
|
||||
pub width: u64,
|
||||
/// Its height, in elements.
|
||||
pub height: u64,
|
||||
/// Its bytes per element.
|
||||
pub bytes_per_element: u64,
|
||||
/// Its bytes per row.
|
||||
pub bytes_per_row: u64,
|
||||
}
|
||||
|
||||
/// One guest IOSurface, retained through the mapper by its mapping ID: one reference to the
|
||||
/// surface, so a hold the guest sees (an unmap of it answers Busy while this lives). Its release
|
||||
/// runs as an entry.
|
||||
///
|
||||
/// Its bytes are the guest's own pages, as the host maps them: on Linux, a surface of several
|
||||
/// pages is one view of them, contiguous from its base address, and a surface of one run of pages
|
||||
/// is that run in the guest's RAM; on macOS, IOSurface's mapping of them at its base address,
|
||||
/// which a lend reaches under `IOSurfaceLock` (`reims_vgpu_metal::os::surface_bytes`); a
|
||||
/// host-only surface is memory of the host's own.
|
||||
pub(crate) struct MappedSurface<P: ApiPlatform = DefaultPlatform> {
|
||||
mapping_id: u64,
|
||||
surface: Ours<P::Surface>,
|
||||
/// Its guest pages, host addresses in the guest's RAM, as runs: what a write of it writes
|
||||
/// ([`crate::device_writes`]); none for a host-only surface.
|
||||
pages: Vec<Range<u64>>,
|
||||
platform: Arc<P>,
|
||||
/// Its memory as the platform lends it to a device, asked for once
|
||||
/// ([`GuestSurface::device_memory`]).
|
||||
device: OnceLock<Option<Box<dyn DeviceMemory>>>,
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> MappedSurface<P> {
|
||||
/// Its planes, in order; empty for a surface without planes, whose layout is its own.
|
||||
fn planes(&self) -> Vec<SurfacePlane> {
|
||||
self.platform.surface_planes(&self.surface)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> fmt::Debug for MappedSurface<P> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let format = self.surface.pixel_format().to_be_bytes();
|
||||
f.debug_struct("MappedSurface")
|
||||
.field("mapping_id", &self.mapping_id)
|
||||
.field("pixel_format", &FourCc(format))
|
||||
.field("width", &self.surface.width())
|
||||
.field("height", &self.surface.height())
|
||||
.field("bytes_per_row", &self.surface.bytes_per_row())
|
||||
.field("alloc_size", &self.surface.alloc_size())
|
||||
.field("planes", &self.planes())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> GuestSurface for MappedSurface<P> {
|
||||
/// Its pixel format, size and planes, as the guest made it.
|
||||
fn layout(&self) -> SurfaceLayout {
|
||||
let size = |v: u64| u32::try_from(v).unwrap_or(u32::MAX);
|
||||
let bytes = |v: u64| usize::try_from(v).unwrap_or(usize::MAX);
|
||||
SurfaceLayout {
|
||||
pixel_format: reims_vgpu_video_core::fourcc::FourCc(self.surface.pixel_format()),
|
||||
width: size(self.surface.width()),
|
||||
height: size(self.surface.height()),
|
||||
planes: (self.planes().iter())
|
||||
.map(|p| PlaneLayout {
|
||||
offset: bytes(p.offset),
|
||||
bytes_per_row: bytes(p.bytes_per_row),
|
||||
width: size(p.width),
|
||||
height: size(p.height),
|
||||
})
|
||||
.collect(),
|
||||
bytes_per_row: bytes(self.surface.bytes_per_row()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lends its bytes, from its first byte to the end of its allocation, through the platform
|
||||
/// ([`ApiPlatform::lend_surface_bytes`]); a surface they cannot be lent of is unreachable.
|
||||
/// Once the lend returns the host's devices' writes have its pages
|
||||
/// ([`crate::device_writes`]).
|
||||
fn write(&self, write: &mut dyn FnMut(&mut [u8])) -> Result<(), SurfaceError> {
|
||||
self.platform
|
||||
.lend_surface_bytes(&self.surface, write)
|
||||
.map_err(|why| {
|
||||
log::warn!(
|
||||
"surface {:#x}: its bytes cannot be lent: {why}",
|
||||
self.mapping_id
|
||||
);
|
||||
SurfaceError::Unreachable(why.to_owned())
|
||||
})?;
|
||||
crate::device_writes::wrote(&self.pages);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Lends its bytes for reading, laid out as [`Self::write`] lends them, through the platform
|
||||
/// ([`ApiPlatform::lend_surface_bytes_for_reading`]): a surface the guest made read-only is
|
||||
/// lent too. One they cannot be lent of is unreachable.
|
||||
fn read(&self, read: &mut dyn FnMut(&[u8])) -> Result<(), SurfaceError> {
|
||||
self.platform
|
||||
.lend_surface_bytes_for_reading(&self.surface, read)
|
||||
.map_err(|why| {
|
||||
log::warn!(
|
||||
"surface {:#x}: its bytes cannot be lent for reading: {why}",
|
||||
self.mapping_id
|
||||
);
|
||||
SurfaceError::Unreachable(why.to_owned())
|
||||
})
|
||||
}
|
||||
|
||||
/// Its memory as the platform lends it to a device ([`ApiPlatform::surface_device_memory`]),
|
||||
/// asked for once for this hold: the bytes [`Self::write`] lends, for the decoders' device to
|
||||
/// write a frame into while the session holds the surface. `None` where the platform lends
|
||||
/// none, said once a hold at debug.
|
||||
fn device_memory(&self) -> Option<&dyn DeviceMemory> {
|
||||
let lent = self.device.get_or_init(|| {
|
||||
entry::run(|_| self.platform.surface_device_memory(&self.surface))
|
||||
.inspect_err(|why| {
|
||||
log::debug!(
|
||||
"surface {:#x}: its memory is lent to no device: {why}",
|
||||
self.mapping_id
|
||||
);
|
||||
})
|
||||
.ok()
|
||||
});
|
||||
lent.as_deref()
|
||||
}
|
||||
|
||||
/// A device wrote its memory ([`Self::device_memory`]): the host's devices' writes have its
|
||||
/// pages ([`crate::device_writes`]).
|
||||
fn device_wrote(&self) {
|
||||
crate::device_writes::wrote(&self.pages);
|
||||
}
|
||||
}
|
||||
|
||||
/// A four-character code as it prints: its characters where all are printable, else its hex.
|
||||
pub(crate) struct FourCc(pub(crate) [u8; 4]);
|
||||
|
||||
impl fmt::Debug for FourCc {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
if self.0.iter().all(|b| b.is_ascii_graphic() || *b == b' ') {
|
||||
let s: String = self.0.iter().map(|&b| char::from(b)).collect();
|
||||
write!(f, "'{s}'")
|
||||
} else {
|
||||
write!(f, "{:#010x}", u32::from_be_bytes(self.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's surfaces, through the IOSurface device's mapper (module doc): the video
|
||||
/// device's, and the scaler device's (`crate::scaler`).
|
||||
pub(crate) struct MapperSurfaces<P: ApiPlatform> {
|
||||
platform: Arc<P>,
|
||||
/// The IOSurface device the config named, unretained; `None`: the process's latest.
|
||||
mapper: Option<Weak<HostDeviceCore<P>>>,
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> MapperSurfaces<P> {
|
||||
/// `device`'s surfaces (`video device`, `scaler device`), mapped through `mapper`, held
|
||||
/// unretained, or through the process's latest IOSurface device at each lookup; logged.
|
||||
pub(crate) fn new(device: &str, platform: Arc<P>, mapper: Option<&IoSurfaceDevice<P>>) -> Self {
|
||||
log::info!(
|
||||
"{device} created, mapping IOSurfaces through {}",
|
||||
if mapper.is_some() {
|
||||
"its IOSurface device"
|
||||
} else {
|
||||
"the process's latest IOSurface device"
|
||||
}
|
||||
);
|
||||
MapperSurfaces {
|
||||
platform,
|
||||
mapper: mapper.map(IoSurfaceDevice::core_weak),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether they are mapped through an IOSurface device the config named.
|
||||
pub(crate) fn names_its_mapper(&self) -> bool {
|
||||
self.mapper.is_some()
|
||||
}
|
||||
|
||||
/// The surface the guest maps at `mapping_id`, retained through the mapper.
|
||||
fn retain(&self, mapping_id: u64) -> Result<MappedSurface<P>, SurfaceError> {
|
||||
let core = match &self.mapper {
|
||||
Some(weak) => weak.upgrade(),
|
||||
None => IoSurfaceHostDevice::latest_core(&*self.platform).and_then(|w| w.upgrade()),
|
||||
};
|
||||
let Some(core) = core else {
|
||||
return Err(SurfaceError::Unreachable(
|
||||
"no IOSurface device to map it through".to_owned(),
|
||||
));
|
||||
};
|
||||
let surface = core.retain_surface_and_pages_with_mapping_id(mapping_id);
|
||||
drop(core);
|
||||
let (surface, pages) = surface.ok_or(SurfaceError::Unknown(mapping_id))?;
|
||||
let pages = crate::device_writes::page_runs(&pages, self.platform.vm().page_size());
|
||||
let surface = MappedSurface {
|
||||
mapping_id,
|
||||
surface: Ours::new(surface),
|
||||
pages,
|
||||
platform: Arc::clone(&self.platform),
|
||||
device: OnceLock::new(),
|
||||
};
|
||||
log::debug!("surface {mapping_id:#x} held: {surface:?}");
|
||||
Ok(surface)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> Surfaces for MapperSurfaces<P> {
|
||||
fn retain(&self, mapping_id: MappingId) -> Result<Box<dyn GuestSurface>, SurfaceError> {
|
||||
entry::run(|_| MapperSurfaces::retain(self, mapping_id.0))
|
||||
.map(|s| Box::new(s) as Box<dyn GuestSurface>)
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's `send_to_guest`, as the session's sink: each message goes to it as it comes.
|
||||
struct CallbackSink(Option<SendToGuest>);
|
||||
|
||||
impl GuestSink for CallbackSink {
|
||||
fn send(&self, message: Vec<u8>) {
|
||||
match read_header(&message, 0) {
|
||||
Ok(h) => log::debug!(
|
||||
"to the guest: {:?} flags {:#x} reply {:#x}, {} bytes",
|
||||
FourCc(h.message_type.to_be_bytes()),
|
||||
h.flags.0,
|
||||
h.reply_id,
|
||||
message.len()
|
||||
),
|
||||
Err(_) => log::debug!("to the guest: {} bytes", message.len()),
|
||||
}
|
||||
if let Some(send) = &self.0 {
|
||||
send(&message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The session's backend: the parts of `chosen`, the device's share of the host's backend
|
||||
/// ([`backend_choice::choose`]), its decoders and encoders logged, and its JPEG decoder too. One
|
||||
/// that did not open has no part, and lists no codec.
|
||||
fn device_backend<P: Platform>(chosen: &backend_choice::Chosen, platform: &Arc<P>) -> Backend {
|
||||
if !chosen.has_backend() {
|
||||
log::info!(
|
||||
"video device: the guest is offered no codec, and its VideoToolbox decodes and \
|
||||
encodes in software"
|
||||
);
|
||||
}
|
||||
let mut backend = chosen.backend();
|
||||
backend.decoders = backend.decoders.map(|inner| {
|
||||
Arc::new(logged::LoggedBackend {
|
||||
inner,
|
||||
name: chosen.label,
|
||||
platform: Arc::clone(platform),
|
||||
}) as Arc<dyn DecoderBackend>
|
||||
});
|
||||
backend.encoders = backend.encoders.map(|inner| {
|
||||
Arc::new(logged::LoggedEncoders {
|
||||
inner,
|
||||
name: chosen.label,
|
||||
platform: Arc::clone(platform),
|
||||
}) as Arc<dyn EncoderBackend>
|
||||
});
|
||||
match &backend.jpeg {
|
||||
Some(jpeg) => log::info!(
|
||||
"video device decodes JPEG on {}: {:?}",
|
||||
chosen.label,
|
||||
jpeg.capabilities()
|
||||
),
|
||||
None => log::info!(
|
||||
"video device: no JPEG decoder on {}: its JPEG engine answers as a host without one",
|
||||
chosen.label
|
||||
),
|
||||
}
|
||||
backend
|
||||
}
|
||||
|
||||
/// The host side of one VideoToolbox device (module doc). Its last drop is a reset.
|
||||
pub struct VideoDevice<P: ApiPlatform = DefaultPlatform> {
|
||||
sink: Arc<CallbackSink>,
|
||||
surfaces: Arc<MapperSurfaces<P>>,
|
||||
/// The backend the host sessions run on, opened with the device.
|
||||
backend: Backend,
|
||||
/// The platform as the host sessions' runtime: their threads and their clock.
|
||||
runtime: Arc<dyn Runtime>,
|
||||
/// The host session, from `start` to the reset that completes its invalidation.
|
||||
session: Mutex<Option<Arc<HostSession>>>,
|
||||
/// The device's share of its backend, which another video device on the same GPU shares
|
||||
/// (`backend_choice`). Last, so that it goes after the session and the parts.
|
||||
_chosen: backend_choice::Chosen,
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> fmt::Debug for VideoDevice<P> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("VideoDevice")
|
||||
.field("mapper", &self.surfaces.names_its_mapper())
|
||||
.field("send_to_guest", &self.sink.0.is_some())
|
||||
.field("backend", &self.backend)
|
||||
.field("session", &self.session.lock().is_some())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoDevice {
|
||||
/// A new video device on the process's platform ([`VideoDevice::with_platform`]).
|
||||
pub fn new(config: VideoDeviceConfig) -> VideoDevice {
|
||||
VideoDevice::with_platform(DefaultPlatform::process(), config)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> VideoDevice<P> {
|
||||
/// A new video device on `platform`, with no host session until [`Self::start`]; its backend
|
||||
/// opens now (module doc). Nothing refuses one: a host with no codecs has a session that lists
|
||||
/// none.
|
||||
pub fn with_platform(platform: Arc<P>, config: VideoDeviceConfig<P>) -> VideoDevice<P> {
|
||||
let runtime = runtime::PlatformRuntime::of(&platform);
|
||||
VideoDevice::picking_from(&backend_choice::OPEN, platform, runtime, config)
|
||||
}
|
||||
|
||||
/// [`Self::with_platform`], its backend picked from `open`, the process's or a test's own,
|
||||
/// its sessions and the backend it opens running on `runtime`: the platform's, or, in a test
|
||||
/// that opens the host's backend, std's, since a backend's waits for its GPU end only on a
|
||||
/// clock that runs.
|
||||
pub(crate) fn picking_from(
|
||||
open: &OpenBackends,
|
||||
platform: Arc<P>,
|
||||
runtime: Arc<dyn Runtime>,
|
||||
config: VideoDeviceConfig<P>,
|
||||
) -> VideoDevice<P> {
|
||||
entry::run(|_| {
|
||||
VideoDevice::make(platform, runtime, config, |runtime| {
|
||||
backend_choice::choose(open, "video device", backend_choice::Need::Video, runtime)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// A new video device on `platform` that opens none of the host's backends, `why` in words:
|
||||
/// its sessions list no codec, as on a host where none opens. For the tests of the device and
|
||||
/// of the C API, which run on core's testkit platform: its clock is virtual, and no test
|
||||
/// advances it while a backend waits for its GPU, so a backend opened there would wait at
|
||||
/// its first such wait for good.
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub fn without_backend(
|
||||
platform: Arc<P>,
|
||||
config: VideoDeviceConfig<P>,
|
||||
why: &str,
|
||||
) -> VideoDevice<P> {
|
||||
entry::run(|_| {
|
||||
let runtime = runtime::PlatformRuntime::of(&platform);
|
||||
VideoDevice::make(platform, runtime, config, |_| {
|
||||
backend_choice::Chosen::none("video device", why)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// The device, its backend the one `choose` gives it on `runtime`, after its surfaces.
|
||||
fn make(
|
||||
platform: Arc<P>,
|
||||
runtime: Arc<dyn Runtime>,
|
||||
config: VideoDeviceConfig<P>,
|
||||
choose: impl FnOnce(&Arc<dyn Runtime>) -> backend_choice::Chosen,
|
||||
) -> VideoDevice<P> {
|
||||
let surfaces = MapperSurfaces::new(
|
||||
"video device",
|
||||
Arc::clone(&platform),
|
||||
config.iosurface_device.as_ref(),
|
||||
);
|
||||
let chosen = choose(&runtime);
|
||||
let backend = device_backend(&chosen, &platform);
|
||||
VideoDevice {
|
||||
sink: Arc::new(CallbackSink(config.send_to_guest)),
|
||||
surfaces: Arc::new(surfaces),
|
||||
backend,
|
||||
runtime,
|
||||
session: Mutex::new(None),
|
||||
_chosen: chosen,
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's DRIVER_OK: a new host session. A session already there is ended for it (both
|
||||
/// phases), as Apple's host replaces its own, which may wait for its threads as
|
||||
/// [`Self::reset`] does.
|
||||
pub fn start(&self) {
|
||||
entry::run(|_| {
|
||||
let session = Arc::new(HostSession::with_backend(
|
||||
Arc::clone(&self.runtime),
|
||||
Arc::clone(&self.sink) as Arc<dyn GuestSink>,
|
||||
Arc::clone(&self.surfaces) as Arc<dyn Surfaces>,
|
||||
&self.backend,
|
||||
));
|
||||
let old = self.session.lock().replace(session);
|
||||
log::info!("video device started: a new host session");
|
||||
if let Some(old) = old {
|
||||
old.invalidate();
|
||||
old.complete_invalidate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// One guest-to-host message: the session holds the surfaces its `subs` atom names while it
|
||||
/// handles it, and answers the status the host writes back (module doc). Without a session,
|
||||
/// [`INVALID_SESSION`]; for a message longer than [`MAX_MESSAGE_SIZE`], [`ALLOCATION_FAILED`],
|
||||
/// and the session sees nothing of it. May call back (`send_to_guest`, on this thread). May
|
||||
/// wait for the IOSurface device's thread, and may take a while: a `jdec` waits for its
|
||||
/// decode, and a session's end (`-dec`, `-enc`, `-mep`) for its thread, 10 s at most each.
|
||||
pub fn deliver(&self, message: &[u8]) -> i32 {
|
||||
entry::run(|_| {
|
||||
if message.len() > MAX_MESSAGE_SIZE {
|
||||
log::warn!(
|
||||
"a guest message of {} bytes, over the {MAX_MESSAGE_SIZE} a message may hold: \
|
||||
answered {ALLOCATION_FAILED}, unread",
|
||||
message.len()
|
||||
);
|
||||
return ALLOCATION_FAILED;
|
||||
}
|
||||
let header = read_header(message, 0).ok();
|
||||
let session = self.session.lock().clone();
|
||||
let status = match session {
|
||||
Some(session) => session.deliver(message),
|
||||
None => {
|
||||
log::warn!(
|
||||
"a guest message of {} bytes with no host session: answered \
|
||||
{INVALID_SESSION}",
|
||||
message.len()
|
||||
);
|
||||
INVALID_SESSION
|
||||
}
|
||||
};
|
||||
match header {
|
||||
Some(h) => log::debug!(
|
||||
"from the guest: {:?} flags {:#x} reply {:#x}, {} bytes: answered {status}",
|
||||
FourCc(h.message_type.to_be_bytes()),
|
||||
h.flags.0,
|
||||
h.reply_id,
|
||||
message.len()
|
||||
),
|
||||
None => log::debug!(
|
||||
"from the guest: {} bytes with no message header: answered {status}",
|
||||
message.len()
|
||||
),
|
||||
}
|
||||
status
|
||||
})
|
||||
}
|
||||
|
||||
/// The first phase of a reset or a stop: the session sends the guest nothing more, and
|
||||
/// answers no new message. Each of its decoder, encoder and motion-estimation sessions is
|
||||
/// told on its thread, after the message in hand there, and this waits for them, 10 s at
|
||||
/// most in all, as core's `HostSession::invalidate` does.
|
||||
pub fn invalidate(&self) {
|
||||
entry::run(|_| {
|
||||
let session = self.session.lock().clone();
|
||||
if let Some(session) = session {
|
||||
session.invalidate();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A reset or a stop, both phases: the session is invalidated, if it was not, then its work
|
||||
/// drains, and it is dropped. May wait for the session's threads: 10 s at most for them to
|
||||
/// take the invalidation, as [`Self::invalidate`] waits, then for those that took it to
|
||||
/// end. One left running past the bound is left detached.
|
||||
pub fn reset(&self) {
|
||||
entry::run(|_| self.end_session());
|
||||
}
|
||||
|
||||
/// Both phases of the session's end, if there is one.
|
||||
fn end_session(&self) {
|
||||
let session = self.session.lock().take();
|
||||
if let Some(session) = session {
|
||||
session.invalidate();
|
||||
session.complete_invalidate();
|
||||
log::info!("video device reset: the host session ended");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: ApiPlatform> Drop for VideoDevice<P> {
|
||||
/// A reset, as an entry.
|
||||
fn drop(&mut self) {
|
||||
entry::run(|_| self.end_session());
|
||||
}
|
||||
}
|
||||
@@ -1,583 +0,0 @@
|
||||
//! Which backend the video device runs on, and on which GPU. Nothing configures it: [`choose`]
|
||||
//! decides from the host, and logs what it chose and why at info. (The scaler device runs on the
|
||||
//! GPU the library draws with, `crate::scaler`, and chooses nothing.)
|
||||
//!
|
||||
//! - **macOS**: VideoToolbox, the host's own; there is nothing to choose.
|
||||
//! - **Linux**: the GPU the library's GPU device runs on, which is the Vulkan runtime's system
|
||||
//! default device's (reims-vgpu-vulkan's `host_gpus`), so a VM pinned to a GPU through the
|
||||
//! loader's environment (`VK_DRIVER_FILES`, and `VK_LOADER_DEVICE_ID_FILTER` where one driver
|
||||
//! drives several GPUs, as reims-ctl pins one) decodes and encodes on that GPU too.
|
||||
//! The answer is the one the GPU device's would be, whether a GPU device was made first or not.
|
||||
//! On that GPU:
|
||||
//! - NVIDIA's NVDEC and NVENC, where it is an NVIDIA GPU and CUDA opens the GPU of its PCI
|
||||
//! address;
|
||||
//! - VA-API on its DRM render node otherwise.
|
||||
//!
|
||||
//! Where that GPU is a CPU implementation (lavapipe, llvmpipe), or its backend lacks what the
|
||||
//! device needs ([`Need`]: any part), the device picks a hardware GPU itself: the first of the
|
||||
//! host's hardware GPUs (`host_gpus::hardware_gpus`) whose backend has it, discrete ones first,
|
||||
//! then integrated, virtual and other ones, each kind in the loader's order. Where none has,
|
||||
//! the device has no backend, and offers the guest no codec.
|
||||
//!
|
||||
//! Each backend is reims-vgpu-video-core's `Backend`, the same to the device whichever it is: the
|
||||
//! video device takes its codecs from it.
|
||||
//!
|
||||
//! **Shared.** A backend is open once per place, VA-API once per render node, NVIDIA's once per
|
||||
//! GPU and VideoToolbox once per host, and every device that picks it there shares it
|
||||
//! ([`SharedBackend`]): the video devices of a process on one GPU open it once. It is released
|
||||
//! when the last device that holds it goes, in whichever order the devices go, and a device made
|
||||
//! after that opens it anew. A backend that does not open, or opens with no part, is not kept, so
|
||||
//! the next device asks again.
|
||||
|
||||
// On macOS the devices take VideoToolbox alone: the GPU choice is Linux's, and its tests run on
|
||||
// every OS.
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
use std::fmt;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_video_core::backend::Backend;
|
||||
use reims_vgpu_video_core::runtime::Runtime;
|
||||
|
||||
/// A backend's kind.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub(crate) enum Kind {
|
||||
/// VA-API, on a GPU's render node (Linux).
|
||||
Vaapi,
|
||||
/// NVIDIA's NVDEC and NVENC, on an NVIDIA GPU by its PCI address (Linux).
|
||||
Nvidia,
|
||||
/// VideoToolbox (macOS).
|
||||
#[cfg_attr(
|
||||
not(target_os = "macos"),
|
||||
allow(dead_code, reason = "macOS's alone, named by the tests elsewhere")
|
||||
)]
|
||||
VideoToolbox,
|
||||
}
|
||||
|
||||
/// What a device needs of a backend.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Need {
|
||||
/// Any part: what the video device offers the guest.
|
||||
Video,
|
||||
}
|
||||
|
||||
impl Need {
|
||||
/// Whether `backend` has it.
|
||||
fn met(self, backend: &Backend) -> bool {
|
||||
match self {
|
||||
Need::Video => {
|
||||
backend.decoders.is_some()
|
||||
|| backend.encoders.is_some()
|
||||
|| backend.motion.is_some()
|
||||
|| backend.jpeg.is_some()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the log says of a backend or GPU that lacks it.
|
||||
fn lacking(self) -> &'static str {
|
||||
match self {
|
||||
Need::Video => "offers no video",
|
||||
}
|
||||
}
|
||||
|
||||
/// What the log says of the GPU sought for it.
|
||||
fn sought(self) -> &'static str {
|
||||
match self {
|
||||
Need::Video => "that offers video",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
/// What the log calls it.
|
||||
pub(crate) const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Kind::Vaapi => "VA-API",
|
||||
Kind::Nvidia => "NVIDIA",
|
||||
Kind::VideoToolbox => "VideoToolbox",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The PCI vendor ID of NVIDIA's GPUs.
|
||||
const NVIDIA_VENDOR: u32 = 0x10de;
|
||||
|
||||
/// The kind of a GPU, from `VkPhysicalDeviceType`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum GpuKind {
|
||||
Discrete,
|
||||
Integrated,
|
||||
Virtual,
|
||||
Cpu,
|
||||
Other,
|
||||
}
|
||||
|
||||
impl GpuKind {
|
||||
/// The order the hardware GPUs are tried in: discrete, integrated, virtual, other, as the
|
||||
/// runtime ranks its devices.
|
||||
fn rank(self) -> u8 {
|
||||
match self {
|
||||
GpuKind::Discrete => 0,
|
||||
GpuKind::Integrated => 1,
|
||||
GpuKind::Virtual => 2,
|
||||
GpuKind::Other => 3,
|
||||
GpuKind::Cpu => 4,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the log calls it.
|
||||
fn word(self) -> &'static str {
|
||||
match self {
|
||||
GpuKind::Discrete => "discrete",
|
||||
GpuKind::Integrated => "integrated",
|
||||
GpuKind::Virtual => "virtual",
|
||||
GpuKind::Cpu => "CPU",
|
||||
GpuKind::Other => "other",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One of the host's GPUs, as the choice sees it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct Gpu {
|
||||
/// Its name, as its Vulkan driver gives it.
|
||||
pub(crate) name: String,
|
||||
pub(crate) kind: GpuKind,
|
||||
/// Its PCI vendor ID.
|
||||
pub(crate) vendor_id: u32,
|
||||
/// Its PCI address, `0000:03:00.0`, which NVIDIA's backend opens it by.
|
||||
pub(crate) pci_address: Option<String>,
|
||||
/// Its DRM render node, `/dev/dri/renderD128`, which VA-API opens it by.
|
||||
pub(crate) render_node: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Gpu {
|
||||
/// Whether `other` is this GPU: of the same PCI address where both have one.
|
||||
fn is(&self, other: &Gpu) -> bool {
|
||||
match (&self.pci_address, &other.pci_address) {
|
||||
(Some(a), Some(b)) => a == b,
|
||||
_ => self == other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Gpu {
|
||||
/// `AMD Radeon RX 7900 XTX (RADV NAVI31) (discrete, 0000:03:00.0, /dev/dri/renderD128)`.
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{} ({}", self.name, self.kind.word())?;
|
||||
if let Some(address) = &self.pci_address {
|
||||
write!(f, ", {address}")?;
|
||||
}
|
||||
if let Some(node) = &self.render_node {
|
||||
write!(f, ", {}", node.display())?;
|
||||
}
|
||||
f.write_str(")")
|
||||
}
|
||||
}
|
||||
|
||||
/// What the choice asks of the host: its GPUs, and a backend's open on one. Linux's is
|
||||
/// `LinuxHost`; the tests bring stand-ins.
|
||||
pub(crate) trait Host {
|
||||
/// The GPU the library's GPU device runs on; `None` where the Vulkan runtime makes no device.
|
||||
fn gpu_device(&self) -> Option<Gpu>;
|
||||
/// The host's hardware GPUs, in the loader's order.
|
||||
fn hardware(&self) -> Vec<Gpu>;
|
||||
/// `kind`'s backend on `gpu`: VA-API's at its render node, NVIDIA's at its PCI address.
|
||||
fn open(&self, kind: Kind, gpu: &Gpu) -> Result<Backend, String>;
|
||||
}
|
||||
|
||||
/// A backend picked for a device, and what its log calls it. The device keeps it for its life:
|
||||
/// it holds the device's share of the backend.
|
||||
pub(crate) struct Chosen {
|
||||
/// The backend, shared with the other devices that picked it there; `None` where none
|
||||
/// opened.
|
||||
opened: Option<Arc<SharedBackend>>,
|
||||
/// `VA-API`, `NVIDIA`, `VideoToolbox`, or `none`.
|
||||
pub(crate) label: &'static str,
|
||||
}
|
||||
|
||||
impl Chosen {
|
||||
/// No backend, for `device`, which opens none (`VideoDevice::without_backend`), `why` in
|
||||
/// words, as the log says.
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
pub(crate) fn none(device: &str, why: &str) -> Chosen {
|
||||
log::info!("{device} opens no backend: {why}");
|
||||
Chosen {
|
||||
opened: None,
|
||||
label: "none",
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend's parts, each shared with the other devices that hold it; with no part where
|
||||
/// none opened.
|
||||
pub(crate) fn backend(&self) -> Backend {
|
||||
self.opened.as_ref().map_or_else(
|
||||
|| Backend::none(self.label),
|
||||
|shared| shared.backend.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether a backend opened for it.
|
||||
pub(crate) fn has_backend(&self) -> bool {
|
||||
self.opened.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
/// A backend open in one place, which every device that picks it there shares (module doc).
|
||||
pub(crate) struct SharedBackend {
|
||||
backend: Backend,
|
||||
/// Where it is open, as the log says it: `VA-API at /dev/dri/renderD128`.
|
||||
place: String,
|
||||
/// The device it was opened for, as the log names it: `video device`.
|
||||
opened_for: String,
|
||||
}
|
||||
|
||||
impl Drop for SharedBackend {
|
||||
fn drop(&mut self) {
|
||||
log::info!("{} released: no device holds it", self.place);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a backend is open: its kind, and the GPU it runs on, by its render node (resolved) for
|
||||
/// VA-API and by its PCI address for NVIDIA; none for VideoToolbox.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
struct Place {
|
||||
kind: Kind,
|
||||
at: Option<String>,
|
||||
}
|
||||
|
||||
impl Place {
|
||||
/// `kind`'s place on `gpu`; `None` where the GPU has no render node (VA-API) or no PCI
|
||||
/// address (NVIDIA).
|
||||
fn on(kind: Kind, gpu: &Gpu) -> Option<Place> {
|
||||
let at = match kind {
|
||||
Kind::Vaapi => {
|
||||
let node = gpu.render_node.as_ref()?;
|
||||
let node = std::fs::canonicalize(node).unwrap_or_else(|_| node.clone());
|
||||
Some(node.display().to_string())
|
||||
}
|
||||
Kind::Nvidia => Some(gpu.pci_address.clone()?),
|
||||
Kind::VideoToolbox => None,
|
||||
};
|
||||
Some(Place { kind, at })
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Place {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match &self.at {
|
||||
Some(at) => write!(f, "{} at {at}", self.kind.label()),
|
||||
None => f.write_str(self.kind.label()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Backends open, each held weakly: a device holds its share, this only finds it for the next
|
||||
/// device. The devices pick from the process's, [`OPEN`]; a test that counts what its own devices
|
||||
/// hold gives them one of its own.
|
||||
pub(crate) struct OpenBackends {
|
||||
open: Mutex<Vec<(Place, Weak<SharedBackend>)>>,
|
||||
}
|
||||
|
||||
impl OpenBackends {
|
||||
pub(crate) const fn new() -> OpenBackends {
|
||||
OpenBackends {
|
||||
open: Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend open at `place`, and `true`; else the one `open` opens there now for
|
||||
/// `device`, and `false`. A backend that does not open is not kept, so the next device asks
|
||||
/// again. The lock is held while it opens, so that two devices made at once open it once.
|
||||
fn get_or_open(
|
||||
&self,
|
||||
place: Place,
|
||||
device: &str,
|
||||
open: impl FnOnce() -> Result<Backend, String>,
|
||||
) -> Result<(Arc<SharedBackend>, bool), String> {
|
||||
let mut open_now = self.open.lock();
|
||||
open_now.retain(|(_, held)| held.strong_count() > 0);
|
||||
let found = (open_now.iter())
|
||||
.filter(|(at, _)| *at == place)
|
||||
.find_map(|(_, held)| held.upgrade());
|
||||
if let Some(shared) = found {
|
||||
return Ok((shared, true));
|
||||
}
|
||||
let backend = open()?;
|
||||
let shared = Arc::new(SharedBackend {
|
||||
backend,
|
||||
place: place.to_string(),
|
||||
opened_for: device.to_owned(),
|
||||
});
|
||||
open_now.push((place, Arc::downgrade(&shared)));
|
||||
Ok((shared, false))
|
||||
}
|
||||
}
|
||||
|
||||
/// The process's open backends.
|
||||
pub(crate) static OPEN: OpenBackends = OpenBackends::new();
|
||||
|
||||
/// How many devices hold the backend open in `open` at VideoToolbox's place: 0 where none is.
|
||||
/// For the devices' test on macOS, the one host whose backend a test can open.
|
||||
#[cfg(all(test, target_os = "macos"))]
|
||||
pub(crate) fn videotoolbox_holders(open: &OpenBackends) -> usize {
|
||||
let place = Place {
|
||||
kind: Kind::VideoToolbox,
|
||||
at: None,
|
||||
};
|
||||
(open.open.lock().iter())
|
||||
.filter(|(at, _)| *at == place)
|
||||
.map(|(_, held)| held.strong_count())
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// A backend, shared, and whether it was open already.
|
||||
type Opened = (Arc<SharedBackend>, bool);
|
||||
|
||||
/// What [`pick`] picked: the backend's label, why, and the backend; or why none opened.
|
||||
struct Picked {
|
||||
label: &'static str,
|
||||
why: String,
|
||||
opened: Result<Opened, String>,
|
||||
}
|
||||
|
||||
/// The host's backend with what `device` (`video device`) needs, opened, or `device`'s share of
|
||||
/// it where it is open already in `open` (module doc), with what it chose and why logged; where
|
||||
/// none has it, none, which the device says what it does without. A backend it opens runs on
|
||||
/// `runtime`, the device's platform's, for its life (`super::runtime`).
|
||||
pub(crate) fn choose(
|
||||
open: &OpenBackends,
|
||||
device: &str,
|
||||
need: Need,
|
||||
runtime: &Arc<dyn Runtime>,
|
||||
) -> Chosen {
|
||||
#[cfg(target_os = "macos")]
|
||||
let picked = Picked {
|
||||
label: Kind::VideoToolbox.label(),
|
||||
why: "this host is macOS".to_owned(),
|
||||
opened: open.get_or_open(
|
||||
Place {
|
||||
kind: Kind::VideoToolbox,
|
||||
at: None,
|
||||
},
|
||||
device,
|
||||
|| open_videotoolbox(runtime),
|
||||
),
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let picked = pick(device, need, &LinuxHost { runtime }, open);
|
||||
#[cfg(target_os = "macos")]
|
||||
let _ = need;
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
let _ = (open, runtime);
|
||||
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
|
||||
let picked = Picked {
|
||||
label: "none",
|
||||
why: "this host has no video backend".to_owned(),
|
||||
opened: Err("none is built for this OS".to_owned()),
|
||||
};
|
||||
let Picked { label, why, opened } = picked;
|
||||
match opened {
|
||||
Ok((shared, was_open)) => {
|
||||
let summary = shared.backend.summary();
|
||||
if was_open {
|
||||
log::info!(
|
||||
"{device} backend {label} ({why}): the one open for the {}, {}: {summary}",
|
||||
shared.opened_for,
|
||||
shared.place
|
||||
);
|
||||
} else {
|
||||
log::info!("{device} backend {label} ({why}): {summary}");
|
||||
}
|
||||
Chosen {
|
||||
opened: Some(shared),
|
||||
label,
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!("{device} has no backend ({why}; {error})");
|
||||
Chosen {
|
||||
opened: None,
|
||||
label,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend `host` offers `device`, with what it needs (module doc): on the GPU device's GPU,
|
||||
/// else on the first hardware GPU that has it, discrete ones first, each opened at `open`'s
|
||||
/// place or taken from there.
|
||||
fn pick(device: &str, need: Need, host: &dyn Host, open: &OpenBackends) -> Picked {
|
||||
let gpu = host.gpu_device();
|
||||
let reason = match &gpu {
|
||||
Some(g) if g.kind != GpuKind::Cpu => match open_on(device, need, host, open, g) {
|
||||
Ok((kind, opened, note)) => {
|
||||
return Picked {
|
||||
label: kind.label(),
|
||||
why: format!("the GPU device's GPU, {g}{note}"),
|
||||
opened: Ok(opened),
|
||||
};
|
||||
}
|
||||
Err(why) => format!("the GPU device's GPU, {g}, {} ({why})", need.lacking()),
|
||||
},
|
||||
Some(g) => format!("the GPU device's GPU, {g}, is a software rasterizer"),
|
||||
None => "the Vulkan runtime makes no device, so there is no GPU device's GPU".to_owned(),
|
||||
};
|
||||
let mut others: Vec<Gpu> = (host.hardware().into_iter())
|
||||
.filter(|other| other.kind != GpuKind::Cpu)
|
||||
.filter(|other| !gpu.as_ref().is_some_and(|g| g.is(other)))
|
||||
.collect();
|
||||
others.sort_by_key(|other| other.kind.rank());
|
||||
let mut refused = Vec::new();
|
||||
for other in others {
|
||||
match open_on(device, need, host, open, &other) {
|
||||
Ok((kind, opened, note)) => {
|
||||
return Picked {
|
||||
label: kind.label(),
|
||||
why: format!(
|
||||
"{reason}: the first hardware GPU {}, discrete ones first, {other}{note}",
|
||||
need.sought()
|
||||
),
|
||||
opened: Ok(opened),
|
||||
};
|
||||
}
|
||||
Err(why) => refused.push(format!("{other}: {why}")),
|
||||
}
|
||||
}
|
||||
let error = if refused.is_empty() {
|
||||
"the host has no other hardware GPU".to_owned()
|
||||
} else {
|
||||
format!(
|
||||
"no other hardware GPU {}: {}",
|
||||
need.sought(),
|
||||
refused.join("; ")
|
||||
)
|
||||
};
|
||||
Picked {
|
||||
label: "none",
|
||||
why: reason,
|
||||
opened: Err(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend on `gpu` with what `device` needs, at `open`'s place or opened there now: NVIDIA's
|
||||
/// where it is an NVIDIA GPU and it has it, else VA-API's; with what the log adds to why (what
|
||||
/// NVIDIA's lacked, on an NVIDIA GPU). `Err` with why where neither has it. A backend opened here
|
||||
/// that lacks it goes again at once.
|
||||
fn open_on(
|
||||
device: &str,
|
||||
need: Need,
|
||||
host: &dyn Host,
|
||||
open: &OpenBackends,
|
||||
gpu: &Gpu,
|
||||
) -> Result<(Kind, Opened, String), String> {
|
||||
let mut why_not = Vec::new();
|
||||
let kinds: &[Kind] = if gpu.vendor_id == NVIDIA_VENDOR {
|
||||
&[Kind::Nvidia, Kind::Vaapi]
|
||||
} else {
|
||||
&[Kind::Vaapi]
|
||||
};
|
||||
for &kind in kinds {
|
||||
let Some(place) = Place::on(kind, gpu) else {
|
||||
why_not.push(match kind {
|
||||
Kind::Nvidia => "NVIDIA's: it has no PCI address".to_owned(),
|
||||
_ => format!("{}'s: it has no DRM render node", kind.label()),
|
||||
});
|
||||
continue;
|
||||
};
|
||||
match open.get_or_open(place, device, || offering(host.open(kind, gpu))) {
|
||||
Ok(opened) if need.met(&opened.0.backend) => {
|
||||
let note = if why_not.is_empty() {
|
||||
String::new()
|
||||
} else {
|
||||
format!(", where {}", why_not.join("; "))
|
||||
};
|
||||
return Ok((kind, opened, note));
|
||||
}
|
||||
Ok(_) => why_not.push(format!("{}'s {}", kind.label(), need.lacking())),
|
||||
Err(why) => why_not.push(format!("{}'s: {why}", kind.label())),
|
||||
}
|
||||
}
|
||||
Err(why_not.join("; "))
|
||||
}
|
||||
|
||||
/// `opened`, where it has a part: a backend with none offers no video, and is not kept.
|
||||
fn offering(opened: Result<Backend, String>) -> Result<Backend, String> {
|
||||
let backend = opened?;
|
||||
if Need::Video.met(&backend) {
|
||||
Ok(backend)
|
||||
} else {
|
||||
Err(format!("it opened with no part: {}", backend.summary()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's GPUs as reims-vgpu-vulkan's `host_gpus` reads them, and its backends, which run
|
||||
/// on `runtime`.
|
||||
#[cfg(target_os = "linux")]
|
||||
struct LinuxHost<'a> {
|
||||
runtime: &'a Arc<dyn Runtime>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl From<reims_vgpu_vulkan::host_gpus::HostGpu> for Gpu {
|
||||
fn from(gpu: reims_vgpu_vulkan::host_gpus::HostGpu) -> Gpu {
|
||||
use reims_vgpu_vulkan::host_gpus::GpuKind as K;
|
||||
Gpu {
|
||||
name: gpu.name,
|
||||
kind: match gpu.kind {
|
||||
K::Discrete => GpuKind::Discrete,
|
||||
K::Integrated => GpuKind::Integrated,
|
||||
K::Virtual => GpuKind::Virtual,
|
||||
K::Cpu => GpuKind::Cpu,
|
||||
K::Other => GpuKind::Other,
|
||||
},
|
||||
vendor_id: gpu.vendor_id,
|
||||
pci_address: gpu.pci_address,
|
||||
render_node: gpu.render_node,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Host for LinuxHost<'_> {
|
||||
fn gpu_device(&self) -> Option<Gpu> {
|
||||
reims_vgpu_vulkan::host_gpus::gpu_device_gpu().map(Gpu::from)
|
||||
}
|
||||
|
||||
fn hardware(&self) -> Vec<Gpu> {
|
||||
(reims_vgpu_vulkan::host_gpus::hardware_gpus().into_iter())
|
||||
.map(Gpu::from)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// VA-API's decoders, encoders and JPEG decoder on the GPU's render node; NVIDIA's NVDEC and
|
||||
/// NVENC on the GPU of its PCI address, with no JPEG decoder, its libraries loaded now, so a
|
||||
/// host without them does not open it.
|
||||
fn open(&self, kind: Kind, gpu: &Gpu) -> Result<Backend, String> {
|
||||
match (kind, &gpu.render_node, &gpu.pci_address) {
|
||||
(Kind::Vaapi, Some(node), _) => {
|
||||
reims_vgpu_video_vaapi::open_backend(node, Arc::clone(self.runtime))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
(Kind::Nvidia, _, Some(address)) => {
|
||||
reims_vgpu_video_nvidia::open_backend(address, Arc::clone(self.runtime))
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
(Kind::VideoToolbox, ..) => Err("VideoToolbox is macOS's".to_owned()),
|
||||
_ => Err("the GPU has no place it opens at".to_owned()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// VideoToolbox's hardware decoders and encoders, with no JPEG decoder; it always opens, with no
|
||||
/// part where this Mac lists none. Its encoders wait on `runtime`'s clock.
|
||||
#[cfg(target_os = "macos")]
|
||||
fn open_videotoolbox(runtime: &Arc<dyn Runtime>) -> Result<Backend, String> {
|
||||
Ok(reims_vgpu_video_videotoolbox::backend(Arc::clone(runtime)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,442 +0,0 @@
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use reims_vgpu_video_core::backend::NoDecoders;
|
||||
#[cfg(target_os = "macos")]
|
||||
use reims_vgpu_video_core::runtime::StdRuntime;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A host of stand-in GPUs: the GPU device's, the hardware ones in the loader's order, and the
|
||||
/// backends that open on each, by kind and GPU name, with decoders, or with no part; any other
|
||||
/// does not open. It counts the opens it is asked for.
|
||||
#[derive(Default)]
|
||||
struct StandIn {
|
||||
gpu_device: Option<Gpu>,
|
||||
hardware: Vec<Gpu>,
|
||||
offers: Vec<(Kind, &'static str)>,
|
||||
empty: Vec<(Kind, &'static str)>,
|
||||
opens: RefCell<Vec<(Kind, String)>>,
|
||||
}
|
||||
|
||||
impl Host for StandIn {
|
||||
fn gpu_device(&self) -> Option<Gpu> {
|
||||
self.gpu_device.clone()
|
||||
}
|
||||
|
||||
fn hardware(&self) -> Vec<Gpu> {
|
||||
self.hardware.clone()
|
||||
}
|
||||
|
||||
fn open(&self, kind: Kind, gpu: &Gpu) -> Result<Backend, String> {
|
||||
self.opens.borrow_mut().push((kind, gpu.name.clone()));
|
||||
let at = (kind, gpu.name.as_str());
|
||||
if self.offers.contains(&at) {
|
||||
Ok(Backend {
|
||||
decoders: Some(Arc::new(NoDecoders)),
|
||||
..Backend::none(format!("{} stand-in", kind.label()))
|
||||
})
|
||||
} else if self.empty.contains(&at) {
|
||||
Ok(Backend::none(format!("{} stand-in", kind.label())))
|
||||
} else {
|
||||
Err("no driver".to_owned())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gpu(name: &str, kind: GpuKind, vendor_id: u32, at: Option<(&str, &str)>) -> Gpu {
|
||||
Gpu {
|
||||
name: name.to_owned(),
|
||||
kind,
|
||||
vendor_id,
|
||||
pci_address: at.map(|(pci, _)| pci.to_owned()),
|
||||
render_node: at.map(|(_, node)| PathBuf::from(node)),
|
||||
}
|
||||
}
|
||||
|
||||
const XTX: &str = "RX 7900 XTX";
|
||||
const IGPU: &str = "Radeon 780M";
|
||||
const RTX: &str = "RTX 5080";
|
||||
|
||||
fn xtx() -> Gpu {
|
||||
let at = ("0000:03:00.0", "/stand-in/renderD128");
|
||||
gpu(XTX, GpuKind::Discrete, 0x1002, Some(at))
|
||||
}
|
||||
|
||||
fn igpu() -> Gpu {
|
||||
let at = ("0000:c9:00.0", "/stand-in/renderD129");
|
||||
gpu(IGPU, GpuKind::Integrated, 0x1002, Some(at))
|
||||
}
|
||||
|
||||
fn rtx() -> Gpu {
|
||||
let at = ("0000:01:00.0", "/stand-in/renderD130");
|
||||
gpu(RTX, GpuKind::Discrete, NVIDIA_VENDOR, Some(at))
|
||||
}
|
||||
|
||||
fn lavapipe() -> Gpu {
|
||||
gpu("llvmpipe", GpuKind::Cpu, 0x10005, None)
|
||||
}
|
||||
|
||||
/// What `host` picks for a device that needs `need`, with its own open backends: its label, its
|
||||
/// place, and why.
|
||||
fn picked_for(host: &StandIn, need: Need) -> (&'static str, Result<String, String>, String) {
|
||||
let open = OpenBackends::new();
|
||||
let Picked { label, why, opened } = pick("a device", need, host, &open);
|
||||
(label, opened.map(|(shared, _)| shared.place.clone()), why)
|
||||
}
|
||||
|
||||
/// What `host` picks for a video device ([`picked_for`]).
|
||||
fn picked(host: &StandIn) -> (&'static str, Result<String, String>, String) {
|
||||
picked_for(host, Need::Video)
|
||||
}
|
||||
|
||||
fn opens(host: &StandIn) -> Vec<(Kind, String)> {
|
||||
host.opens.borrow().clone()
|
||||
}
|
||||
|
||||
/// The devices run on the GPU device's GPU: VA-API on its render node, opened once
|
||||
#[test]
|
||||
fn the_devices_follow_the_gpu_devices_gpu() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(xtx()),
|
||||
hardware: vec![igpu(), xtx(), lavapipe()],
|
||||
offers: vec![(Kind::Vaapi, XTX), (Kind::Vaapi, IGPU)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (label, place, why) = picked(&host);
|
||||
assert_eq!(label, "VA-API");
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD128"));
|
||||
assert_eq!(
|
||||
why,
|
||||
"the GPU device's GPU, RX 7900 XTX (discrete, 0000:03:00.0, /stand-in/renderD128)"
|
||||
);
|
||||
assert_eq!(opens(&host), [(Kind::Vaapi, XTX.to_owned())]);
|
||||
}
|
||||
|
||||
/// A GPU device pinned to an integrated GPU has the devices there, though a discrete one offers
|
||||
/// video too
|
||||
#[test]
|
||||
fn a_pinned_integrated_gpu_is_the_devices_too() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(igpu()),
|
||||
hardware: vec![igpu()],
|
||||
offers: vec![(Kind::Vaapi, XTX), (Kind::Vaapi, IGPU)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (label, place, _) = picked(&host);
|
||||
assert_eq!(label, "VA-API");
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD129"));
|
||||
}
|
||||
|
||||
/// An NVIDIA GPU runs NVIDIA's backend, by its PCI address
|
||||
#[test]
|
||||
fn an_nvidia_gpu_runs_nvidias_backend() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(rtx()),
|
||||
offers: vec![(Kind::Nvidia, RTX), (Kind::Vaapi, RTX)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (label, place, _) = picked(&host);
|
||||
assert_eq!(label, "NVIDIA");
|
||||
assert_eq!(place.as_deref(), Ok("NVIDIA at 0000:01:00.0"));
|
||||
assert_eq!(opens(&host), [(Kind::Nvidia, RTX.to_owned())]);
|
||||
}
|
||||
|
||||
/// On an NVIDIA GPU whose backend does not open (no CUDA), VA-API on its render node, saying why
|
||||
#[test]
|
||||
fn an_nvidia_gpu_without_cuda_runs_vaapi() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(rtx()),
|
||||
offers: vec![(Kind::Vaapi, RTX)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (label, place, why) = picked(&host);
|
||||
assert_eq!(label, "VA-API");
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD130"));
|
||||
assert!(why.ends_with(", where NVIDIA's: no driver"), "{why}");
|
||||
}
|
||||
|
||||
/// A GPU device on lavapipe has the devices pick a hardware GPU: a discrete one first, whatever
|
||||
/// the loader's order
|
||||
#[test]
|
||||
fn a_software_rasterizer_has_the_devices_pick_a_hardware_gpu() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(lavapipe()),
|
||||
hardware: vec![igpu(), xtx()],
|
||||
offers: vec![(Kind::Vaapi, XTX), (Kind::Vaapi, IGPU)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (label, place, why) = picked(&host);
|
||||
assert_eq!(label, "VA-API");
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD128"));
|
||||
assert_eq!(
|
||||
why,
|
||||
"the GPU device's GPU, llvmpipe (CPU), is a software rasterizer: the first hardware GPU \
|
||||
that offers video, discrete ones first, RX 7900 XTX (discrete, 0000:03:00.0, \
|
||||
/stand-in/renderD128)"
|
||||
);
|
||||
assert_eq!(opens(&host), [(Kind::Vaapi, XTX.to_owned())]);
|
||||
}
|
||||
|
||||
/// A discrete GPU whose backend opens with no part offers no video: the integrated one is picked
|
||||
#[test]
|
||||
fn a_gpu_without_video_is_passed_over() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(lavapipe()),
|
||||
hardware: vec![xtx(), igpu()],
|
||||
offers: vec![(Kind::Vaapi, IGPU)],
|
||||
empty: vec![(Kind::Vaapi, XTX)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (_, place, _) = picked(&host);
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD129"));
|
||||
}
|
||||
|
||||
/// The GPU device's GPU that offers no video is not tried again among the hardware ones
|
||||
#[test]
|
||||
fn the_gpu_devices_gpu_without_video_is_tried_once() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(xtx()),
|
||||
hardware: vec![xtx(), igpu()],
|
||||
offers: vec![(Kind::Vaapi, IGPU)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (_, place, why) = picked(&host);
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD129"));
|
||||
assert!(
|
||||
why.starts_with(
|
||||
"the GPU device's GPU, RX 7900 XTX (discrete, 0000:03:00.0, /stand-in/renderD128), \
|
||||
offers no video (VA-API's: no driver): the first hardware GPU"
|
||||
),
|
||||
"{why}"
|
||||
);
|
||||
assert_eq!(
|
||||
opens(&host),
|
||||
[
|
||||
(Kind::Vaapi, XTX.to_owned()),
|
||||
(Kind::Vaapi, IGPU.to_owned())
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// Without a hardware GPU that offers video, no backend, saying why; without a GPU device's
|
||||
/// GPU, a hardware one
|
||||
#[test]
|
||||
fn a_host_without_video_offers_none() {
|
||||
let host = StandIn {
|
||||
gpu_device: Some(lavapipe()),
|
||||
..StandIn::default()
|
||||
};
|
||||
let (label, place, why) = picked(&host);
|
||||
assert_eq!(label, "none");
|
||||
assert_eq!(place, Err("the host has no other hardware GPU".to_owned()));
|
||||
assert!(why.ends_with("is a software rasterizer"), "{why}");
|
||||
|
||||
let host = StandIn {
|
||||
hardware: vec![xtx()],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (_, place, _) = picked(&host);
|
||||
assert_eq!(
|
||||
place,
|
||||
Err(
|
||||
"no other hardware GPU that offers video: RX 7900 XTX (discrete, 0000:03:00.0, \
|
||||
/stand-in/renderD128): VA-API's: no driver"
|
||||
.to_owned()
|
||||
)
|
||||
);
|
||||
|
||||
let host = StandIn {
|
||||
hardware: vec![xtx()],
|
||||
offers: vec![(Kind::Vaapi, XTX)],
|
||||
..StandIn::default()
|
||||
};
|
||||
let (_, place, why) = picked(&host);
|
||||
assert_eq!(place.as_deref(), Ok("VA-API at /stand-in/renderD128"));
|
||||
assert!(
|
||||
why.starts_with("the Vulkan runtime makes no device"),
|
||||
"{why}"
|
||||
);
|
||||
}
|
||||
|
||||
/// On macOS the video device's backend is VideoToolbox, and on this Mac it decodes.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn a_macs_devices_run_videotoolbox() {
|
||||
let chosen = choose(
|
||||
&OpenBackends::new(),
|
||||
"video device",
|
||||
Need::Video,
|
||||
&StdRuntime::shared(),
|
||||
);
|
||||
assert_eq!(chosen.label, "VideoToolbox");
|
||||
assert!(chosen.has_backend());
|
||||
let summary = chosen.backend().summary();
|
||||
assert!(summary.starts_with("VideoToolbox: decodes"), "{summary}");
|
||||
}
|
||||
|
||||
/// A stand-in for a backend's open: counts its calls, and fails when told to.
|
||||
fn opener(opens: &Cell<u32>, fail: bool) -> impl FnOnce() -> Result<Backend, String> {
|
||||
move || {
|
||||
opens.set(opens.get() + 1);
|
||||
if fail {
|
||||
Err("no such driver".to_owned())
|
||||
} else {
|
||||
Ok(Backend::none("stand-in"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn place(node: &str) -> Place {
|
||||
Place {
|
||||
kind: Kind::Vaapi,
|
||||
at: Some(node.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Two devices on one node open the backend once and share it; another node opens its own.
|
||||
#[test]
|
||||
fn devices_on_one_node_share_one_backend() {
|
||||
let open = OpenBackends::new();
|
||||
let opens = Cell::new(0);
|
||||
let (video, was_open) = open
|
||||
.get_or_open(place("/n/128"), "video device", opener(&opens, false))
|
||||
.expect("opens");
|
||||
assert!(!was_open);
|
||||
let (another, was_open) = open
|
||||
.get_or_open(
|
||||
place("/n/128"),
|
||||
"another video device",
|
||||
opener(&opens, false),
|
||||
)
|
||||
.expect("opens");
|
||||
assert!(was_open);
|
||||
assert!(Arc::ptr_eq(&video, &another));
|
||||
assert_eq!(another.opened_for, "video device");
|
||||
let (other, was_open) = open
|
||||
.get_or_open(
|
||||
place("/n/129"),
|
||||
"another video device",
|
||||
opener(&opens, false),
|
||||
)
|
||||
.expect("opens");
|
||||
assert!(!was_open);
|
||||
assert!(!Arc::ptr_eq(&video, &other));
|
||||
assert_eq!(opens.get(), 2);
|
||||
}
|
||||
|
||||
/// The backend lives while either device holds it, in either order they go, and a device
|
||||
/// made after both went opens it anew.
|
||||
#[test]
|
||||
fn a_shared_backend_lives_until_its_last_device_goes() {
|
||||
for video_first in [true, false] {
|
||||
let open = OpenBackends::new();
|
||||
let opens = Cell::new(0);
|
||||
let get = |device| {
|
||||
open.get_or_open(place("/n/128"), device, opener(&opens, false))
|
||||
.expect("opens")
|
||||
.0
|
||||
};
|
||||
let (video, another) = (get("video device"), get("another video device"));
|
||||
let weak = Arc::downgrade(&video);
|
||||
let (first, second) = if video_first {
|
||||
(video, another)
|
||||
} else {
|
||||
(another, video)
|
||||
};
|
||||
drop(first);
|
||||
assert!(weak.upgrade().is_some(), "the other device still holds it");
|
||||
let third = get("video device");
|
||||
assert_eq!(opens.get(), 1, "a device made meanwhile shares it");
|
||||
drop((second, third));
|
||||
assert!(weak.upgrade().is_none(), "released with its last device");
|
||||
let _again = get("video device");
|
||||
assert_eq!(opens.get(), 2, "opened anew after");
|
||||
}
|
||||
}
|
||||
|
||||
/// A backend that did not open is not kept: the next device asks again.
|
||||
#[test]
|
||||
fn a_failed_open_is_asked_again() {
|
||||
let open = OpenBackends::new();
|
||||
let opens = Cell::new(0);
|
||||
assert!(
|
||||
open.get_or_open(place("/n/128"), "video device", opener(&opens, true))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
open.get_or_open(
|
||||
place("/n/128"),
|
||||
"another video device",
|
||||
opener(&opens, false)
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
assert_eq!(opens.get(), 2);
|
||||
}
|
||||
|
||||
/// Two video devices themselves share the backend, and it is released with the last of them, in
|
||||
/// either order, as their destroys (QEMU's unrealize) drop them. This Mac's VideoToolbox is the
|
||||
/// backend, on std's runtime, not the testkit platform's, whose virtual clock no backend's wait
|
||||
/// for its GPU would pass. The devices pick from backends open of the test's own, not the
|
||||
/// process's, which the other tests' devices in the process share meanwhile, so the count is of
|
||||
/// what this test made.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn the_devices_share_their_backend_until_the_last_goes() {
|
||||
use reims_vgpu_core::testkit::FakePlatform;
|
||||
|
||||
use crate::video::{VideoDevice, VideoDeviceConfig};
|
||||
|
||||
let open = OpenBackends::new();
|
||||
for first_first in [true, false] {
|
||||
let platform = Arc::new(FakePlatform::new());
|
||||
let device = |platform| {
|
||||
VideoDevice::picking_from(
|
||||
&open,
|
||||
platform,
|
||||
StdRuntime::shared(),
|
||||
VideoDeviceConfig::default(),
|
||||
)
|
||||
};
|
||||
let first = device(Arc::clone(&platform));
|
||||
let second = device(platform);
|
||||
assert_eq!(
|
||||
videotoolbox_holders(&open),
|
||||
2,
|
||||
"both devices hold one backend"
|
||||
);
|
||||
let (gone, left) = if first_first {
|
||||
(first, second)
|
||||
} else {
|
||||
(second, first)
|
||||
};
|
||||
drop(gone);
|
||||
assert_eq!(
|
||||
videotoolbox_holders(&open),
|
||||
1,
|
||||
"the other device still holds it"
|
||||
);
|
||||
drop(left);
|
||||
assert_eq!(
|
||||
videotoolbox_holders(&open),
|
||||
0,
|
||||
"released with the last device"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A place is its kind and where it runs: a render node for VA-API, a PCI address for NVIDIA,
|
||||
/// nothing for VideoToolbox.
|
||||
#[test]
|
||||
fn a_place_says_its_backend_and_gpu() {
|
||||
assert_eq!(place("/n/128").to_string(), "VA-API at /n/128");
|
||||
let nvidia = Place::on(Kind::Nvidia, &rtx()).expect("a PCI address");
|
||||
assert_eq!(nvidia.to_string(), "NVIDIA at 0000:01:00.0");
|
||||
assert_eq!(Place::on(Kind::Vaapi, &lavapipe()), None);
|
||||
let mac = Place {
|
||||
kind: Kind::VideoToolbox,
|
||||
at: None,
|
||||
};
|
||||
assert_eq!(mac.to_string(), "VideoToolbox");
|
||||
}
|
||||
@@ -1,337 +0,0 @@
|
||||
//! The video device's backends as its host session reaches them, logged: each decoder's and
|
||||
//! encoder's opening and end at info, and each frame it decodes or encodes at debug
|
||||
//! (`reims_vgpu::video`), with the time the backend took on the platform's clock. Host-side
|
||||
//! evidence that a guest's frames decode and encode where the backend says, VA-API's on Linux.
|
||||
//!
|
||||
//! Every method of core's traits is passed on, those with a default too: a default here would
|
||||
//! answer the session in the backend's place, as one for `frames_decoded` would lend an AV1 unit
|
||||
//! one buffer a frame output, and one for `session_capabilities` would answer `+enc` with the
|
||||
//! listed entry while VideoToolbox has no encoder session to give.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::os::clock::Clock as _;
|
||||
use reims_vgpu_video_core::backend::{
|
||||
BackendDecoder, BackendError, Codec, CodecCapabilities, CompressedFrame, DecodedFrame,
|
||||
DecoderBackend, DecoderConfig, FrameDecoded, PixelFormat,
|
||||
};
|
||||
use reims_vgpu_video_core::encoder_backend::{
|
||||
BackendEncoder, EncodedFrame, EncoderBackend, EncoderCapabilities, EncoderConfig,
|
||||
EncoderSettings, SourceFrame,
|
||||
};
|
||||
use reims_vgpu_video_core::status::OsStatus;
|
||||
|
||||
/// A backend as the session reaches it: `inner`, logged (module doc).
|
||||
pub(super) struct LoggedBackend<P: Platform> {
|
||||
pub(super) inner: Arc<dyn DecoderBackend>,
|
||||
pub(super) name: &'static str,
|
||||
pub(super) platform: Arc<P>,
|
||||
}
|
||||
|
||||
impl<P: Platform> DecoderBackend for LoggedBackend<P> {
|
||||
fn capabilities(&self) -> Vec<CodecCapabilities> {
|
||||
self.inner.capabilities()
|
||||
}
|
||||
|
||||
fn open(&self, config: &DecoderConfig) -> Result<Box<dyn BackendDecoder>, BackendError> {
|
||||
match self.inner.open(config) {
|
||||
Ok(inner) => {
|
||||
log::info!(
|
||||
"{} decoder opened: {:?} {}x{}, {} bytes of configuration, output {:?}",
|
||||
self.name,
|
||||
config.codec,
|
||||
config.width,
|
||||
config.height,
|
||||
config.configuration.len(),
|
||||
inner.output_format()
|
||||
);
|
||||
Ok(Box::new(LoggedDecoder {
|
||||
inner,
|
||||
name: self.name,
|
||||
platform: Arc::clone(&self.platform),
|
||||
decoded: 0,
|
||||
failed: 0,
|
||||
emitted: 0,
|
||||
busy: std::time::Duration::ZERO,
|
||||
}))
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"{} decoder for {:?} {}x{} not opened: {error}",
|
||||
self.name,
|
||||
config.codec,
|
||||
config.width,
|
||||
config.height
|
||||
);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One decoder of a [`LoggedBackend`], counting what it decodes.
|
||||
struct LoggedDecoder<P: Platform> {
|
||||
inner: Box<dyn BackendDecoder>,
|
||||
name: &'static str,
|
||||
platform: Arc<P>,
|
||||
decoded: usize,
|
||||
failed: usize,
|
||||
emitted: usize,
|
||||
busy: std::time::Duration,
|
||||
}
|
||||
|
||||
impl<P: Platform> BackendDecoder for LoggedDecoder<P> {
|
||||
fn output_format(&self) -> PixelFormat {
|
||||
self.inner.output_format()
|
||||
}
|
||||
|
||||
fn decode(
|
||||
&mut self,
|
||||
frame: &CompressedFrame<'_>,
|
||||
) -> Result<Vec<Box<dyn DecodedFrame>>, BackendError> {
|
||||
let clock = self.platform.clock();
|
||||
let start = clock.now_mono();
|
||||
let decoded = self.inner.decode(frame);
|
||||
let took = clock.now_mono().saturating_duration_since(start);
|
||||
self.busy += took;
|
||||
match &decoded {
|
||||
Ok(out) => {
|
||||
self.decoded += 1;
|
||||
self.emitted += out.len();
|
||||
log::debug!(
|
||||
"{} decode: frame {} of {} bytes in {:.3} ms, {} out",
|
||||
self.name,
|
||||
frame.frame_id,
|
||||
frame.data.len(),
|
||||
took.as_secs_f64() * 1e3,
|
||||
out.len()
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
self.failed += 1;
|
||||
log::warn!(
|
||||
"{} decode: frame {} of {} bytes failed: {error}",
|
||||
self.name,
|
||||
frame.frame_id,
|
||||
frame.data.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
decoded
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<Vec<Box<dyn DecodedFrame>>, BackendError> {
|
||||
let flushed = self.inner.flush();
|
||||
if let Ok(out) = &flushed {
|
||||
self.emitted += out.len();
|
||||
log::debug!("{} flush: {} out", self.name, out.len());
|
||||
}
|
||||
flushed
|
||||
}
|
||||
|
||||
fn can_accept(&self, config: &DecoderConfig) -> bool {
|
||||
self.inner.can_accept(config)
|
||||
}
|
||||
|
||||
/// The backend's own answer: without it the session copies one frame at a time, and the
|
||||
/// GPU waits through every copy back.
|
||||
fn decodes_while_copying(&self) -> bool {
|
||||
self.inner.decodes_while_copying()
|
||||
}
|
||||
|
||||
/// The backend's own answer: without it the session lends an AV1 unit one buffer a frame
|
||||
/// output, where Apple's decoder lends one a frame decoded and holds it while it is
|
||||
/// referenced.
|
||||
fn frames_decoded(&mut self) -> Vec<FrameDecoded> {
|
||||
self.inner.frames_decoded()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for LoggedDecoder<P> {
|
||||
fn drop(&mut self) {
|
||||
log::info!(
|
||||
"{} decoder closed: {} frames decoded, {} failed, {} out, {:.1} ms in the backend",
|
||||
self.name,
|
||||
self.decoded,
|
||||
self.failed,
|
||||
self.emitted,
|
||||
self.busy.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An encoder backend as the session reaches it: `inner`, logged as a [`LoggedBackend`] is: each
|
||||
/// encoder's opening and end at info, and each frame it encodes at debug, with the time the
|
||||
/// backend took.
|
||||
pub(super) struct LoggedEncoders<P: Platform> {
|
||||
pub(super) inner: Arc<dyn EncoderBackend>,
|
||||
pub(super) name: &'static str,
|
||||
pub(super) platform: Arc<P>,
|
||||
}
|
||||
|
||||
impl<P: Platform> EncoderBackend for LoggedEncoders<P> {
|
||||
fn encoders(&self) -> Vec<EncoderCapabilities> {
|
||||
self.inner.encoders()
|
||||
}
|
||||
|
||||
/// The backend's own answer, logged where it is a status: VideoToolbox's -12912 while every
|
||||
/// hardware encoder session is taken, which `+enc` answers as Apple's host does.
|
||||
fn session_capabilities(&self, codec: Codec) -> Result<Option<EncoderCapabilities>, OsStatus> {
|
||||
let answered = self.inner.session_capabilities(codec);
|
||||
if let Err(status) = answered {
|
||||
log::warn!("{} encoder for {codec:?} not made now: {status}", self.name);
|
||||
}
|
||||
answered
|
||||
}
|
||||
|
||||
fn open(&self, config: &EncoderConfig) -> Result<Box<dyn BackendEncoder>, BackendError> {
|
||||
match self.inner.open(config) {
|
||||
Ok(inner) => {
|
||||
log::info!(
|
||||
"{} encoder opened: {:?} {}x{}, {:?}",
|
||||
self.name,
|
||||
config.codec,
|
||||
config.width,
|
||||
config.height,
|
||||
config.settings
|
||||
);
|
||||
Ok(Box::new(LoggedEncoder {
|
||||
inner,
|
||||
name: self.name,
|
||||
platform: Arc::clone(&self.platform),
|
||||
encoded: 0,
|
||||
failed: 0,
|
||||
out: 0,
|
||||
bytes: 0,
|
||||
busy: std::time::Duration::ZERO,
|
||||
}))
|
||||
}
|
||||
Err(error) => {
|
||||
log::warn!(
|
||||
"{} encoder for {:?} {}x{} not opened: {error}",
|
||||
self.name,
|
||||
config.codec,
|
||||
config.width,
|
||||
config.height
|
||||
);
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn check_property(
|
||||
&self,
|
||||
codec: Codec,
|
||||
key: &str,
|
||||
value: &reims_vgpu_video_core::plist::Value,
|
||||
) -> Result<(), OsStatus> {
|
||||
let checked = self.inner.check_property(codec, key, value);
|
||||
if let Err(status) = checked {
|
||||
log::info!("{} encoder refuses {key} = {value:?}: {status}", self.name);
|
||||
}
|
||||
checked
|
||||
}
|
||||
}
|
||||
|
||||
/// One encoder of a [`LoggedEncoders`], counting what it encodes.
|
||||
struct LoggedEncoder<P: Platform> {
|
||||
inner: Box<dyn BackendEncoder>,
|
||||
name: &'static str,
|
||||
platform: Arc<P>,
|
||||
encoded: usize,
|
||||
failed: usize,
|
||||
out: usize,
|
||||
bytes: usize,
|
||||
busy: std::time::Duration,
|
||||
}
|
||||
|
||||
impl<P: Platform> LoggedEncoder<P> {
|
||||
fn count(&mut self, frames: &[EncodedFrame]) {
|
||||
self.out += frames.len();
|
||||
self.bytes += frames.iter().map(|frame| frame.data.len()).sum::<usize>();
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> BackendEncoder for LoggedEncoder<P> {
|
||||
fn configuration(&self) -> Vec<u8> {
|
||||
self.inner.configuration()
|
||||
}
|
||||
|
||||
fn encode(&mut self, frame: &SourceFrame<'_>) -> Result<Vec<EncodedFrame>, BackendError> {
|
||||
let clock = self.platform.clock();
|
||||
let start = clock.now_mono();
|
||||
let encoded = self.inner.encode(frame);
|
||||
let took = clock.now_mono().saturating_duration_since(start);
|
||||
self.busy += took;
|
||||
match &encoded {
|
||||
Ok(out) => {
|
||||
self.encoded += 1;
|
||||
self.count(out);
|
||||
log::debug!(
|
||||
"{} encode: frame {} {:?} {}x{} in {:.3} ms, {} out of {} bytes",
|
||||
self.name,
|
||||
frame.frame_id,
|
||||
frame.pixel_format,
|
||||
frame.width,
|
||||
frame.height,
|
||||
took.as_secs_f64() * 1e3,
|
||||
out.len(),
|
||||
out.iter().map(|frame| frame.data.len()).sum::<usize>()
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
self.failed += 1;
|
||||
log::warn!(
|
||||
"{} encode: frame {} failed: {error}",
|
||||
self.name,
|
||||
frame.frame_id
|
||||
);
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<Vec<EncodedFrame>, BackendError> {
|
||||
let flushed = self.inner.flush();
|
||||
if let Ok(out) = &flushed {
|
||||
self.count(out);
|
||||
log::debug!("{} encoder flush: {} out", self.name, out.len());
|
||||
}
|
||||
flushed
|
||||
}
|
||||
|
||||
fn reconfigure(&mut self, settings: &EncoderSettings) -> Result<(), BackendError> {
|
||||
let reconfigured = self.inner.reconfigure(settings);
|
||||
match &reconfigured {
|
||||
Ok(()) => log::info!("{} encoder reconfigured: {settings:?}", self.name),
|
||||
Err(error) => log::info!("{} encoder not reconfigured: {error}", self.name),
|
||||
}
|
||||
reconfigured
|
||||
}
|
||||
|
||||
/// The guest's `epfr`, passed on: the VideoToolbox backend prepares its session there, as
|
||||
/// Apple's host prepares its encoder, and the default would leave it to the first frame.
|
||||
fn prepare(&mut self) -> Result<(), BackendError> {
|
||||
let prepared = self.inner.prepare();
|
||||
if let Err(error) = &prepared {
|
||||
log::info!("{} encoder not prepared: {error}", self.name);
|
||||
}
|
||||
prepared
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Drop for LoggedEncoder<P> {
|
||||
fn drop(&mut self) {
|
||||
log::info!(
|
||||
"{} encoder closed: {} frames encoded, {} failed, {} out of {} bytes, {:.1} ms in the \
|
||||
backend",
|
||||
self.name,
|
||||
self.encoded,
|
||||
self.failed,
|
||||
self.out,
|
||||
self.bytes,
|
||||
self.busy.as_secs_f64() * 1e3
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,8 @@
|
||||
//! handles from std's threads.
|
||||
//! - **The clock** is the platform's monotonic clock, and a wait is the platform's
|
||||
//! [`Clock::wait_until`] on a deadline on it: a bound counts the time the host sleeps, as the
|
||||
//! platform's own bounds do, and a test's virtual clock is a session's too. A backend the
|
||||
//! device opens waits for its GPU on the same clock, so a test on a virtual clock opens none
|
||||
//! (`VideoDevice::without_backend`), and one that opens the host's gives it std's runtime.
|
||||
//! platform's own bounds do, and a test's virtual clock is a session's too. A backend waits
|
||||
//! for its GPU on the same clock, so a test on a virtual clock opens none.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -27,10 +26,24 @@ use reims_vgpu_video_core::runtime::{MonoTime, Rings, Runtime, TimedOut};
|
||||
use reims_vgpu_video_core::sync::{Condvar, MutexGuard};
|
||||
|
||||
/// `P` as a video crate's runtime (module doc).
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(
|
||||
dead_code,
|
||||
reason = "the graphics device's video arms run their sessions on it"
|
||||
)
|
||||
)]
|
||||
pub(crate) struct PlatformRuntime<P: Platform>(Arc<P>);
|
||||
|
||||
impl<P: Platform> PlatformRuntime<P> {
|
||||
/// `platform`'s runtime, to hand a session or a backend.
|
||||
#[cfg_attr(
|
||||
not(test),
|
||||
expect(
|
||||
dead_code,
|
||||
reason = "the graphics device's video arms run their sessions on it"
|
||||
)
|
||||
)]
|
||||
pub(crate) fn of(platform: &Arc<P>) -> Arc<dyn Runtime> {
|
||||
Arc::new(PlatformRuntime(Arc::clone(platform)))
|
||||
}
|
||||
|
||||
@@ -1,379 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::testkit::FakePlatform;
|
||||
use reims_vgpu_video_core::backend::{
|
||||
BackendDecoder, BackendError, Codec, CodecCapabilities, CompressedFrame, DecodedFrame,
|
||||
DecoderConfig, FrameDecoded, PixelFormat,
|
||||
};
|
||||
use reims_vgpu_video_core::encoder_backend::{
|
||||
BackendEncoder, EncodedFrame, EncoderBackend, EncoderCapabilities, EncoderConfig,
|
||||
EncoderSettings, SourceFrame,
|
||||
};
|
||||
use reims_vgpu_video_core::wire::surface_boxes::read_surface_release;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A watcher of the host's devices' writes that keeps what it is told.
|
||||
struct Seen(Mutex<Vec<std::ops::Range<u64>>>);
|
||||
|
||||
impl crate::device_writes::Watcher for Seen {
|
||||
fn wrote(&self, runs: &[std::ops::Range<u64>]) {
|
||||
self.0.lock().extend_from_slice(runs);
|
||||
}
|
||||
}
|
||||
|
||||
/// A device's write of a held surface's memory reports the surface's pages to the host's
|
||||
/// devices' watchers; a lend for writing that fails reports nothing
|
||||
#[test]
|
||||
fn a_held_surfaces_writes_report_its_pages() {
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let surface = p.fake_surfaces().make_simple(4, 4, 0, 4);
|
||||
// Addresses no other test writes, as the watchers are the process's.
|
||||
let at = 0x5ee0_0000_0000;
|
||||
let held = MappedSurface {
|
||||
mapping_id: 7,
|
||||
surface: Ours::new(surface),
|
||||
platform: Arc::clone(&p),
|
||||
device: OnceLock::new(),
|
||||
pages: crate::device_writes::page_runs(&[at, at + 0x4000, at + 0x10000], 0x4000),
|
||||
};
|
||||
let seen = Arc::new(Seen(Mutex::new(Vec::new())));
|
||||
let watcher: Arc<dyn crate::device_writes::Watcher> = Arc::clone(&seen) as _;
|
||||
crate::device_writes::watch(&watcher);
|
||||
assert!(
|
||||
held.write(&mut |_| {}).is_err(),
|
||||
"the fake platform lends nothing"
|
||||
);
|
||||
assert!(seen.0.lock().is_empty());
|
||||
held.device_wrote();
|
||||
assert_eq!(
|
||||
seen.0.lock().as_slice(),
|
||||
[at..at + 0x8000, at + 0x10000..at + 0x14000]
|
||||
);
|
||||
}
|
||||
|
||||
/// A `subs` atom naming `ids`, the rest 0.
|
||||
fn subs(ids: &[u64]) -> Vec<u8> {
|
||||
let mut m = Vec::new();
|
||||
m.extend_from_slice(&0x30u32.to_be_bytes());
|
||||
m.extend_from_slice(b"subs");
|
||||
for i in 0..5 {
|
||||
m.extend_from_slice(&ids.get(i).copied().unwrap_or(0).to_be_bytes());
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// A `vtpv` request of type `kind` the guest expects a reply to, of the zero UUID and reply
|
||||
/// identifier `reply`, with `,ver` as `=u32` 6: the guest's `decs` and `encs`, written by hand.
|
||||
fn request(kind: &[u8; 4], reply: u64) -> Vec<u8> {
|
||||
let mut m = Vec::new();
|
||||
m.extend_from_slice(&0x30u32.to_be_bytes());
|
||||
m.extend_from_slice(b"vtpv");
|
||||
m.extend_from_slice(kind);
|
||||
m.extend_from_slice(&1u32.to_be_bytes());
|
||||
m.extend_from_slice(&[0; 16]);
|
||||
m.extend_from_slice(&reply.to_be_bytes());
|
||||
m.extend_from_slice(&[0; 8]);
|
||||
m.extend_from_slice(&20u32.to_be_bytes());
|
||||
m.extend_from_slice(b"para,ver=u32");
|
||||
m.extend_from_slice(&6u32.to_be_bytes());
|
||||
m
|
||||
}
|
||||
|
||||
type Sent = Arc<Mutex<Vec<Vec<u8>>>>;
|
||||
|
||||
/// Why the tests' devices open no backend of the host's (`VideoDevice::without_backend`).
|
||||
const NO_BACKEND: &str = "a test's, on the testkit platform's virtual clock";
|
||||
|
||||
/// A device over `sent`, which opens none of the host's backends: what these tests check is the
|
||||
/// device's, the same whatever the host decodes on.
|
||||
fn device(sent: &Sent) -> VideoDevice<FakePlatform> {
|
||||
let sent = Arc::clone(sent);
|
||||
let send: SendToGuest = Arc::new(move |message| sent.lock().push(message.to_vec()));
|
||||
VideoDevice::without_backend(
|
||||
Arc::new(FakePlatform::new()),
|
||||
VideoDeviceConfig {
|
||||
iosurface_device: None,
|
||||
send_to_guest: Some(send),
|
||||
},
|
||||
NO_BACKEND,
|
||||
)
|
||||
}
|
||||
|
||||
/// The header fields of a message the host sent: its type, flags and reply identifier.
|
||||
fn header_of(message: &[u8]) -> ([u8; 4], u32, u64) {
|
||||
let h = read_header(message, 0).unwrap();
|
||||
(h.message_type.to_be_bytes(), h.flags.0, h.reply_id)
|
||||
}
|
||||
|
||||
/// No session before the start and after a reset: a message answers INVALID_SESSION and nothing
|
||||
/// is sent; between them the host session answers `decs` with its reply, through send_to_guest
|
||||
#[test]
|
||||
fn a_session_runs_from_start_to_reset() {
|
||||
let sent: Sent = Arc::default();
|
||||
let d = device(&sent);
|
||||
let decs = request(b"decs", 41);
|
||||
assert_eq!(d.deliver(&decs), INVALID_SESSION);
|
||||
assert!(sent.lock().is_empty());
|
||||
d.start();
|
||||
assert_eq!(d.deliver(&decs), 0);
|
||||
let replies = std::mem::take(&mut *sent.lock());
|
||||
assert_eq!(replies.len(), 1);
|
||||
assert_eq!(header_of(&replies[0]), (*b"decs", 4, 41));
|
||||
d.reset();
|
||||
assert_eq!(d.deliver(&decs), INVALID_SESSION);
|
||||
d.start();
|
||||
d.start();
|
||||
assert_eq!(d.deliver(&request(b"encs", 42)), 0);
|
||||
let replies = std::mem::take(&mut *sent.lock());
|
||||
assert_eq!(replies.len(), 1);
|
||||
assert_eq!(header_of(&replies[0]), (*b"encs", 4, 42));
|
||||
}
|
||||
|
||||
/// A message longer than MAX_MESSAGE_SIZE is answered ALLOCATION_FAILED, session or none, and
|
||||
/// the session sees nothing of it: no reply, and no hold of the surfaces its `subs` names, so
|
||||
/// no `rels`. One of MAX_MESSAGE_SIZE bytes is the session's
|
||||
#[test]
|
||||
fn a_message_past_the_bound_is_answered_unread() {
|
||||
let sent: Sent = Arc::default();
|
||||
let d = device(&sent);
|
||||
let mut m = subs(&[3]);
|
||||
m.extend_from_slice(&request(b"decs", 9));
|
||||
m.resize(MAX_MESSAGE_SIZE + 1, 0);
|
||||
assert_eq!(d.deliver(&m), ALLOCATION_FAILED);
|
||||
d.start();
|
||||
assert_eq!(d.deliver(&m), ALLOCATION_FAILED);
|
||||
assert!(sent.lock().is_empty());
|
||||
m.truncate(MAX_MESSAGE_SIZE);
|
||||
assert_ne!(d.deliver(&m), ALLOCATION_FAILED);
|
||||
assert!(!sent.lock().is_empty(), "the session's rels, at least");
|
||||
}
|
||||
|
||||
/// After the first phase of a reset the session sends nothing more
|
||||
#[test]
|
||||
fn an_invalidated_session_sends_nothing() {
|
||||
let sent: Sent = Arc::default();
|
||||
let d = device(&sent);
|
||||
d.start();
|
||||
d.invalidate();
|
||||
d.deliver(&request(b"decs", 1));
|
||||
assert!(sent.lock().is_empty());
|
||||
d.reset();
|
||||
}
|
||||
|
||||
/// With no IOSurface device in the process, a named surface is unreachable; the message it came
|
||||
/// with is still answered, with none of its surfaces, and the `rels` after it names the failed
|
||||
/// hold's ID 0, as Apple's host's does (core's `MappedSurfaces::hold`)
|
||||
#[test]
|
||||
fn surfaces_without_a_mapper_are_unreachable() {
|
||||
let sent: Sent = Arc::default();
|
||||
let d = device(&sent);
|
||||
d.start();
|
||||
assert!(matches!(
|
||||
d.surfaces.retain(3),
|
||||
Err(SurfaceError::Unreachable(_))
|
||||
));
|
||||
let mut m = subs(&[3, 4]);
|
||||
m.extend_from_slice(&request(b"decs", 7));
|
||||
assert_eq!(d.deliver(&m), 0);
|
||||
let sent = std::mem::take(&mut *sent.lock());
|
||||
assert_eq!(sent.len(), 2);
|
||||
assert_eq!(header_of(&sent[0]), (*b"decs", 4, 7));
|
||||
let (released, _) = read_surface_release(&sent[1]).unwrap();
|
||||
assert_eq!(released, [MappingId(0)]);
|
||||
}
|
||||
|
||||
/// Without a send_to_guest the session's messages are dropped
|
||||
#[test]
|
||||
fn without_send_to_guest_messages_are_dropped() {
|
||||
let d = VideoDevice::without_backend(
|
||||
Arc::new(FakePlatform::new()),
|
||||
VideoDeviceConfig::default(),
|
||||
NO_BACKEND,
|
||||
);
|
||||
d.start();
|
||||
assert_eq!(d.deliver(&request(b"decs", 1)), 0);
|
||||
}
|
||||
|
||||
/// Four-character codes print as text where they are, as hex where they are not
|
||||
#[test]
|
||||
fn four_character_codes_print() {
|
||||
assert_eq!(format!("{:?}", FourCc(*b"420v")), "'420v'");
|
||||
assert_eq!(format!("{:?}", FourCc([0, 1, 2, 3])), "0x00010203");
|
||||
}
|
||||
|
||||
/// A backend whose decoders decode nothing, decode while copying as `0` says, and tell the
|
||||
/// frames of an AV1 temporal unit of two: one decoded hidden, then one shown.
|
||||
struct DecodesAhead(bool);
|
||||
|
||||
impl DecoderBackend for DecodesAhead {
|
||||
fn capabilities(&self) -> Vec<CodecCapabilities> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn open(&self, _: &DecoderConfig) -> Result<Box<dyn BackendDecoder>, BackendError> {
|
||||
Ok(Box::new(DecodesAheadDecoder(self.0)))
|
||||
}
|
||||
}
|
||||
|
||||
struct DecodesAheadDecoder(bool);
|
||||
|
||||
/// The frames [`DecodesAheadDecoder`] tells it decoded.
|
||||
fn two_frames() -> Vec<FrameDecoded> {
|
||||
let frame = |picture, output| FrameDecoded {
|
||||
picture,
|
||||
shown_again: false,
|
||||
refused: false,
|
||||
width: 64,
|
||||
height: 64,
|
||||
references: [Some(picture); 8],
|
||||
primary_reference: None,
|
||||
output,
|
||||
largest: (64, 64),
|
||||
};
|
||||
vec![frame(1, false), frame(2, true)]
|
||||
}
|
||||
|
||||
impl BackendDecoder for DecodesAheadDecoder {
|
||||
fn output_format(&self) -> PixelFormat {
|
||||
PixelFormat::Nv12VideoRange
|
||||
}
|
||||
|
||||
fn decode(
|
||||
&mut self,
|
||||
_: &CompressedFrame<'_>,
|
||||
) -> Result<Vec<Box<dyn DecodedFrame>>, BackendError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<Vec<Box<dyn DecodedFrame>>, BackendError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn can_accept(&self, _: &DecoderConfig) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn decodes_while_copying(&self) -> bool {
|
||||
self.0
|
||||
}
|
||||
|
||||
fn frames_decoded(&mut self) -> Vec<FrameDecoded> {
|
||||
two_frames()
|
||||
}
|
||||
}
|
||||
|
||||
/// A logged decoder of the stand-in backend that decodes while copying as `ahead` says.
|
||||
fn logged_decoder(ahead: bool) -> Box<dyn BackendDecoder> {
|
||||
let logged = logged::LoggedBackend {
|
||||
inner: Arc::new(DecodesAhead(ahead)),
|
||||
name: "stand-in",
|
||||
platform: Arc::new(FakePlatform::new()),
|
||||
};
|
||||
let config = DecoderConfig {
|
||||
codec: Codec::Av1,
|
||||
width: 64,
|
||||
height: 64,
|
||||
configuration: Vec::new(),
|
||||
};
|
||||
logged.open(&config).unwrap()
|
||||
}
|
||||
|
||||
/// The logged decoder decodes while copying as the backend's own does: the session decodes the
|
||||
/// next frame during a copy back only where the backend says it may.
|
||||
#[test]
|
||||
fn a_logged_decoder_decodes_while_copying_as_the_backends_does() {
|
||||
for ahead in [false, true] {
|
||||
assert_eq!(logged_decoder(ahead).decodes_while_copying(), ahead);
|
||||
}
|
||||
}
|
||||
|
||||
/// The logged decoder tells the frames each decode took as the backend's own does, so that the
|
||||
/// session lends and holds an AV1 unit's buffers as Apple's AV1 decoder does, not one buffer a
|
||||
/// frame output.
|
||||
#[test]
|
||||
fn a_logged_decoder_tells_the_frames_its_backends_decoded() {
|
||||
assert_eq!(logged_decoder(false).frames_decoded(), two_frames());
|
||||
}
|
||||
|
||||
/// A backend whose encoders encode nothing and count their prepares, and whose `+enc` answers
|
||||
/// -12912, as VideoToolbox's does while every hardware encoder session is taken.
|
||||
struct CountsPrepares(Arc<std::sync::atomic::AtomicUsize>);
|
||||
|
||||
/// What [`CountsPrepares`] answers a `+enc`.
|
||||
const ENCODERS_TAKEN: i32 = -12912;
|
||||
|
||||
impl EncoderBackend for CountsPrepares {
|
||||
fn encoders(&self) -> Vec<EncoderCapabilities> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn session_capabilities(&self, _: Codec) -> Result<Option<EncoderCapabilities>, i32> {
|
||||
Err(ENCODERS_TAKEN)
|
||||
}
|
||||
|
||||
fn open(&self, _: &EncoderConfig) -> Result<Box<dyn BackendEncoder>, BackendError> {
|
||||
Ok(Box::new(CountsPreparesEncoder(self.0.clone())))
|
||||
}
|
||||
}
|
||||
|
||||
struct CountsPreparesEncoder(Arc<std::sync::atomic::AtomicUsize>);
|
||||
|
||||
impl BackendEncoder for CountsPreparesEncoder {
|
||||
fn configuration(&self) -> Vec<u8> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
fn encode(&mut self, _: &SourceFrame<'_>) -> Result<Vec<EncodedFrame>, BackendError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> Result<Vec<EncodedFrame>, BackendError> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
fn reconfigure(&mut self, _: &EncoderSettings) -> Result<(), BackendError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare(&mut self) -> Result<(), BackendError> {
|
||||
self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The logged encoder passes the guest's `epfr` on to the backend's, where the VideoToolbox
|
||||
/// backend prepares its session as Apple's host prepares its encoder.
|
||||
#[test]
|
||||
fn a_logged_encoder_prepares_as_the_backends_does() {
|
||||
let prepares = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let logged = logged::LoggedEncoders {
|
||||
inner: Arc::new(CountsPrepares(prepares.clone())),
|
||||
name: "stand-in",
|
||||
platform: Arc::new(FakePlatform::new()),
|
||||
};
|
||||
let config = EncoderConfig {
|
||||
codec: Codec::H264,
|
||||
width: 64,
|
||||
height: 64,
|
||||
settings: EncoderSettings::default(),
|
||||
};
|
||||
let mut encoder = logged.open(&config).unwrap();
|
||||
encoder.prepare().unwrap();
|
||||
assert_eq!(prepares.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
/// The logged encoders answer a `+enc` as the backend's own do: VideoToolbox's -12912 while
|
||||
/// every hardware encoder session is taken, as Apple's host answers it, not the listed entry.
|
||||
#[test]
|
||||
fn logged_encoders_answer_a_session_as_the_backends_do() {
|
||||
let logged = logged::LoggedEncoders {
|
||||
inner: Arc::new(CountsPrepares(Arc::default())),
|
||||
name: "stand-in",
|
||||
platform: Arc::new(FakePlatform::new()),
|
||||
};
|
||||
assert_eq!(
|
||||
logged.session_capabilities(Codec::H264),
|
||||
Err(ENCODERS_TAKEN)
|
||||
);
|
||||
}
|
||||
@@ -1,237 +1,13 @@
|
||||
//! A display's own window ([`DisplayConfig::window`](crate::DisplayConfig::window)): the tee that
|
||||
//! tells the window what the guest does, the link that closes it with the display's last
|
||||
//! reference, the modes and density a display matching its host screen offers, and the sink that
|
||||
//! draws the display's current frame into the window: on macOS, on the product's platform,
|
||||
//! `metal::MetalSink`, into each drawable the window's render thread takes of its layer; on the
|
||||
//! Vulkan platform (`cfg(vulkan_platform)`: Linux's, and macOS's with the `vulkan` feature),
|
||||
//! `vulkan::SwapchainSink`, into the window's swapchain (on macOS one over the window's
|
||||
//! `CAMetalLayer`, whose images are its drawables).
|
||||
//!
|
||||
//! **What the guest sees.** A window display has all five display callbacks, whatever the host
|
||||
//! gives ([`tee`]): the guest reads a cursor glyph size limit of 256 and both cursor handler
|
||||
//! bits. Each callback tells the window first, then calls the host's where the host gave one.
|
||||
//! Without a window, nothing here runs and the display is as the config says.
|
||||
//!
|
||||
//! **The guest's cursor.** At each cursor doorbell the window reads the guest's cursor position
|
||||
//! through its sink ([`SinkDisplay::cursor_position`]), on the thread of the display's callbacks,
|
||||
//! through the display's core, which never ends the process: none while the guest display is
|
||||
//! paused. Where the guest moves its cursor on its own (`reims_vgpu_window`'s `handle`), each
|
||||
//! sink has the display draw it over the frame at that position, in the frame's own render pass,
|
||||
//! with the objects made before the frame's encode (`cursor`).
|
||||
//!
|
||||
//! **Lifetime: a window frame is a frame.** Nothing on the window's side holds the display: the
|
||||
//! tee's closures hold the window, and the sink holds the display weakly. A draw upgrades that
|
||||
//! reference for its encode and commit alone, and the encode's completion handler holds the
|
||||
//! display until the frame completes, as it does for a [`Frame`](crate::Frame). So a release
|
||||
//! that races a window frame ends the display on the window's render thread or on the platform's
|
||||
//! completion thread (Metal's, or the runtime's), as a frame's would. The display's last
|
||||
//! reference drops its [`WindowLink`] before its own reference to the display, which closes the
|
||||
//! window: from then on no window callback of the host's runs, but one already running on the
|
||||
//! window's UI thread (the main thread on macOS, the library's `reims-vgpu.ui` on Linux). It
|
||||
//! waits for nothing: not for the UI thread, the render thread or the GPU.
|
||||
//! A graphics device's window, as the device's last reference ends it ([`WindowLink`]).
|
||||
|
||||
use std::any::{Any, TypeId};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::display::{Display as CoreDisplay, DisplayCore};
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
use reims_vgpu_core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
|
||||
use reims_vgpu_core::raise::OnFault;
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_window::policy::{self, Density, OfferedMode};
|
||||
use reims_vgpu_window::{DrawnCursor, FrameSink, HostScreen, PixelRect, Window};
|
||||
use reims_vgpu_window::Window;
|
||||
|
||||
use crate::display::{CursorGlyph, DisplayCallbacks, no_catch};
|
||||
use crate::entry;
|
||||
use crate::stats::{self, DisplayStats};
|
||||
|
||||
/// The host screen the window of the display on `port` opens on: on the product's platform and
|
||||
/// on the Vulkan platform (`cfg(vulkan_platform)`), the one `reims_vgpu_window::screens` picks from
|
||||
/// the host's screens; on the testkit's, `crate::platform::FAKE_HOST_SCREEN`; on any other,
|
||||
/// none. A display matching its host screen is offered modes without one too ([`host_matched`]).
|
||||
pub(crate) fn host_screen<P: Platform>(port: u64) -> Option<HostScreen> {
|
||||
if on_host_screens::<P>() {
|
||||
return reims_vgpu_window::screens::screen_for_port(port);
|
||||
}
|
||||
#[cfg(any(test, feature = "testkit"))]
|
||||
if TypeId::of::<P>() == TypeId::of::<reims_vgpu_core::testkit::FakePlatform>() {
|
||||
return Some(crate::platform::FAKE_HOST_SCREEN);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Whether a window display on `P` opens on the host's own screens ([`host_screen`]): on the
|
||||
/// product's platform and on the Vulkan platform (`cfg(vulkan_platform)`).
|
||||
fn on_host_screens<P: Platform>() -> bool {
|
||||
let platform = TypeId::of::<P>();
|
||||
#[cfg(vulkan_platform)]
|
||||
if platform == TypeId::of::<reims_vgpu_vulkan::VulkanPlatform>() {
|
||||
return true;
|
||||
}
|
||||
platform == TypeId::of::<crate::DefaultPlatform>()
|
||||
}
|
||||
|
||||
/// What draws a window display's current frame into its window, over `display`, held weakly, in
|
||||
/// command buffers of `frame_queue`, the process's frame queue for the display's device (a Metal
|
||||
/// device, or the runtime's on Vulkan): on macOS, on the product's platform, a
|
||||
/// `metal::MetalSink`, and on the Vulkan platform (`cfg(vulkan_platform)`) the sink of `vulkan`,
|
||||
/// which draws each frame into the window's swapchain, on either OS. `None` on any other platform
|
||||
/// (the testkit's among them), or without a frame queue: nothing draws, and the window never
|
||||
/// opens.
|
||||
pub(crate) fn window_sink<P: Platform>(
|
||||
platform: &Arc<P>,
|
||||
display: Weak<CoreDisplay<P>>,
|
||||
frame_queue: Option<P::CommandQueue>,
|
||||
) -> Option<Arc<dyn FrameSink>> {
|
||||
let display: Box<dyn Any> = Box::new(display);
|
||||
let frame_queue: Box<dyn Any> = Box::new(frame_queue);
|
||||
#[cfg(target_os = "macos")]
|
||||
let (display, frame_queue) = match metal::sink(display, frame_queue) {
|
||||
Ok(sink) => return sink,
|
||||
Err(unmatched) => unmatched,
|
||||
};
|
||||
#[cfg(vulkan_platform)]
|
||||
let display = match display.downcast::<Weak<CoreDisplay<reims_vgpu_vulkan::VulkanPlatform>>>() {
|
||||
Ok(display) => {
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
let platform: Arc<dyn Any + Send + Sync> = Arc::clone(platform) as _;
|
||||
let platform = platform.downcast::<VulkanPlatform>().ok()?;
|
||||
let frame_queue = frame_queue
|
||||
.downcast::<Option<<VulkanPlatform as Platform>::CommandQueue>>()
|
||||
.ok()?;
|
||||
return vulkan::sink(platform, *display, (*frame_queue)?);
|
||||
}
|
||||
Err(display) => display,
|
||||
};
|
||||
let _ = (platform, display, frame_queue);
|
||||
None
|
||||
}
|
||||
|
||||
/// What a display matching its host screen offers the guest for `screen`: with a chosen `mode`,
|
||||
/// that mode first and the standard sizes within it, at `ppi` (`WindowConfig::mode_ppi`) or else
|
||||
/// a 1× density; without one, the policy's modes for the screen, the first the preferred, at the
|
||||
/// screen's density. The density is that of the first mode. `None` when the policy offers no
|
||||
/// mode: the display then offers what its config says. The modes run at `refresh_hz`
|
||||
/// (`REIMS_VGPU_WINDOW_REFRESH`) where given, else at the screen's rate (its current mode's).
|
||||
///
|
||||
/// With no `screen`, the chosen mode as with one, or else `policy::UNMATCHED_MODE` at 1×, at
|
||||
/// `refresh_hz` or else 60 Hz: offering none would leave the guest no mode to set (`policy`).
|
||||
pub(crate) fn host_matched(
|
||||
screen: Option<&HostScreen>,
|
||||
mode: Option<(u16, u16)>,
|
||||
ppi: Option<f64>,
|
||||
refresh_hz: Option<f64>,
|
||||
) -> Option<(Vec<OfferedMode>, Density)> {
|
||||
let modes = match (mode, screen) {
|
||||
(Some(mode), _) => policy::modes_up_to(mode, screen, refresh_hz),
|
||||
(None, Some(screen)) => policy::offered_modes(screen, refresh_hz),
|
||||
(None, None) => policy::modes_up_to(policy::UNMATCHED_MODE, None, refresh_hz),
|
||||
};
|
||||
let first = modes.first()?;
|
||||
let first = (first.width, first.height);
|
||||
let density = match (mode, screen) {
|
||||
(Some(_), _) => policy::density_chosen(first, ppi),
|
||||
(None, Some(screen)) => policy::density(screen, first),
|
||||
(None, None) => policy::density_1x(first),
|
||||
};
|
||||
Some((modes, density))
|
||||
}
|
||||
|
||||
/// What a display's callbacks tell its window: [`Window`]'s calls, behind a trait so the tee is
|
||||
/// tested over a recorder.
|
||||
pub(crate) trait GuestEvents: Send + Sync + 'static {
|
||||
/// The guest set a mode.
|
||||
fn guest_mode(&self, width: u16, height: u16);
|
||||
/// The guest presented a frame.
|
||||
fn new_frame(&self);
|
||||
/// The guest set a cursor glyph.
|
||||
fn cursor_glyph(&self, glyph: &CursorGlyph<'_>);
|
||||
/// The guest showed (`true`) or hid its cursor.
|
||||
fn cursor_show(&self, show: bool);
|
||||
/// The guest moved its cursor, or rang the doorbell that reports its moves.
|
||||
fn cursor_moved(&self);
|
||||
}
|
||||
|
||||
impl GuestEvents for Window {
|
||||
fn guest_mode(&self, width: u16, height: u16) {
|
||||
Window::guest_mode(self, width, height);
|
||||
}
|
||||
|
||||
fn new_frame(&self) {
|
||||
Window::new_frame(self);
|
||||
}
|
||||
|
||||
fn cursor_glyph(&self, glyph: &CursorGlyph<'_>) {
|
||||
Window::cursor_glyph(self, glyph.width, glyph.height, glyph.hot_spot, glyph.rgba);
|
||||
}
|
||||
|
||||
fn cursor_show(&self, show: bool) {
|
||||
Window::cursor_show(self, show);
|
||||
}
|
||||
|
||||
fn cursor_moved(&self) {
|
||||
Window::cursor_moved(self);
|
||||
}
|
||||
}
|
||||
|
||||
/// A window display's callbacks: each tells `window`, then calls the host's in `host` where it
|
||||
/// gave one. All five are present, which the guest reads (module doc). The closures hold the
|
||||
/// window and the host's closures, never the display.
|
||||
pub(crate) fn tee<W: GuestEvents>(window: &Arc<W>, host: DisplayCallbacks) -> DisplayCallbacks {
|
||||
let DisplayCallbacks {
|
||||
mode_change,
|
||||
new_frame,
|
||||
cursor_glyph,
|
||||
cursor_show,
|
||||
cursor_move,
|
||||
} = host;
|
||||
let w = window.clone();
|
||||
let mode_change: crate::ModeChangeFn = Arc::new(move |width, height, format| {
|
||||
w.guest_mode(width, height);
|
||||
if let Some(f) = &mode_change {
|
||||
f(width, height, format);
|
||||
}
|
||||
});
|
||||
let w = window.clone();
|
||||
let new_frame: crate::NewFrameFn = Arc::new(move || {
|
||||
w.new_frame();
|
||||
if let Some(f) = &new_frame {
|
||||
f();
|
||||
}
|
||||
});
|
||||
let w = window.clone();
|
||||
let cursor_glyph: crate::CursorGlyphFn = Arc::new(move |glyph: &CursorGlyph<'_>| {
|
||||
w.cursor_glyph(glyph);
|
||||
if let Some(f) = &cursor_glyph {
|
||||
f(glyph);
|
||||
}
|
||||
});
|
||||
let w = window.clone();
|
||||
let cursor_show: crate::CursorShowFn = Arc::new(move |show| {
|
||||
w.cursor_show(show != 0);
|
||||
if let Some(f) = &cursor_show {
|
||||
f(show);
|
||||
}
|
||||
});
|
||||
let w = window.clone();
|
||||
let cursor_move: crate::CursorMoveFn = Arc::new(move || {
|
||||
w.cursor_moved();
|
||||
if let Some(f) = &cursor_move {
|
||||
f();
|
||||
}
|
||||
});
|
||||
DisplayCallbacks {
|
||||
mode_change: Some(mode_change),
|
||||
new_frame: Some(new_frame),
|
||||
cursor_glyph: Some(cursor_glyph),
|
||||
cursor_show: Some(cursor_show),
|
||||
cursor_move: Some(cursor_move),
|
||||
}
|
||||
}
|
||||
|
||||
/// A display's window, as every reference to the display shares it: its drop, at the display's
|
||||
/// last reference, is the window's end ([`Window::close`]).
|
||||
/// A device's window, as every reference to the device shares it: its drop, at the device's last
|
||||
/// reference, is the window's end ([`Window::close`]).
|
||||
pub(crate) struct WindowLink {
|
||||
window: Arc<Window>,
|
||||
}
|
||||
@@ -241,11 +17,6 @@ impl WindowLink {
|
||||
pub(crate) fn new(window: Arc<Window>) -> WindowLink {
|
||||
WindowLink { window }
|
||||
}
|
||||
|
||||
/// The window.
|
||||
pub(crate) fn window(&self) -> &Arc<Window> {
|
||||
&self.window
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WindowLink {
|
||||
@@ -255,156 +26,3 @@ impl Drop for WindowLink {
|
||||
entry::run(|_| self.window.close());
|
||||
}
|
||||
}
|
||||
|
||||
/// What a window sink draws from: the display, held weakly, and the process's frame queue for its
|
||||
/// device, whose command buffers the sink's frames are encoded in. Neither keeps the display
|
||||
/// alive (module doc). Every sink draws through it, each frame a [`WindowFrame`], with the
|
||||
/// guest's cursor over it where the window draws it ([`cursor::CursorPass`]), and each frame it
|
||||
/// commits counts as a window frame in the display's statistics, where they are on
|
||||
/// ([`crate::stats`]).
|
||||
pub(crate) struct SinkDisplay<P: Platform> {
|
||||
/// The display, held only for a draw.
|
||||
display: Weak<CoreDisplay<P>>,
|
||||
/// Its core, which the guest's cursor position is read through.
|
||||
core: Weak<DisplayCore<P>>,
|
||||
/// The frame queue.
|
||||
queue: P::CommandQueue,
|
||||
/// The display's statistics, where they are on.
|
||||
stats: Option<Arc<DisplayStats>>,
|
||||
/// What draws the guest's cursor over a frame; only the window's render thread draws.
|
||||
cursor: Mutex<cursor::CursorPass<P>>,
|
||||
}
|
||||
|
||||
/// One window frame, as a sink draws it: the steps in which the sinks differ, which
|
||||
/// [`SinkDisplay::encode`] runs in order. The frame is dropped after the commit, or where the
|
||||
/// draw ends without one.
|
||||
pub(crate) trait WindowFrame<P: Platform> {
|
||||
/// The texture the frame is encoded into, asked once the command buffer is made; `None`
|
||||
/// draws nothing, and the command buffer goes uncommitted.
|
||||
fn texture(&mut self) -> Option<&P::Texture>;
|
||||
|
||||
/// The frame is encoded in `command_buffer`, which is committed next.
|
||||
fn encoded(&mut self, command_buffer: &P::CommandBuffer);
|
||||
}
|
||||
|
||||
impl<P: Platform> SinkDisplay<P> {
|
||||
/// `display`, drawn in command buffers of `queue`, the frame queue of its device, the
|
||||
/// guest's cursor glyph in textures `own_texture` makes ([`cursor::OwnTexture`]). Its maker
|
||||
/// holds the display, just made, so the upgrade that reaches its core is never its last
|
||||
/// release.
|
||||
pub(crate) fn new(
|
||||
display: Weak<CoreDisplay<P>>,
|
||||
queue: P::CommandQueue,
|
||||
own_texture: cursor::OwnTexture<P>,
|
||||
) -> SinkDisplay<P> {
|
||||
let core = display
|
||||
.upgrade()
|
||||
.map_or_else(Weak::new, |d| Arc::downgrade(d.core()));
|
||||
SinkDisplay {
|
||||
stats: stats::of_display(&display),
|
||||
display,
|
||||
core,
|
||||
queue,
|
||||
cursor: Mutex::new(cursor::CursorPass::new(own_texture)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor position, in its mode's pixels, as the display reads it now
|
||||
/// ([`DisplayCore::guest_cursor_position`]): what the sinks answer
|
||||
/// [`FrameSink::guest_cursor_position`] with. Asked on the thread of the display's callbacks,
|
||||
/// where the block that runs one holds the core, so the core's upgrade here is never its last
|
||||
/// release, and never the display's end, which its own reference runs. `None` once the core
|
||||
/// has gone.
|
||||
pub(crate) fn cursor_position(&self) -> Option<(u16, u16)> {
|
||||
let at = self.core.upgrade()?.guest_cursor_position()?;
|
||||
Some((at.x, at.y))
|
||||
}
|
||||
|
||||
/// The display's statistics, where they are on: a sink that measures its frames' GPU time
|
||||
/// reports it there.
|
||||
#[cfg_attr(
|
||||
not(vulkan_platform),
|
||||
expect(
|
||||
dead_code,
|
||||
reason = "only the Vulkan platform's sink measures its frames' GPU time"
|
||||
)
|
||||
)]
|
||||
pub(crate) fn stats(&self) -> Option<&Arc<DisplayStats>> {
|
||||
self.stats.as_ref()
|
||||
}
|
||||
|
||||
/// Draws `frame`: the display's current frame over `region` into its texture, with `cursor`
|
||||
/// over it, in a new command buffer of the frame queue, which is committed after `frame` has
|
||||
/// seen it. In order: the display's upgrade, the command buffer, [`WindowFrame::texture`], the
|
||||
/// cursor's objects ([`cursor::CursorPass::prepare`]), the encode, with the cursor drawn in
|
||||
/// the display's pass ([`cursor::Prepared::draw`]), [`WindowFrame::encoded`] and the commit:
|
||||
/// `true` once committed. `false`, with nothing
|
||||
/// committed, when the display has ended, when the frame queue gives no command buffer, when
|
||||
/// the frame has no texture, or when the display refuses the encode (a texture on another
|
||||
/// device, or one it cannot render into). A command buffer not committed goes with nothing
|
||||
/// encoded in it. Waits for nothing.
|
||||
///
|
||||
/// The display is held from its upgrade to the commit, and the encode's completion handler
|
||||
/// holds it on until the frame completes. So when the host has released the display in the
|
||||
/// meantime, this draw's release, inside this entry, may be the display's end.
|
||||
pub(crate) fn encode(
|
||||
&self,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
frame: impl WindowFrame<P>,
|
||||
) -> bool {
|
||||
entry::run(|_| {
|
||||
let Some(display) = self.display.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
let committed = self.commit_frame(&display, region, cursor, frame);
|
||||
drop(display);
|
||||
committed
|
||||
})
|
||||
}
|
||||
|
||||
/// [`SinkDisplay::encode`]'s work, with the display held.
|
||||
fn commit_frame(
|
||||
&self,
|
||||
display: &CoreDisplay<P>,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
mut frame: impl WindowFrame<P>,
|
||||
) -> bool {
|
||||
let Some(command_buffer) = no_catch(self.queue.command_buffer(OnFault::Die)) else {
|
||||
return false;
|
||||
};
|
||||
let Some(texture) = frame.texture() else {
|
||||
return false;
|
||||
};
|
||||
let cursor = cursor.and_then(|c| self.cursor.lock().prepare(display, texture, region, c));
|
||||
let frame_region = MtlRegion::new(
|
||||
MtlOrigin::new(region.x, region.y, 0),
|
||||
MtlSize::new(region.width, region.height, 1),
|
||||
);
|
||||
let overlay = cursor.as_ref().map(cursor::Prepared::draw);
|
||||
let encoded = display.encode_current_frame_with(
|
||||
&command_buffer,
|
||||
texture,
|
||||
frame_region,
|
||||
overlay.as_ref(),
|
||||
);
|
||||
if !no_catch(encoded) {
|
||||
return false;
|
||||
}
|
||||
frame.encoded(&command_buffer);
|
||||
no_catch(command_buffer.commit(OnFault::Die));
|
||||
if let Some(stats) = &self.stats {
|
||||
stats.window_present();
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
mod cursor;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod metal;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(vulkan_platform)]
|
||||
mod vulkan;
|
||||
@@ -1,403 +0,0 @@
|
||||
//! The guest's cursor drawn into a window frame where the window draws it itself, the guest moving
|
||||
//! it on its own ([`DrawnCursor`], `reims_vgpu_window::handle`'s module doc): the glyph over the
|
||||
//! frame the display drew, by its alpha, at the guest's cursor position the window last read.
|
||||
//!
|
||||
//! The glyph is a second draw in the display's own render pass, after the frame's
|
||||
//! ([`DisplayCore::encode_current_frame_with`]), so the frame's target is stored once, with no
|
||||
//! pass that loads it again: the display's strip, a quad over the whole viewport, drawn over a
|
||||
//! viewport that is the glyph's rectangle in the target, its hot spot at the cursor's position, a
|
||||
//! glyph pixel to a guest pixel at the image's scale, with a scissor that clips it to the image.
|
||||
//! It draws with the display's overlay pipeline for the target's format
|
||||
//! ([`DisplayCore::overlay_pipeline`]): the display's vertex function and
|
||||
//! `displayPresentFragment`, which samples the glyph as the frame is sampled, filtered where the
|
||||
//! image scales it, blending over by alpha (`RenderPipelineDesc::blend_over`). The guest's alpha
|
||||
//! is straight, and the texture holds the glyph premultiplied, so that the filter, where the
|
||||
//! image scales the glyph, does not darken its edges with the colour of its transparent pixels:
|
||||
//! at one texel a pixel, each pixel is the glyph's colour over the frame's by its alpha, as with
|
||||
//! straight alpha. The glyph's colours are drawn as the guest gives them, with no gamma table or
|
||||
//! colour matrix, as the host's cursor shows them over the image.
|
||||
//!
|
||||
//! **What the guest reads.** The draw makes no buffer: it binds the display's. The pipeline is
|
||||
//! the display's, kept in its cache with its own and made of its functions, so it lives as they
|
||||
//! do. The glyph's texture is the sink's platform's own ([`OwnTexture`]): on the Vulkan platform
|
||||
//! one that takes no resource ID and no range of Metal's space, so that no address or ID the
|
||||
//! guest reads moves for it; on Metal a plain texture, a resource of Metal's like the layer's
|
||||
//! drawables the window already draws into. The texture is made again only for a new glyph.
|
||||
//!
|
||||
//! **Before the frame.** The pipeline and the texture are made before the display encodes the
|
||||
//! frame ([`CursorPass::prepare`]), from which the frame counts as in flight, which a guest's
|
||||
//! present waits on. What the platform refuses of them leaves the frame without the guest's
|
||||
//! cursor, logged once; the host's cursor stays hidden over the image while the guest leads, so
|
||||
//! neither shows. An encode the platform refuses dies at its send, as the display's own does; the
|
||||
//! draw's values are ones the platforms take: a scissor inside the target, and a viewport inside
|
||||
//! the least bounds Vulkan sets every device (the runtime hands a viewport to Vulkan as it is),
|
||||
//! [`VIEWPORT_BOUNDS`] and [`VIEWPORT_DIMENSION`]; a glyph that would reach past them is not drawn
|
||||
//! (only near the far edge of a window over 8000 pixels across). Nothing here reaches the guest
|
||||
//! or the C API: the cursor is in the window's pixels alone.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::display::DisplayCore;
|
||||
use reims_vgpu_core::display::pipeline::OverlayDraw;
|
||||
use reims_vgpu_core::platform::resource::Texture as _;
|
||||
use reims_vgpu_core::platform::types::{
|
||||
MtlOrigin, MtlRegion, MtlScissorRect, MtlSize, MtlViewport,
|
||||
};
|
||||
use reims_vgpu_core::platform::values::TextureDesc;
|
||||
use reims_vgpu_core::platform::{Handle as _, HostRange, Platform};
|
||||
use reims_vgpu_window::{DrawnCursor, Glyph, PixelRect};
|
||||
|
||||
use crate::display::no_catch;
|
||||
|
||||
/// The least `viewportBoundsRange` Vulkan sets every device: a viewport's edges lie inside it.
|
||||
const VIEWPORT_BOUNDS: (f64, f64) = (-8192.0, 8191.0);
|
||||
/// The least `maxViewportDimensions` Vulkan sets every device: a viewport's width and height.
|
||||
const VIEWPORT_DIMENSION: f64 = 4096.0;
|
||||
|
||||
/// How a sink's platform makes the glyph's texture from its descriptor: a texture the guest never
|
||||
/// reaches (the module doc), or `None` where the platform makes none.
|
||||
pub(crate) type OwnTexture<P> = fn(
|
||||
&<P as Platform>::Device,
|
||||
&<P as Platform>::TextureDescriptor,
|
||||
) -> Option<<P as Platform>::Texture>;
|
||||
|
||||
/// What draws the guest's cursor over a window's frames, kept from one frame to the next.
|
||||
pub(crate) struct CursorPass<P: Platform> {
|
||||
/// How the glyph's texture is made.
|
||||
own_texture: OwnTexture<P>,
|
||||
/// The glyph last drawn, and its texture.
|
||||
glyph: Option<(Arc<Glyph>, P::Texture)>,
|
||||
/// A refusal of the platform's has been logged.
|
||||
refusal_logged: bool,
|
||||
}
|
||||
|
||||
/// One frame's cursor, made ready before the display encodes the frame
|
||||
/// ([`CursorPass::prepare`]), which draws it ([`Prepared::draw`]).
|
||||
pub(crate) struct Prepared<P: Platform> {
|
||||
/// The display's overlay pipeline for the target's format.
|
||||
pipeline: P::RenderPipeline,
|
||||
/// The glyph's texture.
|
||||
texture: P::Texture,
|
||||
/// The glyph's rectangle in the target, and its clip to the image ([`placement`]).
|
||||
viewport: MtlViewport,
|
||||
/// The scissor.
|
||||
scissor: MtlScissorRect,
|
||||
}
|
||||
|
||||
impl<P: Platform> CursorPass<P> {
|
||||
/// A pass that has made nothing yet, whose glyph textures `own_texture` makes.
|
||||
pub(crate) fn new(own_texture: OwnTexture<P>) -> CursorPass<P> {
|
||||
CursorPass {
|
||||
own_texture,
|
||||
glyph: None,
|
||||
refusal_logged: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What drawing `cursor` over the frame `display` draws into `target` over `region` binds:
|
||||
/// the display's overlay pipeline for the target's format, made the first time
|
||||
/// ([`DisplayCore::overlay_pipeline`]), the glyph's texture, made again only for a new
|
||||
/// glyph, and where it draws ([`placement`]). Asked before the frame is encoded (the module
|
||||
/// doc). `None` where nothing would show, and where the platform refuses the pipeline or the
|
||||
/// texture (logged once).
|
||||
pub(crate) fn prepare(
|
||||
&mut self,
|
||||
display: &DisplayCore<P>,
|
||||
target: &P::Texture,
|
||||
region: PixelRect,
|
||||
cursor: &DrawnCursor,
|
||||
) -> Option<Prepared<P>> {
|
||||
let (viewport, scissor) = placement(region, (target.width(), target.height()), cursor)?;
|
||||
let Some(pipeline) = display.overlay_pipeline(target.pixel_format()) else {
|
||||
return self.refused("the pipeline");
|
||||
};
|
||||
let texture = match &self.glyph {
|
||||
Some((drawn, texture)) if Arc::ptr_eq(drawn, &cursor.glyph) => texture.clone_ref(),
|
||||
_ => {
|
||||
let made = display.mtl_device().and_then(|device| {
|
||||
glyph_texture(display.platform(), device, self.own_texture, &cursor.glyph)
|
||||
});
|
||||
let Some(texture) = made else {
|
||||
return self.refused("a texture for the glyph");
|
||||
};
|
||||
self.glyph = Some((Arc::clone(&cursor.glyph), texture.clone_ref()));
|
||||
texture
|
||||
}
|
||||
};
|
||||
Some(Prepared {
|
||||
pipeline,
|
||||
texture,
|
||||
viewport,
|
||||
scissor,
|
||||
})
|
||||
}
|
||||
|
||||
/// Logs, the first time, that the platform refused `what`: the cursor is not drawn.
|
||||
fn refused<T>(&mut self, what: &str) -> Option<T> {
|
||||
if !std::mem::replace(&mut self.refusal_logged, true) {
|
||||
log::warn!(
|
||||
target: "reims_vgpu::window",
|
||||
"the window draws no guest cursor: the platform refused {what}"
|
||||
);
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Platform> Prepared<P> {
|
||||
/// The draw the display makes of the cursor in its pass, after the frame's (the module doc).
|
||||
pub(crate) fn draw(&self) -> OverlayDraw<'_, P> {
|
||||
OverlayDraw {
|
||||
pipeline: &self.pipeline,
|
||||
texture: &self.texture,
|
||||
viewport: self.viewport,
|
||||
scissor: self.scissor,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `cursor` draws over `region` of a target of `size` pixels: the viewport, the glyph's
|
||||
/// rectangle in the target, its hot spot at the cursor's position in the mode's pixels, a glyph
|
||||
/// pixel to a guest pixel at the image's scale; and the scissor, the target's pixels that
|
||||
/// rectangle touches inside the image and the target. The viewport may reach past the target,
|
||||
/// which only the scissor clips. `None` where nothing would show: an empty mode, glyph or
|
||||
/// region, or a glyph wholly off the image; and where the viewport would reach past
|
||||
/// [`VIEWPORT_BOUNDS`] or be larger than [`VIEWPORT_DIMENSION`] (the module doc).
|
||||
fn placement(
|
||||
region: PixelRect,
|
||||
size: (u64, u64),
|
||||
cursor: &DrawnCursor,
|
||||
) -> Option<(MtlViewport, MtlScissorRect)> {
|
||||
let (mode, glyph) = (cursor.mode, &cursor.glyph);
|
||||
if mode.0 == 0 || mode.1 == 0 || glyph.width == 0 || glyph.height == 0 {
|
||||
return None;
|
||||
}
|
||||
#[expect(clippy::as_conversions, reason = "u64 to f64 rounds to nearest")]
|
||||
let [x, y, width, height, target_width, target_height] = [
|
||||
region.x,
|
||||
region.y,
|
||||
region.width,
|
||||
region.height,
|
||||
size.0,
|
||||
size.1,
|
||||
]
|
||||
.map(|v| v as f64);
|
||||
let (per_x, per_y) = (width / f64::from(mode.0), height / f64::from(mode.1));
|
||||
let left = x + (f64::from(cursor.at.0) - f64::from(glyph.hot_spot.0)) * per_x;
|
||||
let top = y + (f64::from(cursor.at.1) - f64::from(glyph.hot_spot.1)) * per_y;
|
||||
let (glyph_width, glyph_height) = (
|
||||
f64::from(glyph.width) * per_x,
|
||||
f64::from(glyph.height) * per_y,
|
||||
);
|
||||
let (x0, y0) = (left.floor().max(x), top.floor().max(y));
|
||||
let x1 = (left + glyph_width).ceil().min(x + width).min(target_width);
|
||||
let y1 = (top + glyph_height)
|
||||
.ceil()
|
||||
.min(y + height)
|
||||
.min(target_height);
|
||||
if x1 <= x0 || y1 <= y0 {
|
||||
return None;
|
||||
}
|
||||
let (low, high) = VIEWPORT_BOUNDS;
|
||||
let within = |start: f64, length: f64| {
|
||||
start >= low && start + length <= high && length <= VIEWPORT_DIMENSION
|
||||
};
|
||||
if !(within(left, glyph_width) && within(top, glyph_height)) {
|
||||
return None;
|
||||
}
|
||||
#[expect(
|
||||
clippy::as_conversions,
|
||||
clippy::cast_possible_truncation,
|
||||
clippy::cast_sign_loss,
|
||||
reason = "whole pixels inside the target, which u64 holds"
|
||||
)]
|
||||
let [sx, sy, sw, sh] = [x0, y0, x1 - x0, y1 - y0].map(|v| v as u64);
|
||||
let viewport = MtlViewport {
|
||||
origin_x: left,
|
||||
origin_y: top,
|
||||
width: glyph_width,
|
||||
height: glyph_height,
|
||||
znear: 0.0,
|
||||
zfar: 1.0,
|
||||
};
|
||||
let scissor = MtlScissorRect {
|
||||
x: sx,
|
||||
y: sy,
|
||||
width: sw,
|
||||
height: sh,
|
||||
};
|
||||
Some((viewport, scissor))
|
||||
}
|
||||
|
||||
/// `glyph`'s pixels in a texture `own_texture` makes, RGBA8, premultiplied (module doc), read by
|
||||
/// shaders, a row its bytes do not reach transparent; `None` for a glyph with no pixels, or
|
||||
/// where the platform makes no texture.
|
||||
fn glyph_texture<P: Platform>(
|
||||
platform: &Arc<P>,
|
||||
device: &P::Device,
|
||||
own_texture: OwnTexture<P>,
|
||||
glyph: &Glyph,
|
||||
) -> Option<P::Texture> {
|
||||
let (width, height) = (u64::from(glyph.width), u64::from(glyph.height));
|
||||
let row = width.checked_mul(4)?;
|
||||
let length = usize::try_from(row.checked_mul(height)?).ok()?;
|
||||
if length == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = glyph.rgba.get(..length).unwrap_or(&glyph.rgba).to_vec();
|
||||
bytes.resize(length, 0);
|
||||
premultiply(&mut bytes);
|
||||
let descriptor = platform.texture_descriptor(&TextureDesc {
|
||||
width,
|
||||
height,
|
||||
..TextureDesc::default()
|
||||
});
|
||||
let texture = own_texture(device, &descriptor)?;
|
||||
no_catch(texture.replace_region(
|
||||
MtlRegion::new(MtlOrigin::new(0, 0, 0), MtlSize::new(width, height, 1)),
|
||||
0,
|
||||
0,
|
||||
HostRange::of_slice(&bytes),
|
||||
row,
|
||||
row * height,
|
||||
));
|
||||
Some(texture)
|
||||
}
|
||||
|
||||
/// Premultiplies RGBA `pixels` by their alpha, each channel rounded to nearest.
|
||||
fn premultiply(pixels: &mut [u8]) {
|
||||
for [red, green, blue, alpha] in pixels.as_chunks_mut::<4>().0 {
|
||||
let alpha = u16::from(*alpha);
|
||||
for channel in [red, green, blue] {
|
||||
let scaled = (u16::from(*channel) * alpha + 127) / 255;
|
||||
*channel = u8::try_from(scaled).unwrap_or(u8::MAX);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// A cursor of a `width` by `height` glyph with its hot spot at `hot_spot`, at `at` in `mode`.
|
||||
fn cursor(
|
||||
(width, height): (u32, u32),
|
||||
hot_spot: (u16, u16),
|
||||
mode: (u16, u16),
|
||||
at: (u16, u16),
|
||||
) -> DrawnCursor {
|
||||
DrawnCursor {
|
||||
glyph: Arc::new(Glyph {
|
||||
width,
|
||||
height,
|
||||
hot_spot,
|
||||
rgba: vec![0xff; usize::try_from(width * height * 4).unwrap()],
|
||||
}),
|
||||
mode,
|
||||
at,
|
||||
}
|
||||
}
|
||||
|
||||
/// A region of the target.
|
||||
fn rect(x: u64, y: u64, width: u64, height: u64) -> PixelRect {
|
||||
PixelRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/// The viewport puts the glyph's hot spot at the guest's cursor position, a glyph pixel to a
|
||||
/// guest pixel at the image's scale, in a letterboxed image too, and the scissor is the
|
||||
/// glyph's rectangle where it lies inside the image
|
||||
#[test]
|
||||
fn the_viewport_puts_the_hot_spot_at_the_cursor() {
|
||||
let c = cursor((10, 5), (10, 0), (100, 50), (60, 20));
|
||||
let (v, s) = placement(rect(0, 0, 100, 50), (100, 50), &c).unwrap();
|
||||
assert_eq!(
|
||||
(v.origin_x, v.origin_y, v.width, v.height),
|
||||
(50.0, 20.0, 10.0, 5.0)
|
||||
);
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (50, 20, 10, 5));
|
||||
// Twice the size, 30 pixels from the left and 10 from the top.
|
||||
let (v, s) = placement(rect(30, 10, 200, 100), (260, 120), &c).unwrap();
|
||||
assert_eq!(
|
||||
(v.origin_x, v.origin_y, v.width, v.height),
|
||||
(130.0, 50.0, 20.0, 10.0)
|
||||
);
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (130, 50, 20, 10));
|
||||
// At a scale of 1.5 the rectangle's edges fall inside pixels, which the scissor takes.
|
||||
let (v, s) = placement(rect(0, 0, 150, 75), (150, 75), &c).unwrap();
|
||||
assert_eq!((v.origin_x, v.width), (75.0, 15.0));
|
||||
assert_eq!((v.origin_y, v.height), (30.0, 7.5));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (75, 30, 15, 8));
|
||||
}
|
||||
|
||||
/// A glyph partly off the image keeps its whole viewport, past the target where it reaches
|
||||
/// there, and the scissor clips it to the image; one wholly off it, an empty glyph and an
|
||||
/// empty mode draw nothing
|
||||
#[test]
|
||||
fn the_scissor_clips_the_glyph_to_the_image() {
|
||||
let region = rect(20, 10, 100, 100);
|
||||
let size = (140, 120);
|
||||
let g = (16, 16);
|
||||
let (v, s) = placement(region, size, &cursor(g, (4, 4), (100, 100), (0, 0))).unwrap();
|
||||
assert_eq!((v.origin_x, v.origin_y, v.width), (16.0, 6.0, 16.0));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (20, 10, 12, 12));
|
||||
let (v, s) = placement(region, size, &cursor(g, (0, 0), (100, 100), (95, 95))).unwrap();
|
||||
assert_eq!((v.origin_x, v.origin_y), (115.0, 105.0));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (115, 105, 5, 5));
|
||||
let at_edge = cursor(g, (8, 8), (100, 100), (0, 0));
|
||||
let (v, s) = placement(rect(0, 0, 100, 100), (100, 100), &at_edge).unwrap();
|
||||
assert_eq!((v.origin_x, v.origin_y), (-8.0, -8.0));
|
||||
assert_eq!((s.x, s.y, s.width, s.height), (0, 0, 8, 8));
|
||||
let none = |c: &DrawnCursor| placement(region, size, c).is_none();
|
||||
assert!(none(&cursor(g, (0, 0), (100, 100), (100, 50))));
|
||||
assert!(none(&cursor(g, (0, 0), (100, 100), (50, 100))));
|
||||
assert!(none(&cursor(g, (0, 0), (100, 100), (u16::MAX, u16::MAX))));
|
||||
assert!(none(&cursor(g, (20, 20), (100, 100), (0, 0))));
|
||||
assert!(none(&cursor((0, 16), (0, 0), (100, 100), (50, 50))));
|
||||
assert!(none(&cursor(g, (0, 0), (0, 100), (50, 50))));
|
||||
assert!(
|
||||
placement(
|
||||
rect(20, 10, 0, 100),
|
||||
size,
|
||||
&cursor(g, (0, 0), (100, 100), (5, 5))
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
/// A glyph whose viewport would reach past Vulkan's least viewport bounds, or be larger than
|
||||
/// its least viewport size, is not drawn, though it shows in the image
|
||||
#[test]
|
||||
fn a_viewport_past_vulkan_s_least_bounds_draws_nothing() {
|
||||
let wide = rect(0, 0, 8192, 100);
|
||||
let size = (8192, 100);
|
||||
let g = (16, 16);
|
||||
assert!(placement(wide, size, &cursor(g, (0, 0), (8192, 100), (8170, 10))).is_some());
|
||||
assert!(placement(wide, size, &cursor(g, (0, 0), (8192, 100), (8180, 10))).is_none());
|
||||
// A glyph of 256 pixels at 17 pixels to a guest pixel is 4352 wide.
|
||||
let scaled = rect(0, 0, 1700, 1700);
|
||||
let big = cursor((256, 1), (0, 0), (100, 100), (0, 0));
|
||||
assert!(placement(scaled, (1700, 1700), &big).is_none());
|
||||
let fits = cursor((240, 1), (0, 0), (100, 100), (0, 0));
|
||||
assert!(placement(scaled, (1700, 1700), &fits).is_some());
|
||||
}
|
||||
|
||||
/// Premultiplying scales each colour channel by the alpha, to nearest, and keeps the alpha
|
||||
#[test]
|
||||
fn premultiplying_scales_the_colour_by_the_alpha() {
|
||||
let mut pixels = [
|
||||
0xff, 0x80, 0x00, 0xff, 0xff, 0x80, 0x10, 0x80, 0xff, 0xff, 0xff, 0x00,
|
||||
];
|
||||
premultiply(&mut pixels);
|
||||
assert_eq!(
|
||||
pixels,
|
||||
[
|
||||
0xff, 0x80, 0x00, 0xff, 0x80, 0x40, 0x08, 0x80, 0x00, 0x00, 0x00, 0x00
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
//! [`MetalSink`]: what draws a window display's frames on the product's platform, straight into
|
||||
//! the window's drawable, which it presents in the same command buffer.
|
||||
|
||||
use std::any::Any;
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_metal::{MTLCommandBuffer as _, MTLCommandQueue as _, MTLDevice, MTLDrawable};
|
||||
use objc2_quartz_core::CAMetalDrawable;
|
||||
use reims_vgpu_core::display::Display as CoreDisplay;
|
||||
use reims_vgpu_core::platform::Platform;
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::raise::OnFault;
|
||||
use reims_vgpu_metal::{MetalPlatform, Obj, msg};
|
||||
use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect};
|
||||
|
||||
use super::{SinkDisplay, WindowFrame};
|
||||
use crate::display::no_catch;
|
||||
use crate::entry;
|
||||
|
||||
/// The sink of a display of the product's platform ([`super::window_sink`]): a [`MetalSink`] over
|
||||
/// `display`, drawn in `frame_queue`, or `None` without a frame queue. `display` and
|
||||
/// `frame_queue` back, unchanged, for a display of another platform.
|
||||
#[expect(
|
||||
clippy::type_complexity,
|
||||
reason = "the two values handed back, as they came"
|
||||
)]
|
||||
pub(super) fn sink(
|
||||
display: Box<dyn Any>,
|
||||
frame_queue: Box<dyn Any>,
|
||||
) -> Result<Option<Arc<dyn FrameSink>>, (Box<dyn Any>, Box<dyn Any>)> {
|
||||
let display = match display.downcast::<Weak<CoreDisplay<MetalPlatform>>>() {
|
||||
Ok(display) => display,
|
||||
Err(display) => return Err((display, frame_queue)),
|
||||
};
|
||||
let Ok(frame_queue) =
|
||||
frame_queue.downcast::<Option<<MetalPlatform as Platform>::CommandQueue>>()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok((*frame_queue).map(|queue| {
|
||||
let sink: Arc<dyn FrameSink> = Arc::new(MetalSink::new(*display, queue));
|
||||
sink
|
||||
}))
|
||||
}
|
||||
|
||||
impl<P: Platform> SinkDisplay<P> {
|
||||
/// `device`, the Metal device the window's layer draws with, while the display lives
|
||||
/// ([`FrameSink::device`]).
|
||||
pub(crate) fn layer_device(
|
||||
&self,
|
||||
device: &<MetalPlatform as Platform>::Device,
|
||||
) -> Option<Retained<ProtocolObject<dyn MTLDevice>>> {
|
||||
(self.display.strong_count() > 0).then(|| device.as_retained().clone())
|
||||
}
|
||||
}
|
||||
|
||||
/// `drawable`'s texture, which both sinks' [`FrameSink::draw`] draw into, as a handle.
|
||||
pub(crate) fn drawable_texture(
|
||||
drawable: &ProtocolObject<dyn CAMetalDrawable>,
|
||||
) -> <MetalPlatform as Platform>::Texture {
|
||||
Obj::from_retained(msg::get("texture", || drawable.texture()))
|
||||
}
|
||||
|
||||
/// What draws a display's current frame into its window's drawable, on Metal: the display and
|
||||
/// its frame queue ([`SinkDisplay`]), and the queue's Metal device, which the window's layer
|
||||
/// draws with. Neither the queue nor the device keeps the display alive.
|
||||
pub(crate) struct MetalSink {
|
||||
/// The display, held only for a draw (the `window` module's doc), and the frame queue.
|
||||
display: SinkDisplay<MetalPlatform>,
|
||||
/// The queue's Metal device: the display's.
|
||||
device: <MetalPlatform as Platform>::Device,
|
||||
}
|
||||
|
||||
impl MetalSink {
|
||||
/// A sink over `display`, drawing in command buffers of `queue`, the frame queue of the
|
||||
/// display's Metal device.
|
||||
pub(crate) fn new(
|
||||
display: Weak<CoreDisplay<MetalPlatform>>,
|
||||
queue: <MetalPlatform as Platform>::CommandQueue,
|
||||
) -> MetalSink {
|
||||
let device = Obj::from_retained(msg::get("device", || queue.device()));
|
||||
MetalSink {
|
||||
display: SinkDisplay::new(display, queue, own_texture),
|
||||
device,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes the display's current frame into `texture` over `region`, with `cursor` over it,
|
||||
/// in a new command buffer of the frame queue, presents `present` in it when there is one,
|
||||
/// and commits ([`SinkDisplay::encode`], whose `false` and lifetimes are this one's).
|
||||
pub(crate) fn encode_into(
|
||||
&self,
|
||||
texture: &<MetalPlatform as Platform>::Texture,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
present: Option<&ProtocolObject<dyn CAMetalDrawable>>,
|
||||
) -> bool {
|
||||
self.display
|
||||
.encode(region, cursor, MetalFrame { texture, present })
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor glyph's texture on Metal: a plain one, a resource of Metal's as the layer's
|
||||
/// drawables are (`super::cursor`'s module doc).
|
||||
pub(crate) fn own_texture(
|
||||
device: &<MetalPlatform as Platform>::Device,
|
||||
descriptor: &<MetalPlatform as Platform>::TextureDescriptor,
|
||||
) -> Option<<MetalPlatform as Platform>::Texture> {
|
||||
no_catch(device.new_texture(OnFault::Die, descriptor))
|
||||
}
|
||||
|
||||
/// A frame of [`MetalSink`]'s: encoded straight into `texture`, the drawable presented in the
|
||||
/// same command buffer.
|
||||
struct MetalFrame<'a> {
|
||||
/// The texture the frame is encoded into: the drawable's.
|
||||
texture: &'a <MetalPlatform as Platform>::Texture,
|
||||
/// The drawable to present, when there is one.
|
||||
present: Option<&'a ProtocolObject<dyn CAMetalDrawable>>,
|
||||
}
|
||||
|
||||
impl WindowFrame<MetalPlatform> for MetalFrame<'_> {
|
||||
fn texture(&mut self) -> Option<&<MetalPlatform as Platform>::Texture> {
|
||||
Some(self.texture)
|
||||
}
|
||||
|
||||
/// Presents the drawable in the command buffer, when there is one.
|
||||
fn encoded(&mut self, command_buffer: &<MetalPlatform as Platform>::CommandBuffer) {
|
||||
if let Some(drawable) = self.present {
|
||||
let drawable: &ProtocolObject<dyn MTLDrawable> = ProtocolObject::from_ref(drawable);
|
||||
msg::get("presentDrawable:", || {
|
||||
command_buffer.get().presentDrawable(drawable);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FrameSink for MetalSink {
|
||||
/// The frame queue's Metal device, while the display lives.
|
||||
fn device(&self) -> Option<Retained<ProtocolObject<dyn MTLDevice>>> {
|
||||
self.display.layer_device(&self.device)
|
||||
}
|
||||
|
||||
/// The drawable's texture, then [`MetalSink::encode_into`] with the drawable to present.
|
||||
fn draw(
|
||||
&self,
|
||||
drawable: &ProtocolObject<dyn CAMetalDrawable>,
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> bool {
|
||||
entry::run(|_| {
|
||||
self.encode_into(&drawable_texture(drawable), region, cursor, Some(drawable))
|
||||
})
|
||||
}
|
||||
|
||||
/// The display's ([`SinkDisplay::cursor_position`]).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
entry::run(|_| self.display.cursor_position())
|
||||
}
|
||||
}
|
||||
@@ -1,728 +0,0 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use reims_vgpu_core::display::DisplayCoord;
|
||||
use reims_vgpu_core::sync::Mutex;
|
||||
use reims_vgpu_core::testkit::host::FakeHost;
|
||||
use reims_vgpu_core::testkit::{FakePlatform, GuestRam};
|
||||
use reims_vgpu_window::{WindowCallbacks, WindowConfig};
|
||||
|
||||
use super::*;
|
||||
use crate::display::DisplayConfig;
|
||||
use crate::platform::FAKE_HOST_SCREEN;
|
||||
use crate::{Device, DeviceConfig, DisplayMode, Error, HostCallbacks};
|
||||
|
||||
/// Lines the test's closures write, in the order they ran.
|
||||
type Log = Arc<Mutex<Vec<String>>>;
|
||||
|
||||
/// Writes its line into the log when dropped: where a closure holding it was let go of.
|
||||
struct Note(&'static str, Log);
|
||||
|
||||
impl Drop for Note {
|
||||
fn drop(&mut self) {
|
||||
self.1.lock().push(self.0.to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// A device on a platform of its own, over the fake host's callbacks, with `ports` ports.
|
||||
fn fake_device(ports: u32) -> (Arc<FakeHost>, Device<FakePlatform>) {
|
||||
let p = Arc::new(FakePlatform::new());
|
||||
let host = FakeHost::new(&p, GuestRam::with_range(0, 0x40_0000).unwrap());
|
||||
let b = host.blocks();
|
||||
let config = DeviceConfig {
|
||||
display_port_count: ports,
|
||||
callbacks: HostCallbacks {
|
||||
create_task: b.create_task,
|
||||
destroy_task: b.destroy_task,
|
||||
map_memory: b.map_memory,
|
||||
unmap_memory: b.unmap_memory,
|
||||
read_memory: b.read_memory,
|
||||
raise_interrupt: b.raise_interrupt,
|
||||
add_trace_range: b.add_trace_range,
|
||||
remove_trace_range: b.remove_trace_range,
|
||||
},
|
||||
..DeviceConfig::default()
|
||||
};
|
||||
(host, Device::with_platform(p, config).unwrap())
|
||||
}
|
||||
|
||||
/// A window config whose close callback holds `held`: the window lets go of it at its end.
|
||||
fn window_config<T: Send + Sync + 'static>(held: T, match_host_screen: bool) -> WindowConfig {
|
||||
WindowConfig {
|
||||
match_host_screen,
|
||||
mode: None,
|
||||
mode_ppi: None,
|
||||
keeps_its_size: false,
|
||||
callbacks: WindowCallbacks {
|
||||
close: Some(Arc::new(move || {
|
||||
let _ = &held;
|
||||
})),
|
||||
..WindowCallbacks::default()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The window's side of the tee, recorded.
|
||||
struct Recorder(Log);
|
||||
|
||||
impl GuestEvents for Recorder {
|
||||
fn guest_mode(&self, width: u16, height: u16) {
|
||||
self.0.lock().push(format!("window mode {width}x{height}"));
|
||||
}
|
||||
|
||||
fn new_frame(&self) {
|
||||
self.0.lock().push("window new_frame".to_owned());
|
||||
}
|
||||
|
||||
fn cursor_glyph(&self, g: &CursorGlyph<'_>) {
|
||||
let (w, h, (x, y), px) = (g.width, g.height, g.hot_spot, g.rgba);
|
||||
self.0
|
||||
.lock()
|
||||
.push(format!("window glyph {w}x{h} at {x},{y} {px:?}"));
|
||||
}
|
||||
|
||||
fn cursor_show(&self, show: bool) {
|
||||
self.0.lock().push(format!("window show {show}"));
|
||||
}
|
||||
|
||||
fn cursor_moved(&self) {
|
||||
self.0.lock().push("window move".to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
/// The host's five callbacks, recorded.
|
||||
fn host_callbacks(log: &Log) -> DisplayCallbacks {
|
||||
let (a, b, c, d, e) = (
|
||||
log.clone(),
|
||||
log.clone(),
|
||||
log.clone(),
|
||||
log.clone(),
|
||||
log.clone(),
|
||||
);
|
||||
DisplayCallbacks {
|
||||
mode_change: Some(Arc::new(move |w, h, format| {
|
||||
a.lock().push(format!("host mode {w}x{h} {format:#x}"));
|
||||
})),
|
||||
new_frame: Some(Arc::new(move || b.lock().push("host new_frame".to_owned()))),
|
||||
cursor_glyph: Some(Arc::new(move |g: &CursorGlyph<'_>| {
|
||||
c.lock()
|
||||
.push(format!("host glyph {}x{}", g.width, g.height));
|
||||
})),
|
||||
cursor_show: Some(Arc::new(move |show| {
|
||||
d.lock().push(format!("host show {show}"))
|
||||
})),
|
||||
cursor_move: Some(Arc::new(move || e.lock().push("host move".to_owned()))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls each of the five callbacks once, the cursor's show twice (hide, then show).
|
||||
fn call_all(cb: &DisplayCallbacks) {
|
||||
(cb.mode_change.as_ref().unwrap())(640, 480, 0x4247_5241);
|
||||
(cb.new_frame.as_ref().unwrap())();
|
||||
(cb.cursor_glyph.as_ref().unwrap())(&CursorGlyph {
|
||||
width: 1,
|
||||
height: 1,
|
||||
hot_spot: (3, 4),
|
||||
rgba: &[1, 2, 3, 4],
|
||||
});
|
||||
(cb.cursor_show.as_ref().unwrap())(0);
|
||||
(cb.cursor_show.as_ref().unwrap())(2);
|
||||
(cb.cursor_move.as_ref().unwrap())();
|
||||
}
|
||||
|
||||
/// Each guest callback reaches the window, then the host's, with the arguments core passed; the
|
||||
/// cursor's show byte is the window's bool
|
||||
#[test]
|
||||
fn the_tee_tells_the_window_before_the_host() {
|
||||
let log = Log::default();
|
||||
let window = Arc::new(Recorder(log.clone()));
|
||||
let cb = tee(&window, host_callbacks(&log));
|
||||
call_all(&cb);
|
||||
assert_eq!(
|
||||
*log.lock(),
|
||||
[
|
||||
"window mode 640x480",
|
||||
"host mode 640x480 0x42475241",
|
||||
"window new_frame",
|
||||
"host new_frame",
|
||||
"window glyph 1x1 at 3,4 [1, 2, 3, 4]",
|
||||
"host glyph 1x1",
|
||||
"window show false",
|
||||
"host show 0",
|
||||
"window show true",
|
||||
"host show 2",
|
||||
"window move",
|
||||
"host move",
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// With no callback of the host's, the tee still has all five, each the window's alone; its
|
||||
/// closures hold the window, which they let go of when they drop
|
||||
#[test]
|
||||
fn the_tee_has_all_five_callbacks_without_the_host_s() {
|
||||
let log = Log::default();
|
||||
let window = Arc::new(Recorder(log.clone()));
|
||||
let cb = tee(&window, DisplayCallbacks::default());
|
||||
call_all(&cb);
|
||||
assert_eq!(
|
||||
*log.lock(),
|
||||
[
|
||||
"window mode 640x480",
|
||||
"window new_frame",
|
||||
"window glyph 1x1 at 3,4 [1, 2, 3, 4]",
|
||||
"window show false",
|
||||
"window show true",
|
||||
"window move",
|
||||
]
|
||||
);
|
||||
assert_eq!(Arc::strong_count(&window), 6);
|
||||
drop(cb);
|
||||
assert_eq!(Arc::strong_count(&window), 1);
|
||||
}
|
||||
|
||||
/// A display with a window has all five callbacks, which the guest reads, and each calls the
|
||||
/// host's where it gave one; the window takes the port, and a title without the display's name.
|
||||
/// Not matching the host screen, the display keeps the config's size, no scale factor and no
|
||||
/// modes
|
||||
#[test]
|
||||
fn a_window_display_has_every_callback() {
|
||||
let (_host, device) = fake_device(2);
|
||||
let log = Log::default();
|
||||
let mut c = DisplayConfig::new(1, 0x5eed_a001);
|
||||
c.name = Some("Studio".to_owned());
|
||||
c.size_in_millimeters = (400.0, 300.0);
|
||||
let host = host_callbacks(&log);
|
||||
c.callbacks.mode_change = host.mode_change;
|
||||
c.window = Some(window_config((), false));
|
||||
let d = device.new_display(c).unwrap();
|
||||
let core = d.core();
|
||||
assert!(core.mode_change_handler().is_some());
|
||||
assert!(core.new_frame_event_handler().is_some());
|
||||
assert!(core.cursor_glyph_handler().is_some());
|
||||
assert!(core.cursor_show_handler().is_some());
|
||||
assert!(core.cursor_move_handler().is_some());
|
||||
(core.mode_change_handler().unwrap())(DisplayCoord { x: 640, y: 480 }, 7);
|
||||
(core.cursor_show_handler().unwrap())(1);
|
||||
(core.cursor_move_handler().unwrap())();
|
||||
assert_eq!(*log.lock(), ["host mode 640x480 0x7"]);
|
||||
let window = d.window().unwrap();
|
||||
assert_eq!((window.port(), window.title()), (1, "Reims vGPU (port 1)"));
|
||||
assert!(!window.match_host_screen() && !window.is_closed());
|
||||
assert_eq!(core.size_in_millimeters(), (400.0, 300.0));
|
||||
assert_eq!(core.scale_factor(), 0);
|
||||
assert!(core.mode_list().is_empty());
|
||||
}
|
||||
|
||||
/// Without a window, the display has the callbacks the host gave and no others, the config's
|
||||
/// size and no scale factor
|
||||
#[test]
|
||||
fn without_a_window_the_display_is_as_its_config_says() {
|
||||
let (_host, device) = fake_device(1);
|
||||
let log = Log::default();
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_a011);
|
||||
c.size_in_millimeters = (400.0, 300.0);
|
||||
c.callbacks.mode_change = host_callbacks(&log).mode_change;
|
||||
let d = device.new_display(c).unwrap();
|
||||
let core = d.core();
|
||||
assert!(core.mode_change_handler().is_some());
|
||||
assert!(core.new_frame_event_handler().is_none());
|
||||
assert!(core.cursor_glyph_handler().is_none());
|
||||
assert!(core.cursor_show_handler().is_none());
|
||||
assert!(core.cursor_move_handler().is_none());
|
||||
assert!(d.window().is_none());
|
||||
assert_eq!(core.size_in_millimeters(), (400.0, 300.0));
|
||||
assert_eq!(core.scale_factor(), 0);
|
||||
assert!(core.mode_list().is_empty());
|
||||
}
|
||||
|
||||
/// Matching the host screen, the display offers the modes the policy gives for the platform's
|
||||
/// screen (the testkit's is Retina: scale factor 2), with the first mode's size in millimetres,
|
||||
/// in place of the config's; the host's own modes then replace them
|
||||
#[test]
|
||||
fn matching_the_host_screen_offers_its_modes_and_density() {
|
||||
let (_host, device) = fake_device(1);
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_a021);
|
||||
c.size_in_millimeters = (400.0, 300.0);
|
||||
c.window = Some(window_config((), true));
|
||||
let d = device.new_display(c).unwrap();
|
||||
let core = d.core();
|
||||
assert!(d.window().unwrap().match_host_screen());
|
||||
let (modes, density) = host_matched(Some(&FAKE_HOST_SCREEN), None, None, None).unwrap();
|
||||
assert_eq!(density.scale_factor, 2);
|
||||
assert_eq!(core.scale_factor(), 2);
|
||||
assert_eq!(core.size_in_millimeters(), density.size_in_millimeters);
|
||||
let got: Vec<(u16, u16, f64, bool, bool)> = core
|
||||
.mode_list()
|
||||
.iter()
|
||||
.map(|m| {
|
||||
let size = m.size_in_pixels;
|
||||
let rate = m.refresh_rate_in_hz;
|
||||
(size.x, size.y, rate, m.supports_edr, m.supports_10bpc)
|
||||
})
|
||||
.collect();
|
||||
let want: Vec<(u16, u16, f64, bool, bool)> = modes
|
||||
.iter()
|
||||
.map(|m| (m.width, m.height, m.refresh_hz, false, false))
|
||||
.collect();
|
||||
assert_eq!(got, want);
|
||||
d.set_modes(&[DisplayMode::new(1280, 720, 60.0)]);
|
||||
assert_eq!(core.mode_list().len(), 1);
|
||||
}
|
||||
|
||||
/// Matching the host screen with a chosen mode, the display offers that mode first, then the
|
||||
/// standard sizes within it, at the screen's rate and a 1× density, and its window opens sized
|
||||
/// for it
|
||||
#[test]
|
||||
fn a_chosen_mode_is_offered_first_at_1x() {
|
||||
let (_host, device) = fake_device(1);
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_a041);
|
||||
c.size_in_millimeters = (400.0, 300.0);
|
||||
let mut w = window_config((), true);
|
||||
w.mode = Some((1920, 1080));
|
||||
c.window = Some(w);
|
||||
let d = device.new_display(c).unwrap();
|
||||
let core = d.core();
|
||||
let (modes, density) =
|
||||
host_matched(Some(&FAKE_HOST_SCREEN), Some((1920, 1080)), None, None).unwrap();
|
||||
assert_eq!((modes[0].width, modes[0].height), (1920, 1080));
|
||||
assert_eq!(density.scale_factor, 1);
|
||||
assert_eq!(core.scale_factor(), 1);
|
||||
assert_eq!(core.size_in_millimeters(), density.size_in_millimeters);
|
||||
let got: Vec<(u16, u16, f64)> = core
|
||||
.mode_list()
|
||||
.iter()
|
||||
.map(|m| (m.size_in_pixels.x, m.size_in_pixels.y, m.refresh_rate_in_hz))
|
||||
.collect();
|
||||
let want: Vec<(u16, u16, f64)> = modes
|
||||
.iter()
|
||||
.map(|m| (m.width, m.height, m.refresh_hz))
|
||||
.collect();
|
||||
assert_eq!(got, want);
|
||||
assert_eq!(d.window().unwrap().offered(), Some((1920, 1080)));
|
||||
}
|
||||
|
||||
/// Matching the host screen with a chosen mode and density, the display tells the guest the
|
||||
/// mode's size at that density: 2560×1600 at 200 ppi has a scale factor of 2, where the same
|
||||
/// mode without a density is 1×
|
||||
#[test]
|
||||
fn a_chosen_mode_at_a_chosen_ppi_is_told_that_density() {
|
||||
let (_host, device) = fake_device(1);
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_a042);
|
||||
c.size_in_millimeters = (400.0, 300.0);
|
||||
let mut w = window_config((), true);
|
||||
w.mode = Some((2560, 1600));
|
||||
w.mode_ppi = Some(200.0);
|
||||
c.window = Some(w);
|
||||
let d = device.new_display(c).unwrap();
|
||||
let core = d.core();
|
||||
let (modes, density) = host_matched(
|
||||
Some(&FAKE_HOST_SCREEN),
|
||||
Some((2560, 1600)),
|
||||
Some(200.0),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!((modes[0].width, modes[0].height), (2560, 1600));
|
||||
assert_eq!(density.scale_factor, 2);
|
||||
assert_eq!(core.scale_factor(), 2);
|
||||
assert_eq!(core.size_in_millimeters(), density.size_in_millimeters);
|
||||
assert_eq!(d.window().unwrap().offered(), Some((2560, 1600)));
|
||||
let (_, at_1x) = host_matched(Some(&FAKE_HOST_SCREEN), Some((2560, 1600)), None, None).unwrap();
|
||||
assert_eq!(at_1x.scale_factor, 1);
|
||||
}
|
||||
|
||||
/// With no host screen (as with no window system to reach), a display matching it still offers
|
||||
/// modes: the chosen mode and the sizes within it at its density, as on a screen, at 60 Hz
|
||||
/// unless the rate is overridden; with no mode chosen, 1920×1080 at 1×.
|
||||
/// Never none, which left a macOS guest no mode to set and stopped its boot at the Apple logo
|
||||
#[test]
|
||||
fn without_a_host_screen_the_chosen_mode_is_offered_at_60_hz() {
|
||||
let sizes = |m: &[OfferedMode]| m.iter().map(|m| (m.width, m.height)).collect::<Vec<_>>();
|
||||
let matched = |screen| host_matched(screen, Some((3840, 2400)), Some(331.0), None).unwrap();
|
||||
let (modes, density) = matched(None);
|
||||
let (on_screen, screen_density) = matched(Some(&FAKE_HOST_SCREEN));
|
||||
assert_eq!(sizes(&modes), sizes(&on_screen));
|
||||
assert!(modes.iter().all(|m| m.refresh_hz == 60.0));
|
||||
assert_eq!(density, screen_density);
|
||||
assert_eq!(density.scale_factor, 2);
|
||||
let (modes, _) = host_matched(None, None, None, Some(120.0)).unwrap();
|
||||
assert!(modes.iter().all(|m| m.refresh_hz == 120.0));
|
||||
let (modes, density) = host_matched(None, None, None, None).unwrap();
|
||||
assert_eq!(
|
||||
(modes[0].width, modes[0].height, modes[0].refresh_hz),
|
||||
(1920, 1080, 60.0)
|
||||
);
|
||||
assert_eq!(density, policy::density_1x((1920, 1080)));
|
||||
}
|
||||
|
||||
/// A window display's window is told the first mode the display offers, which it opens sized
|
||||
/// for: matching the host screen, the policy's first; otherwise the first the host sets, each
|
||||
/// time it sets a list
|
||||
#[test]
|
||||
fn the_window_is_told_the_first_mode_offered() {
|
||||
let (_host, device) = fake_device(2);
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_a031);
|
||||
c.window = Some(window_config((), true));
|
||||
let matched = device.new_display(c).unwrap();
|
||||
let (modes, _) = host_matched(Some(&FAKE_HOST_SCREEN), None, None, None).unwrap();
|
||||
let first = (modes[0].width, modes[0].height);
|
||||
assert_eq!(matched.window().unwrap().offered(), Some(first));
|
||||
let mut c = DisplayConfig::new(1, 0x5eed_a032);
|
||||
c.window = Some(window_config((), false));
|
||||
let d = device.new_display(c).unwrap();
|
||||
let window = d.window().unwrap();
|
||||
assert_eq!(window.offered(), None);
|
||||
d.set_modes(&[
|
||||
DisplayMode::new(1280, 720, 60.0),
|
||||
DisplayMode::new(1920, 1080, 60.0),
|
||||
]);
|
||||
assert_eq!(window.offered(), Some((1280, 720)));
|
||||
d.set_modes(&[]);
|
||||
assert_eq!(window.offered(), Some((1280, 720)));
|
||||
d.set_modes(&[DisplayMode::new(1024, 768, 60.0)]);
|
||||
assert_eq!(window.offered(), Some((1024, 768)));
|
||||
}
|
||||
|
||||
/// A refused window display closes its window before the create returns: the window's
|
||||
/// callbacks are let go of, even where the refused display's new-frame closure, which the
|
||||
/// display thread frees, still holds the window
|
||||
#[test]
|
||||
fn a_refused_window_display_closes_its_window() {
|
||||
let (_host, device) = fake_device(1);
|
||||
let first = device
|
||||
.new_display(DisplayConfig::new(0, 0x5eed_a101))
|
||||
.unwrap();
|
||||
for (port, serial, refusal) in [
|
||||
(0, 0x5eed_a102, Error::PortInUse),
|
||||
(1, 0x5eed_a103, Error::PortOutOfRange),
|
||||
(0, 0x5eed_a101, Error::SerialInUse),
|
||||
] {
|
||||
let held = Arc::new(());
|
||||
let weak = Arc::downgrade(&held);
|
||||
let mut c = DisplayConfig::new(port, serial);
|
||||
c.window = Some(window_config(held, true));
|
||||
assert_eq!(device.new_display(c).err(), Some(refusal));
|
||||
assert!(weak.upgrade().is_none(), "{refusal:?}");
|
||||
}
|
||||
drop(first);
|
||||
}
|
||||
|
||||
/// The window lives while any reference to the display does; the last reference closes it,
|
||||
/// letting go of the host's window callbacks, before the display's end lets go of the host's
|
||||
/// display callbacks
|
||||
#[test]
|
||||
fn the_last_reference_closes_the_window_before_the_display_ends() {
|
||||
let (_host, device) = fake_device(1);
|
||||
let log = Log::default();
|
||||
let display_note = Note("display ended", log.clone());
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_a201);
|
||||
c.callbacks.cursor_move = Some(Arc::new(move || {
|
||||
let _ = &display_note;
|
||||
}));
|
||||
c.window = Some(window_config(Note("window closed", log.clone()), false));
|
||||
let d = device.new_display(c).unwrap();
|
||||
let window = d.window().unwrap().clone();
|
||||
let d2 = d.clone_ref();
|
||||
drop(d);
|
||||
assert!(log.lock().is_empty() && !window.is_closed());
|
||||
drop(d2);
|
||||
assert!(window.is_closed());
|
||||
assert_eq!(*log.lock(), ["window closed", "display ended"]);
|
||||
}
|
||||
|
||||
/// Set in the child of [`a_window_frame_keeps_its_display_until_it_completes`].
|
||||
#[cfg(target_os = "macos")]
|
||||
const METAL_CHILD: &str = "RVG_WINDOW_METAL_CHILD";
|
||||
|
||||
/// A display released while a frame the sink drew is in flight ends when the frame completes,
|
||||
/// not at the release: its port stays taken until then, as for a frame's display
|
||||
/// (`api.lifetime.display_through_a_committed_frame`). The sink then draws nothing, and has no
|
||||
/// device to give. On real Metal, in a child, since the process's platform installs the aborting
|
||||
/// panic hook. A command buffer ahead of the frame's in the frame queue waits for an event the
|
||||
/// test signals after the release, so the frame is in flight then.
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn a_window_frame_keeps_its_display_until_it_completes() {
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::event::{EventRef, SharedEvent as _};
|
||||
|
||||
use crate::PixelFormat;
|
||||
use crate::platform::api_state;
|
||||
use crate::window::metal::MetalSink;
|
||||
|
||||
if std::env::var_os(METAL_CHILD).is_none() {
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"window::tests::a_window_frame_keeps_its_display_until_it_completes",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.env(METAL_CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stdout).contains(" 1 passed"),
|
||||
"{out:?}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let device = Device::new(DeviceConfig::default()).unwrap();
|
||||
let target = device
|
||||
.new_frame_target(64, 64, PixelFormat::Bgra8Unorm)
|
||||
.unwrap();
|
||||
let held = Arc::new(());
|
||||
let alive = Arc::downgrade(&held);
|
||||
let mut c = DisplayConfig::new(0, 0x5eed_7a00);
|
||||
c.callbacks.cursor_move = Some(Arc::new(move || {
|
||||
let _ = &held;
|
||||
}));
|
||||
let display = device.new_display(c).unwrap();
|
||||
let (queue, event) = entry::run(|_| {
|
||||
let metal = device.core().mtl_device_ref();
|
||||
let queue = api_state(device.platform()).frame_queue(metal).unwrap();
|
||||
let event = metal.new_shared_event().unwrap();
|
||||
let blocker = no_catch(queue.command_buffer(OnFault::Die)).unwrap();
|
||||
no_catch(blocker.encode_wait(Some(EventRef::Shared(&event)), 1));
|
||||
no_catch(blocker.commit(OnFault::Die));
|
||||
(queue, event)
|
||||
});
|
||||
let sink = MetalSink::new(display.core().downgrade(), queue);
|
||||
assert!(sink.device().is_some());
|
||||
let region = PixelRect {
|
||||
x: 8,
|
||||
y: 8,
|
||||
width: 48,
|
||||
height: 48,
|
||||
};
|
||||
assert!(sink.encode_into(target.texture(), region, None, None));
|
||||
drop(display);
|
||||
assert!(alive.upgrade().is_some());
|
||||
assert_eq!(
|
||||
device.new_display(DisplayConfig::new(0, 0x5eed_7a01)).err(),
|
||||
Some(Error::PortInUse)
|
||||
);
|
||||
entry::run(|_| no_catch(event.set_signaled_value(1)));
|
||||
for _ in 0..500 {
|
||||
if alive.upgrade().is_none() {
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(alive.upgrade().is_none());
|
||||
let again = device.new_display(DisplayConfig::new(0, 0x5eed_7a02));
|
||||
assert!(again.is_ok());
|
||||
assert!(sink.device().is_none());
|
||||
assert!(!sink.encode_into(target.texture(), region, None, None));
|
||||
}
|
||||
|
||||
/// Set in the child of [`a_metal_window_frame_has_the_guest_s_cursor_over_it`].
|
||||
#[cfg(target_os = "macos")]
|
||||
const METAL_CURSOR_CHILD: &str = "RVG_WINDOW_METAL_CURSOR_CHILD";
|
||||
|
||||
/// On Metal, a sink draws the guest's cursor over a window frame by its straight alpha, where the
|
||||
/// window draws it: over a display with no frame yet, all the clear's black, in an image
|
||||
/// letterboxed in the target, the glyph's opaque rows are its colour, its half-transparent row
|
||||
/// half of it, its transparent row black whatever its colour bytes, and the rest stays black;
|
||||
/// a glyph past the image's top left edge is clipped there, the bars beside it left black. In a
|
||||
/// child, as the process's platform installs the aborting panic hook
|
||||
#[cfg(target_os = "macos")]
|
||||
#[test]
|
||||
fn a_metal_window_frame_has_the_guest_s_cursor_over_it() {
|
||||
use reims_vgpu_core::platform::Handle as _;
|
||||
use reims_vgpu_core::platform::blit::{BlitCmd, BlitEncoder as _};
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::resource::Buffer as _;
|
||||
use reims_vgpu_metal::MetalPlatform;
|
||||
use reims_vgpu_window::{DrawnCursor, Glyph};
|
||||
|
||||
use crate::PixelFormat;
|
||||
use crate::platform::api_state;
|
||||
|
||||
/// A frame drawn into the test's target, copied into `buffer` in its command buffer.
|
||||
struct Readback<'a> {
|
||||
texture: &'a <MetalPlatform as Platform>::Texture,
|
||||
buffer: &'a <MetalPlatform as Platform>::Buffer,
|
||||
committed: Option<<MetalPlatform as Platform>::CommandBuffer>,
|
||||
}
|
||||
|
||||
impl WindowFrame<MetalPlatform> for &mut Readback<'_> {
|
||||
fn texture(&mut self) -> Option<&<MetalPlatform as Platform>::Texture> {
|
||||
Some(self.texture)
|
||||
}
|
||||
|
||||
fn encoded(&mut self, command_buffer: &<MetalPlatform as Platform>::CommandBuffer) {
|
||||
let blit = no_catch(command_buffer.blit_encoder(OnFault::Die)).unwrap();
|
||||
no_catch(blit.encode(
|
||||
OnFault::Die,
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture: self.texture,
|
||||
source_slice: 0,
|
||||
source_level: 0,
|
||||
source_origin: MtlOrigin::new(0, 0, 0),
|
||||
source_size: MtlSize::new(WIDTH, HEIGHT, 1),
|
||||
destination_buffer: self.buffer,
|
||||
destination_offset: 0,
|
||||
destination_bytes_per_row: WIDTH * 4,
|
||||
destination_bytes_per_image: WIDTH * HEIGHT * 4,
|
||||
},
|
||||
));
|
||||
no_catch(blit.encode(OnFault::Die, BlitCmd::EndEncoding));
|
||||
self.committed = Some(command_buffer.clone_ref());
|
||||
}
|
||||
}
|
||||
|
||||
const WIDTH: u64 = 24;
|
||||
const HEIGHT: u64 = 20;
|
||||
if std::env::var_os(METAL_CURSOR_CHILD).is_none() {
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"window::tests::a_metal_window_frame_has_the_guest_s_cursor_over_it",
|
||||
"--nocapture",
|
||||
"--test-threads=1",
|
||||
])
|
||||
.env(METAL_CURSOR_CHILD, "1")
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(out.status.success(), "{out:?}");
|
||||
assert!(
|
||||
String::from_utf8_lossy(&out.stdout).contains(" 1 passed"),
|
||||
"{out:?}"
|
||||
);
|
||||
return;
|
||||
}
|
||||
let device = Device::new(DeviceConfig::default()).unwrap();
|
||||
let target = device
|
||||
.new_frame_target(24, 20, PixelFormat::Bgra8Unorm)
|
||||
.unwrap();
|
||||
let display = device
|
||||
.new_display(DisplayConfig::new(0, 0x5eed_7a20))
|
||||
.unwrap();
|
||||
// Four rows of four: opaque red, opaque green, blue at alpha 0x80, white at alpha 0.
|
||||
let rows: [[u8; 4]; 4] = [
|
||||
[0xff, 0, 0, 0xff],
|
||||
[0, 0xff, 0, 0xff],
|
||||
[0, 0, 0xff, 0x80],
|
||||
[0xff, 0xff, 0xff, 0],
|
||||
];
|
||||
let glyph = Arc::new(Glyph {
|
||||
width: 4,
|
||||
height: 4,
|
||||
hot_spot: (1, 2),
|
||||
rgba: rows.iter().flat_map(|row| row.repeat(4)).collect(),
|
||||
});
|
||||
// A 16 by 16 image 4 pixels from the left and 2 from the top.
|
||||
let region = PixelRect {
|
||||
x: 4,
|
||||
y: 2,
|
||||
width: 16,
|
||||
height: 16,
|
||||
};
|
||||
let sink = SinkDisplay::new(
|
||||
display.core().downgrade(),
|
||||
entry::run(|_| {
|
||||
api_state(device.platform())
|
||||
.frame_queue(device.core().mtl_device_ref())
|
||||
.unwrap()
|
||||
}),
|
||||
crate::window::metal::own_texture,
|
||||
);
|
||||
let draw = |at: (u16, u16)| {
|
||||
let cursor = DrawnCursor {
|
||||
glyph: Arc::clone(&glyph),
|
||||
mode: (16, 16),
|
||||
at,
|
||||
};
|
||||
entry::run(|_| {
|
||||
let metal = device.core().mtl_device_ref();
|
||||
let length = WIDTH * HEIGHT * 4;
|
||||
let buffer = no_catch(metal.new_buffer_of_length(OnFault::Die, length, 0)).unwrap();
|
||||
let mut frame = Readback {
|
||||
texture: target.texture(),
|
||||
buffer: &buffer,
|
||||
committed: None,
|
||||
};
|
||||
assert!(sink.encode(region, Some(&cursor), &mut frame));
|
||||
no_catch(frame.committed.unwrap().wait_until_completed(OnFault::Die));
|
||||
// SAFETY: the buffer is shared, `length` bytes long, and the copy into it has
|
||||
// completed.
|
||||
unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
buffer.contents().as_ptr::<u8>(),
|
||||
usize::try_from(length).unwrap(),
|
||||
)
|
||||
}
|
||||
.to_vec()
|
||||
})
|
||||
};
|
||||
// The glyph's top left is the region's, plus the cursor's position, less the hot spot.
|
||||
for (at, left, top) in [((5, 9), 8, 9), ((0, 0), 3, 0)] {
|
||||
let bytes = draw(at);
|
||||
for (i, got) in bytes.chunks(4).enumerate() {
|
||||
let (x, y) = (i % 24, i / 24);
|
||||
let inside = (4..20).contains(&x) && (2..18).contains(&y);
|
||||
let want = match (x.checked_sub(left), y.checked_sub(top)) {
|
||||
(Some(gx), Some(gy)) if inside && gx < 4 && gy < 4 => {
|
||||
let [r, g, b, a] = rows[gy];
|
||||
let over =
|
||||
|v: u8| u8::try_from((u16::from(v) * u16::from(a) + 127) / 255).unwrap();
|
||||
[over(b), over(g), over(r), 0xff]
|
||||
}
|
||||
_ => [0, 0, 0, 0xff],
|
||||
};
|
||||
let near = got.iter().zip(want).all(|(&g, w)| g.abs_diff(w) <= 1);
|
||||
assert!(near, "at {at:?}, ({x}, {y}): {got:?} for {want:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// On the Vulkan platform, the window opens on the host screen CoreGraphics gives for the port,
|
||||
/// as on Metal; the testkit's platform does not ask CoreGraphics
|
||||
#[cfg(all(vulkan_platform, target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_vulkan_display_s_window_opens_on_the_host_screen() {
|
||||
use reims_vgpu_metal::MetalPlatform;
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
|
||||
assert!(on_host_screens::<VulkanPlatform>());
|
||||
assert!(on_host_screens::<MetalPlatform>());
|
||||
assert!(!on_host_screens::<FakePlatform>());
|
||||
for port in 0..3 {
|
||||
assert_eq!(
|
||||
host_screen::<VulkanPlatform>(port),
|
||||
host_screen::<MetalPlatform>(port)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A Vulkan display's window has a sink over it, which presents itself, through a swapchain of
|
||||
/// the window's layer: it names no device for the layer, which the swapchain sets, and the
|
||||
/// layer's drawables are not framebuffer-only, as the swapchain's images take transfers too;
|
||||
/// without a frame queue it has none, and the window never opens
|
||||
#[cfg(all(vulkan_platform, target_os = "macos"))]
|
||||
#[test]
|
||||
fn a_vulkan_display_has_a_window_sink() {
|
||||
use reims_vgpu_core::tasks::isolation::TaskThreads;
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
|
||||
use crate::platform::api_state;
|
||||
|
||||
let platform = Arc::new(VulkanPlatform::new(Box::new(TaskThreads::new())));
|
||||
let device = Device::with_platform(platform.clone(), DeviceConfig::default())
|
||||
.expect("a Vulkan device (MoltenVK)");
|
||||
let display = device
|
||||
.new_display(DisplayConfig::new(0, 0x5eed_7a10))
|
||||
.unwrap();
|
||||
let queue = entry::run(|_| {
|
||||
api_state(&platform)
|
||||
.frame_queue(device.core().mtl_device_ref())
|
||||
.unwrap()
|
||||
});
|
||||
let sink = window_sink(&platform, display.core().downgrade(), Some(queue)).unwrap();
|
||||
assert!(sink.presents());
|
||||
assert!(!sink.render_target_only());
|
||||
assert!(sink.device().is_none());
|
||||
assert!(window_sink(&platform, display.core().downgrade(), None).is_none());
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
//! What draws a window display's frames on the Vulkan platform: the runtime draws each frame into
|
||||
//! the window's swapchain, on either OS (`swapchain.rs`), and each OS's window asks the sink for
|
||||
//! it its own way (`linux.rs`, `macos.rs`).
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod macos;
|
||||
mod swapchain;
|
||||
|
||||
pub(crate) use swapchain::sink;
|
||||
@@ -1,19 +0,0 @@
|
||||
//! What Linux's window asks of the Vulkan platform's sink ([`FrameSink`]): a presenter over the
|
||||
//! window's swapchain ([`SwapchainSink::make_presenter`]), which SDL's window makes its surface
|
||||
//! for.
|
||||
|
||||
use reims_vgpu_window::{FrameSink, Presenter, VulkanTarget};
|
||||
|
||||
use super::swapchain::SwapchainSink;
|
||||
|
||||
impl FrameSink for SwapchainSink {
|
||||
/// The presenter ([`SwapchainSink::make_presenter`]).
|
||||
fn presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>> {
|
||||
self.make_presenter(target)
|
||||
}
|
||||
|
||||
/// The display's ([`SwapchainSink::cursor_position`]).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
self.cursor_position()
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
//! What macOS's window asks of the Vulkan platform's sink ([`FrameSink`]): it presents itself,
|
||||
//! through a presenter over a swapchain of the window's `CAMetalLayer`
|
||||
//! ([`SwapchainSink::make_presenter`]), whose images are the layer's drawables. So the window's
|
||||
//! render thread takes no drawable for it, and its swapchain sets the layer up (its device among
|
||||
//! the rest): the sink names no device, draws into no drawable it is given, and lets the layer's
|
||||
//! drawables take copies, as its swapchain's images allow (their usage beside a render target's
|
||||
//! is the transfers' and sampling's, `reims_vgpu_vulkan::swapchain`).
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use objc2::rc::Retained;
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2_metal::MTLDevice;
|
||||
use objc2_quartz_core::CAMetalDrawable;
|
||||
use reims_vgpu_window::{DrawnCursor, FrameSink, PixelRect, Presenter, VulkanTarget};
|
||||
|
||||
use super::swapchain::SwapchainSink;
|
||||
|
||||
impl FrameSink for SwapchainSink {
|
||||
/// None: the swapchain sets the layer's device.
|
||||
fn device(&self) -> Option<Retained<ProtocolObject<dyn MTLDevice>>> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Nothing: the sink presents itself, and is given no drawable.
|
||||
fn draw(
|
||||
&self,
|
||||
_drawable: &ProtocolObject<dyn CAMetalDrawable>,
|
||||
_region: PixelRect,
|
||||
_cursor: Option<&DrawnCursor>,
|
||||
) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// False: the swapchain's images take transfers and sampling too, as the swapchain sets
|
||||
/// the layer.
|
||||
fn render_target_only(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// True: the sink presents through [`FrameSink::presenter`].
|
||||
fn presents(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// The presenter ([`SwapchainSink::make_presenter`]).
|
||||
fn presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>> {
|
||||
self.make_presenter(target)
|
||||
}
|
||||
|
||||
/// The display's ([`SwapchainSink::cursor_position`]).
|
||||
fn guest_cursor_position(&self) -> Option<(u16, u16)> {
|
||||
self.cursor_position()
|
||||
}
|
||||
}
|
||||
@@ -1,490 +0,0 @@
|
||||
//! The Vulkan platform's window sink on macOS: the swapchain's image of a frame is what the
|
||||
//! display's compose draws into a texture of the window's size, with no copy between.
|
||||
|
||||
use std::ffi::c_void;
|
||||
use std::sync::Arc;
|
||||
|
||||
use ash::vk;
|
||||
use objc2::rc::Retained;
|
||||
use objc2_core_foundation::{CGPoint, CGRect, CGSize};
|
||||
use objc2_metal::MTLTextureUsage;
|
||||
use objc2_quartz_core::CAMetalLayer;
|
||||
use reims_vgpu_core::display::{GammaTableArgs, MINIMUM_TEXTURE_USAGE};
|
||||
use reims_vgpu_core::num::ToU64 as _;
|
||||
use reims_vgpu_core::platform::descriptor::TextureDescriptor as _;
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::resource::Texture as _;
|
||||
use reims_vgpu_core::platform::types::{MtlOrigin, MtlRegion, MtlSize};
|
||||
use reims_vgpu_core::platform::{Handle as _, HostRange, Platform};
|
||||
use reims_vgpu_core::raise::OnFault;
|
||||
use reims_vgpu_core::rt::Hold;
|
||||
use reims_vgpu_core::tasks::isolation::TaskThreads;
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
use reims_vgpu_vulkan::swapchain::Swapchain;
|
||||
use reims_vgpu_window::{PixelRect, VulkanTarget};
|
||||
|
||||
use super::super::swapchain::own_texture;
|
||||
use super::super::swapchain::tests::{draw_and_read_back, read_back};
|
||||
use crate::PixelFormat;
|
||||
use crate::display::no_catch;
|
||||
use crate::entry;
|
||||
use crate::platform::api_state;
|
||||
use crate::window::{SinkDisplay, WindowFrame};
|
||||
use crate::{Device, DeviceConfig, Display, DisplayConfig};
|
||||
|
||||
/// The platform's command queue.
|
||||
type Queue = <VulkanPlatform as Platform>::CommandQueue;
|
||||
/// Its command buffer.
|
||||
type CommandBuffer = <VulkanPlatform as Platform>::CommandBuffer;
|
||||
/// Its texture.
|
||||
type Texture = <VulkanPlatform as Platform>::Texture;
|
||||
|
||||
/// `MTLResourceStorageModeShared`, with the default CPU cache and hazard tracking modes.
|
||||
const SHARED: u64 = 0;
|
||||
|
||||
/// `MTLResourceStorageModePrivate`: a drawable's storage.
|
||||
const PRIVATE: u64 = 0x20;
|
||||
|
||||
/// The frame queue of `device`'s Metal device.
|
||||
fn frame_queue(device: &Device<VulkanPlatform>) -> Queue {
|
||||
entry::run(|_| {
|
||||
api_state(device.platform())
|
||||
.frame_queue(device.core().mtl_device_ref())
|
||||
.unwrap()
|
||||
})
|
||||
}
|
||||
|
||||
/// A Vulkan device on a platform of its own, and a display on its port 0 that takes
|
||||
/// presents: one with a new-frame callback.
|
||||
fn presenting_display(serial: u32) -> (Device<VulkanPlatform>, Display<VulkanPlatform>) {
|
||||
let platform = Arc::new(VulkanPlatform::new(Box::new(TaskThreads::new())));
|
||||
let device = Device::with_platform(platform, DeviceConfig::default())
|
||||
.expect("a Vulkan device (MoltenVK)");
|
||||
let mut c = DisplayConfig::new(0, serial);
|
||||
c.callbacks.new_frame = Some(Arc::new(|| {}));
|
||||
let display = device.new_display(c).unwrap();
|
||||
(device, display)
|
||||
}
|
||||
|
||||
/// Presents to `display` a frame of `(width, height)`, BGRA, of every colour channel a
|
||||
/// gradient of its own, opaque: what the window draws next.
|
||||
fn present_a_fixed_frame(
|
||||
device: &Device<VulkanPlatform>,
|
||||
display: &Display<VulkanPlatform>,
|
||||
(width, height): (u64, u64),
|
||||
) {
|
||||
let bytes: Vec<u8> = (0..height)
|
||||
.flat_map(|y| (0..width).map(move |x| (x, y)))
|
||||
.flat_map(|(x, y)| {
|
||||
let cut = |v: u64| u8::try_from(v % 256).unwrap();
|
||||
[
|
||||
cut(x * 255 / (width - 1)),
|
||||
cut(y * 255 / (height - 1)),
|
||||
cut((x * 7 + y * 13) % 256),
|
||||
0xff,
|
||||
]
|
||||
})
|
||||
.collect();
|
||||
entry::run(|_| {
|
||||
let format = u64::from(PixelFormat::Bgra8Unorm.metal());
|
||||
let td = no_catch(device.platform().texture_2d_descriptor(
|
||||
OnFault::Die,
|
||||
format,
|
||||
width,
|
||||
height,
|
||||
false,
|
||||
));
|
||||
td.set_usage(MTLTextureUsage::ShaderRead.0.to_u64());
|
||||
td.set_resource_options(SHARED);
|
||||
let frame = no_catch(
|
||||
device
|
||||
.core()
|
||||
.mtl_device_ref()
|
||||
.new_texture(OnFault::Die, &td),
|
||||
)
|
||||
.unwrap();
|
||||
no_catch(frame.replace_region(
|
||||
MtlRegion::new(MtlOrigin::new(0, 0, 0), MtlSize::new(width, height, 1)),
|
||||
0,
|
||||
0,
|
||||
HostRange::of_slice(&bytes),
|
||||
width * 4,
|
||||
width * 4 * height,
|
||||
));
|
||||
no_catch(display.core().present_frame(
|
||||
Hold::NONE,
|
||||
OnFault::Die,
|
||||
Some(frame),
|
||||
u32::from_be_bytes(*b"BGRA"),
|
||||
0,
|
||||
None,
|
||||
GammaTableArgs::default(),
|
||||
None,
|
||||
Box::new(|| {}),
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
/// A `CAMetalLayer` of `(width, height)` pixels at a scale of 1, in no window: what a
|
||||
/// swapchain over it sizes its images by.
|
||||
fn a_layer((width, height): (u64, u64)) -> Retained<CAMetalLayer> {
|
||||
let layer = CAMetalLayer::new();
|
||||
layer.setBounds(CGRect::new(
|
||||
CGPoint::new(0.0, 0.0),
|
||||
CGSize::new(
|
||||
f64::from(u32::try_from(width).unwrap()),
|
||||
f64::from(u32::try_from(height).unwrap()),
|
||||
),
|
||||
));
|
||||
layer.setContentsScale(1.0);
|
||||
layer
|
||||
}
|
||||
|
||||
/// A layer as the window's render thread gives it: a surface of it is made with
|
||||
/// `VK_EXT_metal_surface` (as `reims_vgpu_window`'s own target makes it).
|
||||
struct LayerTarget<'a>(&'a CAMetalLayer);
|
||||
|
||||
impl VulkanTarget for LayerTarget<'_> {
|
||||
fn create_surface(
|
||||
&self,
|
||||
get_instance_proc_addr: vk::PFN_vkGetInstanceProcAddr,
|
||||
instance: vk::Instance,
|
||||
) -> Option<vk::SurfaceKHR> {
|
||||
// SAFETY: a live instance's look-up of an instance command by its name.
|
||||
let found =
|
||||
unsafe { get_instance_proc_addr(instance, c"vkCreateMetalSurfaceEXT".as_ptr()) }?;
|
||||
// SAFETY: the command the loader answers for the name.
|
||||
let create: vk::PFN_vkCreateMetalSurfaceEXT = unsafe { std::mem::transmute(found) };
|
||||
let layer: *const c_void = std::ptr::from_ref(self.0).cast();
|
||||
let info = vk::MetalSurfaceCreateInfoEXT::default().layer(layer);
|
||||
let mut surface = vk::SurfaceKHR::null();
|
||||
// SAFETY: a valid create info naming a live layer, which outlives the surface.
|
||||
let made = unsafe { create(instance, &info, std::ptr::null(), &mut surface) };
|
||||
(made == vk::Result::SUCCESS).then_some(surface)
|
||||
}
|
||||
}
|
||||
|
||||
/// A frame drawn into a texture of the test's own, as a sink draws one into its target: the
|
||||
/// command buffer it was encoded in, once committed.
|
||||
struct Plain<'a> {
|
||||
/// The texture.
|
||||
texture: &'a Texture,
|
||||
/// The frame's command buffer.
|
||||
committed: Option<CommandBuffer>,
|
||||
}
|
||||
|
||||
impl WindowFrame<VulkanPlatform> for &mut Plain<'_> {
|
||||
fn texture(&mut self) -> Option<&Texture> {
|
||||
Some(self.texture)
|
||||
}
|
||||
|
||||
fn encoded(&mut self, command_buffer: &CommandBuffer) {
|
||||
self.committed = Some(command_buffer.clone_ref());
|
||||
}
|
||||
}
|
||||
|
||||
/// What the display's compose draws of its current frame over `region` into a private BGRA
|
||||
/// texture of `size`, a drawable's format and storage, read back.
|
||||
fn composed(
|
||||
device: &Device<VulkanPlatform>,
|
||||
display: &Display<VulkanPlatform>,
|
||||
queue: &Queue,
|
||||
size: (u64, u64),
|
||||
region: PixelRect,
|
||||
) -> Vec<u8> {
|
||||
let texture = entry::run(|_| {
|
||||
let format = u64::from(PixelFormat::Bgra8Unorm.metal());
|
||||
let td = no_catch(device.platform().texture_2d_descriptor(
|
||||
OnFault::Die,
|
||||
format,
|
||||
size.0,
|
||||
size.1,
|
||||
false,
|
||||
));
|
||||
td.set_usage(MINIMUM_TEXTURE_USAGE);
|
||||
td.set_resource_options(PRIVATE);
|
||||
no_catch(
|
||||
device
|
||||
.core()
|
||||
.mtl_device_ref()
|
||||
.new_texture(OnFault::Die, &td),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let sink = SinkDisplay::new(display.core().downgrade(), queue.clone_ref(), own_texture);
|
||||
let mut plain = Plain {
|
||||
texture: &texture,
|
||||
committed: None,
|
||||
};
|
||||
assert!(sink.encode(region, None, &mut plain), "the frame is drawn");
|
||||
assert!(plain.committed.is_some());
|
||||
read_back(queue, &texture, size)
|
||||
}
|
||||
|
||||
/// The swapchain's image of a frame is, byte for byte, what the display's compose draws into a
|
||||
/// texture of the window's size and format: a fixed frame scaled into a region of the window,
|
||||
/// its rest cleared, so the same format, colour and scaling, with no copy between. (The staging
|
||||
/// sink the swapchain replaced drew the same bytes: the comparison of the two passed before it
|
||||
/// went.) The frame is one the display draws visibly, not all the clear
|
||||
#[test]
|
||||
fn the_swapchain_holds_the_composed_frame() {
|
||||
let (device, display) = presenting_display(0x5eed_7b70);
|
||||
present_a_fixed_frame(&device, &display, (64, 40));
|
||||
let size = (61, 37);
|
||||
let region = PixelRect {
|
||||
x: 4,
|
||||
y: 3,
|
||||
width: 50,
|
||||
height: 30,
|
||||
};
|
||||
let queue = frame_queue(&device);
|
||||
let theirs = composed(&device, &display, &queue, size, region);
|
||||
|
||||
let layer = a_layer(size);
|
||||
let made = entry::run(|_| {
|
||||
// SAFETY: the target makes the surface on the instance it is given, and hands it over;
|
||||
// the layer outlives the swapchain.
|
||||
unsafe {
|
||||
Swapchain::over(&queue, |get_instance_proc_addr, instance| {
|
||||
LayerTarget(&layer).create_surface(get_instance_proc_addr, instance)
|
||||
})
|
||||
}
|
||||
});
|
||||
let mut swapchain = made.unwrap();
|
||||
let ours = draw_and_read_back(
|
||||
display.core().downgrade(),
|
||||
&queue,
|
||||
&mut swapchain,
|
||||
size,
|
||||
region,
|
||||
);
|
||||
entry::run(|_| drop(swapchain));
|
||||
drop(layer);
|
||||
|
||||
let black = [0, 0, 0, 0xff];
|
||||
assert!(
|
||||
theirs.chunks(4).any(|p| p != black),
|
||||
"the frame shows: not all the clear"
|
||||
);
|
||||
assert_eq!(ours.len(), theirs.len());
|
||||
let first = (ours.chunks(4).zip(theirs.chunks(4)))
|
||||
.position(|(a, b)| a != b)
|
||||
.map(|i| {
|
||||
(
|
||||
i % 61,
|
||||
i / 61,
|
||||
&ours[i * 4..i * 4 + 4],
|
||||
&theirs[i * 4..i * 4 + 4],
|
||||
)
|
||||
});
|
||||
assert_eq!(
|
||||
first, None,
|
||||
"the first pixel that differs: (x, y, ours, theirs)"
|
||||
);
|
||||
}
|
||||
|
||||
/// What a window frame of `size` pixels shows over `region`, read back: the display's fixed
|
||||
/// frame of `frame_size` alone, then with `cursor` drawn over it, as a sink draws it
|
||||
/// ([`SinkDisplay::encode`]).
|
||||
fn a_frame_with_the_cursor(
|
||||
serial: u32,
|
||||
frame_size: (u64, u64),
|
||||
size: (u64, u64),
|
||||
region: PixelRect,
|
||||
cursor: &reims_vgpu_window::DrawnCursor,
|
||||
) -> (Vec<u8>, Vec<u8>) {
|
||||
let (device, display) = presenting_display(serial);
|
||||
present_a_fixed_frame(&device, &display, frame_size);
|
||||
let queue = frame_queue(&device);
|
||||
let frame = composed(&device, &display, &queue, size, region);
|
||||
let texture = entry::run(|_| {
|
||||
let format = u64::from(PixelFormat::Bgra8Unorm.metal());
|
||||
let td = no_catch(device.platform().texture_2d_descriptor(
|
||||
OnFault::Die,
|
||||
format,
|
||||
size.0,
|
||||
size.1,
|
||||
false,
|
||||
));
|
||||
td.set_usage(MINIMUM_TEXTURE_USAGE);
|
||||
td.set_resource_options(PRIVATE);
|
||||
no_catch(
|
||||
device
|
||||
.core()
|
||||
.mtl_device_ref()
|
||||
.new_texture(OnFault::Die, &td),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let sink = SinkDisplay::new(display.core().downgrade(), queue.clone_ref(), own_texture);
|
||||
let mut plain = Plain {
|
||||
texture: &texture,
|
||||
committed: None,
|
||||
};
|
||||
assert!(
|
||||
sink.encode(region, Some(cursor), &mut plain),
|
||||
"the frame is drawn"
|
||||
);
|
||||
(frame, read_back(&queue, &texture, size))
|
||||
}
|
||||
|
||||
/// Pixel `(x, y)` of `bytes`, rows of `width` BGRA pixels.
|
||||
fn pixel(bytes: &[u8], width: u64, (x, y): (u64, u64)) -> [u8; 4] {
|
||||
let i = usize::try_from((y * width + x) * 4).unwrap();
|
||||
bytes[i..i + 4].try_into().unwrap()
|
||||
}
|
||||
|
||||
/// Four rows of four: opaque red, opaque green, blue at alpha 0x80, white at alpha 0.
|
||||
const ROWS: [[u8; 4]; 4] = [
|
||||
[0xff, 0, 0, 0xff],
|
||||
[0, 0xff, 0, 0xff],
|
||||
[0, 0, 0xff, 0x80],
|
||||
[0xff, 0xff, 0xff, 0],
|
||||
];
|
||||
|
||||
/// The cursor of [`ROWS`]'s glyph, its hot spot at `hot_spot`, at `at` in a mode of 64 by 40.
|
||||
fn rows_cursor(hot_spot: (u16, u16), at: (u16, u16)) -> reims_vgpu_window::DrawnCursor {
|
||||
reims_vgpu_window::DrawnCursor {
|
||||
glyph: Arc::new(reims_vgpu_window::Glyph {
|
||||
width: 4,
|
||||
height: 4,
|
||||
hot_spot,
|
||||
rgba: ROWS.iter().flat_map(|row| row.repeat(4)).collect(),
|
||||
}),
|
||||
mode: (64, 40),
|
||||
at,
|
||||
}
|
||||
}
|
||||
|
||||
/// `drawn` is `frame`, of `size` pixels, with [`ROWS`]'s glyph over it a pixel to a pixel, its
|
||||
/// top left at `(left, top)`, wherever it lies inside `region`, each pixel over the frame by the
|
||||
/// glyph's alpha (opaque rows the glyph's colour, a half-transparent row half over the frame, a
|
||||
/// transparent row the frame's, whatever its colour bytes); everywhere else it is `frame`.
|
||||
fn assert_rows_over(
|
||||
frame: &[u8],
|
||||
drawn: &[u8],
|
||||
size: (u64, u64),
|
||||
region: PixelRect,
|
||||
(left, top): (i64, i64),
|
||||
) {
|
||||
for y in 0..size.1 {
|
||||
for x in 0..size.0 {
|
||||
let (under, got) = (pixel(frame, size.0, (x, y)), pixel(drawn, size.0, (x, y)));
|
||||
let in_region = (region.x..region.x + region.width).contains(&x)
|
||||
&& (region.y..region.y + region.height).contains(&y);
|
||||
let (gx, gy) = (
|
||||
i64::try_from(x).unwrap() - left,
|
||||
i64::try_from(y).unwrap() - top,
|
||||
);
|
||||
if !(in_region && (0..4).contains(&gx) && (0..4).contains(&gy)) {
|
||||
assert_eq!(got, under, "outside the glyph, ({x}, {y})");
|
||||
continue;
|
||||
}
|
||||
let [r, g, b, a] = ROWS[usize::try_from(gy).unwrap()];
|
||||
// The target is BGRA; each channel the glyph's over the frame's by the glyph's alpha.
|
||||
let over = |glyph: u8, frame: u8| {
|
||||
(f64::from(glyph) * f64::from(a) + f64::from(frame) * f64::from(255 - a)) / 255.0
|
||||
};
|
||||
for (channel, (want, have)) in [over(b, under[0]), over(g, under[1]), over(r, under[2])]
|
||||
.into_iter()
|
||||
.zip(got)
|
||||
.enumerate()
|
||||
{
|
||||
assert!(
|
||||
(want - f64::from(have)).abs() <= 1.0,
|
||||
"({x}, {y}) channel {channel}: {have} for {want:.1}, over {under:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The guest's cursor, drawn over a frame where the window draws it: its hot spot at the guest's
|
||||
/// position, a glyph pixel to a guest pixel at a 1:1 image, each pixel over the frame by its
|
||||
/// alpha, and the rest of the frame untouched ([`assert_rows_over`])
|
||||
#[test]
|
||||
fn the_guest_s_cursor_is_drawn_over_the_frame_by_its_alpha() {
|
||||
let size = (64, 40);
|
||||
let region = PixelRect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
};
|
||||
let cursor = rows_cursor((1, 1), (10, 20));
|
||||
let (frame, drawn) = a_frame_with_the_cursor(0x5eed_7b71, size, size, region, &cursor);
|
||||
// The glyph's top left is the hot spot's place less the hot spot: (9, 19).
|
||||
assert_rows_over(&frame, &drawn, size, region, (9, 19));
|
||||
}
|
||||
|
||||
/// In an image letterboxed in the window, the glyph is placed from the image's top left, and a
|
||||
/// glyph past the image's top left edge is clipped there: the bars beside it keep the frame's
|
||||
/// clear, though the glyph's viewport reaches over them
|
||||
#[test]
|
||||
fn the_guest_s_cursor_is_clipped_to_a_letterboxed_image() {
|
||||
let size = (80, 50);
|
||||
let region = PixelRect {
|
||||
x: 6,
|
||||
y: 4,
|
||||
width: 64,
|
||||
height: 40,
|
||||
};
|
||||
let cursor = rows_cursor((1, 1), (0, 0));
|
||||
let (frame, drawn) = a_frame_with_the_cursor(0x5eed_7b73, (64, 40), size, region, &cursor);
|
||||
// The glyph's top left is (6 - 1, 4 - 1); its first row and column fall on the bars.
|
||||
assert_rows_over(&frame, &drawn, size, region, (5, 3));
|
||||
assert_ne!(
|
||||
pixel(&drawn, size.0, (6, 4)),
|
||||
pixel(&frame, size.0, (6, 4)),
|
||||
"the glyph's second row and column, inside the image"
|
||||
);
|
||||
}
|
||||
|
||||
/// Where the image scales the glyph, its filtered edge is the glyph's coverage of the frame: at
|
||||
/// 2 pixels a guest pixel, an opaque white texel beside a transparent black one gives the pixels
|
||||
/// between them a quarter and three quarters of white over the frame, not the darker values
|
||||
/// filtering straight alpha would give (9/16 and 1/16 of white)
|
||||
#[test]
|
||||
fn a_scaled_glyph_s_edges_are_its_coverage_of_white() {
|
||||
use reims_vgpu_window::{DrawnCursor, Glyph};
|
||||
|
||||
let size = (128, 80);
|
||||
let region = PixelRect {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: size.0,
|
||||
height: size.1,
|
||||
};
|
||||
let cursor = DrawnCursor {
|
||||
glyph: Arc::new(Glyph {
|
||||
width: 2,
|
||||
height: 1,
|
||||
hot_spot: (0, 0),
|
||||
rgba: vec![0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0],
|
||||
}),
|
||||
mode: (64, 40),
|
||||
at: (10, 20),
|
||||
};
|
||||
let (frame, drawn) = a_frame_with_the_cursor(0x5eed_7b72, (64, 40), size, region, &cursor);
|
||||
// The glyph covers pixels 20..24 of rows 40 and 41; the samples of the pixels between its
|
||||
// texels' centres weigh the white texel 3/4 (x 21) and 1/4 (x 22).
|
||||
for y in [40, 41] {
|
||||
for (x, white) in [(20, 1.0), (21, 0.75), (22, 0.25), (23, 0.0)] {
|
||||
let (under, got) = (pixel(&frame, size.0, (x, y)), pixel(&drawn, size.0, (x, y)));
|
||||
for (channel, (&have, &frame)) in got.iter().zip(&under).take(3).enumerate() {
|
||||
let want = 255.0 * white + f64::from(frame) * (1.0 - white);
|
||||
assert!(
|
||||
(want - f64::from(have)).abs() <= 2.0,
|
||||
"({x}, {y}) channel {channel}: {have} for {want:.1}, over {under:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (x, y) in [(19, 40), (24, 40), (20, 39), (20, 42)] {
|
||||
assert_eq!(
|
||||
pixel(&drawn, size.0, (x, y)),
|
||||
pixel(&frame, size.0, (x, y)),
|
||||
"outside the glyph, ({x}, {y})"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,346 +0,0 @@
|
||||
//! [`SwapchainSink`]: what draws a window display's frames on the Vulkan platform, on either OS,
|
||||
//! into the window's swapchain on the runtime's own device, with no copy.
|
||||
//!
|
||||
//! The window's render thread asks the sink for a presenter at its first draw: the sink makes the
|
||||
//! window's Vulkan surface on the runtime's instance (through the window's [`VulkanTarget`]: SDL's
|
||||
//! window on Linux, the window's `CAMetalLayer` on macOS) and a swapchain over it, presented on a
|
||||
//! presenting queue of the swapchain's own, apart from the guest's queues where the device has one
|
||||
//! to spare (`reims_vgpu_vulkan::swapchain`). Each draw then takes the swapchain's next image, has
|
||||
//! the display draw its current frame into the image's texture in a command buffer of the frame
|
||||
//! queue, as any window frame ([`SinkDisplay::encode`]), with the image's semaphore signalled
|
||||
//! after it, and presents the image once the runtime has scheduled that command buffer. The
|
||||
//! image's wait is the render thread's alone: the frame's command buffer waits for nothing of the
|
||||
//! compositor's, so the guest's frames never wait for the window. Where the swapchain's images are
|
||||
//! not the window's size (a surface with a size of its own, a step ahead of the window's during a
|
||||
//! resize), the frame's region is scaled to them ([`fit`]). On macOS the images are the layer's
|
||||
//! drawables, each fetched on the render thread as the image is taken
|
||||
//! (`reims_vgpu_vulkan::swapchain`), and no Metal call of the sink's draws or presents them.
|
||||
//!
|
||||
//! What each OS's window asks of the sink is its own (`FrameSink`): `linux.rs` and `macos.rs`
|
||||
//! give it the presenter made here ([`SwapchainSink::make_presenter`]).
|
||||
//!
|
||||
//! **Lifetime.** The display is held weakly, as the Metal platform's sink holds it, and upgraded
|
||||
//! for an encode and its commit alone. A presenter holds the frame queue, and with it the
|
||||
//! display's device, until the window's render thread ends at the window's end: its swapchain and
|
||||
//! surface go there, before the window under them.
|
||||
//!
|
||||
//! **Statistics.** With `REIMS_VGPU_STATS` on, each frame committed counts as a window frame, as
|
||||
//! every sink's does, and its command buffer's GPU time is the window's ([`crate::stats`]).
|
||||
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use reims_vgpu_core::display::Display as CoreDisplay;
|
||||
use reims_vgpu_core::platform::{Handle as _, Platform};
|
||||
use reims_vgpu_vulkan::VulkanPlatform;
|
||||
use reims_vgpu_vulkan::swapchain::{self, Acquired, Frame, Swapchain};
|
||||
use reims_vgpu_window::{Drawn, DrawnCursor, FrameSink, PixelRect, Presenter, VulkanTarget};
|
||||
|
||||
use crate::entry;
|
||||
use crate::stats::DisplayStats;
|
||||
use crate::window::{SinkDisplay, WindowFrame};
|
||||
|
||||
/// The platform's command queue.
|
||||
type Queue = <VulkanPlatform as Platform>::CommandQueue;
|
||||
/// Its command buffer.
|
||||
type CommandBuffer = <VulkanPlatform as Platform>::CommandBuffer;
|
||||
/// Its texture.
|
||||
type Texture = <VulkanPlatform as Platform>::Texture;
|
||||
|
||||
/// The sink of a window display on `display`, drawn in command buffers of `queue`, the frame
|
||||
/// queue of its device.
|
||||
pub(crate) fn sink(
|
||||
platform: Arc<VulkanPlatform>,
|
||||
display: Weak<CoreDisplay<VulkanPlatform>>,
|
||||
queue: Queue,
|
||||
) -> Option<Arc<dyn FrameSink>> {
|
||||
drop(platform);
|
||||
let port = display.upgrade().map(|d| d.port());
|
||||
let sink: Arc<dyn FrameSink> = Arc::new(SwapchainSink {
|
||||
display: Arc::new(SinkDisplay::new(display, queue.clone_ref(), own_texture)),
|
||||
queue,
|
||||
port,
|
||||
});
|
||||
Some(sink)
|
||||
}
|
||||
|
||||
/// The guest's cursor glyph's texture on the Vulkan platform: one of the platform's own, which
|
||||
/// takes no resource ID and no range of Metal's space (`VulkanDevice::new_own_texture`), so no
|
||||
/// address or ID the guest reads moves for it.
|
||||
pub(in crate::window::vulkan) fn own_texture(
|
||||
device: &<VulkanPlatform as Platform>::Device,
|
||||
descriptor: &<VulkanPlatform as Platform>::TextureDescriptor,
|
||||
) -> Option<Texture> {
|
||||
device.new_own_texture(descriptor)
|
||||
}
|
||||
|
||||
/// What draws a display's current frame into its window on the Vulkan platform (module doc).
|
||||
pub(crate) struct SwapchainSink {
|
||||
/// The display, held only for a draw, and the frame queue; shared with the presenters.
|
||||
display: Arc<SinkDisplay<VulkanPlatform>>,
|
||||
/// The frame queue, of whose device the swapchain makes its presenting queue.
|
||||
queue: Queue,
|
||||
/// The display's port, which names its window in the log.
|
||||
port: Option<u64>,
|
||||
}
|
||||
|
||||
impl SwapchainSink {
|
||||
/// The guest's cursor position, as the display reads it now ([`SinkDisplay::cursor_position`]).
|
||||
pub(crate) fn cursor_position(&self) -> Option<(u16, u16)> {
|
||||
entry::run(|_| self.display.cursor_position())
|
||||
}
|
||||
|
||||
/// The window's surface on the runtime's instance, and a swapchain over it; none where either
|
||||
/// is refused, which is logged, as are the present mode a swapchain takes, MAILBOX where the
|
||||
/// surface offers it, else FIFO, and whether its presents signal fences
|
||||
/// (`reims_vgpu_vulkan::swapchain`).
|
||||
pub(crate) fn make_presenter(&self, target: &dyn VulkanTarget) -> Option<Box<dyn Presenter>> {
|
||||
// SAFETY: the target makes the surface on the instance it is given, and hands it over.
|
||||
let made = entry::run(|_| unsafe {
|
||||
Swapchain::over(&self.queue, |get_instance_proc_addr, instance| {
|
||||
target.create_surface(get_instance_proc_addr, instance)
|
||||
})
|
||||
});
|
||||
match made {
|
||||
Ok(swapchain) => {
|
||||
log::info!(
|
||||
target: "reims_vgpu::window",
|
||||
"the window of the display on port {} presents with {}, {}",
|
||||
self.port.map_or_else(|| "?".to_owned(), |p| p.to_string()),
|
||||
if swapchain.is_mailbox() { "MAILBOX" } else { "FIFO" },
|
||||
if swapchain.has_present_fences() {
|
||||
"each present fenced"
|
||||
} else {
|
||||
"with no present fences"
|
||||
}
|
||||
);
|
||||
Some(Box::new(SwapchainPresenter {
|
||||
display: Arc::clone(&self.display),
|
||||
swapchain,
|
||||
}))
|
||||
}
|
||||
Err(refused) => {
|
||||
log::warn!(
|
||||
target: "reims_vgpu::window",
|
||||
"no swapchain for the window ({refused}): it stays empty"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A window's presenter: the display and the window's swapchain, on its render thread.
|
||||
struct SwapchainPresenter {
|
||||
/// The display and the frame queue.
|
||||
display: Arc<SinkDisplay<VulkanPlatform>>,
|
||||
/// The swapchain.
|
||||
swapchain: Swapchain,
|
||||
}
|
||||
|
||||
impl Presenter for SwapchainPresenter {
|
||||
/// The next image, the display's frame encoded into it with `cursor` over it, and its
|
||||
/// present (module doc).
|
||||
fn draw(
|
||||
&mut self,
|
||||
drawable: (u64, u64),
|
||||
region: PixelRect,
|
||||
cursor: Option<&DrawnCursor>,
|
||||
) -> Drawn {
|
||||
entry::run(|_| {
|
||||
let frame = match self.swapchain.acquire(drawable) {
|
||||
Acquired::Image(frame) => frame,
|
||||
Acquired::Retry => return Drawn::Retry,
|
||||
Acquired::Failed => return Drawn::Ended,
|
||||
};
|
||||
let region = self
|
||||
.swapchain
|
||||
.extent()
|
||||
.map_or(region, |extent| fit(region, drawable, extent));
|
||||
let mut image = ImageFrame {
|
||||
swapchain: &self.swapchain,
|
||||
frame,
|
||||
stats: self.display.stats(),
|
||||
ready: None,
|
||||
};
|
||||
if !self.display.encode(region, cursor, &mut image) {
|
||||
return Drawn::Nothing;
|
||||
}
|
||||
let Some(command_buffer) = image.ready else {
|
||||
return Drawn::Nothing;
|
||||
};
|
||||
self.swapchain.present(frame, command_buffer);
|
||||
Drawn::Presented
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `region` of a drawable of `drawable` pixels, scaled to one of `extent` pixels and kept within
|
||||
/// it: the swapchain's images can be another size than the window's ([`Swapchain::extent`]).
|
||||
fn fit(region: PixelRect, drawable: (u64, u64), extent: (u64, u64)) -> PixelRect {
|
||||
if drawable == extent || drawable.0 == 0 || drawable.1 == 0 {
|
||||
return region;
|
||||
}
|
||||
// Pixel counts are far below 2^32, so the products fit, and the rounding is to the nearest.
|
||||
let scale = |v: u64, from: u64, to: u64| (v.saturating_mul(to) + from / 2) / from;
|
||||
let x = scale(region.x, drawable.0, extent.0).min(extent.0);
|
||||
let y = scale(region.y, drawable.1, extent.1).min(extent.1);
|
||||
PixelRect {
|
||||
x,
|
||||
y,
|
||||
width: scale(region.width, drawable.0, extent.0).min(extent.0 - x),
|
||||
height: scale(region.height, drawable.1, extent.1).min(extent.1 - y),
|
||||
}
|
||||
}
|
||||
|
||||
/// One window frame into a swapchain image.
|
||||
struct ImageFrame<'a> {
|
||||
/// The swapchain.
|
||||
swapchain: &'a Swapchain,
|
||||
/// The image taken.
|
||||
frame: Frame,
|
||||
/// The display's statistics, where they are on.
|
||||
stats: Option<&'a Arc<DisplayStats>>,
|
||||
/// The frame's command buffer, once the image's semaphore is signalled in it: the image is
|
||||
/// presented only then.
|
||||
ready: Option<CommandBuffer>,
|
||||
}
|
||||
|
||||
impl WindowFrame<VulkanPlatform> for &mut ImageFrame<'_> {
|
||||
/// The image's texture.
|
||||
fn texture(&mut self) -> Option<&Texture> {
|
||||
self.swapchain.texture(self.frame)
|
||||
}
|
||||
|
||||
/// Signals the image's semaphore after the frame, and has its GPU time reported.
|
||||
fn encoded(&mut self, command_buffer: &CommandBuffer) {
|
||||
if !self.swapchain.encode_ready(self.frame, command_buffer) {
|
||||
return;
|
||||
}
|
||||
if let Some(stats) = self.stats {
|
||||
let stats = Arc::clone(stats);
|
||||
swapchain::report_gpu_time(command_buffer, move |time| stats.window_gpu_time(time));
|
||||
}
|
||||
self.ready = Some(command_buffer.clone_ref());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The bytes of `texture`, `size` pixels of a 4-byte format, once the work committed before
|
||||
/// on `queue` has completed: a blit into a shared buffer, committed and waited for. Rows of
|
||||
/// `size.0 * 4` bytes.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::window::vulkan) fn read_back(
|
||||
queue: &Queue,
|
||||
texture: &Texture,
|
||||
size: (u64, u64),
|
||||
) -> Vec<u8> {
|
||||
use reims_vgpu_core::platform::blit::{BlitCmd, BlitEncoder as _};
|
||||
use reims_vgpu_core::platform::command::{CommandBuffer as _, CommandQueue as _};
|
||||
use reims_vgpu_core::platform::device::GpuDevice as _;
|
||||
use reims_vgpu_core::platform::resource::Buffer as _;
|
||||
use reims_vgpu_core::platform::types::{MtlOrigin, MtlSize};
|
||||
use reims_vgpu_core::raise::OnFault;
|
||||
|
||||
use crate::display::no_catch;
|
||||
|
||||
entry::run(|_| {
|
||||
let length = size.0 * size.1 * 4;
|
||||
let buffer =
|
||||
no_catch(queue.device.new_buffer_of_length(OnFault::Die, length, 0)).unwrap();
|
||||
let copy = no_catch(queue.command_buffer(OnFault::Die)).unwrap();
|
||||
let blit = no_catch(copy.blit_encoder(OnFault::Die)).unwrap();
|
||||
no_catch(blit.encode(
|
||||
OnFault::Die,
|
||||
BlitCmd::CopyTextureToBuffer {
|
||||
source_texture: texture,
|
||||
source_slice: 0,
|
||||
source_level: 0,
|
||||
source_origin: MtlOrigin::new(0, 0, 0),
|
||||
source_size: MtlSize::new(size.0, size.1, 1),
|
||||
destination_buffer: &buffer,
|
||||
destination_offset: 0,
|
||||
destination_bytes_per_row: size.0 * 4,
|
||||
destination_bytes_per_image: length,
|
||||
},
|
||||
));
|
||||
no_catch(blit.encode(OnFault::Die, BlitCmd::EndEncoding));
|
||||
no_catch(copy.commit(OnFault::Die));
|
||||
no_catch(copy.wait_until_completed(OnFault::Die));
|
||||
// SAFETY: the buffer is shared, `length` bytes long, and the copy into it has
|
||||
// completed.
|
||||
unsafe {
|
||||
std::slice::from_raw_parts(
|
||||
buffer.contents().as_ptr::<u8>(),
|
||||
usize::try_from(length).unwrap(),
|
||||
)
|
||||
}
|
||||
.to_vec()
|
||||
})
|
||||
}
|
||||
|
||||
/// Draws `display`'s current frame over `region` into the next image of `swapchain`, made
|
||||
/// for a window of `size` pixels, in a command buffer of `queue`, as a presenter's draw
|
||||
/// does, then reads the image back ([`read_back`]) before it is presented. The swapchain's
|
||||
/// pixels, for a test's comparison (`macos.rs`).
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::window::vulkan) fn draw_and_read_back(
|
||||
display: Weak<CoreDisplay<VulkanPlatform>>,
|
||||
queue: &Queue,
|
||||
swapchain: &mut Swapchain,
|
||||
size: (u64, u64),
|
||||
region: PixelRect,
|
||||
) -> Vec<u8> {
|
||||
entry::run(|_| {
|
||||
let Acquired::Image(frame) = swapchain.acquire(size) else {
|
||||
panic!("no image of the swapchain");
|
||||
};
|
||||
let sink = SinkDisplay::new(display, queue.clone_ref(), super::own_texture);
|
||||
let mut image = ImageFrame {
|
||||
swapchain,
|
||||
frame,
|
||||
stats: None,
|
||||
ready: None,
|
||||
};
|
||||
assert!(sink.encode(region, None, &mut image), "the frame is drawn");
|
||||
let command_buffer = image.ready.take().unwrap();
|
||||
let bytes = read_back(queue, swapchain.texture(frame).unwrap(), size);
|
||||
swapchain.present(frame, command_buffer);
|
||||
bytes
|
||||
})
|
||||
}
|
||||
|
||||
/// A rectangle.
|
||||
fn rect(x: u64, y: u64, width: u64, height: u64) -> PixelRect {
|
||||
PixelRect {
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
}
|
||||
}
|
||||
|
||||
/// The region is the window's where the images are the window's size
|
||||
#[test]
|
||||
fn the_region_stays_where_the_images_are_the_windows_size() {
|
||||
let region = rect(10, 20, 300, 200);
|
||||
assert_eq!(fit(region, (320, 240), (320, 240)), region);
|
||||
}
|
||||
|
||||
/// The region scales with the images where they are another size, and stays within them
|
||||
#[test]
|
||||
fn the_region_scales_to_images_of_another_size() {
|
||||
assert_eq!(
|
||||
fit(rect(100, 0, 800, 600), (1000, 600), (500, 300)),
|
||||
rect(50, 0, 400, 300)
|
||||
);
|
||||
assert_eq!(
|
||||
fit(rect(0, 0, 1000, 600), (1000, 600), (1001, 601)),
|
||||
rect(0, 0, 1001, 601)
|
||||
);
|
||||
let within = fit(rect(999, 599, 1, 1), (1000, 600), (10, 10));
|
||||
assert!(within.x + within.width <= 10 && within.y + within.height <= 10);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user