diff --git a/wgpu-hal/Cargo.toml b/wgpu-hal/Cargo.toml index e0c079f96..da99cb126 100644 --- a/wgpu-hal/Cargo.toml +++ b/wgpu-hal/Cargo.toml @@ -76,6 +76,7 @@ metal = [ "dep:arrayvec", "dep:block2", "dep:bytemuck", + "dep:libloading", "dep:objc2", "dep:objc2-core-foundation", "dep:objc2-core-graphics", diff --git a/wgpu-hal/src/metal/surface.rs b/wgpu-hal/src/metal/surface.rs index 87eac95f0..f8028a4f3 100644 --- a/wgpu-hal/src/metal/surface.rs +++ b/wgpu-hal/src/metal/surface.rs @@ -1,3 +1,5 @@ +use std::sync::LazyLock; + use alloc::borrow::ToOwned as _; use objc2::{ @@ -204,6 +206,42 @@ impl super::Surface { } } +// objc2 strings are not, in general, thread-safe, but these should be constants. +unsafe impl Send for ColorSpaces {} +unsafe impl Sync for ColorSpaces {} + +struct ColorSpaces { + extended_display_p3: &'static CFString, + itur_bt2100_pq: &'static CFString, + itur_bt2100_hlg: &'static CFString, +} + +static COLOR_SPACES: LazyLock> = LazyLock::new(|| { + // Stable Rust doesn't support weak linkage, so objc2 doesn't + // offer it. To avoid link errors on old OS versions, resolve + // these dynamically. + let lib = unsafe { + libloading::Library::new("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics") + .map_err(|_| crate::SurfaceError::Other("error loading CoreGraphics"))? + }; + fn lookup( + lib: &libloading::Library, + name: &[u8], + ) -> Result<&'static CFString, crate::SurfaceError> { + let sym = unsafe { lib.get(name) } + .map_err(|_| crate::SurfaceError::Other("error resolving symbol in CoreGraphics"))?; + Ok(*sym) + } + let extended_display_p3 = lookup(&lib, b"kCGColorSpaceExtendedDisplayP3\0")?; + let itur_bt2100_pq = lookup(&lib, b"kCGColorSpaceITUR_2100_PQ\0")?; + let itur_bt2100_hlg = lookup(&lib, b"kCGColorSpaceITUR_2100_HLG\0")?; + Ok(ColorSpaces { + extended_display_p3, + itur_bt2100_pq, + itur_bt2100_hlg, + }) +}); + impl crate::Surface for super::Surface { type A = super::Api; @@ -258,7 +296,13 @@ impl crate::Surface for super::Surface { Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedSRGB }) } wgt::SurfaceColorSpace::ExtendedDisplayP3 => { - Some(unsafe { objc2_core_graphics::kCGColorSpaceExtendedDisplayP3 }) + // TODO: This needs protection in `surface_capabilities` like the BT.2100 cases. + Some( + COLOR_SPACES + .as_ref() + .map_err(|e| e.clone())? + .extended_display_p3, + ) } wgt::SurfaceColorSpace::DisplayP3 => { Some(unsafe { objc2_core_graphics::kCGColorSpaceDisplayP3 }) @@ -270,9 +314,12 @@ impl crate::Surface for super::Surface { unreachable!("BT.2100 PQ/HLG color spaces are only reported on macOS 11.0+/iOS 14.0+/tvOS 14.0+"); } Some(if config.color_space == wgt::SurfaceColorSpace::Bt2100Pq { - unsafe { objc2_core_graphics::kCGColorSpaceITUR_2100_PQ } + COLOR_SPACES.as_ref().map_err(|e| e.clone())?.itur_bt2100_pq } else { - unsafe { objc2_core_graphics::kCGColorSpaceITUR_2100_HLG } + COLOR_SPACES + .as_ref() + .map_err(|e| e.clone())? + .itur_bt2100_hlg }) } };