From c1288ab89eaa9fb2111db1883c57527dd9aed72e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Thu, 26 Nov 2026 18:25:46 +0000 Subject: [PATCH 01/16] Add video effects to the own camera: colour filters, a mirror choice, and blur and backgrounds behind a segmenter (ADR-0068, needs owner approval) The worker applies the effect to the I420 camera picture before the own tile and the SFU. Colour filters (greyscale, warm, cool, brighten) and the mirror choice work now. Background blur and the four drawn backgrounds go through a segmenter interface; this build has no segmenter, so the worker refuses them, keeps the camera off for a join that asks for one, and never sends the plain picture instead. The model step waits for owner approval. The effect and the mirror are saved in the call device record, sent with the join, and changeable at once from the settings and the call window. The own preview stays mirrored by default, as before. Co-Authored-By: Claude Opus 5.5 --- crates/call-protocol/AGENTS.md | 3 +- crates/call-protocol/src/lib.rs | 450 +++++- crates/call-worker/AGENTS.md | 1 + crates/call-worker/src/effects.rs | 1248 +++++++++++++++++ crates/call-worker/src/main.rs | 2 + crates/call-worker/src/mapping.rs | 1 + crates/call-worker/src/segmenter.rs | 44 + crates/call-worker/src/session.rs | 106 +- crates/contracts/fixtures/call-status.json | 4 +- crates/contracts/generated/contracts.ts | 41 +- crates/contracts/src/lib.rs | 180 ++- crates/contracts/tests/contracts.rs | 19 + crates/contracts/tests/type-contracts.ts | 16 +- crates/core-protocol/src/lib.rs | 51 +- crates/core/AGENTS.md | 1 + crates/core/src/calls/controller.rs | 327 ++++- crates/core/src/calls/devices.rs | 171 ++- crates/core/src/calls/status.rs | 15 + crates/core/src/lib.rs | 84 +- crates/core/tests/serve.rs | 102 ++ ...rs-and-a-mirrored-preview-to-call-video.md | 250 ++++ docs/adr/index.md | 1 + frontend/AGENTS.md | 1 + frontend/src/App.svelte | 2 +- frontend/src/CallDevices.svelte | 59 +- frontend/src/CallVideo.svelte | 10 +- frontend/src/CallVideoEffects.svelte | 117 ++ frontend/src/CallWindow.svelte | 2 +- frontend/src/CallWindowDevices.svelte | 55 +- frontend/src/bridge/index.ts | 13 + frontend/src/callDevicePanel.ts | 70 +- frontend/src/calls.ts | 121 +- frontend/tests/bridge-calls.test.mjs | 5 + frontend/tests/calls.test.mjs | 5 +- frontend/tests/video-effects.test.mjs | 235 ++++ src-tauri/AGENTS.md | 2 +- src-tauri/build.rs | 1 + src-tauri/capabilities/call.json | 3 +- src-tauri/capabilities/main.json | 1 + .../autogenerated/call_video_effect.toml | 11 + src-tauri/src/lib.rs | 19 + src-tauri/tests/ipc.rs | 94 +- 42 files changed, 3862 insertions(+), 81 deletions(-) create mode 100644 crates/call-worker/src/effects.rs create mode 100644 crates/call-worker/src/segmenter.rs create mode 100644 docs/adr/0068-add-background-blur-backgrounds-colour-filters-and-a-mirrored-preview-to-call-video.md create mode 100644 frontend/src/CallVideoEffects.svelte create mode 100644 frontend/tests/video-effects.test.mjs create mode 100644 src-tauri/permissions/autogenerated/call_video_effect.toml diff --git a/crates/call-protocol/AGENTS.md b/crates/call-protocol/AGENTS.md index b0d89605..7fbd5465 100644 --- a/crates/call-protocol/AGENTS.md +++ b/crates/call-protocol/AGENTS.md @@ -17,7 +17,8 @@ This crate defines the bounded binary messages between the key-holding core and - Microphone settings (ADR-0062): wire version 11 added `ToWorker::SetMicrophone { auto_level, mic_gain }` (tag 16, no answer), and `Join` ends with `auto_level` and `mic_gain` (two bytes). `Reader::mic_gain` refuses a gain over `MAX_MIC_GAIN_PERCENT` (400) or off the step of `MIC_GAIN_STEP_PERCENT` (5); use `valid_mic_gain` wherever a gain is used. - Screen targets (ADR-0053 amendment of 25 November 2026, ADR-0064): wire version 12 changed `SetScreen`'s `ScreenTarget::Monitor` (tag 2) from a list index to the Windows GDI device name (`MonitorName`: a length byte, then 1 to `MAX_MONITOR_NAME` (32) printable ASCII bytes other than space: 0x21 to 0x7E, `u8::is_ascii_graphic`; a name with a space is an invalid value), the width and height, and the monitor's rectangle (`DesktopRect`: four big-endian `i32` edges, each side 1 to `MAX_MONITOR_SIDE`, each edge within `MAX_DESKTOP_COORDINATE` of 0), and added `ScreenTarget::Display { id, width, height }` (tag 3, the macOS CoreGraphics display ID, never 0). `Reader::monitor_size` refuses a side outside 1 to `MAX_MONITOR_SIDE`. Tag 1 (`Portal { node }`) is unchanged. - Call statistics (ADR-0066): wire version 13 added `ToWorker::SetStats { on }` (tag 17) and `FromWorker::Stats(CallStats)` (`src/stats.rs`). The message is closed and numeric: integers with a unit and a bound that the reader checks (`MAX_STATS_*`), `Option` for a value that is not known yet, at most `MAX_PARTICIPANTS` remote entries and `MAX_STATS_CONNECTIONS` connection entries, each participant (connection and identity) and each connection at most once. It carries no address, port, candidate type, SSRC, codec or other text beyond the already validated identities. The writer cuts each list to its limit and writes every entry as given; the caller (`mapping::stats` in the worker) leaves out an entry that the reader would refuse and clamps the numbers, because the reader refuses the whole message for one such entry. Tag 16 and wire version 11 are the microphone settings above (ADR-0062). The `MAX_STATS_*` bounds are repeated as `CALL_STATS_*` in `crates/contracts`; `crates/core/src/calls/stats.rs` checks at compile time that they match. -- Windows screen frames (ADR-0067, wire version 14): `ToWorker::ScreenFrames { share, handle }` (tag 18, `handle` never 0, a 32-bit handle value valid inside the worker) names the read end of the capture helper's frame pipe, directly before the `SetScreen` of the same share. `screen_frame.rs` is the pipe's own format, shared by the helper (writer) and the worker (reader): a media-protocol `Control` frame with a 23-byte frame message or a 7-byte end message, then, for a picture, one `RgbaPixels` frame that holds BGRA bytes. `read_item` checks the share number, the format, the size (`screen_capture_size_ok`), the stride (exactly `width * 4`, no padding) and the body length (`height * stride`, at most `MAX_FRAME_BYTES`) before it allocates the body, and `write_picture` refuses what the reader would refuse. `ScreenEnd` is a closed set (stopped, not found, unavailable). Change the reader and the writer together. The next wire change takes tag 19 and the next free version. +- Windows screen frames (ADR-0067, wire version 14): `ToWorker::ScreenFrames { share, handle }` (tag 18, `handle` never 0, a 32-bit handle value valid inside the worker) names the read end of the capture helper's frame pipe, directly before the `SetScreen` of the same share. `screen_frame.rs` is the pipe's own format, shared by the helper (writer) and the worker (reader): a media-protocol `Control` frame with a 23-byte frame message or a 7-byte end message, then, for a picture, one `RgbaPixels` frame that holds BGRA bytes. `read_item` checks the share number, the format, the size (`screen_capture_size_ok`), the stride (exactly `width * 4`, no padding) and the body length (`height * stride`, at most `MAX_FRAME_BYTES`) before it allocates the body, and `write_picture` refuses what the reader would refuse. `ScreenEnd` is a closed set (stopped, not found, unavailable). Change the reader and the writer together. +- Video effects (ADR-0068, proposed, wire version 15): `ToWorker::SetVideoEffect { effect }` (tag 19, during a call and during a camera test), `FromWorker::VideoEffect { effect, refused }` (tag 24, the effect in use), `CameraState::EffectUnavailable` (4), `Join` ends with the effect, and `Devices` ends with the `background_effects` flag (one byte, 0 or 1). The effect is three bytes: the background kind (0 none, 1 blur, 2 picture), its value (0 for none, the blur strength `BlurStrength` of 10 to 100 percent in steps of 10, or the `BackgroundPicture` 1 to 4), and the `ColourFilter` 0 to 4. `VideoEffect::from_bytes` refuses any other combination; `to_bytes` writes only what it accepts. The sets are closed: no image, path or URL crosses. The next wire change takes tag 20 to the worker, tag 25 from the worker, and version 16. - Coordinate wire changes with `crates/core` and `crates/call-worker` (planned), and bump the version byte. ## Checks diff --git a/crates/call-protocol/src/lib.rs b/crates/call-protocol/src/lib.rs index ace1e859..e8a26a23 100644 --- a/crates/call-protocol/src/lib.rs +++ b/crates/call-protocol/src/lib.rs @@ -22,7 +22,7 @@ pub use stats::{ VideoReceiveStats, VideoSendStats, }; -pub const VERSION: u8 = 14; +pub const VERSION: u8 = 15; pub const MAX_MESSAGE_BYTES: usize = 64 * 1024; /// Longest diagnostic record target (ADR-0058). pub const MAX_DIAGNOSTIC_TARGET_BYTES: usize = 64; @@ -165,6 +165,167 @@ pub const DEFAULT_MIC_GAIN_PERCENT: u16 = 100; pub const fn valid_mic_gain(percent: u16) -> bool { percent <= MAX_MIC_GAIN_PERCENT && percent.is_multiple_of(MIC_GAIN_STEP_PERCENT) } + +/// The weakest background blur, in percent (ADR-0068). +pub const MIN_BLUR_PERCENT: u8 = 10; +/// The strongest background blur, in percent (ADR-0068). +pub const MAX_BLUR_PERCENT: u8 = 100; +/// The blur strength moves in steps of this many percent (ADR-0068). +pub const BLUR_STEP_PERCENT: u8 = 10; +/// The blur strength that the page offers first (ADR-0068). +pub const DEFAULT_BLUR_PERCENT: u8 = 50; + +/// A background blur strength: [`MIN_BLUR_PERCENT`] to [`MAX_BLUR_PERCENT`] +/// in whole steps of [`BLUR_STEP_PERCENT`] (ADR-0068). No other value can be +/// made. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] +pub struct BlurStrength(u8); + +impl BlurStrength { + /// The strength of `percent`, or `None` when it is out of range or off + /// the step. + pub const fn new(percent: u8) -> Option { + if percent >= MIN_BLUR_PERCENT + && percent <= MAX_BLUR_PERCENT + && percent.is_multiple_of(BLUR_STEP_PERCENT) + { + Some(Self(percent)) + } else { + None + } + } + + pub const fn percent(self) -> u8 { + self.0 + } +} + +/// A background picture that the worker draws from code (ADR-0068). A +/// closed set; no image file is read. +#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] +#[repr(u8)] +pub enum BackgroundPicture { + Dusk = 1, + Sea = 2, + Forest = 3, + Studio = 4, +} + +impl BackgroundPicture { + pub const ALL: [Self; 4] = [Self::Dusk, Self::Sea, Self::Forest, Self::Studio]; +} + +impl TryFrom for BackgroundPicture { + type Error = DecodeError; + + fn try_from(value: u8) -> Result { + Ok(match value { + 1 => Self::Dusk, + 2 => Self::Sea, + 3 => Self::Forest, + 4 => Self::Studio, + _ => return Err(DecodeError::InvalidValue), + }) + } +} + +/// What the own camera shows behind the person (ADR-0068). +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)] +pub enum Background { + /// The camera's own background. + #[default] + None, + /// The background blurred, the person sharp. + Blur(BlurStrength), + /// The background replaced with a picture, the person kept. + Picture(BackgroundPicture), +} + +/// A colour filter on the whole own camera picture (ADR-0068). A closed set. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)] +#[repr(u8)] +pub enum ColourFilter { + #[default] + None = 0, + Greyscale = 1, + Warm = 2, + Cool = 3, + /// Lifts the dark parts of the picture. + Brighten = 4, +} + +impl ColourFilter { + pub const ALL: [Self; 5] = [ + Self::None, + Self::Greyscale, + Self::Warm, + Self::Cool, + Self::Brighten, + ]; +} + +impl TryFrom for ColourFilter { + type Error = DecodeError; + + fn try_from(value: u8) -> Result { + Ok(match value { + 0 => Self::None, + 1 => Self::Greyscale, + 2 => Self::Warm, + 3 => Self::Cool, + 4 => Self::Brighten, + _ => return Err(DecodeError::InvalidValue), + }) + } +} + +/// The own camera's video effect (ADR-0068): the background first, then the +/// colour filter. The worker applies it to each camera picture before the +/// own preview and the SFU get it. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)] +pub struct VideoEffect { + pub background: Background, + pub filter: ColourFilter, +} + +impl VideoEffect { + /// No effect: the camera picture as captured. + pub const NONE: Self = Self { + background: Background::None, + filter: ColourFilter::None, + }; + + /// Whether the effect needs a person mask: blur and pictures do. + pub const fn needs_mask(self) -> bool { + !matches!(self.background, Background::None) + } + + /// The three wire bytes: the background kind (0 none, 1 blur, 2 + /// picture), its value (0, the blur strength or the picture number) and + /// the filter. + pub const fn to_bytes(self) -> [u8; 3] { + let (kind, value) = match self.background { + Background::None => (0, 0), + Background::Blur(strength) => (1, strength.percent()), + Background::Picture(picture) => (2, picture as u8), + }; + [kind, value, self.filter as u8] + } + + /// The effect of three wire bytes. Any byte outside its set is refused. + pub fn from_bytes([kind, value, filter]: [u8; 3]) -> Result { + let background = match kind { + 0 if value == 0 => Background::None, + 1 => Background::Blur(BlurStrength::new(value).ok_or(DecodeError::InvalidValue)?), + 2 => Background::Picture(BackgroundPicture::try_from(value)?), + _ => return Err(DecodeError::InvalidValue), + }; + Ok(Self { + background, + filter: ColourFilter::try_from(filter)?, + }) + } +} /// The highest received sound level (ADR-0055): 0 dBFS. 0 is -60 dBFS or /// quieter, and each step is 0.6 dB. pub const MAX_SOUND_LEVEL: u8 = 100; @@ -312,6 +473,8 @@ pub enum ToWorker { /// processing: 0 to [`MAX_MIC_GAIN_PERCENT`] in steps of /// [`MIC_GAIN_STEP_PERCENT`] (ADR-0062). mic_gain: u16, + /// The own camera's video effect (ADR-0068). + video_effect: VideoEffect, }, /// Only as the first message: report the devices, then exit. ListDevices, @@ -419,6 +582,13 @@ pub enum ToWorker { SetStats { on: bool, }, + /// Change the own camera's video effect in a running call or a camera + /// test (ADR-0068). The worker answers with [`FromWorker::VideoEffect`]. + /// An effect that the worker cannot apply is refused, and the old one + /// stays. + SetVideoEffect { + effect: VideoEffect, + }, } /// The device that [`ToWorker::TestDevice`] tests. A closed set. @@ -460,6 +630,7 @@ impl std::fmt::Debug for ToWorker { volume, auto_level, mic_gain, + video_effect, } => f .debug_struct("Join") .field("sfu_url", sfu_url) @@ -475,6 +646,7 @@ impl std::fmt::Debug for ToWorker { .field("volume", volume) .field("auto_level", auto_level) .field("mic_gain", mic_gain) + .field("video_effect", video_effect) .finish(), Self::ListDevices => f.write_str("ListDevices"), Self::SetKey { identity, key } => f @@ -545,6 +717,10 @@ impl std::fmt::Debug for ToWorker { .field("playout", playout) .finish(), Self::SetStats { on } => f.debug_struct("SetStats").field("on", on).finish(), + Self::SetVideoEffect { effect } => f + .debug_struct("SetVideoEffect") + .field("effect", effect) + .finish(), } } } @@ -765,6 +941,9 @@ pub enum CameraState { NotFound = 2, /// No camera, the OS denied it, it is in use, or capture failed. Unavailable = 3, + /// The chosen video effect cannot run, so the camera stays off + /// (ADR-0068). + EffectUnavailable = 4, } impl TryFrom for CameraState { @@ -776,6 +955,7 @@ impl TryFrom for CameraState { 1 => Self::On, 2 => Self::NotFound, 3 => Self::Unavailable, + 4 => Self::EffectUnavailable, _ => return Err(DecodeError::InvalidValue), }) } @@ -851,6 +1031,16 @@ pub enum FromWorker { recording: Vec, playout: Vec, cameras: Vec, + /// Whether this worker can run the effects that need a person mask: + /// background blur and pictures (ADR-0068). + background_effects: bool, + }, + /// The video effect in use, after every `SetVideoEffect` (ADR-0068). + /// `refused` is set when the worker could not apply the requested + /// effect; `effect` is then the one that stayed. + VideoEffect { + effect: VideoEffect, + refused: bool, }, /// The camera state. Sent after every `SetCamera`, after a join with /// the camera on, and when capture fails during a call. @@ -931,6 +1121,7 @@ const TO_SET_DEVICES: u8 = 15; const TO_SET_MICROPHONE: u8 = 16; const TO_SET_STATS: u8 = 17; const TO_SCREEN_FRAMES: u8 = 18; +const TO_SET_VIDEO_EFFECT: u8 = 19; // Tags of worker to core messages. const FROM_READY: u8 = 1; @@ -956,6 +1147,7 @@ const FROM_PARTICIPANT_LEVEL: u8 = 20; const FROM_PARTICIPANT_MUTED: u8 = 21; const FROM_DEVICES_SET: u8 = 22; const FROM_STATS: u8 = 23; +const FROM_VIDEO_EFFECT: u8 = 24; #[derive(Clone, Copy)] enum CharRule { @@ -993,6 +1185,12 @@ impl<'a> Reader<'a> { Ok(u16::from_be_bytes([bytes[0], bytes[1]])) } + /// A video effect: see [`VideoEffect::from_bytes`]. + fn video_effect(&mut self) -> Result { + let bytes = self.take(3)?; + VideoEffect::from_bytes([bytes[0], bytes[1], bytes[2]]) + } + /// A microphone gain: see [`valid_mic_gain`]. fn mic_gain(&mut self) -> Result { let percent = self.u16()?; @@ -1237,6 +1435,7 @@ impl ToWorker { volume, auto_level, mic_gain, + video_effect, } => { out.push(TO_JOIN); put_str(&mut out, sfu_url); @@ -1257,6 +1456,7 @@ impl ToWorker { out.push(*volume); out.push(u8::from(*auto_level)); out.extend_from_slice(&mic_gain.to_be_bytes()); + out.extend_from_slice(&video_effect.to_bytes()); } Self::ListDevices => out.push(TO_LIST_DEVICES), Self::SetKey { identity, key } => { @@ -1367,6 +1567,10 @@ impl ToWorker { out.push(TO_SET_STATS); out.push(u8::from(*on)); } + Self::SetVideoEffect { effect } => { + out.push(TO_SET_VIDEO_EFFECT); + out.extend_from_slice(&effect.to_bytes()); + } } out } @@ -1410,6 +1614,7 @@ impl ToWorker { volume: reader.volume()?, auto_level: reader.bool()?, mic_gain: reader.mic_gain()?, + video_effect: reader.video_effect()?, } } TO_LIST_DEVICES => Self::ListDevices, @@ -1509,6 +1714,9 @@ impl ToWorker { camera: reader.device_choice()?, }, TO_SET_STATS => Self::SetStats { on: reader.bool()? }, + TO_SET_VIDEO_EFFECT => Self::SetVideoEffect { + effect: reader.video_effect()?, + }, _ => return Err(DecodeError::UnknownTag), }; reader.finish()?; @@ -1526,6 +1734,7 @@ impl FromWorker { mut recording: Vec, mut playout: Vec, mut cameras: Vec, + background_effects: bool, ) -> Self { fn list_len(list: &[MediaDevice]) -> usize { // The count, then each ID and name with its two-byte length. @@ -1535,8 +1744,8 @@ impl FromWorker { .sum::() } loop { - // The version and the tag, then the three lists. - let size = 2 + list_len(&recording) + list_len(&playout) + list_len(&cameras); + // The version and the tag, the three lists, then the flag. + let size = 3 + list_len(&recording) + list_len(&playout) + list_len(&cameras); if size <= MAX_MESSAGE_BYTES { break; } @@ -1550,6 +1759,7 @@ impl FromWorker { recording, playout, cameras, + background_effects, } } @@ -1632,11 +1842,18 @@ impl FromWorker { recording, playout, cameras, + background_effects, } => { out.push(FROM_DEVICES); put_devices(&mut out, recording); put_devices(&mut out, playout); put_devices(&mut out, cameras); + out.push(u8::from(*background_effects)); + } + Self::VideoEffect { effect, refused } => { + out.push(FROM_VIDEO_EFFECT); + out.extend_from_slice(&effect.to_bytes()); + out.push(u8::from(*refused)); } Self::Camera { state } => { out.push(FROM_CAMERA); @@ -1752,6 +1969,11 @@ impl FromWorker { recording: reader.devices()?, playout: reader.devices()?, cameras: reader.devices()?, + background_effects: reader.bool()?, + }, + FROM_VIDEO_EFFECT => Self::VideoEffect { + effect: reader.video_effect()?, + refused: reader.bool()?, }, FROM_CAMERA => Self::Camera { state: CameraState::try_from(reader.u8()?)?, @@ -2100,6 +2322,10 @@ mod tests { volume: 65, auto_level: false, mic_gain: 250, + video_effect: VideoEffect { + background: Background::Blur(BlurStrength::new(40).expect("valid")), + filter: ColourFilter::Warm, + }, } } @@ -2125,6 +2351,7 @@ mod tests { volume: MAX_VOLUME_PERCENT, auto_level: true, mic_gain: DEFAULT_MIC_GAIN_PERCENT, + video_effect: VideoEffect::NONE, } .encode() .to_vec() @@ -2232,6 +2459,21 @@ mod tests { ToWorker::SetDiagnostics { on: false }, ToWorker::SetStats { on: true }, ToWorker::SetStats { on: false }, + ToWorker::SetVideoEffect { + effect: VideoEffect::NONE, + }, + ToWorker::SetVideoEffect { + effect: VideoEffect { + background: Background::Blur(BlurStrength::new(MAX_BLUR_PERCENT).unwrap()), + filter: ColourFilter::Greyscale, + }, + }, + ToWorker::SetVideoEffect { + effect: VideoEffect { + background: Background::Picture(BackgroundPicture::Studio), + filter: ColourFilter::Brighten, + }, + }, ToWorker::TestDevice { test: DeviceTest::Microphone, device: None, @@ -2302,11 +2544,13 @@ mod tests { recording: vec![device("{0.0.1.00000000}.{6a2c}", "Microphone (Headset)")], playout: vec![device("p", ""), device("q", "Lautsprecher (Ü)")], cameras: vec![device("usb#cam", "Integrated Camera")], + background_effects: true, }, FromWorker::Devices { recording: Vec::new(), playout: Vec::new(), cameras: Vec::new(), + background_effects: false, }, FromWorker::Camera { state: CameraState::Off, @@ -2320,6 +2564,23 @@ mod tests { FromWorker::Camera { state: CameraState::Unavailable, }, + FromWorker::Camera { + state: CameraState::EffectUnavailable, + }, + FromWorker::VideoEffect { + effect: VideoEffect { + background: Background::None, + filter: ColourFilter::Cool, + }, + refused: true, + }, + FromWorker::VideoEffect { + effect: VideoEffect { + background: Background::Picture(BackgroundPicture::Dusk), + filter: ColourFilter::None, + }, + refused: false, + }, FromWorker::Screen { state: ScreenState::Off, share: 3, @@ -2622,11 +2883,11 @@ mod tests { Err(DecodeError::UnknownTag) ); assert_eq!( - ToWorker::decode(&[VERSION, 19]), + ToWorker::decode(&[VERSION, 20]), Err(DecodeError::UnknownTag) ); assert_eq!( - FromWorker::decode(&[VERSION, 24]), + FromWorker::decode(&[VERSION, 25]), Err(DecodeError::UnknownTag) ); assert_eq!(FromWorker::decode(&[]), Err(DecodeError::Truncated)); @@ -2799,6 +3060,7 @@ mod tests { volume: MAX_VOLUME_PERCENT, auto_level: true, mic_gain: DEFAULT_MIC_GAIN_PERCENT, + video_effect: VideoEffect::NONE, } } @@ -2820,9 +3082,10 @@ mod tests { recording: full('r'), playout: full('p'), cameras: full('c'), + background_effects: true, }; assert!(unfitted.encode().len() > MAX_MESSAGE_BYTES); - let fitted = FromWorker::devices(full('r'), full('p'), full('c')); + let fitted = FromWorker::devices(full('r'), full('p'), full('c'), true); let encoded = fitted.encode(); assert!(encoded.len() <= MAX_MESSAGE_BYTES); assert!(write_message(&mut Vec::new(), &fitted).is_ok()); @@ -2831,6 +3094,7 @@ mod tests { recording, playout, cameras, + background_effects: true, } = fitted else { panic!("not a device list"); @@ -2846,6 +3110,7 @@ mod tests { vec![device("r", "R")], vec![device("p", "P")], vec![device("c", "C")], + false, ); assert_eq!( small, @@ -2853,6 +3118,7 @@ mod tests { recording: vec![device("r", "R")], playout: vec![device("p", "P")], cameras: vec![device("c", "C")], + background_effects: false, } ); } @@ -2869,6 +3135,7 @@ mod tests { recording, playout: Vec::new(), cameras: Vec::new(), + background_effects: false, }; let full_id = "d".repeat(MAX_DEVICE_ID_BYTES); let full_name = "n".repeat(MAX_DEVICE_NAME_BYTES); @@ -2950,6 +3217,7 @@ mod tests { recording: vec![cut], playout: vec![named], cameras: Vec::new(), + background_effects: false, }; assert!(FromWorker::decode(&fits.encode()).is_ok()); } @@ -3168,7 +3436,7 @@ mod tests { &[VERSION, FROM_VIDEO_STARTED, 1, 0, 0, 0], DecodeError::TooShort, ), - (&[VERSION, FROM_CAMERA, 4], invalid), + (&[VERSION, FROM_CAMERA, 5], invalid), ]; for (body, expected) in cases { assert_eq!(FromWorker::decode(body), Err(expected), "{body:?}"); @@ -3244,7 +3512,7 @@ mod tests { /// 640x360 at 15 per second. #[test] fn given_tiles_when_limits_asked_then_screen_differs_from_camera() { - assert_eq!((VIDEO_TILES, SCREEN_TILE, VERSION), (6, 5, 14)); + assert_eq!((VIDEO_TILES, SCREEN_TILE, VERSION), (6, 5, 15)); assert_eq!(MAX_SCREEN_BYTES, 3_686_400); assert_eq!(MAX_SCREEN_PIXELS, 921_600); for tile in 0..SCREEN_TILE { @@ -3585,6 +3853,7 @@ mod tests { volume: 0, auto_level: true, mic_gain: DEFAULT_MIC_GAIN_PERCENT, + video_effect: VideoEffect::NONE, } .encode() }; @@ -3601,6 +3870,7 @@ mod tests { recording: Vec::new(), playout: Vec::new(), cameras, + background_effects: false, }; let full: Vec = (0..MAX_DEVICES).map(|_| device("c", "n")).collect(); assert!(FromWorker::decode(&cameras(full).encode()).is_ok()); @@ -3747,13 +4017,13 @@ mod tests { ); } - /// GIVEN a message of the previous wire versions (6 to 13) + /// GIVEN a message of the previous wire versions (6 to 14) /// WHEN it is decoded in either direction /// THEN the version is refused. #[test] fn given_older_wire_versions_when_decoded_then_they_are_refused() { - assert_eq!(VERSION, 14); - for old in [6, 7, 8, 9, 10, 11, 12, 13] { + assert_eq!(VERSION, 15); + for old in [6, 7, 8, 9, 10, 11, 12, 13, 14] { assert_eq!( ToWorker::decode(&[old, TO_LEAVE]), Err(DecodeError::UnknownVersion) @@ -3811,8 +4081,9 @@ mod tests { panic!("join decodes"); }; assert_eq!(volume, 65); - // The volume, the automatic level flag and the two gain bytes end it. - let at = body.len() - 4; + // The volume, the automatic level flag, the two gain bytes and the + // three effect bytes end it. + let at = body.len() - 7; body[at] = MAX_VOLUME_PERCENT + 1; assert_eq!(ToWorker::decode(&body), Err(DecodeError::InvalidValue)); } @@ -3859,12 +4130,13 @@ mod tests { ToWorker::decode(&[VERSION, TO_SET_MICROPHONE, 1, 0, 100, 0]), Err(DecodeError::TrailingBytes) ); - // A Join with a gain over the limit is refused as a whole. + // A Join with a gain over the limit is refused as a whole. The gain + // comes before the three effect bytes. let mut body = join().encode().to_vec(); - let end = body.len(); - body[end - 2..].copy_from_slice(&405_u16.to_be_bytes()); + let end = body.len() - 3; + body[end - 2..end].copy_from_slice(&405_u16.to_be_bytes()); assert_eq!(ToWorker::decode(&body), invalid); - body[end - 2..].copy_from_slice(&MAX_MIC_GAIN_PERCENT.to_be_bytes()); + body[end - 2..end].copy_from_slice(&MAX_MIC_GAIN_PERCENT.to_be_bytes()); assert!(matches!( ToWorker::decode(&body), Ok(ToWorker::Join { @@ -3876,6 +4148,150 @@ mod tests { assert!(!valid_mic_gain(2) && !valid_mic_gain(405)); } + /// Every video effect: each background with each filter. + fn all_effects() -> Vec { + let mut backgrounds = vec![Background::None]; + backgrounds.extend( + (MIN_BLUR_PERCENT..=MAX_BLUR_PERCENT) + .step_by(usize::from(BLUR_STEP_PERCENT)) + .map(|percent| Background::Blur(BlurStrength::new(percent).unwrap())), + ); + backgrounds.extend(BackgroundPicture::ALL.map(Background::Picture)); + backgrounds + .into_iter() + .flat_map(|background| { + ColourFilter::ALL.map(|filter| VideoEffect { background, filter }) + }) + .collect() + } + + /// GIVEN every blur strength from 0 to 255 + /// WHEN it is checked + /// THEN exactly 10 to 100 in steps of 10 are strengths. + #[test] + fn given_blur_percent_when_checked_then_only_the_steps_are_strengths() { + let accepted: Vec = (0..=u8::MAX) + .filter(|percent| BlurStrength::new(*percent).is_some()) + .collect(); + assert_eq!(accepted, [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]); + assert_eq!( + BlurStrength::new(DEFAULT_BLUR_PERCENT).map(BlurStrength::percent), + Some(50) + ); + } + + /// GIVEN every video effect + /// WHEN it is sent in a SetVideoEffect, a Join and a VideoEffect answer + /// THEN it round-trips as its three documented bytes, and only blur and + /// pictures need the person mask. + #[test] + fn given_every_video_effect_when_round_tripped_then_it_is_unchanged() { + let effects = all_effects(); + assert_eq!(effects.len(), (1 + 10 + 4) * 5); + for effect in effects { + let set = ToWorker::SetVideoEffect { effect }; + assert_eq!(ToWorker::decode(&set.encode()), Ok(set)); + let answer = FromWorker::VideoEffect { + effect, + refused: false, + }; + assert_eq!(FromWorker::decode(&answer.encode()), Ok(answer)); + let mut body = join().encode().to_vec(); + let end = body.len(); + body[end - 3..].copy_from_slice(&effect.to_bytes()); + assert!(matches!( + ToWorker::decode(&body), + Ok(ToWorker::Join { video_effect, .. }) if video_effect == effect + )); + assert_eq!( + effect.needs_mask(), + effect.background != Background::None, + "{effect:?}" + ); + } + let blur = VideoEffect { + background: Background::Blur(BlurStrength::new(30).unwrap()), + filter: ColourFilter::Warm, + }; + assert_eq!(blur.to_bytes(), [1, 30, 2]); + let picture = VideoEffect { + background: Background::Picture(BackgroundPicture::Forest), + filter: ColourFilter::None, + }; + assert_eq!(picture.to_bytes(), [2, 3, 0]); + assert_eq!(VideoEffect::NONE.to_bytes(), [0, 0, 0]); + assert_eq!(VideoEffect::default(), VideoEffect::NONE); + } + + /// GIVEN video effect bytes outside their sets, or a short or long + /// message + /// WHEN they are decoded in a SetVideoEffect, a Join or an answer + /// THEN each is refused. + #[test] + fn given_bad_video_effect_bytes_when_decoded_then_they_are_refused() { + let invalid = Some(DecodeError::InvalidValue); + for bytes in [ + [0, 1, 0], // no background with a value + [1, 0, 0], // blur of 0 + [1, 5, 0], // blur off the step + [1, 110, 0], // blur over the top + [2, 0, 0], // picture 0 + [2, 5, 0], // picture past the set + [3, 0, 0], // an unknown kind + [0, 0, 5], // an unknown filter + [0, 0, 255], + ] { + assert_eq!(VideoEffect::from_bytes(bytes).err(), invalid, "{bytes:?}"); + let set = [VERSION, TO_SET_VIDEO_EFFECT, bytes[0], bytes[1], bytes[2]]; + assert_eq!(ToWorker::decode(&set).err(), invalid, "{bytes:?}"); + let answer = [VERSION, FROM_VIDEO_EFFECT, bytes[0], bytes[1], bytes[2], 0]; + assert_eq!(FromWorker::decode(&answer).err(), invalid, "{bytes:?}"); + let mut body = join().encode().to_vec(); + let end = body.len(); + body[end - 3..].copy_from_slice(&bytes); + assert_eq!(ToWorker::decode(&body).err(), invalid, "{bytes:?}"); + } + // A bad refused flag, and a short or long message. + assert_eq!( + FromWorker::decode(&[VERSION, FROM_VIDEO_EFFECT, 0, 0, 0, 2]).err(), + invalid + ); + assert_eq!( + ToWorker::decode(&[VERSION, TO_SET_VIDEO_EFFECT, 0, 0]), + Err(DecodeError::Truncated) + ); + assert!(ToWorker::decode(&[VERSION, TO_SET_VIDEO_EFFECT, 0, 0, 0, 0]).is_err()); + let mut short_join = join().encode().to_vec(); + short_join.pop(); + assert_eq!(ToWorker::decode(&short_join), Err(DecodeError::Truncated)); + // The new camera state decodes; the next value does not. + assert_eq!( + FromWorker::decode(&[VERSION, FROM_CAMERA, 4]), + Ok(FromWorker::Camera { + state: CameraState::EffectUnavailable + }) + ); + assert_eq!( + FromWorker::decode(&[VERSION, FROM_CAMERA, 5]).err(), + invalid + ); + } + + /// GIVEN a device list whose background effects flag is not 0 or 1, or + /// is missing + /// WHEN it is decoded + /// THEN it is refused. + #[test] + fn given_bad_background_effects_flag_when_decoded_then_it_is_refused() { + let empty = FromWorker::devices(Vec::new(), Vec::new(), Vec::new(), true); + let mut body = empty.encode(); + assert_eq!(FromWorker::decode(&body), Ok(empty)); + *body.last_mut().unwrap() = 2; + assert_eq!(FromWorker::decode(&body), Err(DecodeError::InvalidValue)); + body.pop(); + assert_eq!(FromWorker::decode(&body), Err(DecodeError::Truncated)); + } + /// GIVEN a sound level over the top, or without its byte /// WHEN it is decoded /// THEN it is rejected; the top level itself decodes. diff --git a/crates/call-worker/AGENTS.md b/crates/call-worker/AGENTS.md index 04ba7e9b..4b540fc0 100644 --- a/crates/call-worker/AGENTS.md +++ b/crates/call-worker/AGENTS.md @@ -31,6 +31,7 @@ The contained process that runs one call (ADR-0043). It joins one LiveKit room w - Microphone settings (ADR-0062): `Join` carries `auto_level` and `mic_gain`, and `SetMicrophone` changes them in a running call. `mapping::Microphone::new` is the worker's own check (a gain over 400 percent or off the step of 5 is `Protocol`; the protocol reader refuses it first). The gain goes to the voice engine's audio processing module through `native::capture_processing::set_capture_gain_percent` (a process-wide value that every live factory applies); the automatic level goes to the published microphone track through `RtcAudioTrack::set_auto_gain_control`. Both apply at once, and `apply_microphone` applies both again after each `SetDevices`. The device tests (`sound_test.rs`) do not use them. A refusal is noted, never fatal. - Audio notes (ADR-0058 amendment of 2026-11-25): `note_audio` in `session.rs` writes `Note` records of the target `persephone::call_worker::audio` while the log is on: the devices at the join (counts and how each was chosen, never an ID or name), the microphone settings with what the audio processing module reports, and every 5 seconds the own level, the playout state and each remote audio track's packets, samples and level (`measure_levels`). Keep them to counts, flags and levels. Never add an identity, a device ID or name, a key or a token. - Call statistics (ADR-0066): `session/stats_probe.rs` reads `get_stats` of the own microphone, camera and screen tracks and of one audio and one video track of each remote participant (at most `MAX_PARTICIPANTS`), only while the core has sent `SetStats { on: true }`, at most once a second, on its own task with a deadline (`StatsProbe`; one read at a time, aborted at shutdown, a report of an older series is dropped by its number). It reads transports through those tracks, not through the room, because a `Room` is not clonable into the task. It never reads an address, port, candidate type, SSRC or codec. `mapping/stats.rs` is pure: `StatsBook` turns raw counters into rates from the change since each counter's sample before, over the time between the two reads, keyed by track ID or transport (a reset, a new track, a missing earlier value, a zero interval or a connection with an unread transport gives no rate, never a wrong one) and clamps every number to the protocol bound. Turning the statistics off and on keeps the one-second spacing of reads. The message goes to `Output::offer_stats`, which keeps at most one waiting reading (newest wins) and writes it after the control messages and the waiting picture of a round. Statistics never use the control queue. +- Video effects (ADR-0068, proposed): `effects.rs` (pure: no LiveKit, OS or I/O types) applies the background and then the colour filter to the I420 picture in `CameraFeed::frame`, after `fitted_i420` and before both the own tile and the SFU, so the others and the preview see the same picture; the camera test applies it the same way. `Planes::new` checks the sides (2 to 640, at most 640x360 pixels) and that each plane fits its stride; the scratch buffers (about 1.4 MB) are kept for the feed and never grow past that picture size. Blur and the pictures need the person mask from `segmenter.rs`. This build has none: `segmenter::available()` is `false`, `Devices` reports that, `SetVideoEffect` refuses such an effect and keeps the old one (`refused`), a `Join` that asks for one keeps the camera off (`CameraState::EffectUnavailable`), and a picture whose mask is missing or bad is dropped, never sent without its effect. Never fall back to sending the plain picture. The pictures are drawn from code; add no image files and no image decoding. The later segmenter (tract with an embedded MediaPipe model) needs its own owner approval for the download, provenance and SHA-256 check, licence and audit entries, per-OS cost measurement and a containment check, as ADR-0068 lists; it goes behind `Segmenter` with no change to the session. The effect reaches the capture thread through `SharedEffect` (one atomic word); the event loop is the only writer. - Pictures never use the control queue. `output.rs` keeps at most one waiting picture per tile (newest wins), and control messages always go out first. Pictures are RGBA in byte order R, G, B, A, at most 640x360 and 15 per second per camera tile, and at most 1280x720 and 5 per second on the screen tile (5), checked by tile index before allocation. ## Build diff --git a/crates/call-worker/src/effects.rs b/crates/call-worker/src/effects.rs new file mode 100644 index 00000000..1663205e --- /dev/null +++ b/crates/call-worker/src/effects.rs @@ -0,0 +1,1248 @@ +//! The own camera's video effects (ADR-0068): a background behind the person +//! (a blur or a picture drawn from code), then a colour filter on the whole +//! picture. Works in place on the I420 picture that goes to both the own +//! preview and the SFU, so others see what the preview shows. +//! +//! No I/O, no LiveKit and no OS types. Every size is checked before a buffer +//! is made, and the scratch buffers are kept for the next picture of the +//! same size. + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +use persephone_call_protocol::{ + Background, BackgroundPicture, BlurStrength, ColourFilter, MAX_VIDEO_PIXELS, MAX_VIDEO_SIDE, + VideoEffect, +}; + +use crate::segmenter::Segmenter; + +/// Box blur passes in each direction. Three passes of a box come close to a +/// Gaussian blur, and each costs the same at any radius. +const BLUR_PASSES: usize = 3; +/// The blur radius is `strength x width / BLUR_RADIUS_DIVISOR` pixels: 2 to +/// 20 pixels at 640 wide (ADR-0068). +const BLUR_RADIUS_DIVISOR: u32 = 3200; +/// The colour shift of the warm and cool filters, in chroma steps. +const WARM_SHIFT: i16 = 10; +const WARM_COUNTER_SHIFT: i16 = 8; +/// The power curve of the brighten filter on the luma range: below 1 lifts +/// the dark parts and keeps black and white. +const BRIGHTEN_GAMMA: f32 = 0.7; +/// Video range luma: black and white (BT.601). +const LUMA_BLACK: u8 = 16; +const LUMA_WHITE: u8 = 235; +/// Neutral chroma. +const CHROMA_ZERO: u8 = 128; + +/// Whether the worker can apply `effect`: an effect that needs the person +/// mask needs a segmenter. +pub const fn can_apply(effect: VideoEffect, segmenter_available: bool) -> bool { + !effect.needs_mask() || segmenter_available +} + +/// The effect to use after a `SetVideoEffect` of `requested`, and whether +/// the request was refused: an effect that cannot run is refused, and +/// `current` stays (ADR-0068). +pub const fn accept_effect( + current: VideoEffect, + requested: VideoEffect, + segmenter_available: bool, +) -> (VideoEffect, bool) { + if can_apply(requested, segmenter_available) { + (requested, false) + } else { + (current, true) + } +} + +/// The effect in use, shared with the camera's capture thread. The event +/// loop stores it; the frame callback loads it for each picture. One atomic +/// value: no lock and no queue. +pub struct SharedEffect(AtomicU32); + +impl SharedEffect { + pub fn new(effect: VideoEffect) -> Arc { + Arc::new(Self(AtomicU32::new(pack(effect)))) + } + + pub fn store(&self, effect: VideoEffect) { + self.0.store(pack(effect), Ordering::Release); + } + + /// The effect in use. `None` only for a value that no `VideoEffect` + /// gives; the caller then drops the picture. + pub fn load(&self) -> Option { + let [_, kind, value, filter] = self.0.load(Ordering::Acquire).to_be_bytes(); + VideoEffect::from_bytes([kind, value, filter]).ok() + } +} + +fn pack(effect: VideoEffect) -> u32 { + let [kind, value, filter] = effect.to_bytes(); + u32::from_be_bytes([0, kind, value, filter]) +} + +/// The size of a picture's chroma planes. +const fn chroma_size(width: usize, height: usize) -> (usize, usize) { + (width.div_ceil(2), height.div_ceil(2)) +} + +/// Whether `len` bytes hold `rows` rows of `width` bytes at `stride`. +fn plane_fits(len: usize, width: usize, rows: usize, stride: usize) -> bool { + stride >= width + && stride + .checked_mul(rows - 1) + .and_then(|start| start.checked_add(width)) + .is_some_and(|needed| needed <= len) +} + +/// One I420 picture's planes, borrowed for processing. Made only by +/// [`Planes::new`], which checks the size and that each plane holds its +/// rows. +pub struct Planes<'a> { + width: usize, + height: usize, + y: &'a mut [u8], + y_stride: usize, + u: &'a mut [u8], + u_stride: usize, + v: &'a mut [u8], + v_stride: usize, +} + +impl<'a> Planes<'a> { + /// The planes of a `width` x `height` picture, or `None` when it is + /// larger than a camera picture (640x360, ADR-0048), smaller than 2x2, + /// or a plane is too short for its stride. + #[allow(clippy::too_many_arguments)] + pub fn new( + width: u32, + height: u32, + y: &'a mut [u8], + y_stride: u32, + u: &'a mut [u8], + u_stride: u32, + v: &'a mut [u8], + v_stride: u32, + ) -> Option { + if !(2..=MAX_VIDEO_SIDE).contains(&width) + || !(2..=MAX_VIDEO_SIDE).contains(&height) + || u64::from(width) * u64::from(height) > u64::from(MAX_VIDEO_PIXELS) + { + return None; + } + let (width, height) = (width as usize, height as usize); + let (y_stride, u_stride, v_stride) = + (y_stride as usize, u_stride as usize, v_stride as usize); + let (chroma_width, chroma_height) = chroma_size(width, height); + let fits = plane_fits(y.len(), width, height, y_stride) + && plane_fits(u.len(), chroma_width, chroma_height, u_stride) + && plane_fits(v.len(), chroma_width, chroma_height, v_stride); + fits.then_some(Self { + width, + height, + y, + y_stride, + u, + u_stride, + v, + v_stride, + }) + } + + /// The three planes with their sizes and strides, for one loop over + /// each. + fn planes_mut(&mut self) -> [PlaneMut<'_>; 3] { + let (chroma_width, chroma_height) = chroma_size(self.width, self.height); + [ + PlaneMut { + data: self.y, + width: self.width, + height: self.height, + stride: self.y_stride, + }, + PlaneMut { + data: self.u, + width: chroma_width, + height: chroma_height, + stride: self.u_stride, + }, + PlaneMut { + data: self.v, + width: chroma_width, + height: chroma_height, + stride: self.v_stride, + }, + ] + } +} + +/// One plane of a [`Planes`]. +struct PlaneMut<'p> { + data: &'p mut [u8], + width: usize, + height: usize, + stride: usize, +} + +impl PlaneMut<'_> { + fn rows_mut(&mut self) -> impl Iterator { + let width = self.width; + self.data + .chunks_mut(self.stride) + .take(self.height) + .map(move |row| &mut row[..width]) + } + + fn rows(&self) -> impl Iterator { + self.data + .chunks(self.stride) + .take(self.height) + .map(|row| &row[..self.width]) + } +} + +/// A person mask: one byte for each pixel, 0 for background and 255 for the +/// person. At most a camera picture's size. +#[derive(Default)] +pub struct Mask { + width: usize, + height: usize, + data: Vec, +} + +impl Mask { + /// Makes the mask `width` x `height`, or refuses a size outside 1x1 to a + /// camera picture's limits. The bytes are then the segmenter's to write. + #[allow(dead_code)] // the segmenter's side (ADR-0068); this build has none + pub fn resize(&mut self, width: u32, height: u32) -> bool { + if !(1..=MAX_VIDEO_SIDE).contains(&width) + || !(1..=MAX_VIDEO_SIDE).contains(&height) + || u64::from(width) * u64::from(height) > u64::from(MAX_VIDEO_PIXELS) + { + return false; + } + self.width = width as usize; + self.height = height as usize; + self.data.resize(self.width * self.height, 0); + true + } + + /// The mask's bytes, row by row with no padding. + #[allow(dead_code)] // the segmenter's side (ADR-0068); this build has none + pub fn data_mut(&mut self) -> &mut [u8] { + &mut self.data + } + + fn is_empty(&self) -> bool { + self.width == 0 || self.height == 0 + } +} + +/// An effect that needs the person mask got none: the picture must not go +/// out. +#[derive(Debug, Eq, PartialEq)] +pub struct NoMask; + +/// A background drawn for one picture size. +struct Drawn { + picture: BackgroundPicture, + width: usize, + height: usize, + planes: [Vec; 3], +} + +/// Applies video effects, keeping its scratch planes between pictures. +pub struct Effects { + /// The blurred or drawn background of each plane, with no padding. + background: [Vec; 3], + /// The mask scaled to the luma and to the chroma size. + alpha: [Vec; 2], + /// Blur scratch. + scratch: Vec, + sums: Vec, + drawn: Option, + brighten: [u8; 256], +} + +impl Default for Effects { + fn default() -> Self { + Self::new() + } +} + +impl Effects { + pub fn new() -> Self { + Self { + background: Default::default(), + alpha: Default::default(), + scratch: Vec::new(), + sums: Vec::new(), + drawn: None, + brighten: brighten_curve(), + } + } + + /// Applies `effect` to `planes` in place: the background with `mask`, + /// then the colour filter. An effect that needs a mask without one + /// changes nothing and returns [`NoMask`]. + pub fn apply( + &mut self, + effect: VideoEffect, + planes: &mut Planes<'_>, + mask: Option<&Mask>, + ) -> Result<(), NoMask> { + match effect.background { + Background::None => {} + background => { + let mask = mask.filter(|mask| !mask.is_empty()).ok_or(NoMask)?; + self.replace_background(background, planes, mask)?; + } + } + self.filter(effect.filter, planes); + Ok(()) + } + + /// Mixes the blurred or drawn background into `planes` where `mask` + /// says background. [`NoMask`] when a plane could not be mixed: the + /// picture is then not sent. + fn replace_background( + &mut self, + background: Background, + planes: &mut Planes<'_>, + mask: &Mask, + ) -> Result<(), NoMask> { + let (width, height) = (planes.width, planes.height); + let (chroma_width, chroma_height) = chroma_size(width, height); + scale_mask(mask, width, height, &mut self.alpha[0]); + scale_mask(mask, chroma_width, chroma_height, &mut self.alpha[1]); + match background { + Background::None => return Ok(()), + Background::Blur(strength) => self.blur(planes, strength), + Background::Picture(picture) => self.draw(picture, width, height), + } + let drawn = self.drawn.as_ref().map(|drawn| &drawn.planes); + for (index, mut plane) in planes.planes_mut().into_iter().enumerate() { + let alpha = &self.alpha[usize::from(index > 0)]; + let background = match background { + Background::Picture(_) => drawn.map_or(&[][..], |planes| &planes[index][..]), + _ => &self.background[index][..], + }; + if !composite(&mut plane, alpha, background) { + return Err(NoMask); + } + } + Ok(()) + } + + /// Blurs each plane of `planes` into `self.background`. + fn blur(&mut self, planes: &mut Planes<'_>, strength: BlurStrength) { + let luma_radius = blur_radius(strength, planes.width); + let chroma_radius = (luma_radius / 2).max(1); + for (index, plane) in planes.planes_mut().into_iter().enumerate() { + let radius = if index == 0 { + luma_radius + } else { + chroma_radius + }; + let out = &mut self.background[index]; + out.clear(); + out.reserve(plane.width * plane.height); + for row in plane.rows() { + out.extend_from_slice(row); + } + box_blur( + out, + &mut self.scratch, + &mut self.sums, + plane.width, + plane.height, + radius, + ); + } + } + + /// Draws `picture` at this size, unless it is drawn already. + fn draw(&mut self, picture: BackgroundPicture, width: usize, height: usize) { + if self.drawn.as_ref().is_some_and(|drawn| { + (drawn.picture, drawn.width, drawn.height) == (picture, width, height) + }) { + return; + } + let mut planes = match self.drawn.take() { + Some(drawn) => drawn.planes, + None => Default::default(), + }; + draw_picture(picture, width, height, &mut planes); + self.drawn = Some(Drawn { + picture, + width, + height, + planes, + }); + } + + fn filter(&self, filter: ColourFilter, planes: &mut Planes<'_>) { + let [mut luma, mut u, mut v] = planes.planes_mut(); + match filter { + ColourFilter::None => {} + ColourFilter::Greyscale => { + for plane in [&mut u, &mut v] { + for row in plane.rows_mut() { + row.fill(CHROMA_ZERO); + } + } + } + ColourFilter::Warm => { + shift(&mut u, -WARM_COUNTER_SHIFT); + shift(&mut v, WARM_SHIFT); + } + ColourFilter::Cool => { + shift(&mut u, WARM_SHIFT); + shift(&mut v, -WARM_COUNTER_SHIFT); + } + ColourFilter::Brighten => { + for row in luma.rows_mut() { + for value in row { + *value = self.brighten[usize::from(*value)]; + } + } + } + } + } +} + +/// The blur radius in pixels for a picture `width` pixels wide: at least 1. +fn blur_radius(strength: BlurStrength, width: usize) -> usize { + let radius = u32::from(strength.percent()) * width as u32 / BLUR_RADIUS_DIVISOR; + (radius as usize).max(1) +} + +/// Adds `by` to every byte of a chroma plane, kept in 0..=255. +fn shift(plane: &mut PlaneMut<'_>, by: i16) { + for row in plane.rows_mut() { + for value in row { + *value = (i16::from(*value) + by).clamp(0, 255) as u8; + } + } +} + +/// The brighten filter's luma curve: a power curve on the video range, with +/// black and white kept and every value outside the range unchanged. +fn brighten_curve() -> [u8; 256] { + let mut curve = [0; 256]; + let range = f32::from(LUMA_WHITE - LUMA_BLACK); + for (value, out) in curve.iter_mut().enumerate() { + let value = value as u8; + *out = if (LUMA_BLACK..=LUMA_WHITE).contains(&value) { + let level = f32::from(value - LUMA_BLACK) / range; + (f32::from(LUMA_BLACK) + range * level.powf(BRIGHTEN_GAMMA)).round() as u8 + } else { + value + }; + } + curve +} + +/// Mixes `background` into `plane` where the mask says background: +/// `alpha` 255 keeps the plane, 0 takes the background. Both are `width` +/// x `height` with no padding. `false`, with nothing changed, when either +/// is too short. +fn composite(plane: &mut PlaneMut<'_>, alpha: &[u8], background: &[u8]) -> bool { + let width = plane.width; + if alpha.len() < width * plane.height || background.len() < width * plane.height { + return false; + } + for (row_index, row) in plane.rows_mut().enumerate() { + let start = row_index * width; + let alpha = &alpha[start..start + width]; + let background = &background[start..start + width]; + for ((value, &a), &back) in row.iter_mut().zip(alpha).zip(background) { + let (a, own, back) = (u32::from(a), u32::from(*value), u32::from(back)); + *value = ((a * own + (255 - a) * back + 127) / 255) as u8; + } + } + true +} + +/// Scales `mask` to `width` x `height` into `out`, bilinear, with pixel +/// centres aligned. +fn scale_mask(mask: &Mask, width: usize, height: usize, out: &mut Vec) { + out.resize(width * height, 0); + if (mask.width, mask.height) == (width, height) { + out.copy_from_slice(&mask.data); + return; + } + // The source position of each output column, once for all rows. + let column = |x: usize, from: usize, to: usize| -> (usize, usize, f32) { + let position = + ((x as f32 + 0.5) * from as f32 / to as f32 - 0.5).clamp(0.0, (from - 1) as f32); + let first = position.floor() as usize; + (first, (first + 1).min(from - 1), position - first as f32) + }; + let columns: Vec<(usize, usize, f32)> = + (0..width).map(|x| column(x, mask.width, width)).collect(); + for (y, out_row) in out.chunks_mut(width).enumerate() { + let (top, bottom, down) = column(y, mask.height, height); + let top = &mask.data[top * mask.width..][..mask.width]; + let bottom = &mask.data[bottom * mask.width..][..mask.width]; + for (value, &(left, right, across)) in out_row.iter_mut().zip(&columns) { + let upper = f32::from(top[left]) * (1.0 - across) + f32::from(top[right]) * across; + let lower = + f32::from(bottom[left]) * (1.0 - across) + f32::from(bottom[right]) * across; + *value = (upper * (1.0 - down) + lower * down).round() as u8; + } + } +} + +/// Blurs a `width` x `height` plane with no padding in place: three box +/// passes across, then three down, with the edge pixels repeated. +fn box_blur( + plane: &mut [u8], + scratch: &mut Vec, + sums: &mut Vec, + width: usize, + height: usize, + radius: usize, +) { + scratch.resize(plane.len(), 0); + for _ in 0..BLUR_PASSES { + box_across(plane, scratch, width, radius); + plane.copy_from_slice(scratch); + } + for _ in 0..BLUR_PASSES { + box_down(plane, scratch, sums, width, height, radius); + plane.copy_from_slice(scratch); + } +} + +/// One box pass along each row of `from` into `to`. +fn box_across(from: &[u8], to: &mut [u8], width: usize, radius: usize) { + let span = (2 * radius + 1) as u32; + let last = width - 1; + for (row, out) in from.chunks(width).zip(to.chunks_mut(width)) { + let mut sum: u32 = (0..=2 * radius) + .map(|k| u32::from(row[k.saturating_sub(radius).min(last)])) + .sum(); + for (x, value) in out.iter_mut().enumerate() { + *value = ((sum + span / 2) / span) as u8; + sum += u32::from(row[(x + radius + 1).min(last)]); + sum -= u32::from(row[x.saturating_sub(radius)]); + } + } +} + +/// One box pass down each column of `from` into `to`, row by row. +fn box_down( + from: &[u8], + to: &mut [u8], + sums: &mut Vec, + width: usize, + height: usize, + radius: usize, +) { + let span = (2 * radius + 1) as u32; + let last = height - 1; + let row = |y: usize| &from[y * width..][..width]; + sums.clear(); + sums.resize(width, 0); + for k in 0..=2 * radius { + for (sum, &value) in sums.iter_mut().zip(row(k.saturating_sub(radius).min(last))) { + *sum += u32::from(value); + } + } + for (y, out) in to.chunks_mut(width).take(height).enumerate() { + for (value, &sum) in out.iter_mut().zip(sums.iter()) { + *value = ((sum + span / 2) / span) as u8; + } + let (add, remove) = ( + row((y + radius + 1).min(last)), + row(y.saturating_sub(radius)), + ); + for ((sum, &add), &remove) in sums.iter_mut().zip(add).zip(remove) { + *sum = *sum + u32::from(add) - u32::from(remove); + } + } +} + +/// Draws `picture` at `width` x `height` into three I420 planes with no +/// padding. +fn draw_picture( + picture: BackgroundPicture, + width: usize, + height: usize, + planes: &mut [Vec; 3], +) { + let aspect = width as f32 / height as f32; + let (chroma_width, chroma_height) = chroma_size(width, height); + let [luma, u, v] = planes; + luma.clear(); + for y in 0..height { + for x in 0..width { + let (fx, fy) = ( + (x as f32 + 0.5) / width as f32, + (y as f32 + 0.5) / height as f32, + ); + luma.push(to_yuv(colour(picture, fx, fy, aspect))[0]); + } + } + u.clear(); + v.clear(); + for y in 0..chroma_height { + for x in 0..chroma_width { + // The centre of the 2x2 block of luma pixels. + let fx = ((2 * x + 1) as f32 / width as f32).min(1.0); + let fy = ((2 * y + 1) as f32 / height as f32).min(1.0); + let [_, chroma_u, chroma_v] = to_yuv(colour(picture, fx, fy, aspect)); + u.push(chroma_u); + v.push(chroma_v); + } + } +} + +type Rgb = [f32; 3]; + +fn mix(from: Rgb, to: Rgb, amount: f32) -> Rgb { + let amount = amount.clamp(0.0, 1.0); + [0, 1, 2].map(|i| from[i] + (to[i] - from[i]) * amount) +} + +/// A soft round light at (`cx`, `cy`), about `size` wide: 1 at its centre. +fn glow(fx: f32, fy: f32, aspect: f32, (cx, cy): (f32, f32), size: f32) -> f32 { + let (dx, dy) = ((fx - cx) * aspect, fy - cy); + (-(dx * dx + dy * dy) / (size * size)).exp() +} + +/// The colour of `picture` at (`fx`, `fy`), each 0 to 1 from the top left. +fn colour(picture: BackgroundPicture, fx: f32, fy: f32, aspect: f32) -> Rgb { + match picture { + BackgroundPicture::Dusk => { + let sky = if fy < 0.55 { + mix([36.0, 40.0, 90.0], [170.0, 85.0, 120.0], fy / 0.55) + } else { + mix( + [170.0, 85.0, 120.0], + [240.0, 150.0, 80.0], + (fy - 0.55) / 0.45, + ) + }; + let sun = glow(fx, fy, aspect, (0.5, 0.82), 0.22); + [0, 1, 2].map(|i| sky[i] + sun * [60.0, 45.0, 15.0][i]) + } + BackgroundPicture::Sea => { + const HORIZON: f32 = 0.45; + let sky = mix([120.0, 170.0, 220.0], [205.0, 225.0, 240.0], fy / HORIZON); + let water = mix( + [40.0, 120.0, 150.0], + [10.0, 45.0, 85.0], + (fy - HORIZON) / (1.0 - HORIZON), + ); + let wave = 8.0 * (fy * 60.0 + 3.0 * (fx * 6.0).sin()).sin() * (fy - HORIZON).max(0.0); + let water = water.map(|c| c + wave); + // A soft horizon, two percent of the height. + mix(sky, water, (fy - HORIZON) / 0.02 + 0.5) + } + BackgroundPicture::Forest => { + let base = mix([25.0, 60.0, 35.0], [55.0, 95.0, 50.0], fy); + let trunk = 0.5 + 0.5 * (fx * 25.0 + 2.0 * (fx * 7.0).sin()).sin(); + let shade = 1.0 - 0.35 * trunk.powi(4); + let light = glow(fx, fy, aspect, (0.2, 0.1), 0.35); + [0, 1, 2].map(|i| base[i] * shade + light * [30.0, 35.0, 15.0][i]) + } + BackgroundPicture::Studio => { + let (dx, dy) = ((fx - 0.5) * aspect, fy - 0.45); + let level = 165.0 - 95.0 * ((dx * dx + dy * dy).sqrt() / 0.9).clamp(0.0, 1.0); + [level, level, level + 6.0] + } + } +} + +/// An RGB colour (0 to 255) as video range BT.601 Y, U and V. +fn to_yuv([r, g, b]: Rgb) -> [u8; 3] { + let [r, g, b] = [r, g, b].map(|c| c.clamp(0.0, 255.0)); + let y = 16.0 + (65.481 * r + 128.553 * g + 24.966 * b) / 255.0; + let u = 128.0 + (-37.797 * r - 74.203 * g + 112.0 * b) / 255.0; + let v = 128.0 + (112.0 * r - 93.786 * g - 18.214 * b) / 255.0; + [y, u, v].map(|value| value.round().clamp(0.0, 255.0) as u8) +} + +/// The effects of one camera feed: the shared effect in use, this feed's +/// segmenter, if any, and the scratch planes. The camera's frame callback +/// (and the camera test's) owns one. +pub struct CameraEffects { + effect: Arc, + segmenter: Option>, + mask: Mask, + effects: Effects, +} + +impl CameraEffects { + pub fn new(effect: Arc, segmenter: Option>) -> Self { + Self { + effect, + segmenter, + mask: Mask::default(), + effects: Effects::new(), + } + } + + /// Applies the effect in use to one picture. `false` when the picture + /// must not go out: the effect needs a mask that the segmenter did not + /// give (fail closed, ADR-0068). + pub fn process(&mut self, planes: &mut Planes<'_>) -> bool { + let Some(effect) = self.effect.load() else { + return false; + }; + let mask = if effect.needs_mask() { + let made = self + .segmenter + .as_mut() + .is_some_and(|segmenter| segmenter.mask(planes, &mut self.mask)); + if !made { + return false; + } + Some(&self.mask) + } else { + None + }; + self.effects.apply(effect, planes, mask).is_ok() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A test picture's planes, owned, with padding at the end of each row. + struct Picture { + width: u32, + height: u32, + stride: u32, + chroma_stride: u32, + y: Vec, + u: Vec, + v: Vec, + } + + impl Picture { + /// Luma from `luma(x, y)`, chroma `u` and `v`. Padding bytes are 7. + fn new(width: u32, height: u32, luma: impl Fn(usize, usize) -> u8, u: u8, v: u8) -> Self { + let (stride, chroma_stride) = (width + 3, width.div_ceil(2) + 2); + let (cw, ch) = chroma_size(width as usize, height as usize); + let mut y = vec![7; (stride * height) as usize]; + for row in 0..height as usize { + for x in 0..width as usize { + y[row * stride as usize + x] = luma(x, row); + } + } + let chroma = |value: u8| { + let mut plane = vec![7; chroma_stride as usize * ch]; + for row in 0..ch { + plane[row * chroma_stride as usize..][..cw].fill(value); + } + plane + }; + Self { + width, + height, + stride, + chroma_stride, + y, + u: chroma(u), + v: chroma(v), + } + } + + fn planes(&mut self) -> Planes<'_> { + Planes::new( + self.width, + self.height, + &mut self.y, + self.stride, + &mut self.u, + self.chroma_stride, + &mut self.v, + self.chroma_stride, + ) + .expect("valid planes") + } + + fn luma(&self, x: usize, y: usize) -> u8 { + self.y[y * self.stride as usize + x] + } + + fn u_at(&self, x: usize, y: usize) -> u8 { + self.u[y * self.chroma_stride as usize + x] + } + + fn v_at(&self, x: usize, y: usize) -> u8 { + self.v[y * self.chroma_stride as usize + x] + } + + /// Every padding byte is still 7. + fn padding_untouched(&self) -> bool { + let (cw, ch) = chroma_size(self.width as usize, self.height as usize); + let rows = |plane: &[u8], stride: usize, width: usize, height: usize| { + plane + .chunks(stride) + .take(height) + .all(|row| row[width..].iter().all(|&b| b == 7)) + }; + rows( + &self.y, + self.stride as usize, + self.width as usize, + self.height as usize, + ) && rows(&self.u, self.chroma_stride as usize, cw, ch) + && rows(&self.v, self.chroma_stride as usize, cw, ch) + } + } + + fn checkerboard(x: usize, y: usize) -> u8 { + if (x / 2 + y / 2).is_multiple_of(2) { + 40 + } else { + 200 + } + } + + fn mask(width: u32, height: u32, value: impl Fn(usize, usize) -> u8) -> Mask { + let mut mask = Mask::default(); + assert!(mask.resize(width, height)); + let w = width as usize; + for (index, byte) in mask.data_mut().iter_mut().enumerate() { + *byte = value(index % w, index / w); + } + mask + } + + fn blur(percent: u8) -> VideoEffect { + VideoEffect { + background: Background::Blur(BlurStrength::new(percent).unwrap()), + filter: ColourFilter::None, + } + } + + fn filter(filter: ColourFilter) -> VideoEffect { + VideoEffect { + background: Background::None, + filter, + } + } + + fn picture(picture: BackgroundPicture) -> VideoEffect { + VideoEffect { + background: Background::Picture(picture), + filter: ColourFilter::None, + } + } + + /// The spread of the luma values of a picture. + fn luma_variance(picture: &Picture) -> f64 { + let values: Vec = (0..picture.height as usize) + .flat_map(|y| (0..picture.width as usize).map(move |x| (x, y))) + .map(|(x, y)| f64::from(picture.luma(x, y))) + .collect(); + let mean = values.iter().sum::() / values.len() as f64; + values.iter().map(|v| (v - mean).powi(2)).sum::() / values.len() as f64 + } + + /// GIVEN planes larger than a camera picture, smaller than 2x2, or with + /// a plane too short for its stride or a stride under the width + /// WHEN they are checked + /// THEN each is refused; the largest camera picture is accepted. + #[test] + fn given_bad_plane_sizes_when_checked_then_they_are_refused() { + let check = |w: u32, h: u32, y_len: usize, y_stride: u32, c_len: usize, c_stride: u32| { + let (mut y, mut u, mut v) = (vec![0; y_len], vec![0; c_len], vec![0; c_len]); + Planes::new(w, h, &mut y, y_stride, &mut u, c_stride, &mut v, c_stride).is_some() + }; + assert!(check(640, 360, 640 * 360, 640, 320 * 180, 320)); + assert!(!check(642, 360, 642 * 360, 642, 321 * 180, 321)); + assert!(!check(640, 362, 640 * 362, 640, 320 * 181, 320)); + assert!(!check(1, 4, 4, 1, 2, 1)); + assert!(!check(64, 36, 64 * 36 - 1, 64, 32 * 18, 32)); + assert!(!check(64, 36, 64 * 36, 64, 32 * 18 - 1, 32)); + assert!(!check(64, 36, 64 * 36, 63, 32 * 18, 32)); + // The last row needs only the width, not the whole stride. + assert!(check(64, 36, 80 * 35 + 64, 80, 40 * 17 + 32, 40)); + } + + /// GIVEN no effect + /// WHEN it is applied to a picture + /// THEN no byte changes. + #[test] + fn given_no_effect_when_applied_then_the_picture_is_unchanged() { + let mut picture = Picture::new(33, 19, checkerboard, 90, 170); + let before = (picture.y.clone(), picture.u.clone(), picture.v.clone()); + let mut effects = Effects::new(); + assert_eq!( + effects.apply(VideoEffect::NONE, &mut picture.planes(), None), + Ok(()) + ); + assert_eq!( + (picture.y.clone(), picture.u.clone(), picture.v.clone()), + before + ); + } + + /// GIVEN each colour filter + /// WHEN it is applied + /// THEN greyscale makes the chroma neutral and keeps the luma; warm adds + /// red and takes blue; cool does the opposite; values stay in 0..=255; + /// no padding byte changes. + #[test] + fn given_colour_filters_when_applied_then_the_colours_move_as_named() { + let mut effects = Effects::new(); + let run = |effects: &mut Effects, filter_kind, u, v| { + let mut picture = Picture::new(10, 6, |x, _| 30 + x as u8 * 10, u, v); + effects + .apply(filter(filter_kind), &mut picture.planes(), None) + .unwrap(); + assert!(picture.padding_untouched(), "{filter_kind:?}"); + picture + }; + let grey = run(&mut effects, ColourFilter::Greyscale, 60, 200); + assert_eq!((grey.u_at(0, 0), grey.v_at(4, 2)), (128, 128)); + assert_eq!(grey.luma(3, 1), 60); + let warm = run(&mut effects, ColourFilter::Warm, 128, 128); + assert!(warm.v_at(1, 1) > 128 && warm.u_at(1, 1) < 128); + let cool = run(&mut effects, ColourFilter::Cool, 128, 128); + assert!(cool.u_at(1, 1) > 128 && cool.v_at(1, 1) < 128); + assert_eq!(cool.luma(5, 5), 80); + let clamped = run(&mut effects, ColourFilter::Warm, 3, 250); + assert_eq!((clamped.u_at(0, 0), clamped.v_at(0, 0)), (0, 255)); + } + + /// GIVEN the brighten filter + /// WHEN its curve is read + /// THEN it keeps black, white and every value outside the video range, + /// never darkens, lifts the dark parts most, and never decreases. + #[test] + fn given_brighten_when_applied_then_dark_parts_rise_and_ends_stay() { + let curve = brighten_curve(); + assert_eq!((curve[16], curve[235]), (16, 235)); + assert!((0..16).chain(236..=255).all(|v| curve[v] == v as u8)); + assert!( + curve + .iter() + .enumerate() + .all(|(v, &out)| usize::from(out) >= v) + ); + assert!(curve.windows(2).all(|pair| pair[0] <= pair[1])); + assert!(curve[40] - 40 > curve[200] - 200); + let mut picture = Picture::new(4, 4, |_, _| 40, 128, 128); + Effects::new() + .apply(filter(ColourFilter::Brighten), &mut picture.planes(), None) + .unwrap(); + assert_eq!(picture.luma(2, 2), curve[40]); + assert_eq!(picture.u_at(1, 1), 128); + } + + /// GIVEN blur or a picture, and no mask or an empty one + /// WHEN the effect is applied + /// THEN it is refused and the picture is unchanged, so it can be dropped. + #[test] + fn given_background_effect_without_mask_when_applied_then_it_is_refused() { + let mut effects = Effects::new(); + for effect in [blur(50), picture(BackgroundPicture::Sea)] { + for empty in [None, Some(&Mask::default())] { + let mut picture = Picture::new(16, 8, checkerboard, 100, 150); + let before = picture.y.clone(); + assert_eq!( + effects.apply(effect, &mut picture.planes(), empty), + Err(NoMask) + ); + assert_eq!(picture.y, before); + } + } + } + + /// GIVEN blur with a mask that marks every pixel as the person + /// WHEN it is applied + /// THEN the picture is unchanged. + #[test] + fn given_blur_and_all_person_mask_when_applied_then_nothing_changes() { + let mut picture = Picture::new(64, 36, checkerboard, 90, 170); + let before = (picture.y.clone(), picture.u.clone(), picture.v.clone()); + let all = mask(32, 18, |_, _| 255); + Effects::new() + .apply(blur(100), &mut picture.planes(), Some(&all)) + .unwrap(); + assert_eq!( + (picture.y.clone(), picture.u.clone(), picture.v.clone()), + before + ); + } + + /// GIVEN blur with a mask that marks every pixel as background + /// WHEN it is applied at a weak and a strong strength + /// THEN the pattern is smoothed, much more at the strong strength, its + /// mean stays, a flat picture stays flat, and no padding byte changes. + #[test] + fn given_blur_and_all_background_mask_when_applied_then_the_picture_is_smoothed() { + let squares = |x: usize, y: usize| { + if (x / 16 + y / 16).is_multiple_of(2) { + 40 + } else { + 200 + } + }; + let background = mask(256, 144, |_, _| 0); + let mut effects = Effects::new(); + let original = Picture::new(640, 360, squares, 128, 128); + let mut weak = Picture::new(640, 360, squares, 128, 128); + effects + .apply(blur(10), &mut weak.planes(), Some(&background)) + .unwrap(); + let mut strong = Picture::new(640, 360, squares, 128, 128); + effects + .apply(blur(100), &mut strong.planes(), Some(&background)) + .unwrap(); + let (v0, v1, v2) = ( + luma_variance(&original), + luma_variance(&weak), + luma_variance(&strong), + ); + assert!(v1 < v0 && v2 < v1 / 4.0, "{v0} {v1} {v2}"); + assert!((i32::from(strong.luma(320, 180)) - 120).abs() <= 3); + assert!(strong.padding_untouched()); + let mut flat = Picture::new(64, 36, |_, _| 77, 99, 155); + effects + .apply(blur(60), &mut flat.planes(), Some(&background)) + .unwrap(); + assert!( + flat.y + .chunks(flat.stride as usize) + .all(|row| row[..64].iter().all(|&b| b == 77)) + ); + assert_eq!((flat.u_at(3, 3), flat.v_at(10, 5)), (99, 155)); + } + + /// GIVEN blur with a mask whose left half is the person + /// WHEN it is applied + /// THEN the left part stays sharp and the right part is blurred. + #[test] + fn given_half_mask_when_blurred_then_only_the_background_changes() { + let mut picture = Picture::new(64, 32, checkerboard, 128, 128); + let half = mask(64, 32, |x, _| if x < 32 { 255 } else { 0 }); + Effects::new() + .apply(blur(100), &mut picture.planes(), Some(&half)) + .unwrap(); + for y in 0..32 { + for x in 0..30 { + assert_eq!(picture.luma(x, y), checkerboard(x, y), "{x} {y}"); + } + } + let right: Vec = (40..64).map(|x| picture.luma(x, 10)).collect(); + assert!(right.iter().all(|&v| v > 60 && v < 180), "{right:?}"); + } + + /// GIVEN each background picture and a mask of all background + /// WHEN it is applied twice, and at two sizes + /// THEN the picture is replaced with the drawn one, the same each time, + /// different for each picture, and the drawn picture follows the size. + #[test] + fn given_background_pictures_when_applied_then_they_replace_the_background() { + let background = mask(20, 10, |_, _| 0); + let mut effects = Effects::new(); + let mut seen = Vec::new(); + for kind in BackgroundPicture::ALL { + let mut first = Picture::new(48, 26, checkerboard, 60, 60); + effects + .apply(picture(kind), &mut first.planes(), Some(&background)) + .unwrap(); + let mut again = Picture::new(48, 26, |_, _| 3, 250, 250); + effects + .apply(picture(kind), &mut again.planes(), Some(&background)) + .unwrap(); + assert_eq!(first.y, again.y, "{kind:?}"); + assert_eq!((first.u.clone(), first.v.clone()), (again.u, again.v)); + assert!(first.padding_untouched()); + seen.push(first.y); + } + for (i, a) in seen.iter().enumerate() { + for b in &seen[i + 1..] { + assert_ne!(a, b); + } + } + // A new size draws again, at that size. + let mut small = Picture::new(12, 6, checkerboard, 60, 60); + effects + .apply( + picture(BackgroundPicture::Studio), + &mut small.planes(), + Some(&background), + ) + .unwrap(); + assert!(small.padding_untouched()); + let centre = small.luma(6, 2); + assert!(centre > small.luma(0, 5), "a lighter centre: {centre}"); + } + + /// GIVEN a picture background with a mask whose top half is the person + /// WHEN it is applied + /// THEN the top keeps the camera picture and the bottom shows the drawn + /// picture. + #[test] + fn given_picture_and_half_mask_when_applied_then_the_person_is_kept() { + let top = mask(16, 16, |_, y| if y < 8 { 255 } else { 0 }); + let mut picture_effect = Picture::new(32, 32, |_, _| 50, 128, 128); + Effects::new() + .apply( + picture(BackgroundPicture::Dusk), + &mut picture_effect.planes(), + Some(&top), + ) + .unwrap(); + assert!((0..14).all(|y| picture_effect.luma(5, y) == 50)); + assert!((18..32).all(|y| picture_effect.luma(5, y) != 50)); + } + + /// GIVEN a background effect and a colour filter together + /// WHEN they are applied + /// THEN the filter applies to the new background too. + #[test] + fn given_background_and_filter_when_applied_then_the_filter_comes_last() { + let background = mask(8, 8, |_, _| 0); + let mut picture_effect = Picture::new(16, 16, checkerboard, 128, 128); + let effect = VideoEffect { + background: Background::Picture(BackgroundPicture::Forest), + filter: ColourFilter::Greyscale, + }; + Effects::new() + .apply(effect, &mut picture_effect.planes(), Some(&background)) + .unwrap(); + assert!( + picture_effect.u[..8] + .iter() + .chain(&picture_effect.v[..8]) + .all(|&b| b == 128) + ); + } + + /// GIVEN a mask of another size + /// WHEN it is scaled to a picture + /// THEN corners keep their values and the middle is between them. + #[test] + fn given_mask_of_another_size_when_scaled_then_values_are_interpolated() { + let ramp = mask(2, 1, |x, _| if x == 0 { 0 } else { 255 }); + let mut out = Vec::new(); + scale_mask(&ramp, 8, 3, &mut out); + assert_eq!(out.len(), 24); + assert_eq!((out[0], out[7]), (0, 255)); + assert!(out[3] > 0 && out[3] < 255 && out[3] < out[4]); + assert_eq!(&out[..8], &out[16..]); + let mut same = Vec::new(); + scale_mask(&ramp, 2, 1, &mut same); + assert_eq!(same, [0, 255]); + } + + /// GIVEN mask sizes at and over the camera limits + /// WHEN a mask is resized + /// THEN only sizes inside the limits are taken. + #[test] + fn given_mask_sizes_when_resized_then_they_are_bounded() { + let mut mask = Mask::default(); + assert!(mask.resize(640, 360) && mask.data_mut().len() == 230_400); + assert!(mask.resize(256, 144) && mask.data_mut().len() == 256 * 144); + assert!(!mask.resize(0, 10) && !mask.resize(641, 1) && !mask.resize(640, 361)); + assert_eq!(mask.data_mut().len(), 256 * 144); + } + + /// GIVEN every blur strength + /// WHEN the radius is taken for 640 and for 2 pixels wide + /// THEN it runs from 2 to 20 at 640 and is never 0. + #[test] + fn given_blur_strengths_when_radius_taken_then_it_scales_with_width() { + let radius = |percent, width| blur_radius(BlurStrength::new(percent).unwrap(), width); + assert_eq!((radius(10, 640), radius(100, 640)), (2, 20)); + assert_eq!(radius(50, 320), 5); + assert_eq!(radius(100, 2), 1); + } + + /// A segmenter for the tests: a fixed mask, or a failure. + struct Fixed(Option); + + impl Segmenter for Fixed { + fn mask(&mut self, _: &Planes<'_>, out: &mut Mask) -> bool { + let Some(value) = self.0 else { + return false; + }; + assert!(out.resize(4, 4)); + out.data_mut().fill(value); + true + } + } + + /// GIVEN a feed with a shared effect + /// WHEN the effect changes, or needs a mask with no segmenter or with + /// one that fails + /// THEN the feed follows the newest effect, and drops every picture + /// that would go out without its background effect. + #[test] + fn given_camera_effects_when_processing_then_pictures_without_their_mask_are_dropped() { + let shared = SharedEffect::new(VideoEffect::NONE); + let mut none = CameraEffects::new(shared.clone(), None); + let mut failing = CameraEffects::new(shared.clone(), Some(Box::new(Fixed(None)))); + let mut working = CameraEffects::new(shared.clone(), Some(Box::new(Fixed(Some(0))))); + let run = |feed: &mut CameraEffects| { + let mut picture = Picture::new(16, 8, checkerboard, 128, 128); + let sent = feed.process(&mut picture.planes()); + (sent, picture.u_at(0, 0)) + }; + assert_eq!(run(&mut none), (true, 128)); + shared.store(filter(ColourFilter::Cool)); + assert_eq!(run(&mut none), (true, 138)); + shared.store(blur(30)); + assert!(!run(&mut none).0); + assert!(!run(&mut failing).0); + assert!(run(&mut working).0); + assert_eq!(shared.load(), Some(blur(30))); + } + + /// GIVEN every effect and each segmenter state + /// WHEN the worker checks whether it can apply it + /// THEN only blur and pictures need the segmenter, and every effect + /// survives the shared value. + #[test] + fn given_effects_when_checked_then_background_effects_need_a_segmenter() { + assert!(can_apply(filter(ColourFilter::Warm), false)); + assert!(can_apply(VideoEffect::NONE, false)); + assert!(!can_apply(blur(10), false) && can_apply(blur(10), true)); + assert!(!can_apply(picture(BackgroundPicture::Sea), false)); + let warm = filter(ColourFilter::Warm); + assert_eq!(accept_effect(warm, blur(20), false), (warm, true)); + assert_eq!(accept_effect(warm, blur(20), true), (blur(20), false)); + assert_eq!( + accept_effect(blur(20), VideoEffect::NONE, false), + (VideoEffect::NONE, false) + ); + let shared = SharedEffect::new(VideoEffect::NONE); + for background in [ + Background::None, + blur(70).background, + picture(BackgroundPicture::Forest).background, + ] { + for filter in ColourFilter::ALL { + let effect = VideoEffect { background, filter }; + shared.store(effect); + assert_eq!(shared.load(), Some(effect)); + } + } + } + + /// GIVEN the drawn colours + /// WHEN they are converted to video range YUV + /// THEN black and white land on the range ends and grey is neutral. + #[test] + fn given_colours_when_converted_then_they_use_the_video_range() { + assert_eq!(to_yuv([0.0, 0.0, 0.0]), [16, 128, 128]); + assert_eq!(to_yuv([255.0, 255.0, 255.0]), [235, 128, 128]); + assert_eq!( + to_yuv([300.0, -5.0, 128.0])[0], + to_yuv([255.0, 0.0, 128.0])[0] + ); + } +} diff --git a/crates/call-worker/src/main.rs b/crates/call-worker/src/main.rs index 499ca702..bb925d6c 100644 --- a/crates/call-worker/src/main.rs +++ b/crates/call-worker/src/main.rs @@ -17,6 +17,7 @@ mod camera; mod camera_channel; mod containment; mod diagnostics; +mod effects; mod mapping; #[cfg(test)] mod native_volume_tests; @@ -24,6 +25,7 @@ mod output; #[cfg(target_os = "linux")] mod pulse; mod screen; +mod segmenter; mod session; mod sound_defaults; mod sound_test; diff --git a/crates/call-worker/src/mapping.rs b/crates/call-worker/src/mapping.rs index 60190c5c..ba1b2bf9 100644 --- a/crates/call-worker/src/mapping.rs +++ b/crates/call-worker/src/mapping.rs @@ -750,6 +750,7 @@ mod tests { volume: 100, auto_level: true, mic_gain: 100, + video_effect: persephone_call_protocol::VideoEffect::NONE, }; assert!(is_first_message_allowed(&join)); } diff --git a/crates/call-worker/src/segmenter.rs b/crates/call-worker/src/segmenter.rs new file mode 100644 index 00000000..84e08931 --- /dev/null +++ b/crates/call-worker/src/segmenter.rs @@ -0,0 +1,44 @@ +//! The person mask for the background effects (ADR-0068): blur and pictures +//! need to know which pixels show the person. +//! +//! This build has no segmenter. [`available`] is `false` and [`open`] gives +//! nothing, so the worker refuses blur and pictures and keeps the camera off +//! for them. The later segmenter (tract with an embedded model, ADR-0068) +//! goes behind [`Segmenter`] and needs no change to `effects.rs` or the +//! session. No LiveKit and no OS types. + +use crate::effects::{Mask, Planes}; + +/// Makes one person mask for one camera picture. +pub trait Segmenter: Send { + /// Writes the mask of `picture` into `out`: 0 is background, 255 is the + /// person, at any size that [`Mask::resize`] allows. `false` when it + /// cannot: the caller then drops the picture, so no picture goes out + /// without its effect. + fn mask(&mut self, picture: &Planes<'_>, out: &mut Mask) -> bool; +} + +/// Whether this build can make person masks. It decides what the worker +/// reports in `Devices` and which effects it accepts. +pub const fn available() -> bool { + false +} + +/// A segmenter for one camera feed, or `None` when this build has none. +pub fn open() -> Option> { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + /// GIVEN this build + /// WHEN the segmenter is asked for + /// THEN none is available, and the report agrees with what `open` gives. + #[test] + fn given_this_build_when_asked_then_no_segmenter_is_available() { + assert!(!available()); + assert_eq!(open().is_some(), available()); + } +} diff --git a/crates/call-worker/src/session.rs b/crates/call-worker/src/session.rs index 0b9243ea..e71b046f 100644 --- a/crates/call-worker/src/session.rs +++ b/crates/call-worker/src/session.rs @@ -41,7 +41,7 @@ use livekit_signaling::SignalError; use persephone_call_protocol::{ CameraState, DeviceTest, FailureCode, FrameKeyMsg, FromWorker, MAX_OTHER_CONNECTIONS, MAX_PARTICIPANTS, MAX_SCREEN_FPS, MAX_VIDEO_FPS, MAX_VIDEO_PIXELS, MAX_VIDEO_SIDE, SCREEN_TILE, - ScreenState, ScreenTarget, ToWorker, VIDEO_TILES, + ScreenState, ScreenTarget, ToWorker, VIDEO_TILES, VideoEffect, }; use tokio::sync::mpsc::{self, Receiver, UnboundedReceiver}; use tokio::task::JoinHandle; @@ -53,6 +53,7 @@ mod stats_probe; use crate::camera::{self, CapturedFrame, Format}; use crate::containment; +use crate::effects::{self, CameraEffects, Planes, SharedEffect}; use crate::mapping::{ AudioRoster, ConnectFault, LevelMeters, Levels, Microphone, Playout, RoomChange, Slot, Slots, SoundPath, SpeakingTracker, apply, bounded_device_list, choose_device, failure_for_connect, @@ -62,6 +63,7 @@ use crate::mapping::{ use crate::mapping::{pulse_device_list, sound_path}; use crate::output::{Closed, Output, PictureSink}; use crate::screen; +use crate::segmenter; use crate::sound_defaults; use crate::sound_test; use crate::video::{ @@ -114,6 +116,7 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) volume, auto_level, mic_gain, + video_effect, } = first else { return fail(output, FailureCode::Protocol).await; @@ -276,6 +279,8 @@ pub async fn run(first: ToWorker, input: &mut Receiver, output: &Output) own_sids, publication: &publication, camera_device, + video_effect, + shared_effect: SharedEffect::new(video_effect), joined_sound, camera: None, stalled: None, @@ -383,7 +388,12 @@ pub async fn list_devices(output: &Output) -> u8 { .await .unwrap_or_default(); if output - .send(FromWorker::devices(recording, playout, cameras)) + .send(FromWorker::devices( + recording, + playout, + cameras, + segmenter::available(), + )) .await .is_err() { @@ -788,6 +798,32 @@ pub async fn test_device(first: ToWorker, input: &mut Receiver, output: & } } +/// The camera test's video effect (ADR-0068): the one in use, shared with +/// the capture thread. +struct TestEffect { + effect: VideoEffect, + shared: Arc, +} + +impl TestEffect { + fn new() -> Self { + Self { + effect: VideoEffect::NONE, + shared: SharedEffect::new(VideoEffect::NONE), + } + } + + /// Applies `requested` unless it cannot run here, as a call does, and + /// gives the answer. + fn set(&mut self, requested: VideoEffect) -> FromWorker { + let (effect, refused) = + effects::accept_effect(self.effect, requested, segmenter::available()); + self.effect = effect; + self.shared.store(effect); + FromWorker::VideoEffect { effect, refused } + } +} + /// Opens the device of a sound test off the runtime threads; it blocks. The /// choice is checked as a call's is (`sound_paths`): on Linux a `pulse:` /// choice must be the sound server name in the launch environment and on @@ -813,6 +849,9 @@ enum TestInput { Continue, /// End the test. Stop, + /// Change the camera test's video effect (ADR-0068). A sound test + /// takes it as `Bad`. + Effect(VideoEffect), Bad, } @@ -822,6 +861,7 @@ fn test_input(message: Option) -> TestInput { crate::diagnostics::global().set_on(on); TestInput::Continue } + Some(Input::Message(ToWorker::SetVideoEffect { effect })) => TestInput::Effect(effect), Some(Input::Message(ToWorker::Leave)) | Some(Input::Eof) | None => TestInput::Stop, Some(Input::Message(_)) | Some(Input::Bad) => TestInput::Bad, } @@ -887,7 +927,7 @@ async fn test_sound( match test_input(message) { TestInput::Continue => {} TestInput::Stop => stop.store(true, std::sync::atomic::Ordering::Release), - TestInput::Bad => { + TestInput::Bad | TestInput::Effect(_) => { bad = true; stop.store(true, std::sync::atomic::Ordering::Release); } @@ -900,6 +940,10 @@ async fn test_sound( async fn test_camera(device: Option, input: &mut Receiver, output: &Output) -> u8 { let pictures = output.pictures(); let mut limiter = RateLimiter::default(); + // The test shows the effect as a call would (ADR-0068). The core sends + // the saved one directly after `TestDevice`. + let mut effect = TestEffect::new(); + let mut feed_effects = CameraEffects::new(effect.shared.clone(), segmenter::open()); let (ended_tx, mut ended) = mpsc::channel::<()>(1); let (open_tx, mut opened) = mpsc::channel::>(1); // On the portal path (Linux) the core sends one remote before @@ -914,7 +958,8 @@ async fn test_camera(device: Option, input: &mut Receiver, output if !limiter.admit(std::time::Instant::now()) { return; } - if let Some(picture) = fitted_i420(&frame) + if let Some(mut picture) = fitted_i420(&frame) + && apply_effects(&mut feed_effects, &mut picture) && let Some((width, height, rgba)) = to_rgba(OWN_TILE, &picture) { pictures.put(OWN_TILE, 0, width, height, rgba); @@ -948,6 +993,11 @@ async fn test_camera(device: Option, input: &mut Receiver, output let _ = output.send(FromWorker::Left).await; return EXIT_DONE; } + TestInput::Effect(requested) => { + if output.send(effect.set(requested)).await.is_err() { + return fail(output, FailureCode::Internal).await; + } + } TestInput::Bad => return fail(output, FailureCode::Protocol).await, }, } @@ -972,6 +1022,11 @@ async fn test_camera(device: Option, input: &mut Receiver, output message = input.recv() => match test_input(message) { TestInput::Continue => {} TestInput::Stop => break, + TestInput::Effect(requested) => { + if output.send(effect.set(requested)).await.is_err() { + code = Some(FailureCode::Internal); + } + } TestInput::Bad => code = Some(FailureCode::Protocol), }, } @@ -1021,6 +1076,12 @@ struct Call<'a> { /// The camera the next camera start opens: the join's choice, then the /// newest `SetDevices` choice (ADR-0059). camera_device: Option, + /// The own camera's video effect (ADR-0068): the join's, then the newest + /// accepted `SetVideoEffect`. It may need a segmenter that this build + /// lacks only when the join asked for it; the camera then stays off. + video_effect: VideoEffect, + /// The same effect, for the camera's capture thread. + shared_effect: Arc, /// The microphone and speaker choice of the join. On Linux no device /// changes during a call, so a `SetDevices` with this choice (a change of /// the camera only) is no sound change there. @@ -1755,6 +1816,8 @@ struct CameraFeed { live: Arc, pictures: PictureSink, limiter: RateLimiter, + /// The video effect (ADR-0068). + effects: CameraEffects, } impl CameraFeed { @@ -1766,9 +1829,14 @@ impl CameraFeed { if !self.limiter.admit(std::time::Instant::now()) { return; } - let Some(picture) = fitted_i420(&frame) else { + let Some(mut picture) = fitted_i420(&frame) else { return; }; + // The effect applies before the preview and the SFU get the + // picture; a picture that it refuses goes to neither (ADR-0068). + if !apply_effects(&mut self.effects, &mut picture) { + return; + } if let Some((width, height, rgba)) = to_rgba(OWN_TILE, &picture) { self.pictures.put(OWN_TILE, 0, width, height, rgba); } @@ -1803,6 +1871,17 @@ impl ScreenFeed { } impl Call<'_> { + /// Applies a new video effect, at once for a running camera and for + /// later camera starts, unless it cannot run here: the old one then + /// stays (ADR-0068). The answer names the effect in use. + fn set_video_effect(&mut self, requested: VideoEffect) -> FromWorker { + let (effect, refused) = + effects::accept_effect(self.video_effect, requested, segmenter::available()); + self.video_effect = effect; + self.shared_effect.store(effect); + FromWorker::VideoEffect { effect, refused } + } + /// Starts turning the camera on. The open runs on its own thread; the /// result arrives in the event loop (`camera_opened`). Returns a state to /// report now: `On` when the camera already runs, `Unavailable` when the @@ -1811,6 +1890,11 @@ impl Call<'_> { /// `grant` is what the camera-on brought. An open takes it; a camera-on /// that opens nothing drops it, which closes its portal remote. fn begin_camera(&mut self, grant: camera::Grant) -> Option { + // An effect that cannot run keeps the camera off: the camera never + // sends the background that the user chose to hide (ADR-0068). + if !effects::can_apply(self.video_effect, segmenter::available()) { + return Some(CameraState::EffectUnavailable); + } // A capture that did not stop still holds the camera: open no second // one. With no open in flight, any capture thread that still runs (a // stalled stop, or an open that timed out) holds a camera too. @@ -1837,6 +1921,7 @@ impl Call<'_> { live: live.clone(), pictures: self.output.pictures(), limiter: RateLimiter::default(), + effects: CameraEffects::new(self.shared_effect.clone(), segmenter::open()), }; let failed = self.camera_failed.clone(); let choice = self.camera_device.clone(); @@ -3066,6 +3151,7 @@ impl Call<'_> { self.apply_microphone(); Ok(vec![FromWorker::DevicesSet { failure }]) } + ToWorker::SetVideoEffect { effect } => Ok(vec![self.set_video_effect(effect)]), ToWorker::Join { .. } | ToWorker::ListDevices | ToWorker::TestDevice { .. } @@ -3419,6 +3505,16 @@ fn use_own_key_index(manager: &E2eeManager, own_sids: &[TrackSid], index: i32) { } } +/// Applies the camera's video effect to `picture` in place (ADR-0068). +/// `false` when the picture must not go out. +fn apply_effects(effects: &mut CameraEffects, picture: &mut I420Buffer) -> bool { + let (width, height) = (picture.width(), picture.height()); + let (y_stride, u_stride, v_stride) = picture.strides(); + let (y, u, v) = picture.data_mut(); + Planes::new(width, height, y, y_stride, u, u_stride, v, v_stride) + .is_some_and(|mut planes| effects.process(&mut planes)) +} + /// A camera picture as I420, scaled to fit 640x360 (no enlarging). fn fitted_i420(frame: &CapturedFrame<'_>) -> Option { let (width, height, stride) = (frame.width, frame.height, frame.stride); diff --git a/crates/contracts/fixtures/call-status.json b/crates/contracts/fixtures/call-status.json index c1747fef..be624691 100644 --- a/crates/contracts/fixtures/call-status.json +++ b/crates/contracts/fixtures/call-status.json @@ -46,5 +46,7 @@ } ], "ringDeclined": true, - "deviceChange": "not_found" + "deviceChange": "not_found", + "effectRefused": true, + "mirror": false } diff --git a/crates/contracts/generated/contracts.ts b/crates/contracts/generated/contracts.ts index d8d17907..e9936110 100644 --- a/crates/contracts/generated/contracts.ts +++ b/crates/contracts/generated/contracts.ts @@ -200,7 +200,7 @@ export type CallEnd = "left" | "connection_failed" | "audio_device" | "containme export type CallJoinError = "already_in_call" | "not_joined" | "not_encrypted" | "no_call_server" | "call_server_unsupported" | "declined" | "unsupported_platform" | "containment" | "no_worker" | "no_delayed_events" | "membership" | "not_permitted" | "call_server" | "keys" | "proxy_unreadable" | "device_setting_unreadable"; -export type CallCamera = "off" | "starting" | "on" | "not_found" | "unavailable"; +export type CallCamera = "off" | "starting" | "on" | "not_found" | "unavailable" | "effect_unavailable"; export type CallScreen = "off" | "starting" | "on" | "not_found" | "unavailable" | "refused"; @@ -266,7 +266,19 @@ ringDeclined: boolean, * the sound may have stopped. Null after a change that worked, and * before any. */ -deviceChange: CallDeviceChange | null, }; +deviceChange: CallDeviceChange | null, +/** + * The last video effect change during this call could not run here + * (ADR-0068); the call keeps the effect it had. False after a change + * that applied, and before any. + */ +effectRefused: boolean, +/** + * The page mirrors the own preview (ADR-0068): the saved choice of the + * call device record. True when idle, and in a status from before the + * choice existed. + */ +mirror: boolean, }; export type CallIntent = "audio" | "video"; @@ -281,7 +293,30 @@ export type CallRings = { rings: Array, }; export type CallDevice = { id: string, name: string, }; -export type CallDevices = { supported: boolean, recording: Array, playout: Array, cameras: Array, selectedRecording: string | null, selectedPlayout: string | null, selectedCamera: string | null, volume: number, autoLevel: boolean, micGain: number, unreadable: boolean, }; +export type CallBackground = "none" | "blur" | "dusk" | "sea" | "forest" | "studio"; + +export type CallColourFilter = "none" | "greyscale" | "warm" | "cool" | "brighten"; + +export type CallVideoEffect = { background: CallBackground, blur: number, filter: CallColourFilter, }; + +export type CallDevices = { supported: boolean, recording: Array, playout: Array, cameras: Array, selectedRecording: string | null, selectedPlayout: string | null, selectedCamera: string | null, volume: number, autoLevel: boolean, micGain: number, +/** + * The saved video effect of the own camera (ADR-0068). No effect when + * nothing is saved. + */ +effect: CallVideoEffect, +/** + * The own camera's preview is shown mirrored (ADR-0068). On when + * nothing is saved, as before the choice existed. Others always see + * the picture as it is. + */ +mirror: boolean, +/** + * Whether this build can run the background effects that need the + * person mask: blur and pictures (ADR-0068). The page offers them only + * when it is true. + */ +backgroundEffects: boolean, unreadable: boolean, }; export type ContactTrust = "unknown" | "no_identity" | "unverified" | "verified" | "changed" | "verified_changed"; diff --git a/crates/contracts/src/lib.rs b/crates/contracts/src/lib.rs index 45c8a195..ea184c91 100644 --- a/crates/contracts/src/lib.rs +++ b/crates/contracts/src/lib.rs @@ -65,6 +65,30 @@ fn call_mic_gain<'de, D: Deserializer<'de>>(deserializer: D) -> Result bool { + percent >= CALL_BLUR_MIN && percent <= CALL_BLUR_MAX && percent.is_multiple_of(CALL_BLUR_STEP) +} + +fn call_blur<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + let value = u8::deserialize(deserializer)?; + if call_blur_valid(value) { + Ok(value) + } else { + Err(D::Error::custom( + "call blur under 10 or over 100 percent, or off the 10 percent step", + )) + } +} + fn call_volume<'de, D: Deserializer<'de>>(deserializer: D) -> Result { let value = u8::deserialize(deserializer)?; if value <= CALL_VOLUME_MAX { @@ -2804,9 +2828,77 @@ pub struct CallDevices { pub auto_level: bool, #[serde(deserialize_with = "call_mic_gain")] pub mic_gain: u16, + /// The saved video effect of the own camera (ADR-0068). No effect when + /// nothing is saved. + pub effect: CallVideoEffect, + /// The own camera's preview is shown mirrored (ADR-0068). On when + /// nothing is saved, as before the choice existed. Others always see + /// the picture as it is. + pub mirror: bool, + /// Whether this build can run the background effects that need the + /// person mask: blur and pictures (ADR-0068). The page offers them only + /// when it is true. + pub background_effects: bool, pub unreadable: bool, } +/// What the own camera shows behind the person (ADR-0068). `blur` blurs +/// the camera's own background; the others are pictures that the call +/// worker draws from code. +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CallBackground { + #[default] + None, + Blur, + Dusk, + Sea, + Forest, + Studio, +} + +/// A colour filter on the whole own camera picture (ADR-0068). +#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum CallColourFilter { + #[default] + None, + Greyscale, + Warm, + Cool, + /// Lifts the dark parts of the picture. + Brighten, +} + +/// The own camera's video effect (ADR-0068): the background first, then the +/// colour filter. `blur` is the blur strength in percent, +/// [`CALL_BLUR_MIN`] to [`CALL_BLUR_MAX`] in steps of [`CALL_BLUR_STEP`]. +/// It is kept while another background is chosen, so the slider keeps its +/// place. +#[derive(Clone, Copy, Debug, Deserialize, Serialize, TS, PartialEq, Eq)] +#[serde(deny_unknown_fields, rename_all = "camelCase")] +pub struct CallVideoEffect { + pub background: CallBackground, + #[serde(deserialize_with = "call_blur")] + pub blur: u8, + pub filter: CallColourFilter, +} + +impl CallVideoEffect { + /// The blur strength the page offers first. + pub const DEFAULT_BLUR: u8 = 50; +} + +impl Default for CallVideoEffect { + fn default() -> Self { + Self { + background: CallBackground::None, + blur: Self::DEFAULT_BLUR, + filter: CallColourFilter::None, + } + } +} + /// Most video tiles a call shows: the own camera, four remote cameras and /// the one remote screen share (ADR-0053). pub const CALL_VIDEO_TILES_MAX: usize = 6; @@ -2823,6 +2915,9 @@ pub enum CallCamera { NotFound, /// No camera, the OS denied it, it is in use, or capture failed. Unavailable, + /// The chosen video effect cannot run here, so the camera stays off + /// (ADR-0068). + EffectUnavailable, } /// The own screen share, as the page shows it (ADR-0053). @@ -2908,6 +3003,21 @@ pub struct CallStatus { /// before any. #[serde(default)] pub device_change: Option, + /// The last video effect change during this call could not run here + /// (ADR-0068); the call keeps the effect it had. False after a change + /// that applied, and before any. + #[serde(default)] + pub effect_refused: bool, + /// The page mirrors the own preview (ADR-0068): the saved choice of the + /// call device record. True when idle, and in a status from before the + /// choice existed. + #[serde(default = "mirrored")] + pub mirror: bool, +} + +/// The own preview is mirrored unless the user turned it off (ADR-0068). +const fn mirrored() -> bool { + true } /// Why a device change during a call did not apply (ADR-0059). @@ -2976,6 +3086,8 @@ impl CallStatus { video: Vec::new(), ring_declined: false, device_change: None, + effect_refused: false, + mirror: true, } } } @@ -3148,6 +3260,9 @@ pub fn generated_typescript() -> String { format!("export {}", CallRing::decl(&config)), format!("export {}", CallRings::decl(&config)), format!("export {}", CallDevice::decl(&config)), + format!("export {}", CallBackground::decl(&config)), + format!("export {}", CallColourFilter::decl(&config)), + format!("export {}", CallVideoEffect::decl(&config)), format!("export {}", CallDevices::decl(&config)), format!("export {}", ContactTrust::decl(&config)), format!("export {}", ContactStatus::decl(&config)), @@ -3385,7 +3500,7 @@ mod personal_contract_tests { fn call_contracts_refuse_unknown_fields_and_codes() { assert_eq!( serde_json::to_string(&CallStatus::idle()).unwrap(), - r#"{"phase":"idle","roomId":null,"muted":false,"deafened":false,"volume":100,"participants":[],"ended":null,"joinError":null,"camera":"off","screen":"off","video":[],"ringDeclined":false,"deviceChange":null}"# + r#"{"phase":"idle","roomId":null,"muted":false,"deafened":false,"volume":100,"participants":[],"ended":null,"joinError":null,"camera":"off","screen":"off","video":[],"ringDeclined":false,"deviceChange":null,"effectRefused":false,"mirror":true}"# ); // A status without the newer fields still reads (ADR-0059). let older: CallStatus = serde_json::from_str( @@ -3425,13 +3540,13 @@ mod personal_contract_tests { } let devices = |volume: &str| { format!( - r#"{{"supported":true,"recording":[],"playout":[],"cameras":[],"selectedRecording":null,"selectedPlayout":null,"selectedCamera":null,"volume":{volume},"autoLevel":true,"micGain":100,"unreadable":false}}"# + r#"{{"supported":true,"recording":[],"playout":[],"cameras":[],"selectedRecording":null,"selectedPlayout":null,"selectedCamera":null,"volume":{volume},"autoLevel":true,"micGain":100,"effect":{{"background":"none","blur":50,"filter":"none"}},"mirror":false,"backgroundEffects":false,"unreadable":false}}"# ) }; // The microphone gain is 0 to 400 in steps of 5; the flag is required. let gain = |gain: &str, level: &str| { format!( - r#"{{"supported":true,"recording":[],"playout":[],"cameras":[],"selectedRecording":null,"selectedPlayout":null,"selectedCamera":null,"volume":100,"autoLevel":{level},"micGain":{gain},"unreadable":false}}"# + r#"{{"supported":true,"recording":[],"playout":[],"cameras":[],"selectedRecording":null,"selectedPlayout":null,"selectedCamera":null,"volume":100,"autoLevel":{level},"micGain":{gain},"effect":{{"background":"none","blur":50,"filter":"none"}},"mirror":false,"backgroundEffects":false,"unreadable":false}}"# ) }; for accepted in ["0", "5", "250", "395", "400"] { @@ -3460,6 +3575,64 @@ mod personal_contract_tests { "{volume}" ); } + // The video effect (ADR-0068): blur 10 to 100 in steps of 10, closed + // names, every field required, nothing else. + let effect = |background: &str, blur: &str, filter: &str| { + format!(r#"{{"background":{background},"blur":{blur},"filter":{filter}}}"#) + }; + for blur in ["10", "50", "100"] { + let wire = effect(r#""blur""#, blur, r#""warm""#); + assert!( + serde_json::from_str::(&wire).is_ok(), + "{wire}" + ); + } + for background in ["none", "blur", "dusk", "sea", "forest", "studio"] { + let wire = effect(&format!("\"{background}\""), "50", r#""none""#); + assert!( + serde_json::from_str::(&wire).is_ok(), + "{wire}" + ); + } + for filter in ["none", "greyscale", "warm", "cool", "brighten"] { + let wire = effect(r#""none""#, "50", &format!("\"{filter}\"")); + assert!( + serde_json::from_str::(&wire).is_ok(), + "{wire}" + ); + } + for wire in [ + effect(r#""blur""#, "0", r#""none""#), + effect(r#""blur""#, "5", r#""none""#), + effect(r#""blur""#, "110", r#""none""#), + effect(r#""blur""#, "50.5", r#""none""#), + effect(r#""blur""#, "null", r#""none""#), + effect(r#""Blur""#, "50", r#""none""#), + effect(r#""beach""#, "50", r#""none""#), + effect(r#""none""#, "50", r#""sepia""#), + effect("null", "50", r#""none""#), + r#"{"background":"none","filter":"none"}"#.to_owned(), + r#"{"background":"none","blur":50,"filter":"none","image":"x"}"#.to_owned(), + ] { + assert!( + serde_json::from_str::(&wire).is_err(), + "{wire}" + ); + } + assert!( + (0..=u8::MAX) + .filter(|p| call_blur_valid(*p)) + .eq((10..=100).step_by(10)) + ); + let defaults = CallVideoEffect::default(); + assert_eq!( + serde_json::to_string(&defaults).unwrap(), + r#"{"background":"none","blur":50,"filter":"none"}"# + ); + assert_eq!( + serde_json::to_string(&CallCamera::EffectUnavailable).unwrap(), + r#""effect_unavailable""# + ); for wire in [ r#"{"available":true,"reason":null,"activeMembers":256}"#, r#"{"available":true,"reason":null,"activeMembers":-1}"#, @@ -3494,6 +3667,7 @@ mod personal_contract_tests { ) .unwrap(); assert!(!status.ring_declined); + assert!(status.mirror, "a status without the choice is mirrored"); let summary: RoomSummary = serde_json::from_str( r#"{"roomId":"!r:s","displayName":null,"unreadCount":0,"encryption":"encrypted"}"#, ) diff --git a/crates/contracts/tests/contracts.rs b/crates/contracts/tests/contracts.rs index a3186369..2541ac1c 100644 --- a/crates/contracts/tests/contracts.rs +++ b/crates/contracts/tests/contracts.rs @@ -861,6 +861,13 @@ fn call_devices_use_camel_case_and_reject_unknown_fields() { volume: 40, auto_level: false, mic_gain: 250, + effect: persephone_contracts::CallVideoEffect { + background: persephone_contracts::CallBackground::Blur, + blur: 70, + filter: persephone_contracts::CallColourFilter::Brighten, + }, + mirror: true, + background_effects: false, unreadable: false, }; let json = serde_json::to_value(&devices).unwrap(); @@ -877,6 +884,9 @@ fn call_devices_use_camel_case_and_reject_unknown_fields() { "volume": 40, "autoLevel": false, "micGain": 250, + "effect": {"background": "blur", "blur": 70, "filter": "brighten"}, + "mirror": true, + "backgroundEffects": false, "unreadable": false }) ); @@ -890,6 +900,15 @@ fn call_devices_use_camel_case_and_reject_unknown_fields() { let mut without = json.clone(); without.as_object_mut().unwrap().remove("cameras"); assert!(serde_json::from_value::(without).is_err()); + // The effect fields are required (ADR-0068). + for field in ["effect", "mirror", "backgroundEffects"] { + let mut without = json.clone(); + without.as_object_mut().unwrap().remove(field); + assert!( + serde_json::from_value::(without).is_err(), + "{field}" + ); + } let mut no_camera = json.clone(); no_camera.as_object_mut().unwrap().remove("selectedCamera"); assert!( diff --git a/crates/contracts/tests/type-contracts.ts b/crates/contracts/tests/type-contracts.ts index a1afc563..ea0fde2c 100644 --- a/crates/contracts/tests/type-contracts.ts +++ b/crates/contracts/tests/type-contracts.ts @@ -275,7 +275,7 @@ void bigintFilter; void unknownAttachment; void unknownSync; void missingHealth; -const idleCall: CallStatus = { phase: "idle", roomId: null, muted: false, deafened: false, volume: 100, participants: [], ended: null, joinError: null, camera: "off", screen: "off", video: [], ringDeclined: false, deviceChange: null }; +const idleCall: CallStatus = { phase: "idle", roomId: null, muted: false, deafened: false, volume: 100, participants: [], ended: null, joinError: null, camera: "off", screen: "off", video: [], ringDeclined: false, deviceChange: null, effectRefused: false, mirror: true }; const readyCall: CallReadiness = { available: false, reason: "no_call_server", activeMembers: 0 }; // @ts-expect-error a status carries codes, never a token or URL const callWithToken: CallStatus = { ...idleCall, token: "secret" }; @@ -285,7 +285,15 @@ const unknownReason: CallUnavailable = "no_microphone"; const unknownEnd: CallEnd = "crashed"; // @ts-expect-error only the defined join errors are accepted const unknownJoin: CallJoinError = "busy"; -const noDevices: CallDevices = { supported: true, recording: [{ id: "a", name: "Microphone" }], playout: [], cameras: [{ id: "c", name: "Camera" }], selectedRecording: null, selectedPlayout: null, selectedCamera: null, volume: 100, autoLevel: true, micGain: 100, unreadable: false }; +const noDevices: CallDevices = { supported: true, recording: [{ id: "a", name: "Microphone" }], playout: [], cameras: [{ id: "c", name: "Camera" }], selectedRecording: null, selectedPlayout: null, selectedCamera: null, volume: 100, autoLevel: true, micGain: 100, effect: { background: "none", blur: 50, filter: "none" }, mirror: true, backgroundEffects: false, unreadable: false }; +// @ts-expect-error only the defined backgrounds are accepted, never a picture path +const backgroundPath: CallDevices = { ...noDevices, effect: { background: "C:/me.jpg", blur: 50, filter: "none" } }; +// @ts-expect-error only the defined colour filters are accepted +const unknownFilter: CallDevices = { ...noDevices, effect: { background: "none", blur: 50, filter: "sepia" } }; +// @ts-expect-error an effect carries its three fields, nothing else +const effectWithUrl: CallDevices = { ...noDevices, effect: { background: "none", blur: 50, filter: "none", url: "https://x" } }; +// @ts-expect-error the device list says whether blur and pictures can run +const missingBackgroundEffects: CallDevices = { ...noDevices, backgroundEffects: undefined }; // @ts-expect-error a device list carries IDs and names, nothing else const deviceWithPath: CallDevices = { ...noDevices, recording: [{ id: "a", name: "b", path: "c" }] }; // @ts-expect-error the saved choice must be explicit null, not missing @@ -352,6 +360,10 @@ void tileWithoutStream; void tileWithUrl; void remoteTile; void noDevices; +void backgroundPath; +void unknownFilter; +void effectWithUrl; +void missingBackgroundEffects; void deviceWithPath; void missingChoice; void idleCall; diff --git a/crates/core-protocol/src/lib.rs b/crates/core-protocol/src/lib.rs index 615b1453..c31479ca 100644 --- a/crates/core-protocol/src/lib.rs +++ b/crates/core-protocol/src/lib.rs @@ -768,6 +768,15 @@ pub enum Call { auto_level: bool, gain: u16, }, + /// Set the own camera's video effect and whether its preview is shown + /// mirrored (ADR-0068). Both are saved for later calls; the effect + /// applies at once to a running or joining call and to a camera test. + /// The blur strength is checked by the type and again by + /// [`call_video_within_limits`]. Replies `CallStatus`. + CallVideoEffect { + effect: persephone_contracts::CallVideoEffect, + mirror: bool, + }, /// Start or stop the call statistics (ADR-0066). While on, the core /// asks the worker to read them and sends [`Event::CallStats`], at most /// about once a second. Only the call window may send it. Off at every @@ -1790,7 +1799,9 @@ pub struct VideoPicture { /// must be non-empty, at most [`MAX_CALL_DEVICE_ID_BYTES`] and free of /// control characters; [`Call::CallVolume`] is at most /// [`MAX_CALL_VOLUME_PERCENT`]; [`Call::CallMicrophone`] has a gain of at most -/// [`MAX_CALL_MIC_GAIN_PERCENT`] on a step of [`CALL_MIC_GAIN_STEP_PERCENT`]. +/// [`MAX_CALL_MIC_GAIN_PERCENT`] on a step of [`CALL_MIC_GAIN_STEP_PERCENT`]; +/// [`Call::CallVideoEffect`] has a blur strength that +/// [`persephone_contracts::call_blur_valid`] accepts. /// Any other call is not constrained here and /// gives `true`. pub fn call_video_within_limits(call: &Call) -> bool { @@ -1818,6 +1829,7 @@ pub fn call_video_within_limits(call: &Call) -> bool { Call::CallMicrophone { gain, .. } => { *gain <= MAX_CALL_MIC_GAIN_PERCENT && gain.is_multiple_of(CALL_MIC_GAIN_STEP_PERCENT) } + Call::CallVideoEffect { effect, .. } => persephone_contracts::call_blur_valid(effect.blur), _ => true, } } @@ -2673,6 +2685,17 @@ mod tests { }, r#"{"id":1,"call":{"command":"call_microphone","auto_level":false,"gain":250}}"#, ), + ( + Call::CallVideoEffect { + effect: persephone_contracts::CallVideoEffect { + background: persephone_contracts::CallBackground::Sea, + blur: 30, + filter: persephone_contracts::CallColourFilter::Cool, + }, + mirror: true, + }, + r#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"sea","blur":30,"filter":"cool"},"mirror":true}}"#, + ), ( Call::CallStatus {}, r#"{"id":1,"call":{"command":"call_status"}}"#, @@ -3156,6 +3179,16 @@ mod tests { br#"{"id":1,"call":{"command":"call_microphone","auto_level":true,"gain":50.5}}"#, br#"{"id":1,"call":{"command":"call_microphone","auto_level":true,"gain":"100"}}"#, br#"{"id":1,"call":{"command":"call_microphone","auto_level":true,"gain":100,"x":1}}"#, + br#"{"id":1,"call":{"command":"call_video_effect"}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","mirror":false}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"none","blur":50,"filter":"none"}}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"blur","blur":55,"filter":"none"},"mirror":false}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"blur","blur":0,"filter":"none"},"mirror":false}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"photo","blur":50,"filter":"none"},"mirror":false}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"none","blur":50,"filter":"sepia"},"mirror":false}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"none","blur":50,"filter":"none","path":"C:/x"},"mirror":false}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"none","blur":50,"filter":"none"},"mirror":1}}"#, + br#"{"id":1,"call":{"command":"call_video_effect","effect":{"background":"none","blur":50,"filter":"none"},"mirror":false,"x":1}}"#, br#"{"id":1,"call":{"command":"call_status","room_id":"!r:s"}}"#, br#"{"id":1,"call":{"command":"call_rings","room_id":"!r:s"}}"#, br#"{"id":1,"call":{"command":"call_decline_ring"}}"#, @@ -3931,6 +3964,22 @@ mod tests { for refused in [1, 99, 401, 405, 1000, u16::MAX] { assert!(!call_video_within_limits(&gain(refused)), "{refused}"); } + // The blur strength is 10 to 100 percent in steps of 10 (ADR-0068), + // also for a value made in Rust rather than read from JSON. + let blur = |blur| Call::CallVideoEffect { + effect: persephone_contracts::CallVideoEffect { + background: persephone_contracts::CallBackground::Blur, + blur, + filter: persephone_contracts::CallColourFilter::None, + }, + mirror: false, + }; + for accepted in [10, 50, 100] { + assert!(call_video_within_limits(&blur(accepted)), "{accepted}"); + } + for refused in [0, 5, 55, 110, u8::MAX] { + assert!(!call_video_within_limits(&blur(refused)), "{refused}"); + } } /// GIVEN video replies of many sizes on camera tiles and the screen tile diff --git a/crates/core/AGENTS.md b/crates/core/AGENTS.md index a17783be..fbf1d7af 100644 --- a/crates/core/AGENTS.md +++ b/crates/core/AGENTS.md @@ -19,6 +19,7 @@ This crate is the application entry process. ADR-0004 assigns sessions, SDK work - Join refusal and the alone rule (ADR-0063, proposed): `CallController::prepare` reads the room's power levels from the local store and answers `CallError::NotPermitted` (`join_error` `not_permitted`) with `can_send_member_state`, the function `readiness` uses, before the SFU discovery, the worker launch, the delayed event and the membership send. A 403 `M_FORBIDDEN` answer to the membership send is the same error (`membership_error`); any other refusal stays `Membership`. `LevelKey::JoinCalls` maps to the call membership event type in `room_settings::state_type`, so the one closed level change sets it. `calls/alone.rs` keeps the remote participants by connection from `ParticipantJoined` and `ParticipantLeft`, and drops a connection's participants on `Connection { up: false }`; the call loop ends the call with `EndReason::Alone` 30 s after `Connected` with nobody else, or after the last one left. At the deadline it first applies the worker's waiting messages (`alone_still_due`), so a join that waits unread keeps the call. The end uses the normal leave path. Keep the set bounded, and keep a call whose set overflowed. Its tests need tokio's `test-util` (dev-dependency only). - Presence (ADR-0057, proposed): `presence.rs` holds the `Writer`, which picks every sync request's `set_presence` and the `PUT` of a changed setting, at most one write a second and a carried sync value at most every 15 seconds, the bounded `Book` of contacts' presence, and `Members`, the bounded book of the members the member panel last listed (`room_settings::readers` sets it). The contacts' two and the members' four lookups a round all run at once, so a round stays within one timeout. Never let a sync request use the SDK's default `online`: pass the writer's value to `account::sync_round`. - Devices and levels (ADR-0059, proposed): `calls/device_test.rs` holds the pure test rules; `CallController::start_device_test` runs one test at a time on its own thread, refuses it while a call runs or joins (`in_call`), stops it when a join starts and ends it after `TEST_LIMIT`. The test worker starts with the `pulse:` name of the tested device only (`device_test::worker_audio`), and on the Linux portal path a camera test sends one portal remote before `TestDevice` (`devices::send_portal_remote`, cancelled by the user's stop). A stop recorded while the test worker starts ends the test before `TestDevice`, so no device opens; a later stop reaches the worker as `Leave`, which closes a device that opened. The test worker gets the diagnostic switch before `TestDevice` and on each change, and its records go to the log (`worker_record`, ADR-0058). A camera test's picture store is the controller's store only while no call runs. `Core::set_call_devices` also sends the microphone, speaker and camera choice to a running or joining call (`CallController::set_devices`, which sends `ToWorker::SetDevices`); the camera applies from the next camera start, and a failed microphone or speaker change is the status's `deviceChange`. Other devices' levels go to the hub as `SoundUpdate::Participants` and leave with the own level under its gap. +- Video effects (ADR-0068, proposed): the own camera's effect and the preview's mirror are in the call device record (`calls/devices.rs`, fields `effect` and `mirror`; none and mirrored when missing), checked by `Selection::is_valid` and changed with `Core::call_video_effect`, which applies them first and then saves them like the microphone settings. `CallController::set_video_effect` sends the effect to the running or joining call through the `video_effect` watch channel (with the mirror, as `OwnVideo`), and to a camera test through `Inner::test_effect`; a camera test starts with the saved effect (`set_test_effect`) and sends `SetVideoEffect` directly after `TestDevice`. `Join` carries the saved effect. The worker's answer sets the status's `effectRefused`; the mirror is `CallStatus.mirror`, for the page only. Saving devices (`set_call_devices`) keeps the effect and the mirror. - Call statistics (ADR-0066, proposed): `calls/stats.rs` makes the page's `CallStats` from the worker's message, naming each remote entry by the member that `View::level_member` says its identity stands for (a current member on a connection that speaks for it) and dropping the whole reading when it fails `CallStats::within_limits`. `CallController::set_stats` is the one switch: on needs a running call or a joining call that the end of the session has not stopped. `Inner::release` and `stop_for_session_end` turn it off under the slot lock, for a running and a joining call alike, and the end of the session drops the waiting reading before it publishes `Ended`. `Core::close` and the host's window reset turn it off too, and `Call::run` sends `SetStats` on each change (`apply_stats`, retry when the queue is full). A reading is dropped unless the switch is on. The hub keeps only the newest and sends `Event::CallStats` at once; it is dropped when the switch goes off. Never send statistics to a page that did not turn them on. - Linux keyring (ADR-0061, proposed): `platform/linux/vault.rs` asks `confirm_keyring_creation` (default "no") only when `ReadAlias("default")` is `/` while a new secret is stored, at most once per open attempt, and only after a yes calls `CreateCollection` ("Login", alias `default`) reads the alias again after the answer (a default made meanwhile is used without `CreateCollection`, which would return it and could relabel it), and uses the collection it created (`created_collection`: the reply's path, or the prompt's result) only if that path was not in the provider's `Collections` list just before and the alias now names it. `store_new` owns the session-bus name `CREATION_NAME` (`CreationLock`) from its first search to its read-back, so no other core on that bus creates an item during the waits; do not move this lock to a file under a per-process directory. A core waits at most `CREATION_WAIT` (5 s) for the name, plus one `CREATION_CALL_TIMEOUT` (1 s) request that started before the end (the lock asks on its own connection with that reply timeout), because `main.rs` opens the profile before any window shows. Another core that still owns the name then is `VaultError::Busy` (`keyring_busy`); no session bus for the lock's connection is `VaultError::Missing(Missing::SessionBus)` (`no_session_bus`); any other lock failure, also a bus that exists but does not answer in time, is `VaultError::Failed` (`key_unreadable`). Never add `SetAlias`. A missing bus, provider, default keyring or display is `VaultError::Missing`, which `store.rs` maps to its own `StoreState`; never fall back to another collection, the kernel keyring, a file or the passphrase alone. - Diagnostic log (ADR-0058, proposed): `diagnostics.rs` is the only writer. It is off at every start; `main.rs` erases the old file (overwrite, sync, truncate, delete) before the profile opens. Every string passes `diagnostics/redact.rs` before the writer thread gets it. `diagnostics/events.rs` writes event metadata only; content is always `[content]`. Request records use `Call::command()`, which reads only the command tag, never arguments. Never format a secret into a record, and keep the queue, line and file limits. Turning it on goes through `confirm_diagnostics` (default "no"). diff --git a/crates/core/src/calls/controller.rs b/crates/core/src/calls/controller.rs index 05701fdc..6caadbec 100644 --- a/crates/core/src/calls/controller.rs +++ b/crates/core/src/calls/controller.rs @@ -52,7 +52,7 @@ use matrix_sdk::{ }; use persephone_call_protocol::{ CameraState, FailureCode, FrameKeyMsg, FromWorker, MAX_VOLUME_PERCENT, ScreenState, ToWorker, - TurnServer, VIDEO_TILES, valid_mic_gain, + TurnServer, VIDEO_TILES, VideoEffect, valid_mic_gain, }; use persephone_contracts::{ CALL_PARTICIPANTS_MAX, CallCamera, CallDeviceChange, CallDeviceTestKind, CallDeviceTestState, @@ -233,6 +233,11 @@ pub enum CallState { ring_declined: bool, /// The last device change of this call failed (ADR-0059). device_change: Option, + /// The last video effect change of this call was refused + /// (ADR-0068). + effect_refused: bool, + /// The page mirrors the own preview (ADR-0068). + mirror: bool, }, Ended { room_id: OwnedRoomId, @@ -381,6 +386,14 @@ impl AudioWants { } } +/// The own camera's video effect and whether the page mirrors its preview +/// (ADR-0068), set together by one page command. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct OwnVideo { + pub(crate) effect: VideoEffect, + pub(crate) mirror: bool, +} + /// What a worker event did to the view. #[derive(Debug, PartialEq, Eq)] enum Applied { @@ -433,6 +446,11 @@ struct View { ring_declined: bool, /// The last device change failed (ADR-0059). device_change: Option, + /// The worker refused the last video effect change (ADR-0068). + effect_refused: bool, + /// The page mirrors the own preview (ADR-0068): the saved choice, then + /// each change. + mirror: bool, } /// Remote video tiles: tiles 1 to 4 are cameras, tile 5 is the screen share. @@ -465,6 +483,8 @@ impl View { video_streams: Default::default(), ring_declined: false, device_change: None, + effect_refused: false, + mirror: true, } } @@ -603,6 +623,21 @@ impl View { (self.camera == CallCamera::On, remote) } + /// Starts the view with the saved mirror choice (ADR-0068). + fn with_mirror(mut self, mirror: bool) -> Self { + self.mirror = mirror; + self + } + + /// The mirror choice changed; the worker has no part in it. + fn set_mirror(&mut self, mirror: bool) -> Applied { + if self.mirror == mirror { + return Applied::Same; + } + self.mirror = mirror; + Applied::Changed + } + /// Starts the view with the saved playout volume. fn with_volume(mut self, volume: u8) -> Self { self.volume = volume.min(MAX_VOLUME_PERCENT); @@ -720,11 +755,19 @@ impl View { self.device_change = change; Applied::Changed } + FromWorker::VideoEffect { refused, .. } => { + if self.effect_refused == *refused { + return Applied::Same; + } + self.effect_refused = *refused; + Applied::Changed + } FromWorker::Camera { state } => self.set_camera(match state { CameraState::Off => CallCamera::Off, CameraState::On => CallCamera::On, CameraState::NotFound => CallCamera::NotFound, CameraState::Unavailable => CallCamera::Unavailable, + CameraState::EffectUnavailable => CallCamera::EffectUnavailable, }), FromWorker::Screen { state, .. } => self.set_screen(match state { ScreenState::Off => CallScreen::Off, @@ -920,6 +963,8 @@ impl View { video: self.video_tiles(), ring_declined: self.ring_declined, device_change: self.device_change, + effect_refused: self.effect_refused, + mirror: self.mirror, } } } @@ -1181,6 +1226,9 @@ struct Joining { /// `None` until one is set: the join sends the saved settings. The call /// task gets the same channel, like `devices`. microphone: watch::Sender>, + /// The video effect set while the call joins (ADR-0068), like + /// `microphone`. + video_effect: watch::Sender>, } struct RunHandle { @@ -1202,6 +1250,9 @@ struct RunHandle { /// The latest microphone settings (ADR-0062) set since the join /// started, kept like the volume. `None` until one is set. microphone: watch::Sender>, + /// The latest video effect (ADR-0068) set since the join started, kept + /// like the microphone settings. `None` until one is set. + video_effect: watch::Sender>, /// The latest microphone and speaker choice made during the call /// (ADR-0059). `None` until one is made. devices: watch::Sender>, @@ -1300,6 +1351,9 @@ struct Inner { device_test: Mutex, /// Tells the owner that the device test changed. test_listener: Mutex>, + /// The video effect that a camera test shows (ADR-0068): the saved one + /// when the test starts, then each change. + test_effect: watch::Sender, } /// One member's sound level and the worker participant that sent it, so a @@ -1458,6 +1512,7 @@ struct JoinGuard { kill: Arc>>>, devices: watch::Sender>, microphone: watch::Sender>, + video_effect: watch::Sender>, armed: bool, } @@ -1509,6 +1564,7 @@ impl CallController { next_id: AtomicU64::new(0), device_test: Mutex::new(DeviceTestSlot::default()), test_listener: Mutex::new(None), + test_effect: watch::channel(VideoEffect::NONE).0, }), } } @@ -1710,6 +1766,7 @@ impl CallController { let kill = Arc::new(Mutex::new(None)); let devices = watch::channel(None).0; let microphone = watch::channel(None).0; + let video_effect = watch::channel(None).0; *slot = Slot::Joining(Joining { id, room_id: room_id.to_owned(), @@ -1717,6 +1774,7 @@ impl CallController { kill: kill.clone(), devices: devices.clone(), microphone: microphone.clone(), + video_effect: video_effect.clone(), }); drop(slot); // The call needs the devices: a device test ends. @@ -1732,6 +1790,7 @@ impl CallController { kill, devices, microphone, + video_effect, armed: true, }) } @@ -1785,6 +1844,7 @@ impl CallController { let screen_control = call.screen_control.clone(); let volume = call.volume.clone(); let microphone = call.microphone.clone(); + let video_effect = call.video_effect.clone(); let devices = call.devices.clone(); let mut call = Some(call); let halted = { @@ -1813,6 +1873,7 @@ impl CallController { screen_control, volume, microphone, + video_effect, devices, task: Some(task), }); @@ -2046,6 +2107,7 @@ impl CallController { volume: scope.devices.volume(), auto_level: scope.devices.auto_level(), mic_gain: scope.devices.mic_gain(), + video_effect: scope.devices.video_effect(), }; // Before the join, so the worker's connection records are kept // (ADR-0058). The call task sends the switch again when it starts. @@ -2072,7 +2134,8 @@ impl CallController { alone: Alone::default(), view: View::new(room_id.to_owned(), sfu.url, scope.video) .with_video_streams(video_streams) - .with_volume(scope.devices.volume()), + .with_volume(scope.devices.volume()) + .with_mirror(scope.devices.mirror()), changes, incoming, failed, @@ -2082,6 +2145,7 @@ impl CallController { audio: AudioWants::default(), volume: watch::channel(scope.devices.volume()).0, microphone: guard.microphone.clone(), + video_effect: guard.video_effect.clone(), devices: guard.devices.clone(), levels: BTreeMap::new(), portal: None, @@ -2198,6 +2262,34 @@ impl CallController { } } + /// Sets the own camera's video effect and the preview's mirror + /// (ADR-0068): the effect at once for a camera test, and both for the + /// running or joining call like the microphone settings. The worker may + /// refuse an effect that cannot run there; the state's `effect_refused` + /// then says so. `NotInCall` without a call. The caller saves both for + /// later calls. + pub fn set_video_effect(&self, effect: VideoEffect, mirror: bool) -> Result<(), CallError> { + self.inner.test_effect.send_replace(effect); + let own = Some(OwnVideo { effect, mirror }); + match &*self.inner.slot() { + Slot::Running(run) => { + run.video_effect.send_replace(own); + Ok(()) + } + Slot::Joining(join) => { + join.video_effect.send_replace(own); + Ok(()) + } + Slot::Idle => Err(CallError::NotInCall), + } + } + + /// The video effect that the next camera test starts with: the saved + /// one (ADR-0068). + pub fn set_test_effect(&self, effect: VideoEffect) { + self.inner.test_effect.send_replace(effect); + } + /// Moves the running or joining call to another microphone and speaker, /// and gives it the camera for its next camera start (ADR-0059). Only /// the newest choice is sent, once the worker is @@ -2706,6 +2798,10 @@ struct Call { /// `None` until one is set, as the Join carried the saved ones. The /// controller sends; the task subscribes. microphone: watch::Sender>, + /// The video effect (ADR-0068) set since the join started; `None` until + /// one is set, as the Join carried the saved one. The controller sends; + /// the task subscribes. + video_effect: watch::Sender>, /// A device change during the call (ADR-0059). The controller sends; /// the task subscribes. devices: watch::Sender>, @@ -3225,15 +3321,27 @@ fn run_device_test( // `TestDevice`; the worker may open the device, and closes it when it // reads `Leave`. let stopped_early = stop.load(Ordering::SeqCst); + // A camera test shows the saved video effect, then each change + // (ADR-0068). The worker answers each with the effect in use. + let mut test_effect = inner.test_effect.subscribe(); + let effect = *test_effect.borrow_and_update(); let sent = if stopped_early { Ok(()) } else { - link.send(ToWorker::SetDiagnostics { on }).and_then(|()| { - link.send(ToWorker::TestDevice { - test: device_test::worker_test(test), - device, + link.send(ToWorker::SetDiagnostics { on }) + .and_then(|()| { + link.send(ToWorker::TestDevice { + test: device_test::worker_test(test), + device, + }) + }) + .and_then(|()| { + if camera { + link.send(ToWorker::SetVideoEffect { effect }) + } else { + Ok(()) + } }) - }) }; let mut state = if stopped_early { CallDeviceTestState::Idle @@ -3261,6 +3369,10 @@ fn run_device_test( let on = *diagnostics.borrow_and_update(); let _ = link.send(ToWorker::SetDiagnostics { on }); } + if camera && leave_by.is_none() && test_effect.has_changed().unwrap_or(false) { + let effect = *test_effect.borrow_and_update(); + let _ = link.send(ToWorker::SetVideoEffect { effect }); + } match link.events.try_recv() { // After the user's stop the meter shows nothing more. Ok(FromWorker::SoundLevel { level }) => { @@ -4380,6 +4492,18 @@ impl Call { Ok(()) } + /// The user changed the video effect or the mirror: the worker applies + /// the effect to the camera at once, or refuses it and keeps the old one, + /// and answers with the effect in use; the page sees the mirror at once + /// (ADR-0068). + fn video_effect_changed(&mut self, inner: &Inner, own: OwnVideo) -> Result<(), EndReason> { + self.send_worker(ToWorker::SetVideoEffect { effect: own.effect })?; + if self.view.set_mirror(own.mirror) == Applied::Changed { + self.publish(inner); + } + Ok(()) + } + /// The user changed the microphone level or gain: the worker applies it /// to the audio processing at once and does not answer. The values were /// checked when they were set; the check here keeps a bad one from ever @@ -4514,6 +4638,9 @@ impl Call { // since the join started, the Join's settings stand. let mut microphone = self.microphone.subscribe(); microphone.mark_changed(); + // The same for the video effect (ADR-0068). + let mut video_effect = self.video_effect.subscribe(); + video_effect.mark_changed(); // A device choice made since the join started; the join used the // saved one. A choice made before this point is sent at once. let mut devices = self.devices.subscribe(); @@ -4573,6 +4700,12 @@ impl Call { self.microphone_changed(settings)?; } } + Ok(()) = video_effect.changed() => { + let own = *video_effect.borrow_and_update(); + if let Some(own) = own { + self.video_effect_changed(inner, own)?; + } + } Ok(()) = devices.changed() => { let choice = devices.borrow_and_update().clone(); if let Some(choice) = choice { @@ -5596,7 +5729,8 @@ mod tests { view.apply(&FromWorker::Devices { recording: Vec::new(), playout: Vec::new(), - cameras: Vec::new() + cameras: Vec::new(), + background_effects: false, }), Applied::End(EndReason::WorkerFailed(FailureCode::Protocol)) ); @@ -6005,6 +6139,115 @@ mod tests { ); } + /// GIVEN a running call task WHEN the video effect changes THEN the + /// worker gets each one as it is (ADR-0068); the worker decides whether + /// it can run it. + #[test] + fn given_a_running_call_when_the_video_effect_changes_then_the_worker_gets_it() { + let fixture = test_call( + no_admission(), + Arc::new(Flags::default()), + Arc::new(AtomicBool::new(false)), + ); + let inner = controller(FakeHost::new(true, None)).inner.clone(); + let (mut call, mut to_worker) = (fixture.call, fixture.to_worker); + call.view.connected = true; + let blur = VideoEffect { + background: persephone_call_protocol::Background::Blur( + persephone_call_protocol::BlurStrength::new(40).unwrap(), + ), + filter: persephone_call_protocol::ColourFilter::Greyscale, + }; + for (effect, mirror) in [(blur, false), (VideoEffect::NONE, true)] { + call.video_effect_changed(&inner, OwnVideo { effect, mirror }) + .unwrap(); + assert_eq!( + to_worker.try_recv().unwrap(), + ToWorker::SetVideoEffect { effect } + ); + assert_eq!(call.view.mirror, mirror, "the page sees the mirror"); + } + } + + /// GIVEN no call, a joining call and a running call WHEN the video + /// effect is set THEN no call is `NotInCall`, a call keeps only the + /// newest value for its task, and a camera test gets each value + /// (ADR-0068). + #[test] + fn given_the_video_effect_when_set_then_the_call_and_the_test_get_the_newest() { + let warm = VideoEffect { + background: persephone_call_protocol::Background::None, + filter: persephone_call_protocol::ColourFilter::Warm, + }; + let cool = VideoEffect { + filter: persephone_call_protocol::ColourFilter::Cool, + ..warm + }; + let calls = controller(FakeHost::new(true, None)); + assert_eq!( + calls.set_video_effect(warm, true), + Err(CallError::NotInCall) + ); + assert_eq!( + *calls.inner.test_effect.borrow(), + warm, + "a camera test shows it without a call" + ); + let guard = calls.claim(room_id!("!r:example.org")).unwrap(); + assert_eq!( + *guard.video_effect.borrow(), + None, + "the join sends the saved one" + ); + assert_eq!(calls.set_video_effect(cool, false), Ok(())); + let mut task = guard.video_effect.subscribe(); + task.mark_changed(); + assert!(task.has_changed().unwrap(), "an earlier value is sent"); + assert_eq!( + *task.borrow_and_update(), + Some(OwnVideo { + effect: cool, + mirror: false + }) + ); + drop(guard); + + let (_store, _commands, _killed) = running_call(&calls, active_state()); + assert_eq!(calls.set_video_effect(warm, false), Ok(())); + assert_eq!(calls.set_video_effect(cool, true), Ok(())); + let Slot::Running(run) = &*calls.inner.slot() else { + panic!("running"); + }; + assert_eq!( + *run.video_effect.subscribe().borrow(), + Some(OwnVideo { + effect: cool, + mirror: true + }), + "only the newest value is kept" + ); + assert_eq!(*calls.inner.test_effect.borrow(), cool); + } + + /// GIVEN a running call WHEN the worker answers a video effect change + /// THEN the state says whether it was refused, and a repeat changes + /// nothing (ADR-0068). + #[test] + fn given_a_video_effect_answer_then_the_state_says_whether_it_was_refused() { + let mut view = view(); + view.apply(&FromWorker::Connected); + assert!(!view.effect_refused); + for refused in [true, false] { + let answer = FromWorker::VideoEffect { + effect: VideoEffect::NONE, + refused, + }; + assert_eq!(view.apply(&answer), Applied::Changed); + assert_eq!(view.effect_refused, refused); + assert_eq!(view.apply(&answer), Applied::Same, "a repeat"); + } + } + /// GIVEN a call that is still joining WHEN the microphone and speaker /// change THEN the choice waits on the join's channel, and a task that /// subscribes later still sees it; WHEN no call runs THEN it is @@ -6202,6 +6445,60 @@ mod tests { sent.try_recv(), Ok(ToWorker::TestDevice { device: Some(id), .. }) if id == "mic" )); + assert_eq!( + sent.try_recv(), + Ok(ToWorker::Leave), + "a sound test gets no video effect, only the closing `Leave`" + ); + } + + /// GIVEN a saved video effect WHEN a camera test starts THEN its worker + /// gets the effect directly after `TestDevice` (ADR-0068), so the first + /// shown picture has it, and the worker's answer does not end the test. + #[test] + fn given_a_camera_test_then_its_worker_gets_the_saved_effect_after_the_test() { + let warm = VideoEffect { + background: persephone_call_protocol::Background::None, + filter: persephone_call_protocol::ColourFilter::Warm, + }; + let host = ScriptHost::new(vec![ + FromWorker::Camera { + state: CameraState::On, + }, + FromWorker::VideoEffect { + effect: warm, + refused: false, + }, + FromWorker::Left, + ]); + let calls = controller(host.clone()); + calls.set_test_effect(warm); + plain(&calls.inner.device_test).generation = 1; + run_device_test( + &calls.inner, + 1, + CallDeviceTestKind::Camera, + None, + &AtomicBool::new(false), + device_test::TEST_LIMIT, + ); + assert_eq!(calls.device_test_status().state, CallDeviceTestState::Done); + let mut sent = host + .sent + .lock() + .unwrap() + .take() + .expect("the worker started"); + assert!(matches!( + sent.try_recv(), + Ok(ToWorker::SetDiagnostics { .. }) + )); + assert!(matches!(sent.try_recv(), Ok(ToWorker::TestDevice { .. }))); + assert_eq!( + sent.try_recv(), + Ok(ToWorker::SetVideoEffect { effect: warm }) + ); + assert_eq!(sent.try_recv(), Ok(ToWorker::Leave), "then only the close"); } /// GIVEN a test that never ran (a camera open that hangs) WHEN the @@ -6443,6 +6740,7 @@ mod tests { screen_control: Arc::default(), volume: watch::channel(MAX_VOLUME_PERCENT).0, microphone: watch::channel(None).0, + video_effect: watch::channel(None).0, devices: watch::channel(None).0, task: None, }); @@ -6694,6 +6992,7 @@ mod tests { audio: AudioWants::default(), volume: watch::channel(MAX_VOLUME_PERCENT).0, microphone: watch::channel(None).0, + video_effect: watch::channel(None).0, devices: watch::channel(None).0, levels: BTreeMap::new(), portal: None, @@ -7349,6 +7648,7 @@ mod tests { volume: watch::channel(MAX_VOLUME_PERCENT).0, devices: watch::channel(None).0, microphone: watch::channel(None).0, + video_effect: watch::channel(None).0, task: None, }); } @@ -7361,6 +7661,7 @@ mod tests { kill: Arc::default(), devices: watch::channel(None).0, microphone: watch::channel(None).0, + video_effect: watch::channel(None).0, }); } @@ -7881,6 +8182,7 @@ mod tests { screen_control: call.screen_control.clone(), volume: call.volume.clone(), microphone: call.microphone.clone(), + video_effect: call.video_effect.clone(), devices: call.devices.clone(), task: None, }); @@ -7937,6 +8239,10 @@ mod tests { (CameraState::On, CallCamera::On), (CameraState::NotFound, CallCamera::NotFound), (CameraState::Unavailable, CallCamera::Unavailable), + ( + CameraState::EffectUnavailable, + CallCamera::EffectUnavailable, + ), (CameraState::Off, CallCamera::Off), ] { assert_eq!(view.apply(&FromWorker::Camera { state }), Applied::Changed); @@ -8115,6 +8421,7 @@ mod tests { screen_control: Arc::default(), volume: watch::channel(MAX_VOLUME_PERCENT).0, microphone: watch::channel(None).0, + video_effect: watch::channel(None).0, devices: watch::channel(None).0, task: None, }); @@ -8134,6 +8441,8 @@ mod tests { video: Vec::new(), ring_declined: false, device_change: None, + effect_refused: false, + mirror: true, } } @@ -8207,6 +8516,8 @@ mod tests { }], ring_declined: false, device_change: None, + effect_refused: false, + mirror: true, }); assert!(calls.video_picture(0, 0, store.stream(0)).is_some()); assert_eq!(calls.set_camera(false), Ok(())); diff --git a/crates/core/src/calls/devices.rs b/crates/core/src/calls/devices.rs index 90fbb216..ca8ef648 100644 --- a/crates/core/src/calls/devices.rs +++ b/crates/core/src/calls/devices.rs @@ -14,9 +14,11 @@ use super::worker::{CallHost, StartError, WorkerAudio}; use crate::{store::Stores, views::project_name}; use matrix_sdk_crypto::store::CryptoStore; use persephone_call_protocol::{ - DEFAULT_MIC_GAIN_PERCENT, FromWorker, MAX_DEVICE_ID_BYTES, MAX_DEVICE_NAME_BYTES, MAX_DEVICES, - MAX_VOLUME_PERCENT, MediaDevice, ToWorker, valid_mic_gain, + Background, BackgroundPicture, BlurStrength, ColourFilter, DEFAULT_MIC_GAIN_PERCENT, + FromWorker, MAX_DEVICE_ID_BYTES, MAX_DEVICE_NAME_BYTES, MAX_DEVICES, MAX_VOLUME_PERCENT, + MediaDevice, ToWorker, VideoEffect, valid_mic_gain, }; +use persephone_contracts::{CallBackground, CallColourFilter, CallVideoEffect, call_blur_valid}; use serde::{Deserialize, Serialize}; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::{Duration, Instant}; @@ -24,9 +26,9 @@ use std::time::{Duration, Instant}; pub const DEVICES_KEY: &str = "persephone.call_devices.v1"; /// The largest saved record: three IDs at the limit, each one escaped to /// at most two bytes a byte (`"` and `\`) plus its quotes, the field names -/// the volume and the microphone settings. Every valid selection serializes -/// under it. -const MAX_RECORD_BYTES: usize = 3 * (2 * MAX_DEVICE_ID_BYTES + 2) + 160; +/// the volume, the microphone settings, the video effect and the mirror +/// flag. Every valid selection serializes under it. +const MAX_RECORD_BYTES: usize = 3 * (2 * MAX_DEVICE_ID_BYTES + 2) + 256; /// How long the worker has to answer `ListDevices`. pub const LIST_TIMEOUT: Duration = Duration::from_secs(10); /// How long the worker has to exit after the list. @@ -56,6 +58,35 @@ pub struct Selection { /// (ADR-0062). `None` is 100 percent. #[serde(default, skip_serializing_if = "Option::is_none")] pub mic_gain: Option, + /// The own camera's video effect (ADR-0068). `None` is no effect. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub effect: Option, + /// The own camera's preview is mirrored on the page (ADR-0068). `None` + /// is on: the page mirrored it before the choice existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub mirror: Option, +} + +/// The worker's form of a saved video effect, or `None` for a blur strength +/// that is out of range or off the step (ADR-0068). +pub fn worker_effect(effect: CallVideoEffect) -> Option { + let blur = BlurStrength::new(effect.blur)?; + let background = match effect.background { + CallBackground::None => Background::None, + CallBackground::Blur => Background::Blur(blur), + CallBackground::Dusk => Background::Picture(BackgroundPicture::Dusk), + CallBackground::Sea => Background::Picture(BackgroundPicture::Sea), + CallBackground::Forest => Background::Picture(BackgroundPicture::Forest), + CallBackground::Studio => Background::Picture(BackgroundPicture::Studio), + }; + let filter = match effect.filter { + CallColourFilter::None => ColourFilter::None, + CallColourFilter::Greyscale => ColourFilter::Greyscale, + CallColourFilter::Warm => ColourFilter::Warm, + CallColourFilter::Cool => ColourFilter::Cool, + CallColourFilter::Brighten => ColourFilter::Brighten, + }; + Some(VideoEffect { background, filter }) } /// Whether `id` can be a device ID: not empty, bounded, no control character. @@ -74,6 +105,26 @@ impl Selection { .volume .is_none_or(|volume| volume <= MAX_VOLUME_PERCENT) && self.mic_gain.is_none_or(valid_mic_gain) + && self + .effect + .is_none_or(|effect| call_blur_valid(effect.blur)) + } + + /// The saved video effect, else none (ADR-0068). + pub fn effect(&self) -> CallVideoEffect { + self.effect.unwrap_or_default() + } + + /// The video effect for the worker. A record that `is_valid` refused + /// never gets here; a blur that is not valid reads as no effect only + /// for such a record. + pub fn video_effect(&self) -> VideoEffect { + worker_effect(self.effect()).unwrap_or(VideoEffect::NONE) + } + + /// Whether the own preview is mirrored: the saved choice, else on. + pub fn mirror(&self) -> bool { + self.mirror.unwrap_or(true) } /// The automatic microphone level to use: the saved one, else on. @@ -144,6 +195,8 @@ pub struct Listing { pub recording: Vec, pub playout: Vec, pub cameras: Vec, + /// The worker can run background blur and pictures (ADR-0068). + pub background_effects: bool, } /// Why the devices could not be listed. The page sees one code. @@ -217,11 +270,13 @@ pub fn list(host: &dyn CallHost, cancel: &AtomicBool) -> Result Ok(Listing { supported: true, recording: clean(recording), playout: clean(playout), cameras: clean(cameras), + background_effects, }), _ => Err(ListError::NoAnswer), } @@ -391,6 +446,103 @@ mod tests { assert!(parse(at_limit.as_bytes()).is_ok()); } + /// GIVEN a record with and without a video effect WHEN read THEN a + /// missing effect is none and the preview is mirrored, a saved one + /// is kept and has its worker form, and a blur off the 10 percent steps + /// or an unknown name is unreadable (ADR-0068). + #[test] + fn given_a_saved_video_effect_then_it_is_read_or_default() { + let old = parse(br#"{"recording":"a","playout":null,"volume":40}"#).unwrap(); + assert_eq!( + (old.effect, old.mirror, old.effect(), old.mirror()), + (None, None, CallVideoEffect::default(), true) + ); + assert_eq!(old.video_effect(), VideoEffect::NONE); + let set = parse( + br#"{"recording":null,"playout":null,"effect":{"background":"blur","blur":70,"filter":"warm"},"mirror":true}"#, + ) + .unwrap(); + assert!(set.mirror()); + let plain = parse(br#"{"recording":null,"playout":null,"mirror":false}"#).unwrap(); + assert!(!plain.mirror(), "a saved choice wins"); + assert_eq!( + set.video_effect(), + VideoEffect { + background: Background::Blur(BlurStrength::new(70).unwrap()), + filter: ColourFilter::Warm, + } + ); + for bad in [ + &br#"{"recording":null,"playout":null,"effect":{"background":"blur","blur":55,"filter":"none"}}"#[..], + br#"{"recording":null,"playout":null,"effect":{"background":"blur","blur":0,"filter":"none"}}"#, + br#"{"recording":null,"playout":null,"effect":{"background":"blur","blur":110,"filter":"none"}}"#, + br#"{"recording":null,"playout":null,"effect":{"background":"moon","blur":50,"filter":"none"}}"#, + br#"{"recording":null,"playout":null,"effect":{"background":"none","blur":50,"filter":"sepia"}}"#, + br#"{"recording":null,"playout":null,"effect":{"background":"none","blur":50}}"#, + br#"{"recording":null,"playout":null,"effect":{"background":"none","blur":50,"filter":"none","x":1}}"#, + br#"{"recording":null,"playout":null,"mirror":1}"#, + ] { + assert_eq!( + parse(bad), + Err(Unreadable), + "{:?}", + String::from_utf8_lossy(bad) + ); + } + } + + /// GIVEN each saved background and filter WHEN given to the worker THEN + /// each has its own worker form, the blur strength goes only with blur, + /// and a blur that is not valid has none (ADR-0068). + #[test] + fn given_each_saved_effect_then_its_worker_form_matches() { + let pictures = [ + (CallBackground::Dusk, BackgroundPicture::Dusk), + (CallBackground::Sea, BackgroundPicture::Sea), + (CallBackground::Forest, BackgroundPicture::Forest), + (CallBackground::Studio, BackgroundPicture::Studio), + ]; + for (saved, picture) in pictures { + let effect = CallVideoEffect { + background: saved, + blur: 30, + filter: CallColourFilter::None, + }; + assert_eq!( + worker_effect(effect).map(|effect| effect.background), + Some(Background::Picture(picture)) + ); + } + let filters = [ + (CallColourFilter::None, ColourFilter::None), + (CallColourFilter::Greyscale, ColourFilter::Greyscale), + (CallColourFilter::Warm, ColourFilter::Warm), + (CallColourFilter::Cool, ColourFilter::Cool), + (CallColourFilter::Brighten, ColourFilter::Brighten), + ]; + for (saved, filter) in filters { + let effect = CallVideoEffect { + filter: saved, + ..CallVideoEffect::default() + }; + assert_eq!( + worker_effect(effect), + Some(VideoEffect { + background: Background::None, + filter, + }) + ); + } + for blur in [0, 5, 55, 110] { + let effect = CallVideoEffect { + background: CallBackground::Blur, + blur, + filter: CallColourFilter::None, + }; + assert_eq!(worker_effect(effect), None, "{blur}"); + } + } + /// GIVEN three IDs at the limit made only of characters JSON escapes /// WHEN saved THEN the record fits under the cap and reads back. #[test] @@ -404,6 +556,12 @@ mod tests { volume: Some(MAX_VOLUME_PERCENT), auto_level: Some(false), mic_gain: Some(MAX_MIC_GAIN_PERCENT), + effect: Some(CallVideoEffect { + background: CallBackground::Forest, + blur: 100, + filter: CallColourFilter::Greyscale, + }), + mirror: Some(false), }; assert!(selection.is_valid()); let bytes = serde_json::to_vec(&selection).unwrap(); @@ -549,6 +707,7 @@ mod tests { ], playout: vec![device("p", "")], cameras: vec![device("c", " Front\u{202E} camera "), device("c", "Again")], + background_effects: true, })); let listing = list(&host, &AtomicBool::new(false)).unwrap(); assert!(listing.supported); @@ -561,6 +720,7 @@ mod tests { ); assert_eq!(listing.playout, vec![device("p", "")]); assert_eq!(listing.cameras, vec![device("c", "Front\u{FFFD} camera")]); + assert!(listing.background_effects); assert!(host.ended.load(Ordering::SeqCst)); for _ in 0..100 { if !host.sent.lock().unwrap().is_empty() { @@ -583,6 +743,7 @@ mod tests { recording: Vec::new(), playout: Vec::new(), cameras: Vec::new(), + background_effects: false, })); assert_eq!( list(&host, &AtomicBool::new(true)), diff --git a/crates/core/src/calls/status.rs b/crates/core/src/calls/status.rs index 34109037..c1295c5f 100644 --- a/crates/core/src/calls/status.rs +++ b/crates/core/src/calls/status.rs @@ -98,6 +98,8 @@ pub fn status(state: &CallState) -> CallStatus { video, ring_declined, device_change, + effect_refused, + mirror, } => CallStatus { phase: CallPhase::Active, room_id: Some(room_id.to_string()), @@ -124,6 +126,8 @@ pub fn status(state: &CallState) -> CallStatus { video: video.iter().take(CALL_VIDEO_TILES_MAX).cloned().collect(), ring_declined: *ring_declined, device_change: *device_change, + effect_refused: *effect_refused, + mirror: *mirror, }, CallState::Ended { room_id, reason } => CallStatus { phase: CallPhase::Ended, @@ -486,6 +490,8 @@ mod tests { video: Vec::new(), ring_declined: false, device_change: None, + effect_refused: false, + mirror: true, }; let refused = join_reply(CallError::Declined, &CallState::Idle); assert_eq!(refused.phase, CallPhase::Idle); @@ -550,8 +556,17 @@ mod tests { ], ring_declined: true, device_change: Some(persephone_contracts::CallDeviceChange::NotFound), + effect_refused: true, + mirror: false, }); assert!(active.ring_declined); + assert!(active.effect_refused); + assert!(!active.mirror); + assert!( + CallStatus::idle().mirror, + "the preview is mirrored by default" + ); + assert!(!CallStatus::idle().effect_refused); assert_eq!( active.device_change, Some(persephone_contracts::CallDeviceChange::NotFound) diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 2ebc28c9..3775d19d 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -1557,6 +1557,12 @@ impl Core { } self.call_microphone(*auto_level, *gain) } + Call::CallVideoEffect { effect, mirror } => { + if !call_video_within_limits(call) { + return Outcome::Error(ErrorCode::InvalidArgument); + } + self.call_video_effect(*effect, *mirror) + } Call::CallStats { on } => self.call_stats(*on), Call::CallCamera { on } => self.call_camera(*on), Call::CallScreen { on } => self.call_screen(*on), @@ -1575,7 +1581,19 @@ impl Core { return Outcome::Error(ErrorCode::InvalidArgument); } match self.calls_open() { - Ok(()) => ok(&self.calls.start_device_test(*test, device.clone())), + Ok(()) => { + // A camera test shows the saved video effect + // (ADR-0068). Its pictures stay on this device, so + // a record that cannot be read shows none. + if *test == persephone_contracts::CallDeviceTestKind::Camera { + let effect = self.saved_call_devices().map_or( + persephone_call_protocol::VideoEffect::NONE, + |(selection, _)| selection.video_effect(), + ); + self.calls.set_test_effect(effect); + } + ok(&self.calls.start_device_test(*test, device.clone())) + } Err(code) => Outcome::Error(code), } } @@ -2772,6 +2790,56 @@ impl Core { ok(&calls::status::status(&self.calls.state())) } + /// Sets the own camera's video effect and whether the own preview is + /// mirrored (ADR-0068): the effect at once for a camera test and a + /// running call, and both saved in the profile's call device record for + /// later calls, like the microphone settings (`call_microphone`). The + /// worker refuses an effect that it cannot run and keeps the old one; the + /// call status then says so. A record that cannot be read is not + /// replaced; the reply is then `unavailable`. + fn call_video_effect( + &self, + effect: persephone_contracts::CallVideoEffect, + mirror: bool, + ) -> Outcome { + if let Err(code) = self.calls_open() { + return Outcome::Error(code); + } + // The dispatch checked the blur, so this has a worker form. + let Some(worker_effect) = calls::devices::worker_effect(effect) else { + return Outcome::Error(ErrorCode::InvalidArgument); + }; + // A running call or camera test changes now, even if the save below + // fails. + let _ = self.calls.set_video_effect(worker_effect, mirror); + if self.session.is_configured() { + let lease = match self.session.admit() { + Ok(lease) => lease, + Err(session::AdmissionError::Locked) => return Outcome::Error(ErrorCode::Locked), + Err(session::AdmissionError::Saturated) => { + return Outcome::Error(ErrorCode::LimitExceeded); + } + }; + let stores = lease.stores(); + let saved = stores.block_on(async { + let Ok(mut selection) = calls::devices::load(stores).await else { + return Err(ErrorCode::Unavailable); + }; + selection.effect = Some(effect); + selection.mirror = Some(mirror); + if calls::devices::save(stores, &selection).await { + Ok(()) + } else { + Err(ErrorCode::Internal) + } + }); + if let Err(code) = saved { + return Outcome::Error(code); + } + } + ok(&calls::status::status(&self.calls.state())) + } + /// Turns the call's technical details on or off (ADR-0066). They are /// read and sent only while on, which needs a call; turning them off /// also drops a reading that waits. @@ -2901,6 +2969,7 @@ impl Core { }; let volume = selection.volume(); let (auto_level, mic_gain) = (selection.auto_level(), selection.mic_gain()); + let (effect, mirror) = (selection.effect(), selection.mirror()); let devices = persephone_contracts::CallDevices { supported: listing.supported, recording: listing.recording.into_iter().map(device).collect(), @@ -2912,6 +2981,9 @@ impl Core { volume, auto_level, mic_gain, + effect, + mirror, + background_effects: listing.background_effects, unreadable, }; within_device_reply(&devices)?; @@ -2957,6 +3029,8 @@ impl Core { volume: None, auto_level: None, mic_gain: None, + effect: None, + mirror: None, }; if !selection.is_valid() { return Outcome::Error(ErrorCode::InvalidArgument); @@ -2973,11 +3047,14 @@ impl Core { }; let stores = lease.stores(); if stores.block_on(async { - // The volume and the microphone settings are kept. + // The volume, the microphone settings and the video effect are + // kept. if let Ok(saved) = calls::devices::load(stores).await { selection.volume = saved.volume; selection.auto_level = saved.auto_level; selection.mic_gain = saved.mic_gain; + selection.effect = saved.effect; + selection.mirror = saved.mirror; } calls::devices::save(stores, &selection).await }) { @@ -4330,6 +4407,9 @@ mod tests { volume: 100, auto_level: true, mic_gain: 100, + effect: persephone_contracts::CallVideoEffect::default(), + mirror: false, + background_effects: false, unreadable: false, }; let ordinary = devices( diff --git a/crates/core/tests/serve.rs b/crates/core/tests/serve.rs index 1585d8b0..f29ac971 100644 --- a/crates/core/tests/serve.rs +++ b/crates/core/tests/serve.rs @@ -668,6 +668,104 @@ fn given_a_profile_when_the_call_volume_is_set_then_it_is_saved_with_the_devices ); } +/// GIVEN an open profile WHEN the page sets the video effect and the mirror +/// THEN both are saved in the call device record, kept when the devices are +/// saved again, and the effect keeps the devices; no call is not an error, +/// and a blur off the 10 percent steps is refused before anything is saved +/// (ADR-0068). +#[test] +fn given_a_profile_when_the_video_effect_is_set_then_it_is_saved_with_the_devices() { + use persephone_contracts::{CallBackground, CallColourFilter, CallStatus, CallVideoEffect}; + use persephone_core::calls::devices::{Selection, load}; + let dir = tempfile::TempDir::new().unwrap(); + let core = Core::default().with_session(common::open_session(dir.path())); + let saved = |core: &Core| -> Selection { + let lease = core.session().admit().unwrap(); + lease.stores().block_on(load(lease.stores())).unwrap() + }; + assert_eq!( + (saved(&core).effect(), saved(&core).mirror()), + (CallVideoEffect::default(), true), + "no record is no effect and a mirrored preview" + ); + let sea = CallVideoEffect { + background: CallBackground::Sea, + blur: 30, + filter: CallColourFilter::Cool, + }; + assert_eq!( + answer::( + &core, + Call::CallVideoEffect { + effect: sea, + mirror: true, + }, + ), + Ok(CallStatus::idle()) + ); + assert_eq!( + (saved(&core).effect, saved(&core).mirror), + (Some(sea), Some(true)) + ); + assert_eq!( + answer::( + &core, + Call::SetCallDevices { + recording: Some("mic".into()), + playout: None, + camera: None, + }, + ), + Ok(serde_json::Value::Null) + ); + let record = saved(&core); + assert_eq!( + (record.effect, record.mirror), + (Some(sea), Some(true)), + "saving the devices keeps the effect" + ); + let plain = CallVideoEffect::default(); + assert_eq!( + answer::( + &core, + Call::CallVideoEffect { + effect: plain, + mirror: false, + }, + ), + Ok(CallStatus::idle()) + ); + let record = saved(&core); + assert_eq!((record.effect, record.mirror), (Some(plain), Some(false))); + assert_eq!( + record.recording.as_deref(), + Some("mic"), + "the effect keeps the devices" + ); + for blur in [0, 55, 110] { + assert_eq!( + answer::( + &core, + Call::CallVideoEffect { + effect: CallVideoEffect { + background: CallBackground::Blur, + blur, + filter: CallColourFilter::None, + }, + mirror: true, + }, + ), + Err(ErrorCode::InvalidArgument), + "{blur}" + ); + } + assert_eq!( + saved(&core).mirror, + Some(false), + "a refused effect saves nothing" + ); +} + /// GIVEN a malformed room ID WHEN the page asks for readiness or a join THEN /// the core refuses it before any other work; a valid ID without a homeserver /// is not found. @@ -769,6 +867,10 @@ fn given_a_profile_then_call_commands_follow_the_session() { Call::CallMute { muted: true }, Call::CallDeafen { deafened: true }, Call::CallVolume { percent: 50 }, + Call::CallVideoEffect { + effect: persephone_contracts::CallVideoEffect::default(), + mirror: false, + }, Call::CallReadiness { room_id: room.into(), }, diff --git a/docs/adr/0068-add-background-blur-backgrounds-colour-filters-and-a-mirrored-preview-to-call-video.md b/docs/adr/0068-add-background-blur-backgrounds-colour-filters-and-a-mirrored-preview-to-call-video.md new file mode 100644 index 00000000..0d224ed6 --- /dev/null +++ b/docs/adr/0068-add-background-blur-backgrounds-colour-filters-and-a-mirrored-preview-to-call-video.md @@ -0,0 +1,250 @@ +# Add background blur, backgrounds, colour filters and a mirrored preview to call video + +* Status: proposed +* Deciders: project owner +* Date: 2026-11-26 + +Technical Story: on 26 November 2026 the owner asked for background blurring +and effects on the call video, and chose the options recorded under "Owner +choices" below. + +## Context and Problem Statement + +The call worker reads the camera, makes one I420 picture of at most 640x360 +from each camera frame, and gives that picture to the own preview (tile 0) +and to the SFU (ADR-0048, `CameraFeed::frame` in +`crates/call-worker/src/session.rs`). The page never has the camera stream. +It gets bounded RGBA pictures only, and it decodes no video (ADR-0003, +ADR-0004). Browser features that process a camera track in the web view +therefore cannot be used. + +Background blur and background replacement need a person mask for each +picture. That needs a segmentation model. Nothing in `Cargo.lock` does +segmentation. + +Facts on 26 November 2026: + +* `tract-tflite` describes itself as "unimplemented". tract reads ONNX and + NNEF. A TFLite model must be converted to ONNX before tract can load it. +* Google's MediaPipe Selfie Segmenter has a square (256x256) and a landscape + (144x256) model. Its model card gives the licence as Apache-2.0. +* `onnx-community/mediapipe_selfie_segmentation_landscape` on Hugging Face + has `onnx/model.onnx` (float32, 462 kB) and smaller float16 and quantized + copies. It is tagged Apache-2.0. Its input is 256x144 pixels scaled to 0..1, + and its output is called `alphas`. The page does not state the source file + or the conversion tool. +* The owner did not yet allow the download of the model or of the tract + crates. Nothing in this change measures tract, the model, or their speed. + +Where do the effects run? How does the preview match what others see? How +does the client fail when an effect cannot run? + +## Decision Drivers + +* Others see exactly what the own preview shows. +* An effect that cannot run never sends the background that the user chose to + hide. +* The page stays keyless and decodes nothing. The worker gets no new + authority: no file, network or device access for the effects. +* Bounded memory and work per picture. No new thread and no new queue. +* Closed sets and bounded values, checked in every process that receives + them. +* The same behaviour on Windows, Linux and macOS. + +## Considered Options + +* Process the I420 picture in the call worker, before the preview and the SFU + get it. +* Process the pictures in the page. +* Use the operating system's camera effects only (Windows Studio Effects, + macOS Video Effects). +* For segmentation: tract with an ONNX model embedded in the worker; + ONNX Runtime through `ort`; own inference code for one fixed model. + +## Decision Outcome + +Proposed option: "Process the I420 picture in the call worker", with tract and +an embedded ONNX model as the later segmenter (owner choice). + +### Effects + +* **Background**: one of + * none; + * blur behind the person, with a strength from 10 to 100 percent in steps + of 10 (owner choice: a slider). The page offers 50 percent first; + * one of four pictures: Dusk, Sea, Forest and Studio. The worker draws them + from code (gradients and soft shapes). They are not image files, so no + image decoding and no picture licence is needed. +* **Colour filter**: none, greyscale, warm, cool or brighten (lifts dark + parts of the picture). +* **Mirror own preview**: the page shows tile 0 mirrored, with CSS only. + Others see the picture as it is. The page mirrors tile 0 already + (`tileLayout` in `frontend/src/video.ts`), so the choice is on by default + and the current preview does not change; the user can turn it off. +* The background applies first, then the colour filter. Both work on the I420 + picture after it is scaled to fit 640x360. The worker converts that same + picture for tile 0 and sends it to the SFU. + +### Segmenter + +* `crates/call-worker/src/segmenter.rs` is the interface: one person mask for + one picture, 0 for background and 255 for the person, at most 640x360. + `effects.rs` scales the mask to the picture and composites. Neither has + LiveKit or OS types. +* This change has no segmenter. `segmenter::available()` is `false`, so blur + and pictures cannot run yet. +* `FromWorker::Devices` ends with `background_effects`. The page offers blur + and pictures only when it is `true`. Otherwise it says why. + +### Failing closed + +* A camera start with an effect that needs the mask, while no segmenter is + available, leaves the camera off. The worker reports + `CameraState::EffectUnavailable`. Audio goes on. +* A `SetVideoEffect` that the worker cannot apply is refused. The old effect + stays, and the worker answers `VideoEffect { effect: , refused: true }`. +* For the later segmenter: a picture without a mask is dropped, so the remote + members keep the last processed picture. After 15 pictures without a mask + in a row (about one second) the worker stops the camera as for a camera + failure, with `EffectUnavailable`. +* A picture larger than 640x360 is refused by the effects code itself. This + repeats the scaling limit. + +### Limits and cost + +* Only the own camera picture is processed. Remote video and the screen share + are not. +* The blur is a box blur of three passes in each direction, so its cost does + not depend on the strength. The radius is `strength x width / 3200` pixels: + 2 to 20 pixels at 640 wide. +* The worker keeps its scratch planes and the drawn background for the + current picture size, at most about 1.4 MB, and makes them again only when + the size changes. +* The effect is shared with the capture thread through one atomic value. The + frame callback reads it for each picture. No lock and no queue are added. + +### Protocol (wire version 15) + +* A video effect is three bytes: the background kind (0 none, 1 blur, + 2 picture), its value (0 for none, the strength for blur, the picture + number 1 to 4) and the filter (0 to 4). Decoding refuses any other value. +* `Join` ends with the video effect. +* `ToWorker::SetVideoEffect` (tag 19) changes it in a running call or in a + camera test. The worker answers `FromWorker::VideoEffect` (tag 24) with the + effect in use and whether the request was refused. +* `CameraState::EffectUnavailable` is 4. +* `FromWorker::Devices` ends with `background_effects` (one byte, 0 or 1). + +### Core, host and page + +* The effect and the mirror choice are part of the call device record + (`persephone.call_devices.v1`, fields `effect` and `mirror`). A record + without them reads as no effect and a mirrored preview. +* The command `call_video_effect` sets both. It applies the effect at once to + a running or joining call and to a running camera test, and saves both for + later calls, like the microphone settings (ADR-0062). It refuses a value + outside the closed sets. The main window and the call window may call it; + the call window's device panel (ADR-0065) shows the same controls as the + settings. +* The core sends `SetVideoEffect` directly after a camera `TestDevice`, so the + settings preview shows the saved effect. +* The call status carries `effectRefused` (the worker refused the newest + effect change of this call) and `mirror` (from the record at the join, then + each change). The main window and the call window show the own tile from + `mirror`, so neither reads the record during a call. +* The page offers blur and the pictures only when the device list's + `backgroundEffects` is true. In this build it is false, and the page shows + a note in their place. The call window's effect saves go into the same + queue as its device saves, because both change the same record. + +### Later step: the segmenter + +Owner choice: tract with the MediaPipe Selfie Segmenter (landscape) in ONNX +form, embedded in the worker binary, so the worker opens no file for it. That +step needs, before any code: + +* the owner's approval to download the model and the tract crates; +* the model's source: convert Google's file with a recorded tool and version, + or record why the `onnx-community` copy is used, and pin its SHA-256; +* a measurement on each OS: model load time, operator support, and the time + for one mask at 256x144 on the capture thread at 15 pictures per second; +* the tract dependency tree through the dependency audit and the licence + list, and the model's Apache-2.0 notice in the third-party notices; +* a containment check on each OS: whether tract starts threads or makes + calls that the call profiles refuse. + +This record is then amended with the results. + +### Owner choices + +* Effects: background blur, bundled backgrounds, colour and light filters, + and a mirrored own preview. +* Segmentation: tract with the MediaPipe model. +* Blur control: a slider. +* Control: saved with the call devices, and changeable from the call window. +* Downloads: not yet. Build the parts that need no model first, behind a + segmenter interface. + +### Positive Consequences + +* Colour filters and the mirror work now on every OS that has a camera. +* The preview is the picture that others get. +* No new secret, process, thread or authority. + +### Negative Consequences + +* Blur and backgrounds do not work until the segmenter step. +* A new wire version. The core and the worker must come from the same build, + as before. +* Processing adds work on the camera's capture thread for each picture. +* The effect is a privacy aid, not a security control. A compromised worker + can send the camera without it. A blurred background can still show light, + colours and large shapes, and the mask can miss parts of the background. +* Not verified live. + +## Pros and Cons of the Options + +### Process in the call worker + +* Good, because the preview and the SFU get the same picture. +* Good, because the page and the core do not change their media handling. +* Bad, because the work adds to the worker's capture thread. + +### Process in the page + +* Bad, because the page does not have the camera stream (ADR-0048), and the + SFU would still get the unprocessed picture. + +### Operating system effects only + +* Good, because no code is needed. +* Bad, because there is nothing on Linux, no control in the app, and the + owner asked for effects in the app. + +### tract with an embedded ONNX model + +* Good, because it is pure Rust, builds from source, and needs no download at + build time. +* Bad, because it adds a dependency tree to audit. + +### ONNX Runtime through `ort` + +* Bad, because it takes a prebuilt native library, and the build must never + download native code. + +### Own inference code + +* Good, because it adds no crate. +* Bad, because it is a large amount of numeric code to write, test and keep. + +## Links + +* [ADR-0003](0003-run-untrusted-media-decoding-in-a-webassembly-sandbox.md) +* [ADR-0004](0004-separate-the-key-holding-core-from-the-web-view-process.md) +* [ADR-0048](0048-add-camera-video-to-calls-in-the-call-worker.md) +* [ADR-0059](0059-test-call-devices-show-each-participants-level-and-switch-devices-during-a-call.md) +* [ADR-0060](0060-show-calls-in-a-separate-call-window.md) +* [ADR-0062](0062-set-the-microphone-gain-and-automatic-level-in-calls.md) +* [ADR-0065](0065-choose-the-large-video-and-change-devices-in-the-call-window.md) +* [MediaPipe image segmenter models](https://developers.google.com/edge/mediapipe/solutions/vision/image_segmenter) +* [onnx-community/mediapipe_selfie_segmentation_landscape](https://huggingface.co/onnx-community/mediapipe_selfie_segmentation_landscape) diff --git a/docs/adr/index.md b/docs/adr/index.md index 7aef1917..ee8bfb7c 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -74,6 +74,7 @@ * [0065 - Choose the large video and change devices in the call window](0065-choose-the-large-video-and-change-devices-in-the-call-window.md) * [0066 - Show call statistics on request](0066-show-call-statistics-on-request.md) * [0067 - Capture the Windows screen in a helper outside the call worker](0067-capture-the-windows-screen-in-a-helper-outside-the-call-worker.md) +* [0068 - Add background blur, backgrounds, colour filters and a mirrored preview to call video](0068-add-background-blur-backgrounds-colour-filters-and-a-mirrored-preview-to-call-video.md) ## Superseded Records diff --git a/frontend/AGENTS.md b/frontend/AGENTS.md index 720af3dc..115c589a 100644 --- a/frontend/AGENTS.md +++ b/frontend/AGENTS.md @@ -4,6 +4,7 @@ This area inherits `../AGENTS.md`. - Build a locally bundled Svelte UI. Keep `vite.config.js` output in `../.local/build/frontend`, relative asset URLs, no inline assets, and no production source maps unless a reviewed requirement changes them. - There are two pages: `index.html` (`src/main.ts`, the main window) and `call.html` (`src/call.ts`, the call window of ADR-0060). The call window may call only the commands in `src-tauri/capabilities/call.json`; do not use other bridge calls in `CallWindow.svelte`. That includes `call_devices` and `set_call_devices` (ADR-0065) for `CallWindowDevices.svelte`, but no device tests. Its load and save order (saves one at a time, none dropped, the newest sets the result) is in `src/callDevicePanel.ts`, which takes the bridge calls as arguments. The choice of the large video is pure logic in `src/callView.ts`: a pick of the viewer wins, a shared screen is large only when nothing is picked, and a feed that goes away drops its pick. Scale pictures with CSS only; never ask the core for a larger one. +- Video effects (ADR-0068): `CallVideoEffects.svelte` holds the controls (background, blur strength, colour filter, mirror) for both `CallDevices.svelte` and `CallWindowDevices.svelte`; the texts, menus and value checks are in `src/calls.ts` (`backgroundOptions`, `blurValue`, `plainEffect`). Offer blur and the pictures only when `CallDevices.backgroundEffects` is true. The call window's effect saves go through `DevicePanel.saveEffect`, in the same queue as its device saves. The mirror is CSS only (`tileLayout`, own tile), from `CallStatus.mirror` in a call and from the device record in the camera test; the others always see the picture as it is. - The technical details (ADR-0066) are `CallStats.svelte` (the panel, opened by one icon button in `CallWindow.svelte`) and the pure `src/callStats.ts` (contract check, units, table rows). The panel turns the readings on when it mounts and off when it is destroyed, through `startCallStats` and `stopCallStats` in the bridge, which send them one at a time in the order asked. After each reading, handled or dropped, the bridge calls `call_stats_read` with the page count, so the host sends the next (it holds one in flight per page). The bridge drops a reading that `parseCallStats` refuses. Show every number with its unit from the reading only, and show user IDs and device IDs as escaped text. A table's caption is `CallStatsCaption.svelte`, which puts the user ID and the device ID each in its own ``. The details and the device panel are open one at a time (`openDevices`, `openStats`). The call window closes the details when the call ends or a call in another room replaces it (`statsStayOpen` in `callWindow.ts`); keep that rule, because the panel starts its readings only when it mounts. - Put all Tauri API access in `src/bridge/index.ts` or another module under `src/bridge/`. Components use the typed bridge. Do not call `invoke`, Tauri globals, or host APIs directly from components. - Import public DTOs from `../crates/contracts/generated/contracts.ts`. Change Rust definitions and run the exporter when the DTO contract changes. TypeScript types do not validate runtime input or authorize commands. diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte index 7731a4f5..00db8c17 100644 --- a/frontend/src/App.svelte +++ b/frontend/src/App.svelte @@ -3250,7 +3250,7 @@

