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
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}
/>