Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(camera-effects): segment with Apple Vision person masks and refine edges with a guided filter

Richie McIlroya6600f37ba25
diff --git a/Cargo.lock b/Cargo.lock
index af9f16909..f059b7eff 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1402,6 +1402,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
+ "cidre",
+ "libc",
"libloading 0.9.0",
"ndarray 0.16.1",
"ort",
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 87e0401cb..9be0e0e0a 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1441,6 +1441,8 @@ version = "0.1.0"
dependencies = [
"anyhow",
"bytemuck",
+ "cidre",
+ "libc",
"libloading 0.9.0",
"ndarray 0.16.1",
"ort",
diff --git a/crates/camera-effects/Cargo.toml b/crates/camera-effects/Cargo.toml
index d8f8c2582..90a21244a 100644
--- a/crates/camera-effects/Cargo.toml
+++ b/crates/camera-effects/Cargo.toml
@@ -27,6 +27,8 @@ ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "n
ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "ndarray", "download-binaries", "copy-dylibs", "tls-native"] }
[target.'cfg(target_os = "macos")'.dependencies]
+cidre = { workspace = true }
+libc = "0.2"
ort = { version = "2.0.0-rc.12", default-features = false, features = ["std", "ndarray", "load-dynamic", "coreml", "api-23"] }
[target.'cfg(target_os = "windows")'.dependencies]
diff --git a/crates/camera-effects/src/blur_pipeline.rs b/crates/camera-effects/src/blur_pipeline.rs
index 64a21b07f..ff99aab8e 100644
--- a/crates/camera-effects/src/blur_pipeline.rs
+++ b/crates/camera-effects/src/blur_pipeline.rs
@@ -253,6 +253,7 @@ pub struct CompositePassInputs<'a> {
pub sharp: &'a wgpu::TextureView,
pub blurred: &'a wgpu::TextureView,
pub mask: &'a wgpu::TextureView,
+ pub matte: &'a wgpu::TextureView,
pub output: &'a wgpu::TextureView,
}
@@ -302,6 +303,16 @@ impl CompositePipeline {
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
+ wgpu::BindGroupLayoutEntry {
+ binding: 4,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable: true },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ },
],
});
@@ -397,6 +408,7 @@ impl CompositePipeline {
sharp: sharp_view,
blurred: blurred_view,
mask: mask_view,
+ matte: matte_view,
output: output_view,
} = inputs;
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -419,6 +431,10 @@ impl CompositePipeline {
binding: 3,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
+ wgpu::BindGroupEntry {
+ binding: 4,
+ resource: wgpu::BindingResource::TextureView(matte_view),
+ },
],
});
diff --git a/crates/camera-effects/src/gpu_tests.rs b/crates/camera-effects/src/gpu_tests.rs
index f8b5eaecc..7fd436b7e 100644
--- a/crates/camera-effects/src/gpu_tests.rs
+++ b/crates/camera-effects/src/gpu_tests.rs
@@ -90,13 +90,17 @@ async fn effects_preserve_foreground_alpha_and_suppress_background_detail() {
processor.set_frame_synchronous(true);
processor.inference_requested = false;
processor.mask_initialized = true;
- for (index, mask) in processor.mask_data.iter_mut().enumerate() {
- *mask = if index % SEGMENTATION_SIZE as usize > SEGMENTATION_SIZE as usize / 2 {
- 1.0
- } else {
- 0.0
- };
- }
+ processor.mask_dimensions = (SEGMENTATION_SIZE, SEGMENTATION_SIZE);
+ processor.mask_bytes = (0..SEGMENTATION_SIZE * SEGMENTATION_SIZE)
+ .map(|index| {
+ if index % SEGMENTATION_SIZE > SEGMENTATION_SIZE / 2 {
+ 255
+ } else {
+ 0
+ }
+ })
+ .collect();
+ processor.mask_dirty = true;
let mut blurred = Vec::new();
for mode in [
BlurMode::Remove,
@@ -138,33 +142,16 @@ async fn effects_preserve_foreground_alpha_and_suppress_background_detail() {
blurred[1] < blurred[0] * 0.25,
"Heavy should remove more detail than Light: {blurred:?}"
);
- for (index, mask) in processor.mask_data.iter_mut().enumerate() {
- let x = index % SEGMENTATION_SIZE as usize;
- let y = index / SEGMENTATION_SIZE as usize;
- *mask = if x > 80 + y / 3 { 1.0 } else { 0.0 };
- }
- processor.mask_dirty = true;
- let output = processor.process(&device, &queue, &input, BlurMode::Remove);
- let diagonal = read_output(&device, &queue, output).await;
- for row in diagonal
- .chunks_exact(width as usize * 4)
- .skip(40)
- .take(height as usize - 80)
- {
- let alpha: Vec<_> = row.chunks_exact(4).map(|pixel| pixel[3]).collect();
- let transition_pixels = alpha
- .iter()
- .filter(|&&value| value > 8 && value < 247)
- .count();
- assert!((3..=12).contains(&transition_pixels));
- assert!(
- alpha
- .windows(2)
- .all(|pair| pair[0].abs_diff(pair[1]) <= 100)
- );
- }
+ // A soft mask edge a few pixels off a hard colour edge: the guided
+ // filter must pull the matte onto the colour edge and keep it sharp.
for pixel in pixels.chunks_exact_mut(4) {
- pixel.copy_from_slice(&[80, 80, 80, 255]);
+ pixel.copy_from_slice(&[40, 60, 200, 255]);
+ }
+ let colour_edge = width * 3 / 5;
+ for row in pixels.chunks_exact_mut(width as usize * 4) {
+ for pixel in row.chunks_exact_mut(4).skip(colour_edge as usize) {
+ pixel.copy_from_slice(&[230, 180, 140, 255]);
+ }
}
queue.write_texture(
input.as_image_copy(),
@@ -176,22 +163,42 @@ async fn effects_preserve_foreground_alpha_and_suppress_background_detail() {
},
input.size(),
);
+ let mask_edge = (colour_edge - 3) as f32 / width as f32;
+ processor.mask_bytes = (0..SEGMENTATION_SIZE * SEGMENTATION_SIZE)
+ .map(|index| {
+ let x = (index % SEGMENTATION_SIZE) as f32 / SEGMENTATION_SIZE as f32;
+ (((x - mask_edge) * 40.0 + 0.5).clamp(0.0, 1.0) * 255.0) as u8
+ })
+ .collect();
+ processor.mask_dirty = true;
let output = processor.process(&device, &queue, &input, BlurMode::Remove);
- let flat_color = read_output(&device, &queue, output).await;
- assert!(
- diagonal
- .chunks_exact(4)
- .zip(flat_color.chunks_exact(4))
- .all(|(before, after)| before[3] == after[3]),
- "Camera texture must not add jagged detail to the cutout contour"
- );
+ let snapped = read_output(&device, &queue, output).await;
+ for row in snapped
+ .chunks_exact(width as usize * 4)
+ .skip(40)
+ .take(height as usize - 80)
+ {
+ let alpha: Vec<_> = row.chunks_exact(4).map(|pixel| pixel[3]).collect();
+ let transition = alpha.iter().position(|&value| value >= 128).unwrap() as i32;
+ assert!(
+ (transition - colour_edge as i32).abs() <= 2,
+ "matte edge at {transition}, colour edge at {colour_edge}"
+ );
+ let soft = alpha
+ .iter()
+ .filter(|&&value| value > 8 && value < 247)
+ .count();
+ // The mask ramps over 16 pixels; the matte must be far tighter.
+ assert!(soft <= 6, "matte edge spread over {soft} pixels");
+ }
processor.frame_time = Some(1.0);
processor.inference_requested = false;
processor.set_frame_time(1.0);
assert!(!processor.inference_requested);
processor.set_frame_time(1.0 + 1.0 / 30.0);
assert!(processor.inference_requested);
- let readback_pointer = processor.readback_pixels.as_ptr();
+ let readback_dimensions = processor.segmenter.input_dimensions(width, height);
+ let mut readback_pointer = None;
for value in [80, 160] {
for pixel in pixels.chunks_exact_mut(4) {
pixel.copy_from_slice(&[value, value, value, 255]);
@@ -211,8 +218,14 @@ async fn effects_preserve_foreground_alpha_and_suppress_background_detail() {
.readback_downsampled(&device, &queue, &input, true)
.is_some()
);
- assert_eq!(processor.readback_pixels.as_ptr(), readback_pointer);
- assert_eq!(processor.readback_pixels.len(), 256 * 256 * 4);
+ assert_eq!(
+ *readback_pointer.get_or_insert(processor.readback_pixels.as_ptr()),
+ processor.readback_pixels.as_ptr()
+ );
+ assert_eq!(
+ processor.readback_pixels.len(),
+ (readback_dimensions.0 * readback_dimensions.1 * 4) as usize
+ );
assert!(
processor
.readback_pixels
diff --git a/crates/camera-effects/src/lib.rs b/crates/camera-effects/src/lib.rs
index 1b047957e..5de23cddf 100644
--- a/crates/camera-effects/src/lib.rs
+++ b/crates/camera-effects/src/lib.rs
@@ -2,7 +2,10 @@ mod blur_pipeline;
#[cfg(test)]
mod gpu_tests;
mod mask_refinement;
+mod matte;
mod segmentation;
+#[cfg(target_os = "macos")]
+mod vision;
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
use std::sync::{Arc, OnceLock};
@@ -12,6 +15,7 @@ use blur_pipeline::{BlurPassInputs, BlurPipeline, CompositePassInputs, Composite
use mask_refinement::MaskRefiner;
#[cfg(test)]
use mask_refinement::smooth_mask_value;
+use matte::{MattePipeline, MatteTextures};
use segmentation::SegmentationModel;
#[cfg(any(target_os = "macos", target_os = "linux", target_os = "windows"))]
@@ -247,6 +251,119 @@ fn validate_mask_samples(mask: &[f32], expected_samples: usize) -> Result<(), Bl
struct ReadbackFrame {
submitted_at: Instant,
dimensions: (u32, u32),
+ input_dimensions: (u32, u32),
+}
+
+struct OnnxSegmenter {
+ model: SegmentationModel,
+ refiner: MaskRefiner,
+ mask_data: Vec<f32>,
+ smoothed_mask: Vec<f32>,
+}
+
+/// What a submitted Vision frame will be reported as once its mask lands.
+#[cfg(target_os = "macos")]
+struct PendingMask {
+ submitted_at: Instant,
+ dimensions: (u32, u32),
+ failure_revision: u64,
+}
+
+enum Segmenter {
+ #[cfg(target_os = "macos")]
+ Vision(Box<vision::VisionSegmenter>),
+ Onnx(Box<OnnxSegmenter>),
+}
+
+impl Segmenter {
+ fn new() -> anyhow::Result<Self> {
+ #[cfg(target_os = "macos")]
+ if std::env::var("CAP_CAMERA_SEGMENTATION").as_deref() != Ok("onnx") {
+ match vision::VisionSegmenter::new() {
+ Ok(segmenter) => return Ok(Self::Vision(Box::new(segmenter))),
+ Err(error) => {
+ tracing::warn!("Vision person segmentation unavailable, using ONNX: {error:#}")
+ }
+ }
+ }
+ let pixel_count = (SEGMENTATION_SIZE * SEGMENTATION_SIZE) as usize;
+ Ok(Self::Onnx(Box::new(OnnxSegmenter {
+ model: SegmentationModel::new()?,
+ refiner: MaskRefiner::new(SEGMENTATION_SIZE as usize, SEGMENTATION_SIZE as usize),
+ mask_data: vec![INITIAL_MASK_VALUE; pixel_count],
+ smoothed_mask: vec![INITIAL_MASK_VALUE; pixel_count],
+ })))
+ }
+
+ fn input_dimensions(&self, width: u32, height: u32) -> (u32, u32) {
+ match self {
+ #[cfg(target_os = "macos")]
+ Self::Vision(_) => vision::input_dimensions(width, height),
+ Self::Onnx(_) => {
+ let _ = (width, height);
+ (SEGMENTATION_SIZE, SEGMENTATION_SIZE)
+ }
+ }
+ }
+
+ /// Vision reads BGRA pixel buffers; the ONNX model takes RGBA.
+ fn wants_bgra(&self) -> bool {
+ match self {
+ #[cfg(target_os = "macos")]
+ Self::Vision(_) => true,
+ Self::Onnx(_) => false,
+ }
+ }
+
+ fn reset(&mut self) {
+ match self {
+ #[cfg(target_os = "macos")]
+ Self::Vision(segmenter) => segmenter.reset(),
+ Self::Onnx(onnx) => reset_mask_buffers([&mut onnx.mask_data, &mut onnx.smoothed_mask]),
+ }
+ }
+}
+
+struct SegmentationInput {
+ dimensions: (u32, u32),
+ texture: wgpu::Texture,
+ view: wgpu::TextureView,
+ readback_buffer: wgpu::Buffer,
+ bytes_per_row: u32,
+}
+
+impl SegmentationInput {
+ fn new(device: &wgpu::Device, (width, height): (u32, u32)) -> Self {
+ let texture = device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Segmentation Input"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::Rgba8Unorm,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::COPY_SRC
+ | wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ });
+ let bytes_per_row = (width * 4).div_ceil(256) * 256;
+ Self {
+ dimensions: (width, height),
+ view: texture.create_view(&Default::default()),
+ texture,
+ readback_buffer: device.create_buffer(&wgpu::BufferDescriptor {
+ label: Some("Segmentation Readback"),
+ size: u64::from(bytes_per_row) * u64::from(height),
+ usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
+ mapped_at_creation: false,
+ }),
+ bytes_per_row,
+ }
+ }
}
const SEGMENTATION_SIZE: u32 = 256;
@@ -260,21 +377,21 @@ fn reset_mask_buffers<const N: usize>(buffers: [&mut [f32]; N]) {
}
pub struct BlurProcessor {
- model: SegmentationModel,
+ segmenter: Segmenter,
blur_pipeline: BlurPipeline,
composite_pipeline: CompositePipeline,
downsample_pipeline: DownsamplePipeline,
+ matte_pipeline: MattePipeline,
textures: Option<ProcessorTextures>,
- mask_data: Vec<f32>,
- smoothed_mask: Vec<f32>,
- mask_refiner: MaskRefiner,
mask_bytes: Vec<u8>,
+ mask_dimensions: (u32, u32),
last_inference: Instant,
- downsample_texture: wgpu::Texture,
- downsample_view: wgpu::TextureView,
- readback_buffer: wgpu::Buffer,
+ segmentation_input: Option<SegmentationInput>,
+ #[cfg(target_os = "macos")]
+ segmentation_source: Option<vision::SharedPixelBuffer>,
+ #[cfg(target_os = "macos")]
+ pending_mask: Option<PendingMask>,
readback_pixels: Vec<u8>,
- readback_bytes_per_row: u32,
readback_state: ReadbackState,
inference_interval: Duration,
inference_requested: bool,
@@ -297,7 +414,7 @@ struct DownsamplePipeline {
}
impl DownsamplePipeline {
- fn new(device: &wgpu::Device) -> Self {
+ fn new(device: &wgpu::Device, bgra: bool) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Downsample Shader"),
source: wgpu::ShaderSource::Wgsl(BLIT_SHADER.into()),
@@ -342,7 +459,7 @@ impl DownsamplePipeline {
},
fragment: Some(wgpu::FragmentState {
module: &shader,
- entry_point: Some("fs_main"),
+ entry_point: Some(if bgra { "fs_bgra" } else { "fs_main" }),
targets: &[Some(wgpu::ColorTargetState {
format: wgpu::TextureFormat::Rgba8Unorm,
blend: None,
@@ -383,6 +500,7 @@ struct ProcessorTextures {
blur_intermediate_view: wgpu::TextureView,
mask_texture: wgpu::Texture,
mask_view: wgpu::TextureView,
+ matte: MatteTextures,
output_texture: wgpu::Texture,
output_view: wgpu::TextureView,
}
@@ -404,56 +522,32 @@ impl BlurProcessor {
output_format: wgpu::TextureFormat,
blur_session: BlurSessionHandle,
) -> anyhow::Result<Self> {
- let model = SegmentationModel::new()?;
+ let segmenter = Segmenter::new()?;
let blur_pipeline = BlurPipeline::new(device);
let composite_pipeline = CompositePipeline::new(device, output_format);
- let downsample_pipeline = DownsamplePipeline::new(device);
- let pixel_count = (SEGMENTATION_SIZE * SEGMENTATION_SIZE) as usize;
-
- let downsample_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("Downsample 256"),
- size: wgpu::Extent3d {
- width: SEGMENTATION_SIZE,
- height: SEGMENTATION_SIZE,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::Rgba8Unorm,
- usage: wgpu::TextureUsages::RENDER_ATTACHMENT
- | wgpu::TextureUsages::COPY_SRC
- | wgpu::TextureUsages::TEXTURE_BINDING,
- view_formats: &[],
- });
- let downsample_view = downsample_texture.create_view(&Default::default());
-
- let readback_bytes_per_row = (SEGMENTATION_SIZE * 4).div_ceil(256) * 256;
- let readback_buffer = device.create_buffer(&wgpu::BufferDescriptor {
- label: Some("Segmentation Readback"),
- size: (readback_bytes_per_row * SEGMENTATION_SIZE) as u64,
- usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
- mapped_at_creation: false,
- });
+ let downsample_pipeline = DownsamplePipeline::new(device, segmenter.wants_bgra());
+ let matte_pipeline = MattePipeline::new(device);
+ let mask_dimensions = (SEGMENTATION_SIZE, SEGMENTATION_SIZE);
+ let pixel_count = (mask_dimensions.0 * mask_dimensions.1) as usize;
Ok(Self {
- model,
+ segmenter,
blur_pipeline,
composite_pipeline,
downsample_pipeline,
+ matte_pipeline,
textures: None,
- mask_data: vec![INITIAL_MASK_VALUE; pixel_count],
- smoothed_mask: vec![INITIAL_MASK_VALUE; pixel_count],
- mask_refiner: MaskRefiner::new(SEGMENTATION_SIZE as usize, SEGMENTATION_SIZE as usize),
mask_bytes: vec![255; pixel_count],
+ mask_dimensions,
last_inference: Instant::now()
.checked_sub(std::time::Duration::from_secs(1))
.unwrap_or_else(Instant::now),
- downsample_texture,
- downsample_view,
- readback_buffer,
- readback_pixels: Vec::with_capacity(pixel_count * 4),
- readback_bytes_per_row,
+ segmentation_input: None,
+ #[cfg(target_os = "macos")]
+ segmentation_source: None,
+ #[cfg(target_os = "macos")]
+ pending_mask: None,
+ readback_pixels: Vec::new(),
readback_state: ReadbackState::Idle,
inference_interval: DEFAULT_INFERENCE_INTERVAL,
inference_requested: false,
@@ -490,13 +584,28 @@ impl BlurProcessor {
self.inference_interval = interval;
}
+ /// The BGRA IOSurface frame behind the next `process*` call's input
+ /// texture. Vision then reads it directly: no GPU downsample, readback
+ /// or copy. Only used for the very next frame.
+ #[cfg(target_os = "macos")]
+ pub fn set_segmentation_source(&mut self, buffer: cidre::arc::R<cidre::cv::PixelBuf>) {
+ self.segmentation_source = Some(vision::SharedPixelBuffer(buffer));
+ }
+
/// Call between outputs after submitting prior work; discard queued output readbacks too.
pub fn reset_mask_history(&mut self) {
- if matches!(self.readback_state, ReadbackState::InFlight { .. }) {
- self.readback_buffer.unmap();
+ if matches!(self.readback_state, ReadbackState::InFlight { .. })
+ && let Some(input) = &self.segmentation_input
+ {
+ input.readback_buffer.unmap();
}
self.readback_state = ReadbackState::Idle;
- reset_mask_buffers([&mut self.mask_data, &mut self.smoothed_mask]);
+ self.segmenter.reset();
+ #[cfg(target_os = "macos")]
+ {
+ self.pending_mask = None;
+ }
+ self.mask_bytes.fill(255);
self.mask_initialized = false;
self.mask_dirty = true;
self.inference_requested = true;
@@ -553,59 +662,79 @@ impl BlurProcessor {
self.ensure_textures(device, width, height);
let input_view = input_texture.create_view(&Default::default());
- if self.inference_requested
+ let should_infer = self.inference_requested
|| !self.mask_initialized
|| (!self.frame_synchronous
&& (matches!(self.readback_state, ReadbackState::InFlight { .. })
- || self.last_inference.elapsed() >= self.inference_interval))
- {
- self.inference_requested = false;
- if self.run_segmentation(device, queue, input_texture) {
- self.last_inference = Instant::now();
- self.mask_dirty = true;
+ || self.last_inference.elapsed() >= self.inference_interval));
+ match self.segmenter {
+ #[cfg(target_os = "macos")]
+ Segmenter::Vision(_) => {
+ if self.run_vision(device, queue, input_texture, should_infer) {
+ self.mask_dirty = true;
+ }
+ }
+ Segmenter::Onnx(_) => {
+ if should_infer {
+ self.inference_requested = false;
+ if self.run_segmentation(device, queue, input_texture) {
+ self.last_inference = Instant::now();
+ self.mask_dirty = true;
+ }
+ }
}
}
if self.mask_dirty {
- self.upload_mask(queue);
+ self.upload_mask(device, queue);
self.mask_dirty = false;
}
let textures = self.textures.as_ref().expect("textures initialized above");
- if mode != BlurMode::Remove {
- self.composite_pipeline.prepare_background(
+ // The guide is re-read every frame, so edges track the live image
+ // even between segmentation updates.
+ self.matte_pipeline.refine(
+ device,
+ encoder,
+ &input_view,
+ &textures.mask_view,
+ &textures.matte,
+ );
+ let matte = &textures.matte.coefficients_view;
+ self.composite_pipeline.prepare_background(
+ device,
+ encoder,
+ CompositePassInputs {
+ sharp: &input_view,
+ blurred: &input_view,
+ mask: &textures.mask_view,
+ matte,
+ output: &textures.background_view,
+ },
+ );
+ // Remove uses the lightly blurred room as the local background
+ // estimate it unmixes edge colours against.
+ let (intensity, passes) = match mode {
+ BlurMode::Light | BlurMode::Remove => (1.5, 1),
+ BlurMode::Heavy => (2.5, 3),
+ };
+ for pass in 0..passes {
+ self.blur_pipeline.blur_two_pass(
device,
encoder,
- CompositePassInputs {
- sharp: &input_view,
- blurred: &input_view,
- mask: &textures.mask_view,
- output: &textures.background_view,
+ BlurPassInputs {
+ source: if pass == 0 {
+ &textures.background_view
+ } else {
+ &textures.blurred_view
+ },
+ intermediate: &textures.blur_intermediate_view,
+ output: &textures.blurred_view,
+ width: textures.blur_dimensions.0,
+ height: textures.blur_dimensions.1,
+ intensity,
},
);
- let (intensity, passes) = match mode {
- BlurMode::Light => (1.5, 1),
- BlurMode::Heavy => (2.5, 3),
- BlurMode::Remove => unreachable!(),
- };
- for pass in 0..passes {
- self.blur_pipeline.blur_two_pass(
- device,
- encoder,
- BlurPassInputs {
- source: if pass == 0 {
- &textures.background_view
- } else {
- &textures.blurred_view
- },
- intermediate: &textures.blur_intermediate_view,
- output: &textures.blurred_view,
- width: textures.blur_dimensions.0,
- height: textures.blur_dimensions.1,
- intensity,
- },
- );
- }
}
self.composite_pipeline.composite(
device,
@@ -614,6 +743,7 @@ impl BlurProcessor {
sharp: &input_view,
blurred: &textures.blurred_view,
mask: &textures.mask_view,
+ matte,
output: &textures.output_view,
},
mode == BlurMode::Remove,
@@ -640,6 +770,14 @@ impl BlurProcessor {
}
self.reset_mask_history();
+ let input_dimensions = self.segmenter.input_dimensions(width, height);
+ if self
+ .segmentation_input
+ .as_ref()
+ .is_none_or(|input| input.dimensions != input_dimensions)
+ {
+ self.segmentation_input = Some(SegmentationInput::new(device, input_dimensions));
+ }
let create_rgba_texture =
|label: &str, w: u32, h: u32, format, usage: wgpu::TextureUsages| {
@@ -692,21 +830,7 @@ impl BlurProcessor {
wgpu::TextureFormat::Rgba8Unorm,
tex_usage,
);
-
- let mask_texture = device.create_texture(&wgpu::TextureDescriptor {
- label: Some("Segmentation Mask"),
- size: wgpu::Extent3d {
- width: SEGMENTATION_SIZE,
- height: SEGMENTATION_SIZE,
- depth_or_array_layers: 1,
- },
- mip_level_count: 1,
- sample_count: 1,
- dimension: wgpu::TextureDimension::D2,
- format: wgpu::TextureFormat::R8Unorm,
- usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
- view_formats: &[],
- });
+ let mask_texture = create_mask_texture(device, self.mask_dimensions);
self.textures = Some(ProcessorTextures {
width,
@@ -720,6 +844,7 @@ impl BlurProcessor {
_blur_intermediate: blur_inter,
mask_view: mask_texture.create_view(&Default::default()),
mask_texture,
+ matte: MatteTextures::new(device, width, height),
output_view: output_texture.create_view(&Default::default()),
output_texture,
});
@@ -734,59 +859,153 @@ impl BlurProcessor {
input_texture: &wgpu::Texture,
) -> bool {
let failure_revision = self.mask_status.failure_revision;
- let rgba_256 = match self.readback_downsampled(
+ let Some(frame) = self.readback_downsampled(
device,
queue,
input_texture,
self.frame_synchronous || !self.mask_initialized,
- ) {
- Some(data) => data,
- None => return false,
+ ) else {
+ return false;
};
- match self.model.run_inference(&self.readback_pixels) {
- Ok(new_mask) => {
- let pixel_count = (SEGMENTATION_SIZE * SEGMENTATION_SIZE) as usize;
- let mask_validation = validate_mask_samples(new_mask, pixel_count);
- if let Err(error) = &mask_validation {
- self.mask_status.fail(error.clone());
- return false;
+ let result = match &mut self.segmenter {
+ #[cfg(target_os = "macos")]
+ Segmenter::Vision(_) => return false,
+ Segmenter::Onnx(onnx) => segment_with_onnx(
+ onnx,
+ &mut self.readback_pixels,
+ self.mask_initialized,
+ &mut self.mask_bytes,
+ )
+ .map(|()| self.mask_dimensions = (SEGMENTATION_SIZE, SEGMENTATION_SIZE)),
+ };
+
+ match result {
+ Ok(()) => {
+ self.mask_initialized = true;
+ self.mask_status.complete(
+ failure_revision,
+ frame.submitted_at,
+ frame.dimensions,
+ Instant::now(),
+ );
+ true
+ }
+ Err(failure) => {
+ if let BlurFailure::Inference(error) = &failure {
+ tracing::warn!("Segmentation inference failed: {error}");
}
- if new_mask.len() >= pixel_count {
- for (i, &raw) in new_mask.iter().take(pixel_count).enumerate() {
- self.smoothed_mask[i] = refine_mask_value(raw);
- }
- self.mask_refiner.refine(
- &mut self.smoothed_mask,
- &self.mask_data,
- &mut self.readback_pixels,
- self.mask_initialized,
- );
- std::mem::swap(&mut self.mask_data, &mut self.smoothed_mask);
+ self.mask_status.fail(failure);
+ false
+ }
+ }
+ }
+
+ /// Vision path: collect a finished mask, then submit the current frame
+ /// if the segmenter is idle. Live callers never wait; synchronous
+ /// callers (export) and the first frame after a reset block so the mask
+ /// matches the frame being rendered.
+ #[cfg(target_os = "macos")]
+ fn run_vision(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ input_texture: &wgpu::Texture,
+ should_infer: bool,
+ ) -> bool {
+ let wait = self.frame_synchronous || !self.mask_initialized;
+ let source = self.segmentation_source.take();
+ let mut updated = self.collect_vision(wait);
+ let busy = matches!(&self.segmenter, Segmenter::Vision(segmenter) if segmenter.is_busy());
+ if !should_infer || busy {
+ return updated;
+ }
+
+ let failure_revision = self.mask_status.failure_revision;
+ let dimensions = (input_texture.width(), input_texture.height());
+ let submitted = if let Some(source) = source
+ .filter(|source| (source.0.width() as u32, source.0.height() as u32) == dimensions)
+ {
+ let Segmenter::Vision(segmenter) = &mut self.segmenter else {
+ return updated;
+ };
+ segmenter
+ .submit_pixel_buffer(source)
+ .map(|()| (Instant::now(), dimensions))
+ } else {
+ // Waiting only covers the small downsample copy; it lets Vision
+ // start on this frame instead of one frame later.
+ let Some(frame) = self.readback_downsampled(device, queue, input_texture, true) else {
+ return updated;
+ };
+ let Segmenter::Vision(segmenter) = &mut self.segmenter else {
+ return updated;
+ };
+ segmenter
+ .submit_pixels(&self.readback_pixels, frame.input_dimensions)
+ .map(|()| (frame.submitted_at, frame.dimensions))
+ };
+ match submitted {
+ Ok((submitted_at, dimensions)) => {
+ self.inference_requested = false;
+ self.last_inference = Instant::now();
+ self.pending_mask = Some(PendingMask {
+ submitted_at,
+ dimensions,
+ failure_revision,
+ });
+ }
+ Err(error) => {
+ self.mask_status
+ .fail(BlurFailure::Inference(format!("{error:#}")));
+ return updated;
+ }
+ }
+ if wait {
+ updated |= self.collect_vision(true);
+ }
+ updated
+ }
+
+ #[cfg(target_os = "macos")]
+ fn collect_vision(&mut self, wait: bool) -> bool {
+ let Segmenter::Vision(segmenter) = &mut self.segmenter else {
+ return false;
+ };
+ let Some(result) = segmenter.collect(wait) else {
+ return false;
+ };
+ let pending = self.pending_mask.take();
+ let failure = match result {
+ Ok((mask, (width, height))) => {
+ let expected_samples = (width * height) as usize;
+ if mask.len() == expected_samples && expected_samples > 0 {
+ self.mask_bytes.clear();
+ self.mask_bytes.extend_from_slice(mask);
+ self.mask_dimensions = (width, height);
self.mask_initialized = true;
- let smoothed_validation = validate_mask_samples(&self.mask_data, pixel_count);
- if let Err(error) = &smoothed_validation {
- self.mask_status.fail(error.clone());
- }
- if mask_validation.is_ok() && smoothed_validation.is_ok() {
+ if let Some(pending) = pending {
self.mask_status.complete(
- failure_revision,
- rgba_256.submitted_at,
- rgba_256.dimensions,
+ pending.failure_revision,
+ pending.submitted_at,
+ pending.dimensions,
Instant::now(),
);
}
return true;
}
- false
+ BlurFailure::InvalidMask {
+ expected_samples,
+ actual_samples: mask.len(),
+ }
}
- Err(e) => {
- tracing::warn!("Segmentation inference failed: {e:#}");
- self.mask_status
- .fail(BlurFailure::Inference(format!("{e:#}")));
- false
+ Err(error) => {
+ tracing::warn!("Segmentation inference failed: {error:#}");
+ BlurFailure::Inference(format!("{error:#}"))
}
- }
+ };
+ self.mask_status.fail(failure);
+ false
}
fn readback_downsampled(
@@ -798,7 +1017,10 @@ impl BlurProcessor {
) -> Option<ReadbackFrame> {
let mut completed = self.take_completed_readback(device, wgpu::PollType::Poll);
- if completed.is_none() && matches!(self.readback_state, ReadbackState::Idle) {
+ if completed.is_none()
+ && matches!(self.readback_state, ReadbackState::Idle)
+ && let Some(segmentation_input) = &self.segmentation_input
+ {
let input_view = input_texture.create_view(&Default::default());
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
@@ -824,7 +1046,7 @@ impl BlurProcessor {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Downsample Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
- view: &self.downsample_view,
+ view: &segmentation_input.view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
@@ -840,25 +1062,25 @@ impl BlurProcessor {
pass.draw(0..3, 0..1);
}
- let bytes_per_row = self.readback_bytes_per_row;
+ let (input_width, input_height) = segmentation_input.dimensions;
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo {
- texture: &self.downsample_texture,
+ texture: &segmentation_input.texture,
mip_level: 0,
origin: wgpu::Origin3d::ZERO,
aspect: wgpu::TextureAspect::All,
},
wgpu::TexelCopyBufferInfo {
- buffer: &self.readback_buffer,
+ buffer: &segmentation_input.readback_buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
- bytes_per_row: Some(bytes_per_row),
- rows_per_image: Some(SEGMENTATION_SIZE),
+ bytes_per_row: Some(segmentation_input.bytes_per_row),
+ rows_per_image: Some(input_height),
},
},
wgpu::Extent3d {
- width: SEGMENTATION_SIZE,
- height: SEGMENTATION_SIZE,
+ width: input_width,
+ height: input_height,
depth_or_array_layers: 1,
},
);
@@ -868,16 +1090,17 @@ impl BlurProcessor {
let status = Arc::new(AtomicU8::new(READBACK_PENDING));
let status_cb = status.clone();
- self.readback_buffer
- .slice(..)
- .map_async(wgpu::MapMode::Read, move |result| {
+ segmentation_input.readback_buffer.slice(..).map_async(
+ wgpu::MapMode::Read,
+ move |result| {
let code = if result.is_ok() {
READBACK_READY_OK
} else {
READBACK_READY_ERR
};
status_cb.store(code, Ordering::Release);
- });
+ },
+ );
self.readback_state = ReadbackState::InFlight {
status,
@@ -900,60 +1123,70 @@ impl BlurProcessor {
device: &wgpu::Device,
poll_type: wgpu::PollType,
) -> Option<ReadbackFrame> {
- if let ReadbackState::InFlight {
+ let ReadbackState::InFlight {
status,
submitted_at,
dimensions,
} = &self.readback_state
- {
- let submitted_at = *submitted_at;
- let dimensions = *dimensions;
- if let Err(error) = device.poll(poll_type) {
- self.mask_status.fail(BlurFailure::Readback(format!(
- "GPU polling failed: {error}"
- )));
- }
- match status.load(Ordering::Acquire) {
- READBACK_READY_OK => {
- let slice = self.readback_buffer.slice(..);
- let data = slice.get_mapped_range();
- let expected_row = (SEGMENTATION_SIZE * 4) as usize;
- let bytes_per_row = self.readback_bytes_per_row as usize;
- self.readback_pixels.clear();
- for row in 0..SEGMENTATION_SIZE as usize {
- let start = row * bytes_per_row;
- self.readback_pixels
- .extend_from_slice(&data[start..start + expected_row]);
- }
- drop(data);
- self.readback_buffer.unmap();
- self.readback_state = ReadbackState::Idle;
- Some(ReadbackFrame {
- submitted_at,
- dimensions,
- })
- }
- READBACK_READY_ERR => {
- self.readback_state = ReadbackState::Idle;
- self.mask_status.fail(BlurFailure::Readback(
- "GPU mask readback failed".to_string(),
- ));
- None
+ else {
+ return None;
+ };
+ let submitted_at = *submitted_at;
+ let dimensions = *dimensions;
+ if let Err(error) = device.poll(poll_type) {
+ self.mask_status.fail(BlurFailure::Readback(format!(
+ "GPU polling failed: {error}"
+ )));
+ }
+ match status.load(Ordering::Acquire) {
+ READBACK_READY_OK => {
+ let input = self.segmentation_input.as_ref()?;
+ let (input_width, input_height) = input.dimensions;
+ let slice = input.readback_buffer.slice(..);
+ let data = slice.get_mapped_range();
+ let expected_row = (input_width * 4) as usize;
+ let bytes_per_row = input.bytes_per_row as usize;
+ self.readback_pixels.clear();
+ for row in 0..input_height as usize {
+ let start = row * bytes_per_row;
+ self.readback_pixels
+ .extend_from_slice(&data[start..start + expected_row]);
}
- _ => None,
+ drop(data);
+ input.readback_buffer.unmap();
+ self.readback_state = ReadbackState::Idle;
+ Some(ReadbackFrame {
+ submitted_at,
+ dimensions,
+ input_dimensions: input.dimensions,
+ })
}
- } else {
- None
+ READBACK_READY_ERR => {
+ self.readback_state = ReadbackState::Idle;
+ self.mask_status.fail(BlurFailure::Readback(
+ "GPU mask readback failed".to_string(),
+ ));
+ None
+ }
+ _ => None,
}
}
- fn upload_mask(&mut self, queue: &wgpu::Queue) {
- let Some(textures) = &self.textures else {
+ fn upload_mask(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) {
+ let Some(textures) = &mut self.textures else {
return;
};
-
- for (output, &value) in self.mask_bytes.iter_mut().zip(&self.mask_data) {
- *output = (value.clamp(0.0, 1.0) * 255.0).round() as u8;
+ let (width, height) = self.mask_dimensions;
+ if self.mask_bytes.len() != (width * height) as usize {
+ return;
+ }
+ if (
+ textures.mask_texture.width(),
+ textures.mask_texture.height(),
+ ) != (width, height)
+ {
+ textures.mask_texture = create_mask_texture(device, self.mask_dimensions);
+ textures.mask_view = textures.mask_texture.create_view(&Default::default());
}
queue.write_texture(
@@ -966,18 +1199,63 @@ impl BlurProcessor {
&self.mask_bytes,
wgpu::TexelCopyBufferLayout {
offset: 0,
- bytes_per_row: Some(SEGMENTATION_SIZE),
- rows_per_image: Some(SEGMENTATION_SIZE),
+ bytes_per_row: Some(width),
+ rows_per_image: Some(height),
},
wgpu::Extent3d {
- width: SEGMENTATION_SIZE,
- height: SEGMENTATION_SIZE,
+ width,
+ height,
depth_or_array_layers: 1,
},
);
}
}
+fn create_mask_texture(device: &wgpu::Device, (width, height): (u32, u32)) -> wgpu::Texture {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: Some("Segmentation Mask"),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format: wgpu::TextureFormat::R8Unorm,
+ usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
+ view_formats: &[],
+ })
+}
+
+fn segment_with_onnx(
+ onnx: &mut OnnxSegmenter,
+ frame: &mut Vec<u8>,
+ initialized: bool,
+ mask_bytes: &mut Vec<u8>,
+) -> Result<(), BlurFailure> {
+ let pixel_count = (SEGMENTATION_SIZE * SEGMENTATION_SIZE) as usize;
+ let new_mask = onnx
+ .model
+ .run_inference(frame)
+ .map_err(|error| BlurFailure::Inference(format!("{error:#}")))?;
+ validate_mask_samples(new_mask, pixel_count)?;
+ for (smoothed, &raw) in onnx.smoothed_mask.iter_mut().zip(new_mask) {
+ *smoothed = refine_mask_value(raw);
+ }
+ onnx.refiner
+ .refine(&mut onnx.smoothed_mask, &onnx.mask_data, frame, initialized);
+ std::mem::swap(&mut onnx.mask_data, &mut onnx.smoothed_mask);
+ validate_mask_samples(&onnx.mask_data, pixel_count)?;
+ mask_bytes.clear();
+ mask_bytes.extend(
+ onnx.mask_data
+ .iter()
+ .map(|value| (value.clamp(0.0, 1.0) * 255.0).round() as u8),
+ );
+ Ok(())
+}
+
fn background_dimensions(width: u32, height: u32) -> (u32, u32) {
let scale = (256.0 / width.max(height) as f64).min(1.0);
(
@@ -1022,6 +1300,11 @@ fn vs_main(@builtin(vertex_index) vi: u32) -> VertexOutput {
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return textureSample(src_tex, src_sampler, in.uv);
}
+
+@fragment
+fn fs_bgra(in: VertexOutput) -> @location(0) vec4<f32> {
+ return textureSample(src_tex, src_sampler, in.uv).bgra;
+}
";
#[cfg(test)]
diff --git a/crates/camera-effects/src/matte.rs b/crates/camera-effects/src/matte.rs
new file mode 100644
index 000000000..bd1c7879e
--- /dev/null
+++ b/crates/camera-effects/src/matte.rs
@@ -0,0 +1,286 @@
+/// Longest side of the guided filter's working resolution. Coefficients are
+/// smooth by construction, so solving them at up to 480px and applying them
+/// to the full frame costs a fraction of a full resolution solve.
+const MAX_WORKING_SIZE: u32 = 480;
+
+const COEFFICIENT_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
+/// The smoothed coefficients the composite samples. Half floats are
+/// filterable, so the composite's cubic upsampling is four bilinear taps;
+/// coefficient magnitudes stay small enough for half precision.
+const SMOOTHED_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
+
+pub fn working_dimensions(width: u32, height: u32) -> (u32, u32) {
+ let scale = (f64::from(MAX_WORKING_SIZE) / f64::from(width.max(height).max(1))).min(1.0);
+ (
+ ((f64::from(width) * scale).round() as u32).max(1),
+ ((f64::from(height) * scale).round() as u32).max(1),
+ )
+}
+
+pub struct MattePipeline {
+ guide: wgpu::RenderPipeline,
+ coefficients: wgpu::RenderPipeline,
+ smooth_horizontal: wgpu::RenderPipeline,
+ smooth_vertical: wgpu::RenderPipeline,
+ sampled_layout: wgpu::BindGroupLayout,
+ unfiltered_layout: wgpu::BindGroupLayout,
+ sampler: wgpu::Sampler,
+}
+
+pub struct MatteTextures {
+ _guide: wgpu::Texture,
+ guide_view: wgpu::TextureView,
+ _raw: wgpu::Texture,
+ raw_view: wgpu::TextureView,
+ _intermediate: wgpu::Texture,
+ intermediate_view: wgpu::TextureView,
+ _coefficients: wgpu::Texture,
+ pub coefficients_view: wgpu::TextureView,
+}
+
+impl MatteTextures {
+ pub fn new(device: &wgpu::Device, width: u32, height: u32) -> Self {
+ let (width, height) = working_dimensions(width, height);
+ let create = |label, format| {
+ device.create_texture(&wgpu::TextureDescriptor {
+ label: Some(label),
+ size: wgpu::Extent3d {
+ width,
+ height,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: wgpu::TextureDimension::D2,
+ format,
+ usage: wgpu::TextureUsages::RENDER_ATTACHMENT
+ | wgpu::TextureUsages::TEXTURE_BINDING,
+ view_formats: &[],
+ })
+ };
+ let guide = create("Matte Guide", wgpu::TextureFormat::Rgba8Unorm);
+ let raw = create("Matte Coefficients Raw", COEFFICIENT_FORMAT);
+ let intermediate = create("Matte Coefficients Intermediate", COEFFICIENT_FORMAT);
+ let coefficients = create("Matte Coefficients", SMOOTHED_FORMAT);
+ Self {
+ guide_view: guide.create_view(&Default::default()),
+ _guide: guide,
+ raw_view: raw.create_view(&Default::default()),
+ _raw: raw,
+ intermediate_view: intermediate.create_view(&Default::default()),
+ _intermediate: intermediate,
+ coefficients_view: coefficients.create_view(&Default::default()),
+ _coefficients: coefficients,
+ }
+ }
+}
+
+impl MattePipeline {
+ pub fn new(device: &wgpu::Device) -> Self {
+ let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
+ label: Some("Guided Filter Shader"),
+ source: wgpu::ShaderSource::Wgsl(include_str!("shaders/guided_filter.wgsl").into()),
+ });
+ let texture_entry = |binding, filterable| wgpu::BindGroupLayoutEntry {
+ binding,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Texture {
+ sample_type: wgpu::TextureSampleType::Float { filterable },
+ view_dimension: wgpu::TextureViewDimension::D2,
+ multisampled: false,
+ },
+ count: None,
+ };
+ let sampled_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Guided Filter Sampled BGL"),
+ entries: &[
+ texture_entry(0, true),
+ texture_entry(1, true),
+ wgpu::BindGroupLayoutEntry {
+ binding: 2,
+ visibility: wgpu::ShaderStages::FRAGMENT,
+ ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ });
+ let unfiltered_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ label: Some("Guided Filter Unfiltered BGL"),
+ entries: &[texture_entry(0, false)],
+ });
+ let create = |label, layout: &wgpu::BindGroupLayout, entry_point, format| {
+ let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
+ label: Some(label),
+ bind_group_layouts: &[layout],
+ push_constant_ranges: &[],
+ });
+ device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
+ label: Some(label),
+ layout: Some(&pipeline_layout),
+ vertex: wgpu::VertexState {
+ module: &shader,
+ entry_point: Some("vs_main"),
+ buffers: &[],
+ compilation_options: Default::default(),
+ },
+ fragment: Some(wgpu::FragmentState {
+ module: &shader,
+ entry_point: Some(entry_point),
+ targets: &[Some(wgpu::ColorTargetState {
+ format,
+ blend: None,
+ write_mask: wgpu::ColorWrites::ALL,
+ })],
+ compilation_options: Default::default(),
+ }),
+ primitive: wgpu::PrimitiveState::default(),
+ depth_stencil: None,
+ multisample: Default::default(),
+ multiview: None,
+ cache: None,
+ })
+ };
+ Self {
+ guide: create(
+ "Matte Guide Pipeline",
+ &sampled_layout,
+ "fs_guide",
+ wgpu::TextureFormat::Rgba8Unorm,
+ ),
+ coefficients: create(
+ "Matte Coefficients Pipeline",
+ &sampled_layout,
+ "fs_coefficients",
+ COEFFICIENT_FORMAT,
+ ),
+ smooth_horizontal: create(
+ "Matte Smooth Horizontal Pipeline",
+ &unfiltered_layout,
+ "fs_smooth_horizontal",
+ COEFFICIENT_FORMAT,
+ ),
+ smooth_vertical: create(
+ "Matte Smooth Vertical Pipeline",
+ &unfiltered_layout,
+ "fs_smooth_vertical",
+ SMOOTHED_FORMAT,
+ ),
+ sampler: device.create_sampler(&wgpu::SamplerDescriptor {
+ address_mode_u: wgpu::AddressMode::ClampToEdge,
+ address_mode_v: wgpu::AddressMode::ClampToEdge,
+ mag_filter: wgpu::FilterMode::Linear,
+ min_filter: wgpu::FilterMode::Linear,
+ ..Default::default()
+ }),
+ sampled_layout,
+ unfiltered_layout,
+ }
+ }
+
+ pub fn refine(
+ &self,
+ device: &wgpu::Device,
+ encoder: &mut wgpu::CommandEncoder,
+ source: &wgpu::TextureView,
+ mask: &wgpu::TextureView,
+ textures: &MatteTextures,
+ ) {
+ let sampled = |texture| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Guided Filter BG"),
+ layout: &self.sampled_layout,
+ entries: &[
+ wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(texture),
+ },
+ wgpu::BindGroupEntry {
+ binding: 1,
+ resource: wgpu::BindingResource::TextureView(mask),
+ },
+ wgpu::BindGroupEntry {
+ binding: 2,
+ resource: wgpu::BindingResource::Sampler(&self.sampler),
+ },
+ ],
+ })
+ };
+ let unfiltered = |texture| {
+ device.create_bind_group(&wgpu::BindGroupDescriptor {
+ label: Some("Guided Filter Smooth BG"),
+ layout: &self.unfiltered_layout,
+ entries: &[wgpu::BindGroupEntry {
+ binding: 0,
+ resource: wgpu::BindingResource::TextureView(texture),
+ }],
+ })
+ };
+ draw(
+ encoder,
+ &self.guide,
+ &sampled(source),
+ &textures.guide_view,
+ "Matte Guide",
+ );
+ draw(
+ encoder,
+ &self.coefficients,
+ &sampled(&textures.guide_view),
+ &textures.raw_view,
+ "Matte Coefficients",
+ );
+ draw(
+ encoder,
+ &self.smooth_horizontal,
+ &unfiltered(&textures.raw_view),
+ &textures.intermediate_view,
+ "Matte Smooth Horizontal",
+ );
+ draw(
+ encoder,
+ &self.smooth_vertical,
+ &unfiltered(&textures.intermediate_view),
+ &textures.coefficients_view,
+ "Matte Smooth Vertical",
+ );
+ }
+}
+
+fn draw(
+ encoder: &mut wgpu::CommandEncoder,
+ pipeline: &wgpu::RenderPipeline,
+ bind_group: &wgpu::BindGroup,
+ target: &wgpu::TextureView,
+ label: &str,
+) {
+ let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
+ label: Some(label),
+ color_attachments: &[Some(wgpu::RenderPassColorAttachment {
+ view: target,
+ resolve_target: None,
+ ops: wgpu::Operations {
+ load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+ pass.set_pipeline(pipeline);
+ pass.set_bind_group(0, bind_group, &[]);
+ pass.draw(0..3, 0..1);
+}
+
+#[cfg(test)]
+mod tests {
+ use super::working_dimensions;
+
+ #[test]
+ fn working_resolution_is_bounded_and_keeps_aspect() {
+ assert_eq!(working_dimensions(1920, 1080), (480, 270));
+ assert_eq!(working_dimensions(1080, 1920), (270, 480));
+ assert_eq!(working_dimensions(480, 270), (480, 270));
+ assert_eq!(working_dimensions(320, 180), (320, 180));
+ }
+}
diff --git a/crates/camera-effects/src/shaders/guided_filter.wgsl b/crates/camera-effects/src/shaders/guided_filter.wgsl
new file mode 100644
index 000000000..7436deec3
--- /dev/null
+++ b/crates/camera-effects/src/shaders/guided_filter.wgsl
@@ -0,0 +1,126 @@
+// Colour guided filter (He et al.) that snaps the low resolution person mask
+// to the camera image's real edges. Coefficients are solved at a reduced
+// working resolution; the composite applies them to the full resolution
+// frame, which is what makes hair and shoulders crisp instead of a smeared
+// upscale of the segmentation mask.
+
+@group(0) @binding(0) var source_tex: texture_2d<f32>;
+@group(0) @binding(1) var mask_tex: texture_2d<f32>;
+@group(0) @binding(2) var linear_sampler: sampler;
+
+const RADIUS: i32 = 3;
+const EPSILON: f32 = 0.0001;
+
+struct VertexOutput {
+ @builtin(position) position: vec4<f32>,
+ @location(0) uv: vec2<f32>,
+};
+
+@vertex
+fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
+ var positions = array<vec2<f32>, 3>(
+ vec2<f32>(-1.0, -1.0),
+ vec2<f32>(3.0, -1.0),
+ vec2<f32>(-1.0, 3.0),
+ );
+ var uvs = array<vec2<f32>, 3>(
+ vec2<f32>(0.0, 1.0),
+ vec2<f32>(2.0, 1.0),
+ vec2<f32>(0.0, -1.0),
+ );
+ var out: VertexOutput;
+ out.position = vec4<f32>(positions[vertex_index], 0.0, 1.0);
+ out.uv = uvs[vertex_index];
+ return out;
+}
+
+// Downscales the camera frame into the guide and resamples the mask into
+// its alpha, so the window loops below read one texel per tap. Four
+// bilinear taps cover a 4x4 source footprint, so 2-4x reductions average
+// instead of alias.
+@fragment
+fn fs_guide(in: VertexOutput) -> @location(0) vec4<f32> {
+ let texel = fwidth(in.uv) * 0.25;
+ var color = textureSampleLevel(source_tex, linear_sampler, in.uv + vec2<f32>(-texel.x, -texel.y), 0.0).rgb;
+ color += textureSampleLevel(source_tex, linear_sampler, in.uv + vec2<f32>(texel.x, -texel.y), 0.0).rgb;
+ color += textureSampleLevel(source_tex, linear_sampler, in.uv + vec2<f32>(-texel.x, texel.y), 0.0).rgb;
+ color += textureSampleLevel(source_tex, linear_sampler, in.uv + vec2<f32>(texel.x, texel.y), 0.0).rgb;
+ let mask = textureSampleLevel(mask_tex, linear_sampler, in.uv, 0.0).r;
+ return vec4<f32>(color * 0.25, mask);
+}
+
+// Solves a = (Sigma + eps I)^-1 cov(I, p), b = mean(p) - a . mean(I) over a
+// (2r + 1)^2 window. Moments are accumulated in f32 registers rather than
+// stored, so variance never suffers half-float cancellation.
+@fragment
+fn fs_coefficients(in: VertexOutput) -> @location(0) vec4<f32> {
+ let size = vec2<i32>(textureDimensions(source_tex));
+ let center = vec2<i32>(in.position.xy);
+ var sum_color = vec3<f32>(0.0);
+ var sum_mask = 0.0;
+ var sum_squares = vec3<f32>(0.0);
+ var sum_cross = vec3<f32>(0.0);
+ var sum_color_mask = vec3<f32>(0.0);
+ for (var y = -RADIUS; y <= RADIUS; y += 1) {
+ for (var x = -RADIUS; x <= RADIUS; x += 1) {
+ let texel = textureLoad(source_tex, clamp(center + vec2<i32>(x, y), vec2<i32>(0), size - 1), 0);
+ let color = texel.rgb;
+ let mask = texel.a;
+ sum_color += color;
+ sum_mask += mask;
+ sum_squares += color * color;
+ sum_cross += color.rrg * color.gbb;
+ sum_color_mask += color * mask;
+ }
+ }
+ let count = f32((2 * RADIUS + 1) * (2 * RADIUS + 1));
+ let mean_color = sum_color / count;
+ let mean_mask = sum_mask / count;
+ let variance = sum_squares / count - mean_color * mean_color + EPSILON;
+ let covariance = sum_cross / count - mean_color.rrg * mean_color.gbb;
+ let color_mask = sum_color_mask / count - mean_color * mean_mask;
+
+ // Symmetric 3x3 inverse via cofactors.
+ let rr = variance.x;
+ let gg = variance.y;
+ let bb = variance.z;
+ let rg = covariance.x;
+ let rb = covariance.y;
+ let gb = covariance.z;
+ let c_rr = gg * bb - gb * gb;
+ let c_rg = rb * gb - rg * bb;
+ let c_rb = rg * gb - rb * gg;
+ let c_gg = rr * bb - rb * rb;
+ let c_gb = rb * rg - rr * gb;
+ let c_bb = rr * gg - rg * rg;
+ let determinant = rr * c_rr + rg * c_rg + rb * c_rb;
+ let a = vec3<f32>(
+ c_rr * color_mask.x + c_rg * color_mask.y + c_rb * color_mask.z,
+ c_rg * color_mask.x + c_gg * color_mask.y + c_gb * color_mask.z,
+ c_rb * color_mask.x + c_gb * color_mask.y + c_bb * color_mask.z,
+ ) / determinant;
+ return vec4<f32>(a, mean_mask - dot(a, mean_color));
+}
+
+// Box-averages the coefficients so every output pixel blends all windows
+// that cover it, the second half of the guided filter. Separable: one
+// horizontal and one vertical pass.
+fn smooth_along(position: vec4<f32>, step: vec2<i32>) -> vec4<f32> {
+ let size = vec2<i32>(textureDimensions(source_tex));
+ let center = vec2<i32>(position.xy);
+ var sum = vec4<f32>(0.0);
+ for (var i = -RADIUS; i <= RADIUS; i += 1) {
+ sum += textureLoad(source_tex, clamp(center + step * i, vec2<i32>(0), size - 1), 0);
+ }
+ return sum / f32(2 * RADIUS + 1);
+}
+
+@fragment
+fn fs_smooth_horizontal(in: VertexOutput) -> @location(0) vec4<f32> {
+ return smooth_along(in.position, vec2<i32>(1, 0));
+}
+
+@fragment
+fn fs_smooth_vertical(in: VertexOutput) -> @location(0) vec4<f32> {
+ return smooth_along(in.position, vec2<i32>(0, 1));
+}
diff --git a/crates/camera-effects/src/shaders/mask_composite.wgsl b/crates/camera-effects/src/shaders/mask_composite.wgsl
index 66050ee11..a202141cf 100644
--- a/crates/camera-effects/src/shaders/mask_composite.wgsl
+++ b/crates/camera-effects/src/shaders/mask_composite.wgsl
@@ -2,6 +2,10 @@
@group(0) @binding(1) var blurred_tex: texture_2d<f32>;
@group(0) @binding(2) var mask_tex: texture_2d<f32>;
@group(0) @binding(3) var tex_sampler: sampler;
+@group(0) @binding(4) var matte_tex: texture_2d<f32>;
+
+const MATTE_LOW: f32 = 0.25;
+const MATTE_HIGH: f32 = 0.9;
struct VertexOutput {
@builtin(position) position: vec4<f32>,
@@ -27,32 +31,55 @@ fn vs_main(@builtin(vertex_index) vertex_index: u32) -> VertexOutput {
return out;
}
+fn cubic_bspline(t: f32) -> vec4<f32> {
+ let t2 = t * t;
+ let t3 = t2 * t;
+ let inverse = 1.0 - t;
+ return vec4<f32>(
+ inverse * inverse * inverse,
+ 3.0 * t3 - 6.0 * t2 + 4.0,
+ -3.0 * t3 + 3.0 * t2 + 3.0 * t + 1.0,
+ t3,
+ ) / 6.0;
+}
+
+// Cubic B-spline upsampling of the coefficients. Bilinear upsampling left
+// the working grid visible as straight facets along the outline; the
+// B-spline is smooth across texels. Four bilinear taps, each placed so the
+// hardware filter blends a pair of texels in the B-spline's proportions.
+fn matte_coefficients(uv: vec2<f32>) -> vec4<f32> {
+ let size = vec2<f32>(textureDimensions(matte_tex));
+ let position = uv * size - 0.5;
+ let base = floor(position);
+ let fraction = position - base;
+ let weights_x = cubic_bspline(fraction.x);
+ let weights_y = cubic_bspline(fraction.y);
+ let group_x = vec2<f32>(weights_x.x + weights_x.y, weights_x.z + weights_x.w);
+ let group_y = vec2<f32>(weights_y.x + weights_y.y, weights_y.z + weights_y.w);
+ let x = (base.x + vec2<f32>(-0.5, 1.5) + vec2<f32>(weights_x.y, weights_x.w) / group_x) / size.x;
+ let y = (base.y + vec2<f32>(-0.5, 1.5) + vec2<f32>(weights_y.y, weights_y.w) / group_y) / size.y;
+ let top = textureSampleLevel(matte_tex, tex_sampler, vec2<f32>(x.x, y.x), 0.0) * group_x.x
+ + textureSampleLevel(matte_tex, tex_sampler, vec2<f32>(x.y, y.x), 0.0) * group_x.y;
+ let bottom = textureSampleLevel(matte_tex, tex_sampler, vec2<f32>(x.x, y.y), 0.0) * group_x.x
+ + textureSampleLevel(matte_tex, tex_sampler, vec2<f32>(x.y, y.y), 0.0) * group_x.y;
+ return top * group_y.x + bottom * group_y.y;
+}
+
+// Applies the guided filter at full resolution, then tightens the soft
+// matte so only genuinely mixed pixels (hair, motion) stay translucent.
fn foreground_alpha(uv: vec2<f32>, color: vec3<f32>) -> f32 {
- let center = textureSampleLevel(mask_tex, tex_sampler, uv, 0.0).r;
- if center <= 0.01 || center >= 0.99 {
- return center;
- }
- let texel = 1.0 / vec2<f32>(textureDimensions(mask_tex));
- var total = 0.0;
- var weights = 0.0;
- for (var y = -1; y <= 1; y += 1) {
- for (var x = -1; x <= 1; x += 1) {
- let offset = vec2<f32>(f32(x), f32(y));
- let sample_uv = uv + offset * texel;
- let neighbor = textureSampleLevel(sharp_tex, tex_sampler, sample_uv, 0.0).rgb;
- let difference = neighbor - color;
- let weight = exp(-dot(difference, difference) * 40.0 - dot(offset, offset) * 0.5);
- total += textureSampleLevel(mask_tex, tex_sampler, sample_uv, 0.0).r * weight;
- weights += weight;
- }
- }
- return clamp(total / weights, 0.0, 1.0);
+ let coefficients = matte_coefficients(uv);
+ let matte = dot(coefficients.rgb, color) + coefficients.a;
+ let t = clamp((matte - MATTE_LOW) / (MATTE_HIGH - MATTE_LOW), 0.0, 1.0);
+ return t * t * (3.0 - 2.0 * t);
}
@fragment
fn fs_background(in: VertexOutput) -> @location(0) vec4<f32> {
let sharp = textureSample(sharp_tex, tex_sampler, in.uv);
- let texel = 1.0 / vec2<f32>(textureDimensions(mask_tex));
+ // Dilate by one output texel of this downscaled pass, so the background
+ // estimate stays clear of the subject whatever the mask resolution.
+ let texel = fwidth(in.uv);
var foreground = textureSample(mask_tex, tex_sampler, in.uv).r;
foreground = max(foreground, textureSample(mask_tex, tex_sampler, in.uv + vec2<f32>(texel.x, 0.0)).r);
foreground = max(foreground, textureSample(mask_tex, tex_sampler, in.uv - vec2<f32>(texel.x, 0.0)).r);
@@ -71,41 +98,22 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
return vec4<f32>(mix(background, sharp.rgb, alpha), sharp.a);
}
-fn cubic_weights(fraction: f32) -> vec4<f32> {
- let inverse = 1.0 - fraction;
- let square = fraction * fraction;
- let cube = square * fraction;
- return vec4<f32>(
- inverse * inverse * inverse,
- 3.0 * cube - 6.0 * square + 4.0,
- -3.0 * cube + 3.0 * square + 3.0 * fraction + 1.0,
- cube,
- ) / 6.0;
-}
-
-fn smooth_cutout_alpha(uv: vec2<f32>) -> f32 {
- let size = vec2<f32>(textureDimensions(mask_tex));
- let position = uv * size - 0.5;
- let base = floor(position);
- let fraction = fract(position);
- let x_weights = cubic_weights(fraction.x);
- let y_weights = cubic_weights(fraction.y);
- let x_groups = x_weights.xz + x_weights.yw;
- let y_groups = y_weights.xz + y_weights.yw;
- let x = (base.x + vec2<f32>(-0.5, 1.5) + x_weights.yw / x_groups) / size.x;
- let y = (base.y + vec2<f32>(-0.5, 1.5) + y_weights.yw / y_groups) / size.y;
- let top_left = textureSampleLevel(mask_tex, tex_sampler, vec2<f32>(x.x, y.x), 0.0).r;
- let top_right = textureSampleLevel(mask_tex, tex_sampler, vec2<f32>(x.y, y.x), 0.0).r;
- let bottom_left = textureSampleLevel(mask_tex, tex_sampler, vec2<f32>(x.x, y.y), 0.0).r;
- let bottom_right = textureSampleLevel(mask_tex, tex_sampler, vec2<f32>(x.y, y.y), 0.0).r;
- let top = mix(top_left, top_right, x_groups.y);
- let bottom = mix(bottom_left, bottom_right, x_groups.y);
- return mix(top, bottom, y_groups.y);
-}
-
@fragment
fn fs_cutout(in: VertexOutput) -> @location(0) vec4<f32> {
let sharp = textureSample(sharp_tex, tex_sampler, in.uv);
- let alpha = clamp((smooth_cutout_alpha(in.uv) - 0.04) / 0.96, 0.0, 1.0);
- return vec4<f32>(sharp.rgb, sharp.a * alpha);
+ let alpha = foreground_alpha(in.uv, sharp.rgb);
+ // Edge pixels are a blend of the person and the room behind them.
+ // Unmixing against the local background estimate (I = aF + (1 - a)B)
+ // stops the old wall colour from fringing the cutout.
+ let background = textureSampleLevel(blurred_tex, tex_sampler, in.uv, 0.0);
+ var color = sharp.rgb;
+ // The estimate is only trusted where the pixel is mostly person, and its
+ // shift is capped: a wrong background guess near the face must not turn
+ // into a saturated fringe.
+ if alpha > 0.0 && alpha < 1.0 && background.a > 0.01 {
+ let unmixed = (sharp.rgb - (1.0 - alpha) * background.rgb / background.a) / alpha;
+ let shift = clamp(unmixed - sharp.rgb, vec3<f32>(-0.25), vec3<f32>(0.25));
+ color = clamp(sharp.rgb + shift * smoothstep(0.2, 0.6, alpha), vec3<f32>(0.0), vec3<f32>(1.0));
+ }
+ return vec4<f32>(color, sharp.a * alpha);
}
diff --git a/crates/camera-effects/src/vision.rs b/crates/camera-effects/src/vision.rs
new file mode 100644
index 000000000..fb2b46e70
--- /dev/null
+++ b/crates/camera-effects/src/vision.rs
@@ -0,0 +1,662 @@
+use anyhow::Context;
+use cidre::{arc, cf, cv, define_obj_type, ns, objc, vn};
+use std::sync::mpsc;
+use std::thread;
+
+use crate::mask_refinement::MaskRefiner;
+
+/// Largest frame handed to Vision. Its balanced person segmentation runs a
+/// fixed-size network, and on webcam footage a 960x540 input produces the
+/// same mask as the full 1080p frame while halving the readback.
+pub const MAX_INPUT_DIMENSIONS: (u32, u32) = (960, 540);
+
+unsafe extern "C" {
+ fn CVPixelBufferGetBaseAddress(pixel_buffer: &cv::PixelBuf) -> *mut u8;
+ fn CVPixelBufferGetBytesPerRow(pixel_buffer: &cv::PixelBuf) -> usize;
+}
+
+/// A BGRA camera frame handed to Vision without copying it. CF objects have
+/// atomic refcounts, so the retain can cross to the segmentation thread.
+pub struct SharedPixelBuffer(pub arc::R<cv::PixelBuf>);
+unsafe impl Send for SharedPixelBuffer {}
+
+/// A finished mask: one byte per sample, and its width and height.
+pub type VisionMask<'a> = (&'a [u8], (u32, u32));
+
+/// Apple Vision person segmentation (`VNGeneratePersonSegmentationRequest`).
+///
+/// Runs on the Neural Engine and is far more accurate than the bundled ONNX
+/// selfie model: it keeps desks, chairs, pillows and background people out
+/// of the mask. Segmentation is asynchronous: a frame is submitted, the
+/// caller keeps rendering with the previous mask, and the finished mask is
+/// collected on a later frame. The thread also owns the autorelease pool
+/// every Vision call needs, the stateful request's temporal smoothing, and
+/// the mask cleanup, so none of that CPU work lands on the render thread.
+pub struct VisionSegmenter {
+ requests: Option<mpsc::Sender<Message>>,
+ results: mpsc::Receiver<VisionJob>,
+ idle: Option<VisionJob>,
+ in_flight: bool,
+ generation: u64,
+ worker: Option<thread::JoinHandle<()>>,
+}
+
+enum Message {
+ Segment(VisionJob),
+ Reset,
+}
+
+enum VisionInput {
+ None,
+ Pixels,
+ PixelBuffer(SharedPixelBuffer),
+}
+
+struct VisionJob {
+ input: VisionInput,
+ bgra: Vec<u8>,
+ dimensions: (u32, u32),
+ generation: u64,
+ mask: Vec<u8>,
+ mask_dimensions: (u32, u32),
+ result: Result<(), String>,
+}
+
+impl VisionJob {
+ fn new() -> Self {
+ Self {
+ input: VisionInput::None,
+ bgra: Vec::new(),
+ dimensions: (0, 0),
+ generation: 0,
+ mask: Vec::new(),
+ mask_dimensions: (0, 0),
+ result: Ok(()),
+ }
+ }
+}
+
+define_obj_type!(
+ #[doc(alias = "VNGeneratePersonInstanceMaskRequest")]
+ PersonInstanceMaskRequest(vn::Request)
+);
+
+define_obj_type!(
+ #[doc(alias = "VNInstanceMaskObservation")]
+ InstanceMaskObservation(vn::Observation)
+);
+
+impl PersonInstanceMaskRequest {
+ /// macOS 14+. Looked up at runtime so older systems fall back to plain
+ /// person segmentation.
+ fn new() -> Option<arc::R<Self>> {
+ let class =
+ unsafe { objc::objc_getClass(c"VNGeneratePersonInstanceMaskRequest".as_ptr().cast()) }?;
+ let class: &objc::Class<Self> = unsafe { std::mem::transmute(class) };
+ Some(unsafe { class.new() })
+ }
+
+ #[objc::msg_send(results)]
+ fn results(&self) -> Option<arc::R<ns::Array<InstanceMaskObservation>>>;
+}
+
+impl InstanceMaskObservation {
+ /// One byte per sample: 0 is background, 1..n the person instances.
+ #[objc::msg_send(instanceMask)]
+ fn instance_mask(&self) -> &cv::PixelBuf;
+
+ #[objc::msg_send(generateMaskForInstances:error:)]
+ unsafe fn generate_mask_err<'ear>(
+ &self,
+ instances: &ns::IndexSet,
+ error: *mut Option<&'ear ns::Error>,
+ ) -> Option<&'ear cv::PixelBuf>;
+}
+
+/// Person instance masks separate everyone in frame, so only the presenter
+/// is kept: people walking behind, other passengers and their chairs never
+/// enter the cutout. They are also cheaper than balanced segmentation (~7ms
+/// against ~10ms). Plain segmentation is the macOS 12-13 fallback.
+enum Request {
+ Instances(arc::R<PersonInstanceMaskRequest>),
+ Segmentation(arc::R<vn::GenPersonSegmentationRequest>),
+}
+
+impl Request {
+ fn new() -> Self {
+ if std::env::var("CAP_CAMERA_SEGMENTATION").as_deref() != Ok("vision-segmentation")
+ && let Some(request) = PersonInstanceMaskRequest::new()
+ {
+ return Self::Instances(request);
+ }
+ Self::Segmentation(create_request())
+ }
+
+ fn as_request(&self) -> &vn::Request {
+ match self {
+ Self::Instances(request) => request.as_ref(),
+ Self::Segmentation(request) => request.as_ref(),
+ }
+ }
+}
+
+struct Session {
+ handler: arc::R<vn::SequenceRequestHandler>,
+ request: Request,
+ input: Option<arc::R<cv::PixelBuf>>,
+ cleanup: Cleanup,
+ instance_areas: Vec<usize>,
+}
+
+/// Drops Vision's low-confidence blobs (pillows, chair backs) that are
+/// detached from the person, and settles still regions over time while
+/// following motion immediately.
+#[derive(Default)]
+struct Cleanup {
+ refiner: Option<((u32, u32), MaskRefiner)>,
+ mask: Vec<f32>,
+ previous: Vec<f32>,
+ motion: Vec<u8>,
+}
+
+fn create_request() -> arc::R<vn::GenPersonSegmentationRequest> {
+ let mut request = vn::GenPersonSegmentationRequest::new();
+ // Fast (256x192) loses arms and keeps pillows even after the guided
+ // filter; accurate costs 50ms+ a frame. Balanced is the only level that
+ // holds up at camera rate.
+ request.set_quality_level(vn::GenPersonSegmentationRequestQualityLevel::Balanced);
+ request
+}
+
+impl Session {
+ fn new() -> Self {
+ Self {
+ handler: vn::SequenceRequestHandler::new(),
+ request: Request::new(),
+ input: None,
+ cleanup: Cleanup::default(),
+ instance_areas: Vec::new(),
+ }
+ }
+
+ fn reset(&mut self) {
+ self.handler = vn::SequenceRequestHandler::new();
+ self.request = Request::new();
+ self.cleanup.previous.clear();
+ }
+
+ fn segment(&mut self, job: &mut VisionJob) -> Result<(), String> {
+ let input = match &job.input {
+ VisionInput::PixelBuffer(buffer) => buffer.0.clone(),
+ VisionInput::Pixels => {
+ let (width, height) = (job.dimensions.0 as usize, job.dimensions.1 as usize);
+ if job.bgra.len() < width * height * 4 || width == 0 || height == 0 {
+ return Err("invalid segmentation input".into());
+ }
+ let input = match &mut self.input {
+ Some(input) if input.width() == width && input.height() == height => input,
+ slot => slot.insert(create_input(width, height)?),
+ };
+ write_bgra(input, &job.bgra, width, height)?;
+ input.clone()
+ }
+ VisionInput::None => return Err("missing segmentation input".into()),
+ };
+
+ let requests = ns::Array::<vn::Request>::from_slice(&[self.request.as_request()]);
+ self.handler
+ .perform_on_cv_pixel_buf(&requests, &input)
+ .map_err(|error| format!("Vision person segmentation failed: {error:?}"))?;
+ match &self.request {
+ Request::Segmentation(request) => {
+ let results = request.results().ok_or("Vision returned no segmentation")?;
+ let observation = results
+ .get(0)
+ .map_err(|_| "Vision returned no segmentation".to_string())?;
+ read_mask(
+ observation.pixel_buffer(),
+ &mut self.cleanup.mask,
+ &mut job.mask_dimensions,
+ )?;
+ }
+ Request::Instances(request) => {
+ let observation = request.results().and_then(|results| {
+ results
+ .get(0)
+ .ok()
+ .map(|observation| observation.retained())
+ });
+ match observation {
+ Some(observation) => primary_person_mask(
+ &observation,
+ &mut self.instance_areas,
+ &mut self.cleanup.mask,
+ &mut job.mask_dimensions,
+ )?,
+ None => {
+ // Nobody in frame: an empty mask at the last size.
+ if job.mask_dimensions == (0, 0) {
+ job.mask_dimensions = (512, 384);
+ }
+ let (width, height) = job.mask_dimensions;
+ self.cleanup.mask.clear();
+ self.cleanup.mask.resize((width * height) as usize, 0.0);
+ }
+ }
+ }
+ }
+ self.cleanup.motion_frame(&input, job.mask_dimensions)?;
+ self.cleanup.finish(job.mask_dimensions, &mut job.mask);
+ Ok(())
+ }
+}
+
+impl Cleanup {
+ /// Samples the analysed frame on the mask's grid, which is what the
+ /// motion-adaptive smoothing compares between frames.
+ fn motion_frame(
+ &mut self,
+ frame: &cv::PixelBuf,
+ (width, height): (u32, u32),
+ ) -> Result<(), String> {
+ let (source_width, source_height) = (frame.width(), frame.height());
+ let motion = &mut self.motion;
+ motion.clear();
+ with_locked_base(
+ &mut frame.retained(),
+ cv::pixel_buffer::LockFlags::READ_ONLY,
+ |base, stride| {
+ if stride < source_width * 4 {
+ return Err("segmentation frame is not addressable".into());
+ }
+ for y in 0..height as usize {
+ let row = unsafe { base.add(y * source_height / height as usize * stride) };
+ for x in 0..width as usize {
+ let pixel = unsafe {
+ std::slice::from_raw_parts(
+ row.add(x * source_width / width as usize * 4),
+ 4,
+ )
+ };
+ motion.extend_from_slice(pixel);
+ }
+ }
+ Ok(())
+ },
+ )
+ }
+
+ fn finish(&mut self, dimensions: (u32, u32), output: &mut Vec<u8>) {
+ let (refiner, resized) = match &mut self.refiner {
+ Some((current, refiner)) if *current == dimensions => (refiner, false),
+ slot => (
+ &mut slot
+ .insert((
+ dimensions,
+ MaskRefiner::new(dimensions.0 as usize, dimensions.1 as usize),
+ ))
+ .1,
+ true,
+ ),
+ };
+ // Pockets up to 0.75% of the frame: logos, glare, jewellery.
+ let max_hole = self.mask.len() * 3 / 400;
+ refiner.fill_holes(&mut self.mask, max_hole);
+ let smooth = !resized && self.previous.len() == self.mask.len();
+ refiner.refine(&mut self.mask, &self.previous, &mut self.motion, smooth);
+ self.previous.clear();
+ self.previous.extend_from_slice(&self.mask);
+ output.clear();
+ output.extend(self.mask.iter().map(|value| (value * 255.0).round() as u8));
+ }
+}
+
+fn create_input(width: usize, height: usize) -> Result<arc::R<cv::PixelBuf>, String> {
+ let properties = cf::Dictionary::new();
+ let attributes = cf::Dictionary::with_keys_values(
+ &[cv::pixel_buffer::keys::io_surf_props().as_ref()],
+ &[properties.as_ref()],
+ )
+ .ok_or("segmentation input attributes")?;
+ cv::PixelBuf::new(width, height, cv::PixelFormat::_32_BGRA, Some(&attributes))
+ .map_err(|error| format!("segmentation input buffer: {error:?}"))
+}
+
+fn write_bgra(
+ buffer: &mut cv::PixelBuf,
+ bgra: &[u8],
+ width: usize,
+ height: usize,
+) -> Result<(), String> {
+ let row = width * 4;
+ with_locked_base(
+ buffer,
+ cv::pixel_buffer::LockFlags::DEFAULT,
+ |base, stride| {
+ if stride < row {
+ return Err("segmentation input is not addressable".into());
+ }
+ for (y, source) in bgra.chunks_exact(row).take(height).enumerate() {
+ unsafe {
+ std::ptr::copy_nonoverlapping(source.as_ptr(), base.add(y * stride), row)
+ };
+ }
+ Ok(())
+ },
+ )
+}
+
+/// The soft mask of the largest person, which for a camera bubble is the
+/// presenter.
+fn primary_person_mask(
+ observation: &InstanceMaskObservation,
+ areas: &mut Vec<usize>,
+ output: &mut Vec<f32>,
+ dimensions: &mut (u32, u32),
+) -> Result<(), String> {
+ let labels = observation.instance_mask();
+ let (width, height) = (labels.width(), labels.height());
+ areas.clear();
+ areas.resize(256, 0);
+ with_locked_base(
+ &mut labels.retained(),
+ cv::pixel_buffer::LockFlags::READ_ONLY,
+ |base, stride| {
+ if stride < width {
+ return Err("Vision instance mask is not addressable".into());
+ }
+ for y in 0..height {
+ let row = unsafe { std::slice::from_raw_parts(base.add(y * stride), width) };
+ for &label in row {
+ areas[usize::from(label)] += 1;
+ }
+ }
+ Ok(())
+ },
+ )?;
+ let Some(primary) = (1..areas.len())
+ .filter(|&label| areas[label] > 0)
+ .max_by_key(|&label| areas[label])
+ else {
+ output.clear();
+ output.resize(width * height, 0.0);
+ *dimensions = (width as u32, height as u32);
+ return Ok(());
+ };
+ let instances = ns::IndexSet::with_index(primary);
+ let mut error = None;
+ let mask = unsafe { observation.generate_mask_err(&instances, &mut error) }
+ .ok_or_else(|| format!("Vision instance mask failed: {error:?}"))?;
+ read_mask(mask, output, dimensions)
+}
+
+fn read_mask(
+ mask: &cv::PixelBuf,
+ output: &mut Vec<f32>,
+ dimensions: &mut (u32, u32),
+) -> Result<(), String> {
+ let format = mask.pixel_format();
+ let bytes_per_sample = if format == cv::PixelFormat::ONE_COMPONENT_8 {
+ 1
+ } else if format == cv::PixelFormat::ONE_COMPONENT_F32 {
+ 4
+ } else {
+ return Err(format!("unexpected Vision mask format {format:?}"));
+ };
+ let (width, height) = (mask.width(), mask.height());
+ output.clear();
+ with_locked_base(
+ &mut mask.retained(),
+ cv::pixel_buffer::LockFlags::READ_ONLY,
+ |base, stride| {
+ if stride < width * bytes_per_sample {
+ return Err("Vision mask is not addressable".into());
+ }
+ for y in 0..height {
+ let row = unsafe { base.add(y * stride) };
+ if bytes_per_sample == 1 {
+ let row = unsafe { std::slice::from_raw_parts(row, width) };
+ output.extend(row.iter().map(|&value| f32::from(value) / 255.0));
+ } else {
+ let row = unsafe { std::slice::from_raw_parts(row.cast::<f32>(), width) };
+ output.extend(row.iter().map(|value| value.clamp(0.0, 1.0)));
+ }
+ }
+ Ok(())
+ },
+ )?;
+ *dimensions = (width as u32, height as u32);
+ Ok(())
+}
+
+fn with_locked_base<R>(
+ buffer: &mut cv::PixelBuf,
+ flags: cv::pixel_buffer::LockFlags,
+ body: impl FnOnce(*mut u8, usize) -> Result<R, String>,
+) -> Result<R, String> {
+ unsafe {
+ buffer
+ .lock_base_addr(flags)
+ .result()
+ .map_err(|error| format!("lock pixel buffer: {error:?}"))?;
+ let base = CVPixelBufferGetBaseAddress(buffer);
+ let stride = CVPixelBufferGetBytesPerRow(buffer);
+ let result = if base.is_null() {
+ Err("pixel buffer has no base address".into())
+ } else {
+ body(base, stride)
+ };
+ let _ = buffer.unlock_lock_base_addr(flags);
+ result
+ }
+}
+
+impl VisionSegmenter {
+ pub fn new() -> anyhow::Result<Self> {
+ let (ready_tx, ready_rx) = mpsc::channel::<Result<(), String>>();
+ let (requests, request_rx) = mpsc::channel::<Message>();
+ let (result_tx, results) = mpsc::channel::<VisionJob>();
+
+ let worker = thread::Builder::new()
+ .name("cap-vision-segmentation".into())
+ .spawn(move || {
+ // A frame is waiting on every mask: keep this thread on the
+ // performance cores rather than letting it drift to the
+ // efficiency cores at default QoS.
+ unsafe {
+ libc::pthread_set_qos_class_self_np(
+ libc::qos_class_t::QOS_CLASS_USER_INTERACTIVE,
+ 0,
+ );
+ }
+ // Probe once so an unavailable request fails construction and
+ // the caller falls back to ONNX instead of failing every frame.
+ let mut session = Session::new();
+ let mut probe = VisionJob::new();
+ probe.input = VisionInput::Pixels;
+ probe.bgra = vec![0; 64 * 64 * 4];
+ probe.dimensions = (64, 64);
+ if let Err(error) = objc::ar_pool(|| session.segment(&mut probe)) {
+ let _ = ready_tx.send(Err(error));
+ return;
+ }
+ session.reset();
+ let _ = ready_tx.send(Ok(()));
+ while let Ok(message) = request_rx.recv() {
+ match message {
+ Message::Reset => session.reset(),
+ Message::Segment(mut job) => {
+ job.result = objc::ar_pool(|| session.segment(&mut job));
+ job.input = VisionInput::None;
+ if result_tx.send(job).is_err() {
+ break;
+ }
+ }
+ }
+ }
+ })
+ .context("Failed to start the Vision segmentation thread")?;
+
+ match ready_rx.recv() {
+ Ok(Ok(())) => {
+ tracing::info!("Camera background segmentation: Apple Vision person segmentation");
+ Ok(Self {
+ requests: Some(requests),
+ results,
+ idle: Some(VisionJob::new()),
+ in_flight: false,
+ generation: 0,
+ worker: Some(worker),
+ })
+ }
+ Ok(Err(error)) => {
+ let _ = worker.join();
+ Err(anyhow::anyhow!(error))
+ }
+ Err(_) => {
+ let _ = worker.join();
+ Err(anyhow::anyhow!(
+ "Vision segmentation thread exited during startup"
+ ))
+ }
+ }
+ }
+
+ /// Clears temporal state so a seek or a new camera does not blend into
+ /// the previous scene. A mask still in flight is discarded on arrival.
+ pub fn reset(&mut self) {
+ self.generation = self.generation.wrapping_add(1);
+ if let Some(requests) = &self.requests {
+ let _ = requests.send(Message::Reset);
+ }
+ }
+
+ pub fn is_busy(&self) -> bool {
+ self.in_flight
+ }
+
+ pub fn submit_pixels(&mut self, bgra: &[u8], dimensions: (u32, u32)) -> anyhow::Result<()> {
+ let mut job = self.take_idle()?;
+ job.bgra.clear();
+ job.bgra.extend_from_slice(bgra);
+ job.dimensions = dimensions;
+ job.input = VisionInput::Pixels;
+ self.send(job)
+ }
+
+ pub fn submit_pixel_buffer(&mut self, buffer: SharedPixelBuffer) -> anyhow::Result<()> {
+ let mut job = self.take_idle()?;
+ job.dimensions = (buffer.0.width() as u32, buffer.0.height() as u32);
+ job.input = VisionInput::PixelBuffer(buffer);
+ self.send(job)
+ }
+
+ /// The finished mask and its dimensions, if one has arrived. `wait`
+ /// blocks until the in-flight frame completes.
+ pub fn collect(&mut self, wait: bool) -> Option<anyhow::Result<VisionMask<'_>>> {
+ if !self.in_flight {
+ return None;
+ }
+ let job = if wait {
+ match self.results.recv() {
+ Ok(job) => job,
+ Err(_) => {
+ self.in_flight = false;
+ return Some(Err(anyhow::anyhow!("Vision segmentation thread stopped")));
+ }
+ }
+ } else {
+ match self.results.try_recv() {
+ Ok(job) => job,
+ Err(mpsc::TryRecvError::Empty) => return None,
+ Err(mpsc::TryRecvError::Disconnected) => {
+ self.in_flight = false;
+ return Some(Err(anyhow::anyhow!("Vision segmentation thread stopped")));
+ }
+ }
+ };
+ self.in_flight = false;
+ let stale = job.generation != self.generation;
+ let job = self.idle.insert(job);
+ if stale {
+ return None;
+ }
+ Some(match std::mem::replace(&mut job.result, Ok(())) {
+ Ok(()) => Ok((&job.mask, job.mask_dimensions)),
+ Err(error) => Err(anyhow::anyhow!(error)),
+ })
+ }
+
+ fn take_idle(&mut self) -> anyhow::Result<VisionJob> {
+ anyhow::ensure!(!self.in_flight, "Vision segmentation is busy");
+ Ok(self.idle.take().unwrap_or_else(VisionJob::new))
+ }
+
+ fn send(&mut self, mut job: VisionJob) -> anyhow::Result<()> {
+ job.generation = self.generation;
+ self.requests
+ .as_ref()
+ .context("Vision segmentation thread stopped")?
+ .send(Message::Segment(job))
+ .map_err(|_| anyhow::anyhow!("Vision segmentation thread stopped"))?;
+ self.in_flight = true;
+ Ok(())
+ }
+}
+
+impl Drop for VisionSegmenter {
+ fn drop(&mut self) {
+ self.requests = None;
+ if let Some(worker) = self.worker.take() {
+ let _ = worker.join();
+ }
+ }
+}
+
+pub fn input_dimensions(width: u32, height: u32) -> (u32, u32) {
+ let (max_width, max_height) = MAX_INPUT_DIMENSIONS;
+ let (long, short) = if width >= height {
+ (max_width, max_height)
+ } else {
+ (max_height, max_width)
+ };
+ let scale = (f64::from(long) / f64::from(width.max(1)))
+ .min(f64::from(short) / f64::from(height.max(1)))
+ .min(1.0);
+ (
+ ((f64::from(width) * scale).round() as u32).max(1),
+ ((f64::from(height) * scale).round() as u32).max(1),
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn input_is_bounded_and_keeps_aspect() {
+ assert_eq!(input_dimensions(1920, 1080), (960, 540));
+ assert_eq!(input_dimensions(3840, 2160), (960, 540));
+ assert_eq!(input_dimensions(1080, 1920), (540, 960));
+ assert_eq!(input_dimensions(640, 480), (640, 480));
+ assert_eq!(input_dimensions(1440, 1080), (720, 540));
+ }
+
+ #[test]
+ #[ignore = "requires macOS Vision"]
+ fn segments_asynchronously_and_discards_masks_from_before_a_reset() {
+ let mut segmenter = VisionSegmenter::new().unwrap();
+ let frame = vec![128; 320 * 180 * 4];
+ segmenter.submit_pixels(&frame, (320, 180)).unwrap();
+ assert!(segmenter.is_busy());
+ assert!(segmenter.submit_pixels(&frame, (320, 180)).is_err());
+ let (mask, (width, height)) = segmenter.collect(true).unwrap().unwrap();
+ assert_eq!(mask.len(), (width * height) as usize);
+ assert!(!segmenter.is_busy());
+
+ segmenter.submit_pixels(&frame, (320, 180)).unwrap();
+ segmenter.reset();
+ assert!(segmenter.collect(true).is_none());
+ assert!(!segmenter.is_busy());
+ }
+}