{/if} {#if callWindowFailed && hasVideo(callState)} - + {/if} {#if selectedRoom}
diff --git a/frontend/src/CallDevices.svelte b/frontend/src/CallDevices.svelte index 094a1bb5..38901b88 100644 --- a/frontend/src/CallDevices.svelte +++ b/frontend/src/CallDevices.svelte @@ -3,7 +3,8 @@ import type { CallDeviceTestKind, CallDeviceTestStatus, - CallDevices + CallDevices, + CallVideoEffect } from '../../crates/contracts/generated/contracts'; import { callDevices, @@ -11,10 +12,12 @@ callDeviceTestStatus, callDeviceTestStop, callMicrophone, + callVideoEffect, callVolume, setCallDevices } from './bridge'; import CallVideo from './CallVideo.svelte'; + import CallVideoEffects from './CallVideoEffects.svelte'; import { DEVICE_FAILURE_TEXT, DEVICE_TEST_LABEL, @@ -34,6 +37,9 @@ MIC_GAIN_MAX, MIC_GAIN_STEP, MIC_SAVE_TEXT, + EFFECT_REFUSED_TEXT, + EFFECT_SAVE_TEXT, + NO_VIDEO_EFFECT, micGainText, micGainValue, deviceChoice, @@ -48,8 +54,8 @@ } from './calls'; import { DeviceTests, testLevel, testLive, testTiles } from './deviceTests'; - // The call microphone, speaker, camera and volume (ADR-0043, ADR-0048, - // ADR-0055). The core lists the devices through a + // The call microphone, speaker, camera, volume and video effect (ADR-0043, + // ADR-0048, ADR-0055, ADR-0068). The core lists the devices through a // contained worker and keeps the choice with the profile. Device names come // from the operating system: they are shown as plain text only. // @@ -111,11 +117,16 @@ let autoLevel = $state(true); let micGain = $state(MIC_GAIN_DEFAULT); let micSaving = $state(false); + // The own camera's video effect and the preview's mirror (ADR-0068). + let videoEffect = $state(NO_VIDEO_EFFECT); + let mirror = $state(true); + let effectSaving = $state(false); + let effectRefused = $state(false); let loading = $state(false); let saving = $state(false); // Any request that reads or writes the device record. A refresh or device // save during a volume save could bring back the old volume, so each waits. - const busy = $derived(loading || saving || volumeSaving || micSaving); + const busy = $derived(loading || saving || volumeSaving || micSaving || effectSaving); let failure = $state(null); let generation = 0; @@ -136,6 +147,8 @@ volume = next.volume; autoLevel = next.autoLevel; micGain = next.micGain; + videoEffect = next.effect; + mirror = next.mirror; } catch (reason) { if (mine === generation) failure = failures[String(reason)] ?? 'The call devices could not be listed.'; } finally { @@ -201,6 +214,31 @@ } } + // Saves the video effect and the mirror after each change. The effect + // applies at once to a camera test and to a call that runs; a call's + // worker may refuse it (ADR-0068). On failure both go back to the saved + // values. + async function saveEffect() { + if (busy || !devices) return; + effectSaving = true; + failure = null; + const wanted = videoEffect; + const wantedMirror = mirror; + try { + const status = await callVideoEffect(wanted, wantedMirror); + effectRefused = status.effectRefused; + if (devices) devices = { ...devices, effect: wanted, mirror: wantedMirror }; + } catch (reason) { + failure = failures[String(reason)] ?? EFFECT_SAVE_TEXT; + if (devices) { + videoEffect = devices.effect; + mirror = devices.mirror; + } + } finally { + effectSaving = false; + } + } + let recordingOptions = $derived(deviceOptions(devices?.recording ?? [], deviceChoice(recording))); let playoutOptions = $derived(deviceOptions(devices?.playout ?? [], deviceChoice(playout))); let cameraOptions = $derived(deviceOptions(devices?.cameras ?? [], deviceChoice(camera))); @@ -284,6 +322,17 @@ onchange={saveMicrophone} />

{MIC_GAIN_HELP}

+ + {#if effectRefused} +

{EFFECT_REFUSED_TEXT}

+ {/if} {#if devices}

{devicesNote(devices)}

{/if} @@ -322,7 +371,7 @@
{/each} {#if cameraTiles.length > 0} - + {/if}
{/if} diff --git a/frontend/src/bridge/index.ts b/frontend/src/bridge/index.ts index 1e45fcf0..65fdcb25 100644 --- a/frontend/src/bridge/index.ts +++ b/frontend/src/bridge/index.ts @@ -26,6 +26,7 @@ import type { CallStats, CallStatus, CallUnavailable, + CallVideoEffect, CallVideoTile, ContactStatus, ConversationStart, @@ -713,6 +714,18 @@ export function callMicrophone(autoLevel: boolean, gain: number): Promise('call_microphone', { autoLevel, gain }); } +/** + * Sets the own camera's video effect and whether the own preview is mirrored + * (ADR-0068). The effect applies at once to a camera test and a running call; + * both are saved for later calls. Only the effect's three fields cross. The + * status says when the worker refused the effect (`effectRefused`): the + * camera then keeps the effect it had. + */ +export function callVideoEffect(effect: CallVideoEffect, mirror: boolean): Promise { + const { background, blur, filter } = effect; + return invoke('call_video_effect', { effect: { background, blur, filter }, mirror }); +} + /** * The call microphones and speakers now connected, and the saved choice * (ADR-0043). The core lists them through a contained worker, so it can take diff --git a/frontend/src/callDevicePanel.ts b/frontend/src/callDevicePanel.ts index 6dfbda0d..7a97a6f2 100644 --- a/frontend/src/callDevicePanel.ts +++ b/frontend/src/callDevicePanel.ts @@ -1,5 +1,12 @@ -import type { CallDevices } from '../../crates/contracts/generated/contracts'; -import { DEVICE_FAILURE_TEXT, DEVICE_SAVE_FAILURE_TEXT, deviceChoice, deviceValue } from './calls.ts'; +import type { CallDevices, CallStatus, CallVideoEffect } from '../../crates/contracts/generated/contracts'; +import { + DEVICE_FAILURE_TEXT, + DEVICE_SAVE_FAILURE_TEXT, + EFFECT_SAVE_TEXT, + deviceChoice, + deviceValue, + plainEffect +} from './calls.ts'; /** The three menus of the device panel; `''` is the system default. */ export interface DeviceMenus { @@ -17,10 +24,19 @@ export interface DevicePanelState { failure: string | null; } +/** What the panel shows about the video effect (ADR-0068). */ +export interface EffectState { + saving: boolean; + // The worker refused the newest effect; the camera keeps the one it had. + refused: boolean; + failure: string | null; +} + /** The bridge calls the panel uses; the component passes the real ones. */ export interface DevicePanelBridge { list: () => Promise; save: (recording: string | null, playout: string | null, camera: string | null) => Promise; + effect: (effect: CallVideoEffect, mirror: boolean) => Promise; } const failureText = (reason: unknown, fallback: string) => DEVICE_FAILURE_TEXT[String(reason)] ?? fallback; @@ -35,39 +51,56 @@ const failureText = (reason: unknown, fallback: string) => DEVICE_FAILURE_TEXT[S * changed while a save runs is sent after it and none is dropped. Each * save sends the three menus as they were when it was asked, so the last * one holds every change. Only the newest save sets the result line. + * - The video effect (ADR-0068) goes into the same queue, as each save + * changes the same device record. Its newest answer sets its own result. * - After `close`, no answer changes the panel. */ export class DevicePanel { readonly #bridge: DevicePanelBridge; readonly #onstate: (state: DevicePanelState) => void; readonly #onmenus: (menus: DeviceMenus) => void; + readonly #oneffect: (state: EffectState) => void; #state: DevicePanelState = { devices: null, loading: false, saving: false, saved: false, failure: null }; + #effect: EffectState = { saving: false, refused: false, failure: null }; #queue: Promise = Promise.resolve(); #saves = 0; #newest = 0; + #effectSaves = 0; + #newestEffect = 0; #open = true; constructor( bridge: DevicePanelBridge, onstate: (state: DevicePanelState) => void, - onmenus: (menus: DeviceMenus) => void + onmenus: (menus: DeviceMenus) => void, + oneffect: (state: EffectState) => void = () => {} ) { this.#bridge = bridge; this.#onstate = onstate; this.#onmenus = onmenus; + this.#oneffect = oneffect; } get state(): DevicePanelState { return this.#state; } + get effect(): EffectState { + return this.#effect; + } + + #setEffect(change: Partial) { + this.#effect = { ...this.#effect, ...change }; + this.#oneffect(this.#effect); + } + #set(change: Partial) { this.#state = { ...this.#state, ...change }; this.#onstate(this.#state); } async load(): Promise { - if (!this.#open || this.#state.loading || this.#saves > 0) return; + if (!this.#open || this.#state.loading || this.#saves > 0 || this.#effectSaves > 0) return; this.#set({ loading: true, failure: null }); try { const devices = await this.#bridge.list(); @@ -107,6 +140,35 @@ export class DevicePanel { } } + /** + * Sets the video effect and the mirror (ADR-0068) after the saves before + * it. The controls keep their values on failure. + */ + async saveEffect(effect: CallVideoEffect, mirror: boolean): Promise { + if (!this.#open) return; + const mine = ++this.#newestEffect; + this.#effectSaves += 1; + this.#setEffect({ saving: true, failure: null }); + const wanted = plainEffect(effect); + const run = () => this.#bridge.effect(wanted, mirror); + const turn = this.#queue.then(run, run); + this.#queue = turn.catch(() => undefined); + let failure: string | null = null; + let refused = false; + try { + refused = (await turn).effectRefused === true; + } catch (reason) { + failure = failureText(reason, EFFECT_SAVE_TEXT); + } + this.#effectSaves -= 1; + if (!this.#open) return; + if (mine === this.#newestEffect) { + this.#setEffect({ saving: this.#effectSaves > 0, refused, failure }); + } else { + this.#setEffect({ saving: this.#effectSaves > 0 }); + } + } + close(): void { this.#open = false; } diff --git a/frontend/src/calls.ts b/frontend/src/calls.ts index 6a2a3889..bc2591e9 100644 --- a/frontend/src/calls.ts +++ b/frontend/src/calls.ts @@ -3,7 +3,9 @@ // full `Record`, so a new code in the contract fails type checking until it // has a text. import type { + CallBackground, CallCamera, + CallColourFilter, CallDevice, CallDeviceChange, CallDevices, @@ -23,7 +25,8 @@ import type { CallRing, CallRings, CallStatus, - CallUnavailable + CallUnavailable, + CallVideoEffect } from '../../crates/contracts/generated/contracts'; import type { DesktopPlatform } from './modules'; @@ -118,7 +121,9 @@ export const IDLE_CALL: CallStatus = { screen: 'off', video: [], ringDeclined: false, - deviceChange: null + deviceChange: null, + effectRefused: false, + mirror: true }; /** This account is in a call, or joining one. */ @@ -210,6 +215,13 @@ export const CAMERA_OFF_LABEL = 'Turn camera off'; export const CAMERA_STARTING_TEXT = 'Starting the camera…'; export const CAMERA_NOT_FOUND_TEXT = 'The chosen camera is not connected'; export const CAMERA_UNAVAILABLE_TEXT = 'The camera could not start'; +/** + * The camera stays off because its background effect cannot run here + * (ADR-0068): the camera never sends the background that the user chose to + * hide. + */ +export const CAMERA_EFFECT_UNAVAILABLE_TEXT = + 'The camera stays off: the chosen background cannot run here. Choose another background in the call settings'; /** The note beside the camera toggle; empty when the camera needs none. */ export const CAMERA_TEXT: Record = { @@ -217,7 +229,8 @@ export const CAMERA_TEXT: Record = { starting: CAMERA_STARTING_TEXT, on: '', not_found: CAMERA_NOT_FOUND_TEXT, - unavailable: CAMERA_UNAVAILABLE_TEXT + unavailable: CAMERA_UNAVAILABLE_TEXT, + effect_unavailable: CAMERA_EFFECT_UNAVAILABLE_TEXT }; export type CameraButtonView = { @@ -228,7 +241,8 @@ export type CameraButtonView = { /** * The camera toggle in the call bar. A camera that failed (`not_found`, - * `unavailable`) is off, so the toggle offers to turn it on again. + * `unavailable`, `effect_unavailable`) is off, so the toggle offers to turn + * it on again. */ export function cameraButton(camera: CallCamera): CameraButtonView { const pressed = camera === 'on' || camera === 'starting'; @@ -502,6 +516,105 @@ export function micGainText(percent: number): string { return `${micGainValue(percent)}%`; } +/** The weakest background blur, in percent (ADR-0068). */ +export const BLUR_MIN = 10; +/** The strongest background blur. */ +export const BLUR_MAX = 100; +/** The blur moves in steps of this many percent. */ +export const BLUR_STEP = 10; +/** The blur when none is saved. */ +export const BLUR_DEFAULT = 50; +/** No video effect: what a profile without a saved one has. */ +export const NO_VIDEO_EFFECT: CallVideoEffect = { background: 'none', blur: BLUR_DEFAULT, filter: 'none' }; +export const VIDEO_EFFECTS_TITLE = 'Video effects'; +export const VIDEO_EFFECTS_HELP = + 'The others in the call see the background and the colour filter. They apply at once, also in a call that runs and in the camera test.'; +export const BACKGROUND_LABEL = 'Background'; +export const BLUR_LABEL = 'Blur strength'; +export const FILTER_LABEL = 'Colour filter'; +export const MIRROR_LABEL = 'Mirror my picture'; +export const MIRROR_HELP = 'Only you see your picture mirrored. The others see it the right way round.'; +/** This build has no person mask, so blur and pictures cannot run (ADR-0068). */ +export const BACKGROUND_EFFECTS_UNAVAILABLE_TEXT = + 'Background blur and background pictures are not available in this version. They need a person mask, which a later version adds.'; +export const EFFECT_REFUSED_TEXT = 'This effect cannot run here. Your camera keeps the effect it had.'; +export const EFFECT_SAVE_TEXT = 'The video effect could not be saved.'; + +/** The background menu's texts, in menu order. */ +export const BACKGROUND_TEXT: Record = { + none: 'None', + blur: 'Blur', + dusk: 'Dusk', + sea: 'Sea', + forest: 'Forest', + studio: 'Studio' +}; + +/** The colour filter menu's texts, in menu order. */ +export const FILTER_TEXT: Record = { + none: 'None', + greyscale: 'Greyscale', + warm: 'Warm', + cool: 'Cool', + brighten: 'Brighten' +}; + +/** One entry of an effect menu. */ +export type EffectOption = { value: T; label: string; disabled: boolean }; + +/** + * The background menu (ADR-0068). Every background but `none` needs the + * person mask; without it (`available` false) those cannot be chosen. The + * one in use stays chosen, so the menu never shows another than the saved. + */ +export function backgroundOptions(available: boolean, current: CallBackground): EffectOption[] { + return (Object.keys(BACKGROUND_TEXT) as CallBackground[]).map((value) => ({ + value, + label: BACKGROUND_TEXT[value], + disabled: !available && value !== 'none' && value !== current + })); +} + +/** The colour filter menu: each filter works without the person mask. */ +export function filterOptions(): EffectOption[] { + return (Object.keys(FILTER_TEXT) as CallColourFilter[]).map((value) => ({ + value, + label: FILTER_TEXT[value], + disabled: false + })); +} + +/** A menu value as a background; anything else keeps `current`. */ +export function backgroundValue(value: string, current: CallBackground): CallBackground { + return Object.hasOwn(BACKGROUND_TEXT, value) ? (value as CallBackground) : current; +} + +/** A menu value as a colour filter; anything else keeps `current`. */ +export function filterValue(value: string, current: CallColourFilter): CallColourFilter { + return Object.hasOwn(FILTER_TEXT, value) ? (value as CallColourFilter) : current; +} + +/** + * A slider value as a blur strength: a whole percent from 10 to 100 in steps + * of 10. Anything that is not a finite number is the default, so the host + * never gets a strength that it refuses. + */ +export function blurValue(value: number): number { + if (!Number.isFinite(value)) return BLUR_DEFAULT; + const clamped = Math.min(BLUR_MAX, Math.max(BLUR_MIN, value)); + return Math.round(clamped / BLUR_STEP) * BLUR_STEP; +} + +/** The text a blur strength is read and shown as. */ +export function blurText(percent: number): string { + return `${blurValue(percent)}%`; +} + +/** The effect with only its three fields, as the host takes it. */ +export function plainEffect(effect: CallVideoEffect): CallVideoEffect { + return { background: effect.background, blur: blurValue(effect.blur), filter: effect.filter }; +} + /** * The label of the own microphone's level meter (ADR-0055, ADR-0059): it * shows what the microphone picks up, so a silent meter means the call does diff --git a/frontend/tests/bridge-calls.test.mjs b/frontend/tests/bridge-calls.test.mjs index 36c978c9..44c89044 100644 --- a/frontend/tests/bridge-calls.test.mjs +++ b/frontend/tests/bridge-calls.test.mjs @@ -232,6 +232,11 @@ test('GIVEN the room, account, settings and profile calls WHEN made THEN each ma [() => bridge.callDeafen(false), 'call_deafen', { deafened: false }], [() => bridge.callVolume(35), 'call_volume', { percent: 35 }], [() => bridge.callMicrophone(false, 250), 'call_microphone', { autoLevel: false, gain: 250 }], + [ + () => bridge.callVideoEffect({ background: 'sea', blur: 30, filter: 'cool', url: 'https://x' }, false), + 'call_video_effect', + { effect: { background: 'sea', blur: 30, filter: 'cool' }, mirror: false } + ], [() => bridge.callStatus(), 'call_status', {}], [() => bridge.callRings(), 'call_rings', {}], [() => bridge.callDeclineRing('!r:s'), 'call_decline_ring', { roomId: '!r:s' }], diff --git a/frontend/tests/calls.test.mjs b/frontend/tests/calls.test.mjs index 020eb8c7..d05efbf1 100644 --- a/frontend/tests/calls.test.mjs +++ b/frontend/tests/calls.test.mjs @@ -289,9 +289,10 @@ test('GIVEN device replies WHEN the note is chosen THEN unsupported, unreadable }); test('GIVEN each camera state WHEN its text is read THEN failures say what happened and working states say nothing', () => { - assert.deepEqual(Object.keys(CAMERA_TEXT).sort(), ['not_found', 'off', 'on', 'starting', 'unavailable']); + assert.deepEqual(Object.keys(CAMERA_TEXT).sort(), ['effect_unavailable', 'not_found', 'off', 'on', 'starting', 'unavailable']); assert.equal(CAMERA_TEXT.not_found, 'The chosen camera is not connected'); assert.equal(CAMERA_TEXT.unavailable, 'The camera could not start'); + assert.match(CAMERA_TEXT.effect_unavailable, /chosen background cannot run here/); assert.equal(CAMERA_TEXT.starting, 'Starting the camera…'); assert.equal(CAMERA_TEXT.off, ''); assert.equal(CAMERA_TEXT.on, ''); @@ -301,7 +302,7 @@ test('GIVEN each camera state WHEN the toggle is built THEN it offers to turn of assert.deepEqual(cameraButton('off'), { label: 'Turn camera on', pressed: false }); assert.deepEqual(cameraButton('on'), { label: 'Turn camera off', pressed: true }); assert.deepEqual(cameraButton('starting'), { label: 'Turn camera off', pressed: true }); - for (const failed of ['not_found', 'unavailable']) { + for (const failed of ['not_found', 'unavailable', 'effect_unavailable']) { assert.deepEqual(cameraButton(failed), { label: 'Turn camera on', pressed: false }); } }); diff --git a/frontend/tests/video-effects.test.mjs b/frontend/tests/video-effects.test.mjs new file mode 100644 index 00000000..b9d3d0ec --- /dev/null +++ b/frontend/tests/video-effects.test.mjs @@ -0,0 +1,235 @@ +import assert from 'node:assert/strict'; +import { after, before, test } from 'node:test'; +import { createServer } from 'vite'; +import { DevicePanel } from '../src/callDevicePanel.ts'; +import { + BACKGROUND_EFFECTS_UNAVAILABLE_TEXT, + BLUR_DEFAULT, + BLUR_MAX, + BLUR_MIN, + BLUR_STEP, + CAMERA_EFFECT_UNAVAILABLE_TEXT, + CAMERA_TEXT, + EFFECT_SAVE_TEXT, + IDLE_CALL, + NO_VIDEO_EFFECT, + backgroundOptions, + backgroundValue, + blurText, + blurValue, + cameraButton, + filterOptions, + filterValue, + plainEffect +} from '../src/calls.ts'; + +let vite; +let render; +let CallVideoEffects; + +before(async () => { + // Its own dependency cache, as in render.test.mjs: test files run in + // parallel. + vite = await createServer({ + configFile: './vite.config.js', + cacheDir: 'node_modules/.vite-tests/video-effects', + optimizeDeps: { noDiscovery: true }, + ssr: { optimizeDeps: { noDiscovery: true } }, + server: { middlewareMode: true, hmr: false, ws: false }, + appType: 'custom' + }); + ({ default: CallVideoEffects } = await vite.ssrLoadModule('/src/CallVideoEffects.svelte')); + ({ render } = await vite.ssrLoadModule('svelte/server')); +}); + +after(async () => { + await vite?.close(); +}); + +test('GIVEN slider values WHEN read as a blur strength THEN they are whole percents from 10 to 100 in steps of 10, and a bad value is the default', () => { + assert.deepEqual([BLUR_MIN, BLUR_MAX, BLUR_STEP, BLUR_DEFAULT], [10, 100, 10, 50]); + assert.equal(blurValue(10), 10); + assert.equal(blurValue(54), 50); + assert.equal(blurValue(55), 60); + assert.equal(blurValue(100), 100); + assert.equal(blurValue(0), 10, 'no blur is not a blur strength'); + assert.equal(blurValue(-30), 10); + assert.equal(blurValue(250), 100); + assert.equal(blurValue(Number.NaN), 50); + assert.equal(blurValue(Number.POSITIVE_INFINITY), 50); + assert.equal(blurText(70), '70%'); + assert.equal(blurText(Number.NaN), '50%'); +}); + +test('GIVEN no person mask WHEN the background menu is made THEN only none can be chosen, and the saved background stays chosen', () => { + const choosable = (options) => options.filter((option) => !option.disabled).map((option) => option.value); + const all = ['none', 'blur', 'dusk', 'sea', 'forest', 'studio']; + assert.deepEqual( + backgroundOptions(true, 'none').map((option) => option.value), + all, + 'every background is in the menu, in order' + ); + assert.deepEqual(choosable(backgroundOptions(true, 'none')), all); + assert.deepEqual(choosable(backgroundOptions(false, 'none')), ['none']); + assert.deepEqual(choosable(backgroundOptions(false, 'sea')), ['none', 'sea'], 'the menu never shows another than the saved'); + assert.deepEqual( + filterOptions().map((option) => [option.value, option.disabled]), + [ + ['none', false], + ['greyscale', false], + ['warm', false], + ['cool', false], + ['brighten', false] + ], + 'the filters need no mask' + ); +}); + +test('GIVEN menu values WHEN read THEN only the closed set is taken, also against names that every object has', () => { + assert.equal(backgroundValue('studio', 'none'), 'studio'); + assert.equal(filterValue('warm', 'none'), 'warm'); + for (const bad of ['moon', 'Blur', '', '__proto__', 'toString', 'constructor']) { + assert.equal(backgroundValue(bad, 'sea'), 'sea', bad); + assert.equal(filterValue(bad, 'cool'), 'cool', bad); + } +}); + +test('GIVEN an effect with more fields WHEN made plain THEN only the three the host takes are left, and the blur is a valid one', () => { + assert.deepEqual(plainEffect({ background: 'blur', blur: 33, filter: 'cool', url: 'https://x' }), { + background: 'blur', + blur: 30, + filter: 'cool' + }); + assert.deepEqual(NO_VIDEO_EFFECT, { background: 'none', blur: 50, filter: 'none' }); +}); + +test('GIVEN a camera that stays off for its effect WHEN shown THEN the call bar says why and offers to turn it on again', () => { + assert.equal(CAMERA_TEXT.effect_unavailable, CAMERA_EFFECT_UNAVAILABLE_TEXT); + assert.match(CAMERA_EFFECT_UNAVAILABLE_TEXT, /stays off/); + assert.equal(cameraButton('effect_unavailable').pressed, false); + assert.equal(IDLE_CALL.mirror, true, 'the own preview is mirrored by default'); + assert.equal(IDLE_CALL.effectRefused, false); +}); + +/** A promise and the functions that settle it, for answers that wait. */ +function later() { + let resolve; + let reject; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} + +const never = () => new Promise(() => {}); +const menus = (recording) => ({ recording, playout: '', camera: '' }); +const sea = { background: 'sea', blur: 50, filter: 'cool' }; + +/** A panel with the given bridge, and what it said about the effect. */ +function panel(bridge) { + const effects = []; + const made = new DevicePanel( + bridge, + () => {}, + () => {}, + (state) => effects.push(state) + ); + return { panel: made, effects, last: () => effects.at(-1) }; +} + +test('GIVEN a device save that runs WHEN the effect changes THEN the effect is sent after it, with only its three fields', async () => { + const first = later(); + const order = []; + const { panel: made, last } = panel({ + list: never, + save: (...choice) => { + order.push(['devices', ...choice]); + return first.promise; + }, + effect: async (effect, mirror) => { + order.push(['effect', effect, mirror]); + return { ...IDLE_CALL, effectRefused: false }; + } + }); + const devices = made.save(menus('mic-1')); + const effect = made.saveEffect({ ...sea, extra: 'x' }, false); + await Promise.resolve(); + assert.deepEqual(order, [['devices', 'mic-1', null, null]], 'the effect waits for the device save'); + assert.equal(last().saving, true); + first.resolve(); + await Promise.all([devices, effect]); + assert.deepEqual(order, [ + ['devices', 'mic-1', null, null], + ['effect', sea, false] + ]); + assert.deepEqual(last(), { saving: false, refused: false, failure: null }); +}); + +test('GIVEN effect answers WHEN the worker refused or the core failed THEN the newest says so, and an older failure is old news', async () => { + const answers = [later(), later()]; + let calls = 0; + const { panel: made, last } = panel({ + list: never, + save: never, + effect: () => answers[calls++].promise + }); + const one = made.saveEffect(sea, true); + const two = made.saveEffect(NO_VIDEO_EFFECT, true); + answers[0].reject('core_unavailable'); + await Promise.resolve(); + await Promise.resolve(); + answers[1].resolve({ ...IDLE_CALL, phase: 'active', effectRefused: true }); + await Promise.all([one, two]); + assert.deepEqual(last(), { saving: false, refused: true, failure: null }); + + const { panel: failing, last: lastFailing } = panel({ + list: never, + save: never, + effect: () => Promise.reject('something_else') + }); + await failing.saveEffect(sea, false); + assert.deepEqual(lastFailing(), { saving: false, refused: false, failure: EFFECT_SAVE_TEXT }); +}); + +test('GIVEN an effect save that runs WHEN a refresh is asked THEN it does not start; WHEN the panel closes THEN a late answer changes nothing', async () => { + const answer = later(); + let listed = 0; + const { panel: made, effects } = panel({ + list: async () => { + listed += 1; + return null; + }, + save: never, + effect: () => answer.promise + }); + const saving = made.saveEffect(sea, true); + await made.load(); + assert.equal(listed, 0, 'a refresh would replace the controls under the save'); + made.close(); + const seen = effects.length; + answer.resolve({ ...IDLE_CALL, effectRefused: true }); + await saving; + assert.equal(effects.length, seen, 'a closed panel takes no late answer'); +}); + +test('GIVEN no person mask WHEN the controls are rendered THEN blur and the pictures cannot be chosen and a note says why; WHEN blur is saved THEN its strength shows', () => { + const html = (props) => + render(CallVideoEffects, { + props: { mirror: true, disabled: false, prefix: 'fx', onsave() {}, ...props } + }).body; + const plain = html({ effect: NO_VIDEO_EFFECT, available: false }); + assert.match(plain, /Video effects/); + assert.ok(plain.includes(BACKGROUND_EFFECTS_UNAVAILABLE_TEXT)); + for (const value of ['blur', 'dusk', 'sea', 'forest', 'studio']) { + assert.match(plain, new RegExp(`