BlueGit

ict rusty-teams

merge: camera effects; overload banner also turns camera effects off

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
9a3428c4afd3abe0fb933bab3379b74e37557d18
23 files changed +1352 −129
ROADMAP.md +1 −0
@@ -172,6 +172,7 @@ Feature parity with the Microsoft Teams desktop client.
172 172 | Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
173 173 | Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |
174 174 | Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
175 | Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
175 176 | Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
176 177 | Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |
177 178 | Meeting recap tab | Partial Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; the Graph and SharePoint calls are not yet run against a real recording |
@@ -172,6 +172,7 @@ Feature parity with the Microsoft Teams desktop client.
172| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
172| Organizer controls | Partial | Amber lobby banner with View (Admit, Deny per person) and Admit all, tile menu (right-click or "..." on hover): Pin for me, Spotlight for everyone, Mute, Lower hand, Remove from meeting with a confirm dialog, "..." controls menu with Mute all. Request bodies built from the Teams code and unit tested; demo checked, not yet live with a second person |
173| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |
173| Live captions | Partial | "..." > Turn on live captions: recorder bot joins, start command with a skype token, captions arrive on the SCTP data channel (data id 3), 2-line overlay with bold speaker that fades after 4 s. Message framing and parsing from the Teams code; not yet seen with real speech |
174| Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
174| Backgrounds | Partial | Camera menu Background: None / Blur / Microsoft's default images / "Add image..." (remembered). The image list and thumbnails are fetched at runtime into the app data folder, nothing of Microsoft's ships with the app; the picture is cover-scaled behind the same segmentation mask (checked with a synthetic mask, demo with generated pictures, the CDN download only through `meet_now --background`). On-device MediaPipe selfie segmentation through tract (Apache-2.0 model, 11 ms per 640x360 frame in a release build), edge feathering, self view shows the result. Checked with a still photo and synthetic frames; not yet on a real camera |
175| Camera effects | Partial | Camera menu "Effects" and Settings > Devices: Mirror my video (self view and camera test only, default on), Auto framing, Adjust brightness, Soft focus (Low / Medium / High in Settings). Framing, brightness and soft focus run on the send path, so others see them; one segmentation mask per frame is shared with the background. Crop planner, gamma and blend are unit tested; not yet checked on a real camera |
175| Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
176| Video calls (1:1 and incoming) | Partial | Camera button in 1:1 calls renegotiates a video line on the same peer connection (modalities Audio and Video), incoming video ring toast with Decline / Audio / Video, accept with video answers the video line sending, accept with audio receive-only. Offer and answer built from the Teams code and unit tested at SDP level; needs a second person |
176| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |
177| Recording | Partial | Organizer "..." > Start recording / Stop recording (confirm) through the recorder bot, red dot and "Recording" in the header for everyone from the meeting state, consent notice that keeps mic and camera off until OK. Bodies unit tested; start and stop run live through `meet_now --record`, consent needs a tenant with the policy on and a second person |
177| Meeting recap tab | Partial Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; the Graph and SharePoint calls are not yet run against a real recording |
178| Meeting recap tab | Partial Recap in meeting chats with a recording: occurrence picker, recording card (duration, Audio only, expiry amber under 7 days), Play in the browser, Download with save dialog and percent, organizer Delete with confirm, searchable read-only transcript with .vtt and .docx download, attendance (muted note when the tenant has reports off), files shared in the chat. Parsing and expiry unit tested, demo checked; the Graph and SharePoint calls are not yet run against a real recording |
crates/app/src/app_state.rs +3 −0
@@ -128,6 +128,7 @@ pub struct AppState {
128 128 pub call_background: crate::call::BackgroundPick,
129 129 pub call_camera: calling::DeviceChoice,
130 130 pub call_mic: calling::MicSettings,
131 pub call_effects: calling::CameraEffects,
131 132 pub meet_now_pending: bool,
132 133 pub call_backgrounds: crate::call::BackgroundLibrary,
133 134 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
@@ -227,6 +228,7 @@ impl AppState {
227 228 call_background: crate::call::BackgroundPick::None,
228 229 call_camera: calling::DeviceChoice::SystemDefault,
229 230 call_mic: calling::MicSettings::default(),
231 call_effects: calling::CameraEffects::default(),
230 232 meet_now_pending: false,
231 233 call_backgrounds: if mode.demo {
232 234 crate::call::demo_library()
@@ -247,6 +249,7 @@ impl AppState {
247 249 state.call_background = crate::call::load_background(&state.store);
248 250 state.call_camera = crate::call::load_camera(&state.store);
249 251 state.call_mic = crate::call::load_mic(&state.store);
252 state.call_effects = crate::call::load_camera_effects(&state.store);
250 253 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
251 254 state.load_cached_translation_settings();
252 255 if !mode.demo {
@@ -128,6 +128,7 @@ pub struct AppState {
128 pub call_background: crate::call::BackgroundPick,
128 pub call_background: crate::call::BackgroundPick,
129 pub call_camera: calling::DeviceChoice,
129 pub call_camera: calling::DeviceChoice,
130 pub call_mic: calling::MicSettings,
130 pub call_mic: calling::MicSettings,
131 pub call_effects: calling::CameraEffects,
131 pub meet_now_pending: bool,
132 pub meet_now_pending: bool,
132 pub call_backgrounds: crate::call::BackgroundLibrary,
133 pub call_backgrounds: crate::call::BackgroundLibrary,
133 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
134 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
@@ -227,6 +228,7 @@ impl AppState {
227 call_background: crate::call::BackgroundPick::None,
228 call_background: crate::call::BackgroundPick::None,
228 call_camera: calling::DeviceChoice::SystemDefault,
229 call_camera: calling::DeviceChoice::SystemDefault,
229 call_mic: calling::MicSettings::default(),
230 call_mic: calling::MicSettings::default(),
231 call_effects: calling::CameraEffects::default(),
230 meet_now_pending: false,
232 meet_now_pending: false,
231 call_backgrounds: if mode.demo {
233 call_backgrounds: if mode.demo {
232 crate::call::demo_library()
234 crate::call::demo_library()
@@ -247,6 +249,7 @@ impl AppState {
247 state.call_background = crate::call::load_background(&state.store);
249 state.call_background = crate::call::load_background(&state.store);
248 state.call_camera = crate::call::load_camera(&state.store);
250 state.call_camera = crate::call::load_camera(&state.store);
249 state.call_mic = crate::call::load_mic(&state.store);
251 state.call_mic = crate::call::load_mic(&state.store);
252 state.call_effects = crate::call::load_camera_effects(&state.store);
250 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
253 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
251 state.load_cached_translation_settings();
254 state.load_cached_translation_settings();
252 if !mode.demo {
255 if !mode.demo {
crates/app/src/call/actions.rs +46 −5
@@ -2,8 +2,8 @@ use std::time::{Duration, Instant};
2 2
3 3 use calling::meeting::LiveMeeting;
4 4 use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice,
6 EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7 7 };
8 8 use gpui_kit::*;
9 9
@@ -38,6 +38,7 @@ const DEMO_LIVE_MINUTES: i64 = 60;
38 38 const ORGID_PREFIX: &str = "8:orgid:";
39 39 pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
40 40 const CAMERA_META_KEY: &str = "call_camera";
41 const EFFECTS_META_KEY: &str = "call_camera_effects";
41 42 const DEFAULT_CAMERA_META: &str = "default";
42 43
43 44 pub fn load_share_sound(store: &store::Store) -> bool {
@@ -51,6 +52,16 @@ pub fn load_camera(store: &store::Store) -> DeviceChoice {
51 52 }
52 53 }
53 54
55 pub fn load_camera_effects(store: &store::Store) -> CameraEffects {
56 store
57 .meta(EFFECTS_META_KEY)
58 .ok()
59 .flatten()
60 .map_or_else(CameraEffects::default, |value| {
61 CameraEffects::from_meta(&value)
62 })
63 }
64
54 65 fn camera_meta(choice: &DeviceChoice) -> &str {
55 66 match choice {
56 67 DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
@@ -231,6 +242,7 @@ impl AppState {
231 242 if self.call_background != BackgroundPick::None {
232 243 self.send_background_command(cx);
233 244 }
245 self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
234 246 self.refresh_call_backgrounds(cx);
235 247 self.new_chat = false;
236 248 self.follow_call(call_id, updates, cx);
@@ -691,6 +703,13 @@ impl AppState {
691 703 self.send_call_command(CallCommand::SetCaptions(on));
692 704 }
693 705
706 pub fn set_call_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
707 let _ = self.store.set_meta(EFFECTS_META_KEY, &effects.to_meta());
708 self.call_effects = effects;
709 self.send_call_command(CallCommand::SetCameraEffects(effects));
710 cx.notify();
711 }
712
694 713 pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
695 714 let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
696 715 self.call_background = pick.clone();
@@ -1109,13 +1128,13 @@ mod tests {
1109 1128 use std::path::PathBuf;
1110 1129
1111 1130 use calling::{
1112 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind,
1113 EndReason, EngineEvent, HoldState, Reaction, call_channel,
1131 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1132 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel,
1114 1133 };
1115 1134 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1116 1135 use store::{ChatRecord, MemberRecord, Store};
1117 1136
1118 use super::{ActiveCall, CallModel, load_camera};
1137 use super::{ActiveCall, CallModel, load_camera, load_camera_effects};
1119 1138 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1120 1139 use crate::call::TransferCandidate;
1121 1140 use crate::call::background::BackgroundPick;
@@ -1261,6 +1280,28 @@ mod tests {
1261 1280 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1262 1281 }
1263 1282
1283 #[gpui_kit::test]
1284 fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1285 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1286 let store = cx.update(|cx| app.read(cx).store.clone());
1287 assert_eq!(load_camera_effects(&store), CameraEffects::default());
1288 let effects = CameraEffects {
1289 mirror: false,
1290 auto_framing: true,
1291 soft_focus: true,
1292 soft_focus_strength: 75,
1293 ..CameraEffects::default()
1294 };
1295 cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));
1296 assert_eq!(
1297 control.try_recv_command(),
1298 Some(CallCommand::SetCameraEffects(effects))
1299 );
1300 assert_eq!(load_camera_effects(&store), effects);
1301 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1302 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1303 }
1304
1264 1305 #[gpui_kit::test]
1265 1306 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1266 1307 cx: &mut TestAppContext,
@@ -2,8 +2,8 @@ use std::time::{Duration, Instant};
2
2
3use calling::meeting::LiveMeeting;
3use calling::meeting::LiveMeeting;
4use calling::{
4use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice,
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7};
7};
8use gpui_kit::*;
8use gpui_kit::*;
9
9
@@ -38,6 +38,7 @@ const DEMO_LIVE_MINUTES: i64 = 60;
38const ORGID_PREFIX: &str = "8:orgid:";
38const ORGID_PREFIX: &str = "8:orgid:";
39pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
39pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
40const CAMERA_META_KEY: &str = "call_camera";
40const CAMERA_META_KEY: &str = "call_camera";
41const EFFECTS_META_KEY: &str = "call_camera_effects";
41const DEFAULT_CAMERA_META: &str = "default";
42const DEFAULT_CAMERA_META: &str = "default";
42
43
43pub fn load_share_sound(store: &store::Store) -> bool {
44pub fn load_share_sound(store: &store::Store) -> bool {
@@ -51,6 +52,16 @@ pub fn load_camera(store: &store::Store) -> DeviceChoice {
51 }
52 }
52}
53}
53
54
55pub fn load_camera_effects(store: &store::Store) -> CameraEffects {
56 store
57 .meta(EFFECTS_META_KEY)
58 .ok()
59 .flatten()
60 .map_or_else(CameraEffects::default, |value| {
61 CameraEffects::from_meta(&value)
62 })
63}
64
54fn camera_meta(choice: &DeviceChoice) -> &str {
65fn camera_meta(choice: &DeviceChoice) -> &str {
55 match choice {
66 match choice {
56 DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
67 DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
@@ -231,6 +242,7 @@ impl AppState {
231 if self.call_background != BackgroundPick::None {
242 if self.call_background != BackgroundPick::None {
232 self.send_background_command(cx);
243 self.send_background_command(cx);
233 }
244 }
245 self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
234 self.refresh_call_backgrounds(cx);
246 self.refresh_call_backgrounds(cx);
235 self.new_chat = false;
247 self.new_chat = false;
236 self.follow_call(call_id, updates, cx);
248 self.follow_call(call_id, updates, cx);
@@ -691,6 +703,13 @@ impl AppState {
691 self.send_call_command(CallCommand::SetCaptions(on));
703 self.send_call_command(CallCommand::SetCaptions(on));
692 }
704 }
693
705
706 pub fn set_call_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
707 let _ = self.store.set_meta(EFFECTS_META_KEY, &effects.to_meta());
708 self.call_effects = effects;
709 self.send_call_command(CallCommand::SetCameraEffects(effects));
710 cx.notify();
711 }
712
694 pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
713 pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
695 let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
714 let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
696 self.call_background = pick.clone();
715 self.call_background = pick.clone();
@@ -1109,13 +1128,13 @@ mod tests {
1109 use std::path::PathBuf;
1128 use std::path::PathBuf;
1110
1129
1111 use calling::{
1130 use calling::{
1112 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind,
1131 BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1113 EndReason, EngineEvent, HoldState, Reaction, call_channel,
1132 DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel,
1114 };
1133 };
1115 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1134 use gpui_kit::{AppContext as _, Entity, TestAppContext};
1116 use store::{ChatRecord, MemberRecord, Store};
1135 use store::{ChatRecord, MemberRecord, Store};
1117
1136
1118 use super::{ActiveCall, CallModel, load_camera};
1137 use super::{ActiveCall, CallModel, load_camera, load_camera_effects};
1119 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1138 use crate::app_state::{AppEvent, AppState, Mode, Selection};
1120 use crate::call::TransferCandidate;
1139 use crate::call::TransferCandidate;
1121 use crate::call::background::BackgroundPick;
1140 use crate::call::background::BackgroundPick;
@@ -1261,6 +1280,28 @@ mod tests {
1261 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1280 assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1262 }
1281 }
1263
1282
1283 #[gpui_kit::test]
1284 fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1285 let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1286 let store = cx.update(|cx| app.read(cx).store.clone());
1287 assert_eq!(load_camera_effects(&store), CameraEffects::default());
1288 let effects = CameraEffects {
1289 mirror: false,
1290 auto_framing: true,
1291 soft_focus: true,
1292 soft_focus_strength: 75,
1293 ..CameraEffects::default()
1294 };
1295 cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));
1296 assert_eq!(
1297 control.try_recv_command(),
1298 Some(CallCommand::SetCameraEffects(effects))
1299 );
1300 assert_eq!(load_camera_effects(&store), effects);
1301 let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1302 assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1303 }
1304
1264 #[gpui_kit::test]
1305 #[gpui_kit::test]
1265 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1306 fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1266 cx: &mut TestAppContext,
1307 cx: &mut TestAppContext,
crates/app/src/call/demo.rs +1 −0
@@ -596,6 +596,7 @@ async fn speak_until_hangup(
596 596 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
597 597 control.send(CallUpdate::IncomingVideo(enabled));
598 598 }
599 Some(CallCommand::SetCameraEffects(_)) => {}
599 600 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
600 601 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
601 602 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
@@ -596,6 +596,7 @@ async fn speak_until_hangup(
596 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
596 people.iter().for_each(|(mri, _)| control.video.forget(&VideoKey::Person(mri.clone())));
597 control.send(CallUpdate::IncomingVideo(enabled));
597 control.send(CallUpdate::IncomingVideo(enabled));
598 }
598 }
599 Some(CallCommand::SetCameraEffects(_)) => {}
599 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
600 Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
600 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
601 Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
601 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
602 Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
crates/app/src/call/features.rs +7 −0
@@ -82,6 +82,13 @@ impl AppState {
82 82
83 83 pub fn turn_off_call_effects(&mut self, cx: &mut Context<Self>) {
84 84 self.set_call_background(BackgroundPick::None, cx);
85 let effects = calling::CameraEffects {
86 auto_framing: false,
87 adjust_brightness: false,
88 soft_focus: false,
89 ..self.call_effects
90 };
91 self.set_call_effects(effects, cx);
85 92 }
86 93
87 94 pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {
@@ -82,6 +82,13 @@ impl AppState {
82
82
83 pub fn turn_off_call_effects(&mut self, cx: &mut Context<Self>) {
83 pub fn turn_off_call_effects(&mut self, cx: &mut Context<Self>) {
84 self.set_call_background(BackgroundPick::None, cx);
84 self.set_call_background(BackgroundPick::None, cx);
85 let effects = calling::CameraEffects {
86 auto_framing: false,
87 adjust_brightness: false,
88 soft_focus: false,
89 ..self.call_effects
90 };
91 self.set_call_effects(effects, cx);
85 }
92 }
86
93
87 pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {
94 pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {
crates/app/src/call/mod.rs +1 −1
@@ -26,7 +26,7 @@ mod target;
26 26 mod view_actions;
27 27 mod view_settings;
28 28
29 pub use actions::{load_camera, load_share_sound};
29 pub use actions::{load_camera, load_camera_effects, load_share_sound};
30 30 pub use mic::load_mic;
31 31 pub use agenda::{AgendaRow, fetch_window, join_available};
32 32 pub use background::{
@@ -26,7 +26,7 @@ mod target;
26mod view_actions;
26mod view_actions;
27mod view_settings;
27mod view_settings;
28
28
29pub use actions::{load_camera, load_share_sound};
29pub use actions::{load_camera, load_camera_effects, load_share_sound};
30pub use mic::load_mic;
30pub use mic::load_mic;
31pub use agenda::{AgendaRow, fetch_window, join_available};
31pub use agenda::{AgendaRow, fetch_window, join_available};
32pub use background::{
32pub use background::{
crates/app/src/call/preview.rs +10 −2
@@ -7,7 +7,7 @@ use calling::blur::BlurSettings;
7 7 use calling::camera::start_camera;
8 8 use calling::capture::Capture;
9 9 use calling::video_frame::picture_from_i420;
10 use calling::{BackgroundChoice, CallUpdate, DeviceChoice, VideoHub, VideoKey};
10 use calling::{BackgroundChoice, CallUpdate, CameraEffects, DeviceChoice, VideoHub, VideoKey};
11 11 use gpui_kit::*;
12 12 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
13 13
@@ -55,12 +55,16 @@ impl CameraPreview {
55 55 let hub = self.hub.clone();
56 56 let frames = self.frames.clone();
57 57 let failure = self.failure.clone();
58 let mirror = self.blur.clone();
58 59 let started = start_camera(
59 60 choice,
60 61 self.blur.clone(),
61 62 move |buffer| {
62 63 frames.fetch_add(1, Ordering::Relaxed);
63 if let Some(picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
64 if let Some(mut picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
65 if mirror.effects().mirror {
66 picture.flip_horizontally();
67 }
64 68 hub.publish(VideoKey::LocalCamera, picture);
65 69 }
66 70 },
@@ -101,6 +105,10 @@ impl CameraPreview {
101 105 }
102 106 }
103 107
108 pub fn set_effects(&self, effects: CameraEffects) {
109 self.blur.set_effects(effects);
110 }
111
104 112 fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
105 113 self.blur.set_picture(picture);
106 114 self.blur.set_enabled(enabled);
@@ -7,7 +7,7 @@ use calling::blur::BlurSettings;
7use calling::camera::start_camera;
7use calling::camera::start_camera;
8use calling::capture::Capture;
8use calling::capture::Capture;
9use calling::video_frame::picture_from_i420;
9use calling::video_frame::picture_from_i420;
10use calling::{BackgroundChoice, CallUpdate, DeviceChoice, VideoHub, VideoKey};
10use calling::{BackgroundChoice, CallUpdate, CameraEffects, DeviceChoice, VideoHub, VideoKey};
11use gpui_kit::*;
11use gpui_kit::*;
12use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
12use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
13
13
@@ -55,12 +55,16 @@ impl CameraPreview {
55 let hub = self.hub.clone();
55 let hub = self.hub.clone();
56 let frames = self.frames.clone();
56 let frames = self.frames.clone();
57 let failure = self.failure.clone();
57 let failure = self.failure.clone();
58 let mirror = self.blur.clone();
58 let started = start_camera(
59 let started = start_camera(
59 choice,
60 choice,
60 self.blur.clone(),
61 self.blur.clone(),
61 move |buffer| {
62 move |buffer| {
62 frames.fetch_add(1, Ordering::Relaxed);
63 frames.fetch_add(1, Ordering::Relaxed);
63 if let Some(picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
64 if let Some(mut picture) = picture_from_i420(buffer, PREVIEW_MAX_WIDTH) {
65 if mirror.effects().mirror {
66 picture.flip_horizontally();
67 }
64 hub.publish(VideoKey::LocalCamera, picture);
68 hub.publish(VideoKey::LocalCamera, picture);
65 }
69 }
66 },
70 },
@@ -101,6 +105,10 @@ impl CameraPreview {
101 }
105 }
102 }
106 }
103
107
108 pub fn set_effects(&self, effects: CameraEffects) {
109 self.blur.set_effects(effects);
110 }
111
104 fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
112 fn apply_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
105 self.blur.set_picture(picture);
113 self.blur.set_picture(picture);
106 self.blur.set_enabled(enabled);
114 self.blur.set_enabled(enabled);
crates/app/src/notify/settings_view.rs +121 −1
@@ -1,7 +1,7 @@
1 1 use std::time::{Duration, Instant};
2 2
3 3 use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};
4 use calling::{DeviceChoice, DeviceEntry, MicSettings, NoiseSuppression, camera_entries};
4 use calling::{CameraEffects, DeviceChoice, DeviceEntry, MicSettings, NoiseSuppression, camera_entries};
5 5 use gpui_kit::assets::IconName;
6 6 use gpui_kit::component::{
7 7 button::Button,
@@ -28,6 +28,7 @@ const SELECT_WIDTH: f32 = 170.;
28 28 const PREVIEW_WIDTH: f32 = 380.;
29 29 const PREVIEW_HEIGHT: f32 = 214.;
30 30 const PREVIEW_RADIUS: f32 = 10.;
31 const SOFT_FOCUS_LEVELS: [(&str, u8); 3] = [("Low", 25), ("Medium", 50), ("High", 75)];
31 32 const CAMERA_IN_USE: &str = "Camera is in use by the call";
32 33
33 34 fn camera_in_call(state: &AppState) -> bool {
@@ -135,6 +136,7 @@ impl SettingsView {
135 136 let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));
136 137 let state = app.read(cx);
137 138 let camera = state.call_camera.clone();
139 preview.set_effects(state.call_effects);
138 140 let preview_blocked = camera_in_call(state);
139 141 let background = Some(state.call_background.clone())
140 142 .filter(|pick| {
@@ -200,6 +202,8 @@ impl SettingsView {
200 202 Section::Devices => {
201 203 self.load_cameras(cx);
202 204 self.apply_background(cx);
205 self.preview
206 .set_effects(self.center.read(cx).app().read(cx).call_effects);
203 207 self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
204 208 self.start_preview();
205 209 }
@@ -260,6 +264,84 @@ impl SettingsView {
260 264 cx.notify();
261 265 }
262 266
267 fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {
268 let app = self.center.read(cx).app().clone();
269 let mut effects = app.read(cx).call_effects;
270 change(&mut effects);
271 self.preview.set_effects(effects);
272 app.update(cx, |state, cx| state.set_call_effects(effects, cx));
273 cx.notify();
274 }
275
276 fn effect_row(
277 &self,
278 id: &'static str,
279 title: &'static str,
280 on: bool,
281 change: fn(&mut CameraEffects),
282 cx: &mut Context<Self>,
283 ) -> Stateful<Div> {
284 let view = cx.entity();
285 h_flex()
286 .id(id)
287 .w_full()
288 .px(px(20.))
289 .py(px(6.))
290 .gap(px(12.))
291 .items_center()
292 .cursor_pointer()
293 .hover(|row| row.bg(theme::row_hover()))
294 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.change_effects(change, cx)))
295 .child(
296 div()
297 .flex_1()
298 .text_size(px(14.))
299 .font_weight(FontWeight::SEMIBOLD)
300 .text_color(theme::text())
301 .child(title),
302 )
303 .child(switch(on))
304 }
305
306 fn strength_row(&self, strength: u8, cx: &mut Context<Self>) -> Stateful<Div> {
307 let levels = SOFT_FOCUS_LEVELS.map(|(label, level)| {
308 let view = cx.entity();
309 let app = self.center.read(cx).app().clone();
310 button(label)
311 .when(strength == level, |button| {
312 button.bg(theme::accent()).text_color(theme::on_accent())
313 })
314 .on_click(move |_, _, cx| {
315 app.update(cx, |state, cx| {
316 let effects = CameraEffects {
317 soft_focus_strength: level,
318 ..state.call_effects
319 };
320 state.set_call_effects(effects, cx);
321 view.update(cx, |view, cx| {
322 view.preview.set_effects(effects);
323 cx.notify();
324 });
325 })
326 })
327 });
328 h_flex()
329 .id("effect-soft-focus-strength")
330 .w_full()
331 .px(px(20.))
332 .py(px(6.))
333 .gap(px(8.))
334 .items_center()
335 .child(
336 div()
337 .flex_1()
338 .text_size(px(12.))
339 .text_color(theme::text_muted())
340 .child("Soft focus strength"),
341 )
342 .children(levels)
343 }
344
263 345 fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
264 346 self.background = pick.clone();
265 347 let app = self.center.read(cx).app().clone();
@@ -437,6 +519,7 @@ impl SettingsView {
437 519 let mic = self.center.read(cx).app().read(cx).call_mic;
438 520 let noise_view = view.clone();
439 521 let music_view = view.clone();
522 let effects = self.center.read(cx).app().read(cx).call_effects;
440 523 let image = self.preview.image(Instant::now());
441 524 let status = if self.preview_blocked {
442 525 CAMERA_IN_USE.to_owned()
@@ -585,6 +668,43 @@ impl SettingsView {
585 668 .child(status),
586 669 ),
587 670 )
671 .child(
672 v_flex()
673 .id("camera-effects")
674 .w_full()
675 .pt(px(8.))
676 .child(self.effect_row(
677 "effect-mirror",
678 "Mirror my video",
679 effects.mirror,
680 |effects| effects.mirror = !effects.mirror,
681 cx,
682 ))
683 .child(self.effect_row(
684 "effect-framing",
685 "Auto framing",
686 effects.auto_framing,
687 |effects| effects.auto_framing = !effects.auto_framing,
688 cx,
689 ))
690 .child(self.effect_row(
691 "effect-brightness",
692 "Adjust brightness",
693 effects.adjust_brightness,
694 |effects| effects.adjust_brightness = !effects.adjust_brightness,
695 cx,
696 ))
697 .child(self.effect_row(
698 "effect-soft-focus",
699 "Soft focus",
700 effects.soft_focus,
701 |effects| effects.soft_focus = !effects.soft_focus,
702 cx,
703 ))
704 .when(effects.soft_focus, |column| {
705 column.child(self.strength_row(effects.soft_focus_strength, cx))
706 }),
707 )
588 708 }
589 709 }
590 710
@@ -1,7 +1,7 @@
1use std::time::{Duration, Instant};
1use std::time::{Duration, Instant};
2
2
3use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};
3use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};
4use calling::{DeviceChoice, DeviceEntry, MicSettings, NoiseSuppression, camera_entries};
4use calling::{CameraEffects, DeviceChoice, DeviceEntry, MicSettings, NoiseSuppression, camera_entries};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{
6use gpui_kit::component::{
7 button::Button,
7 button::Button,
@@ -28,6 +28,7 @@ const SELECT_WIDTH: f32 = 170.;
28const PREVIEW_WIDTH: f32 = 380.;
28const PREVIEW_WIDTH: f32 = 380.;
29const PREVIEW_HEIGHT: f32 = 214.;
29const PREVIEW_HEIGHT: f32 = 214.;
30const PREVIEW_RADIUS: f32 = 10.;
30const PREVIEW_RADIUS: f32 = 10.;
31const SOFT_FOCUS_LEVELS: [(&str, u8); 3] = [("Low", 25), ("Medium", 50), ("High", 75)];
31const CAMERA_IN_USE: &str = "Camera is in use by the call";
32const CAMERA_IN_USE: &str = "Camera is in use by the call";
32
33
33fn camera_in_call(state: &AppState) -> bool {
34fn camera_in_call(state: &AppState) -> bool {
@@ -135,6 +136,7 @@ impl SettingsView {
135 let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));
136 let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));
136 let state = app.read(cx);
137 let state = app.read(cx);
137 let camera = state.call_camera.clone();
138 let camera = state.call_camera.clone();
139 preview.set_effects(state.call_effects);
138 let preview_blocked = camera_in_call(state);
140 let preview_blocked = camera_in_call(state);
139 let background = Some(state.call_background.clone())
141 let background = Some(state.call_background.clone())
140 .filter(|pick| {
142 .filter(|pick| {
@@ -200,6 +202,8 @@ impl SettingsView {
200 Section::Devices => {
202 Section::Devices => {
201 self.load_cameras(cx);
203 self.load_cameras(cx);
202 self.apply_background(cx);
204 self.apply_background(cx);
205 self.preview
206 .set_effects(self.center.read(cx).app().read(cx).call_effects);
203 self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
207 self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
204 self.start_preview();
208 self.start_preview();
205 }
209 }
@@ -260,6 +264,84 @@ impl SettingsView {
260 cx.notify();
264 cx.notify();
261 }
265 }
262
266
267 fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {
268 let app = self.center.read(cx).app().clone();
269 let mut effects = app.read(cx).call_effects;
270 change(&mut effects);
271 self.preview.set_effects(effects);
272 app.update(cx, |state, cx| state.set_call_effects(effects, cx));
273 cx.notify();
274 }
275
276 fn effect_row(
277 &self,
278 id: &'static str,
279 title: &'static str,
280 on: bool,
281 change: fn(&mut CameraEffects),
282 cx: &mut Context<Self>,
283 ) -> Stateful<Div> {
284 let view = cx.entity();
285 h_flex()
286 .id(id)
287 .w_full()
288 .px(px(20.))
289 .py(px(6.))
290 .gap(px(12.))
291 .items_center()
292 .cursor_pointer()
293 .hover(|row| row.bg(theme::row_hover()))
294 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.change_effects(change, cx)))
295 .child(
296 div()
297 .flex_1()
298 .text_size(px(14.))
299 .font_weight(FontWeight::SEMIBOLD)
300 .text_color(theme::text())
301 .child(title),
302 )
303 .child(switch(on))
304 }
305
306 fn strength_row(&self, strength: u8, cx: &mut Context<Self>) -> Stateful<Div> {
307 let levels = SOFT_FOCUS_LEVELS.map(|(label, level)| {
308 let view = cx.entity();
309 let app = self.center.read(cx).app().clone();
310 button(label)
311 .when(strength == level, |button| {
312 button.bg(theme::accent()).text_color(theme::on_accent())
313 })
314 .on_click(move |_, _, cx| {
315 app.update(cx, |state, cx| {
316 let effects = CameraEffects {
317 soft_focus_strength: level,
318 ..state.call_effects
319 };
320 state.set_call_effects(effects, cx);
321 view.update(cx, |view, cx| {
322 view.preview.set_effects(effects);
323 cx.notify();
324 });
325 })
326 })
327 });
328 h_flex()
329 .id("effect-soft-focus-strength")
330 .w_full()
331 .px(px(20.))
332 .py(px(6.))
333 .gap(px(8.))
334 .items_center()
335 .child(
336 div()
337 .flex_1()
338 .text_size(px(12.))
339 .text_color(theme::text_muted())
340 .child("Soft focus strength"),
341 )
342 .children(levels)
343 }
344
263 fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
345 fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
264 self.background = pick.clone();
346 self.background = pick.clone();
265 let app = self.center.read(cx).app().clone();
347 let app = self.center.read(cx).app().clone();
@@ -437,6 +519,7 @@ impl SettingsView {
437 let mic = self.center.read(cx).app().read(cx).call_mic;
519 let mic = self.center.read(cx).app().read(cx).call_mic;
438 let noise_view = view.clone();
520 let noise_view = view.clone();
439 let music_view = view.clone();
521 let music_view = view.clone();
522 let effects = self.center.read(cx).app().read(cx).call_effects;
440 let image = self.preview.image(Instant::now());
523 let image = self.preview.image(Instant::now());
441 let status = if self.preview_blocked {
524 let status = if self.preview_blocked {
442 CAMERA_IN_USE.to_owned()
525 CAMERA_IN_USE.to_owned()
@@ -585,6 +668,43 @@ impl SettingsView {
585 .child(status),
668 .child(status),
586 ),
669 ),
587 )
670 )
671 .child(
672 v_flex()
673 .id("camera-effects")
674 .w_full()
675 .pt(px(8.))
676 .child(self.effect_row(
677 "effect-mirror",
678 "Mirror my video",
679 effects.mirror,
680 |effects| effects.mirror = !effects.mirror,
681 cx,
682 ))
683 .child(self.effect_row(
684 "effect-framing",
685 "Auto framing",
686 effects.auto_framing,
687 |effects| effects.auto_framing = !effects.auto_framing,
688 cx,
689 ))
690 .child(self.effect_row(
691 "effect-brightness",
692 "Adjust brightness",
693 effects.adjust_brightness,
694 |effects| effects.adjust_brightness = !effects.adjust_brightness,
695 cx,
696 ))
697 .child(self.effect_row(
698 "effect-soft-focus",
699 "Soft focus",
700 effects.soft_focus,
701 |effects| effects.soft_focus = !effects.soft_focus,
702 cx,
703 ))
704 .when(effects.soft_focus, |column| {
705 column.child(self.strength_row(effects.soft_focus_strength, cx))
706 }),
707 )
588 }
708 }
589}
709}
590
710
crates/app/src/views/call_extras.rs +75 −8
@@ -1,10 +1,11 @@
1 1 use std::path::PathBuf;
2 2
3 use calling::HoldState;
3 use calling::{CameraEffects, HoldState};
4 4 use gpui_kit::assets::IconName;
5 5 use gpui_kit::component::button::{Button, ButtonVariants as _};
6 6 use gpui_kit::component::dialog::DialogFooter;
7 7 use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
8 use gpui_kit::component::switch::Switch;
8 9 use gpui_kit::component::tooltip::Tooltip;
9 10 use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
10 11 use gpui_kit::*;
@@ -288,16 +289,17 @@ pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mu
288 289 }
289 290
290 291 #[derive(Clone)]
291 pub struct BackgroundMenu {
292 pub struct CameraMenu {
292 293 pub pick: BackgroundPick,
293 294 pub images: Vec<(String, String, Option<PathBuf>)>,
294 295 pub customs: Vec<PathBuf>,
296 pub effects: CameraEffects,
295 297 }
296 298
297 impl BackgroundMenu {
299 impl CameraMenu {
298 300 pub fn of(state: &AppState) -> Self {
299 301 let library = &state.call_backgrounds;
300 BackgroundMenu {
302 CameraMenu {
301 303 pick: state.call_background.clone(),
302 304 images: library
303 305 .shown()
@@ -311,6 +313,7 @@ impl BackgroundMenu {
311 313 })
312 314 .collect(),
313 315 customs: library.customs.clone(),
316 effects: state.call_effects,
314 317 }
315 318 }
316 319 }
@@ -354,11 +357,75 @@ fn thumbnail(
354 357 .into_any_element()
355 358 }
356 359
357 pub fn background_items(
358 popup: PopupMenu,
360 fn effect_change(
359 361 app: &Entity<AppState>,
360 menu: &BackgroundMenu,
361 ) -> PopupMenu {
362 change: fn(&mut CameraEffects),
363 ) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
364 let app = app.clone();
365 move |_, _, cx| {
366 app.update(cx, |state, cx| {
367 let mut effects = state.call_effects;
368 change(&mut effects);
369 state.set_call_effects(effects, cx);
370 })
371 }
372 }
373
374 fn effect_switch_item(
375 app: &Entity<AppState>,
376 id: &'static str,
377 label: &'static str,
378 on: bool,
379 change: fn(&mut CameraEffects),
380 ) -> PopupMenuItem {
381 PopupMenuItem::element(move |_, _| {
382 h_flex()
383 .id(id)
384 .w_full()
385 .gap(px(16.))
386 .items_center()
387 .justify_between()
388 .child(label)
389 .child(Switch::new(id).checked(on))
390 })
391 .on_click(effect_change(app, change))
392 }
393
394 pub fn effect_items(popup: PopupMenu, app: &Entity<AppState>, effects: CameraEffects) -> PopupMenu {
395 popup
396 .separator()
397 .item(PopupMenuItem::label("Effects"))
398 .item(effect_switch_item(
399 app,
400 "call-effect-mirror",
401 "Mirror my video",
402 effects.mirror,
403 |effects| effects.mirror = !effects.mirror,
404 ))
405 .item(effect_switch_item(
406 app,
407 "call-effect-framing",
408 "Auto framing",
409 effects.auto_framing,
410 |effects| effects.auto_framing = !effects.auto_framing,
411 ))
412 .item(effect_switch_item(
413 app,
414 "call-effect-brightness",
415 "Adjust brightness",
416 effects.adjust_brightness,
417 |effects| effects.adjust_brightness = !effects.adjust_brightness,
418 ))
419 .item(effect_switch_item(
420 app,
421 "call-effect-soft-focus",
422 "Soft focus",
423 effects.soft_focus,
424 |effects| effects.soft_focus = !effects.soft_focus,
425 ))
426 }
427
428 pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraMenu) -> PopupMenu {
362 429 let (none_app, blur_app, add_app, grid_app) =
363 430 (app.clone(), app.clone(), app.clone(), app.clone());
364 431 let grid_menu = menu.clone();
@@ -1,10 +1,11 @@
1use std::path::PathBuf;
1use std::path::PathBuf;
2
2
3use calling::HoldState;
3use calling::{CameraEffects, HoldState};
4use gpui_kit::assets::IconName;
4use gpui_kit::assets::IconName;
5use gpui_kit::component::button::{Button, ButtonVariants as _};
5use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::dialog::DialogFooter;
6use gpui_kit::component::dialog::DialogFooter;
7use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
7use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};
8use gpui_kit::component::switch::Switch;
8use gpui_kit::component::tooltip::Tooltip;
9use gpui_kit::component::tooltip::Tooltip;
9use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
10use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
10use gpui_kit::*;
11use gpui_kit::*;
@@ -288,16 +289,17 @@ pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mu
288}
289}
289
290
290#[derive(Clone)]
291#[derive(Clone)]
291pub struct BackgroundMenu {
292pub struct CameraMenu {
292 pub pick: BackgroundPick,
293 pub pick: BackgroundPick,
293 pub images: Vec<(String, String, Option<PathBuf>)>,
294 pub images: Vec<(String, String, Option<PathBuf>)>,
294 pub customs: Vec<PathBuf>,
295 pub customs: Vec<PathBuf>,
296 pub effects: CameraEffects,
295}
297}
296
298
297impl BackgroundMenu {
299impl CameraMenu {
298 pub fn of(state: &AppState) -> Self {
300 pub fn of(state: &AppState) -> Self {
299 let library = &state.call_backgrounds;
301 let library = &state.call_backgrounds;
300 BackgroundMenu {
302 CameraMenu {
301 pick: state.call_background.clone(),
303 pick: state.call_background.clone(),
302 images: library
304 images: library
303 .shown()
305 .shown()
@@ -311,6 +313,7 @@ impl BackgroundMenu {
311 })
313 })
312 .collect(),
314 .collect(),
313 customs: library.customs.clone(),
315 customs: library.customs.clone(),
316 effects: state.call_effects,
314 }
317 }
315 }
318 }
316}
319}
@@ -354,11 +357,75 @@ fn thumbnail(
354 .into_any_element()
357 .into_any_element()
355}
358}
356
359
357pub fn background_items(
360fn effect_change(
358 popup: PopupMenu,
359 app: &Entity<AppState>,
361 app: &Entity<AppState>,
360 menu: &BackgroundMenu,
362 change: fn(&mut CameraEffects),
361) -> PopupMenu {
363) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static {
364 let app = app.clone();
365 move |_, _, cx| {
366 app.update(cx, |state, cx| {
367 let mut effects = state.call_effects;
368 change(&mut effects);
369 state.set_call_effects(effects, cx);
370 })
371 }
372}
373
374fn effect_switch_item(
375 app: &Entity<AppState>,
376 id: &'static str,
377 label: &'static str,
378 on: bool,
379 change: fn(&mut CameraEffects),
380) -> PopupMenuItem {
381 PopupMenuItem::element(move |_, _| {
382 h_flex()
383 .id(id)
384 .w_full()
385 .gap(px(16.))
386 .items_center()
387 .justify_between()
388 .child(label)
389 .child(Switch::new(id).checked(on))
390 })
391 .on_click(effect_change(app, change))
392}
393
394pub fn effect_items(popup: PopupMenu, app: &Entity<AppState>, effects: CameraEffects) -> PopupMenu {
395 popup
396 .separator()
397 .item(PopupMenuItem::label("Effects"))
398 .item(effect_switch_item(
399 app,
400 "call-effect-mirror",
401 "Mirror my video",
402 effects.mirror,
403 |effects| effects.mirror = !effects.mirror,
404 ))
405 .item(effect_switch_item(
406 app,
407 "call-effect-framing",
408 "Auto framing",
409 effects.auto_framing,
410 |effects| effects.auto_framing = !effects.auto_framing,
411 ))
412 .item(effect_switch_item(
413 app,
414 "call-effect-brightness",
415 "Adjust brightness",
416 effects.adjust_brightness,
417 |effects| effects.adjust_brightness = !effects.adjust_brightness,
418 ))
419 .item(effect_switch_item(
420 app,
421 "call-effect-soft-focus",
422 "Soft focus",
423 effects.soft_focus,
424 |effects| effects.soft_focus = !effects.soft_focus,
425 ))
426}
427
428pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraMenu) -> PopupMenu {
362 let (none_app, blur_app, add_app, grid_app) =
429 let (none_app, blur_app, add_app, grid_app) =
363 (app.clone(), app.clone(), app.clone(), app.clone());
430 (app.clone(), app.clone(), app.clone(), app.clone());
364 let grid_menu = menu.clone();
431 let grid_menu = menu.clone();
crates/app/src/views/call_organizer.rs +8 −4
@@ -13,7 +13,7 @@ use gpui_kit::*;
13 13
14 14 use super::avatar::person_avatar;
15 15 use super::call_extras::{
16 BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker,
16 CameraMenu, background_items, confirm_stop_recording, effect_items, open_transfer_picker,
17 17 };
18 18 use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
19 19 use super::widgets::icon;
@@ -513,7 +513,7 @@ pub fn chevron_button(button_id: &'static str, face_id: &'static str) -> Button
513 513 pub fn camera_menu_button(
514 514 app: &Entity<AppState>,
515 515 model: &CallModel,
516 backgrounds: BackgroundMenu,
516 backgrounds: CameraMenu,
517 517 ) -> Option<AnyElement> {
518 518 if !model.can_use_camera() {
519 519 return None;
@@ -533,7 +533,7 @@ fn camera_menu(
533 533 popup: PopupMenu,
534 534 app: &Entity<AppState>,
535 535 model: &CallModel,
536 backgrounds: &BackgroundMenu,
536 backgrounds: &CameraMenu,
537 537 ) -> PopupMenu {
538 538 let camera_app = app.clone();
539 539 let cameras = super::call_view::device_items(
@@ -549,7 +549,11 @@ fn camera_menu(
549 549 for item in cameras {
550 550 popup = popup.item(item);
551 551 }
552 background_items(popup, app, backgrounds)
552 background_items(
553 effect_items(popup, app, backgrounds.effects),
554 app,
555 backgrounds,
556 )
553 557 }
554 558
555 559 pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
@@ -13,7 +13,7 @@ use gpui_kit::*;
13
13
14use super::avatar::person_avatar;
14use super::avatar::person_avatar;
15use super::call_extras::{
15use super::call_extras::{
16 BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker,
16 CameraMenu, background_items, confirm_stop_recording, effect_items, open_transfer_picker,
17};
17};
18use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
18use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
19use super::widgets::icon;
19use super::widgets::icon;
@@ -513,7 +513,7 @@ pub fn chevron_button(button_id: &'static str, face_id: &'static str) -> Button
513pub fn camera_menu_button(
513pub fn camera_menu_button(
514 app: &Entity<AppState>,
514 app: &Entity<AppState>,
515 model: &CallModel,
515 model: &CallModel,
516 backgrounds: BackgroundMenu,
516 backgrounds: CameraMenu,
517) -> Option<AnyElement> {
517) -> Option<AnyElement> {
518 if !model.can_use_camera() {
518 if !model.can_use_camera() {
519 return None;
519 return None;
@@ -533,7 +533,7 @@ fn camera_menu(
533 popup: PopupMenu,
533 popup: PopupMenu,
534 app: &Entity<AppState>,
534 app: &Entity<AppState>,
535 model: &CallModel,
535 model: &CallModel,
536 backgrounds: &BackgroundMenu,
536 backgrounds: &CameraMenu,
537) -> PopupMenu {
537) -> PopupMenu {
538 let camera_app = app.clone();
538 let camera_app = app.clone();
539 let cameras = super::call_view::device_items(
539 let cameras = super::call_view::device_items(
@@ -549,7 +549,11 @@ fn camera_menu(
549 for item in cameras {
549 for item in cameras {
550 popup = popup.item(item);
550 popup = popup.item(item);
551 }
551 }
552 background_items(popup, app, backgrounds)
552 background_items(
553 effect_items(popup, app, backgrounds.effects),
554 app,
555 backgrounds,
556 )
553}
557}
554
558
555pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
559pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
crates/app/src/views/call_view.rs +2 −2
@@ -17,7 +17,7 @@ use gpui_kit::*;
17 17
18 18 use super::avatar::person_avatar;
19 19 use super::call_extras::{
20 BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
20 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
21 21 room_chip, whiteboard_stage,
22 22 };
23 23 use super::call_health::{health_banner, health_indicator};
@@ -1096,7 +1096,7 @@ pub fn render_call_view(
1096 1096 .rounded_full()
1097 1097 .bg(theme::surface_raised())
1098 1098 .child(camera_button(app, model))
1099 .children(camera_menu_button(app, model, BackgroundMenu::of(state))),
1099 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1100 1100 )
1101 1101 .child(share_button(
1102 1102 app,
@@ -17,7 +17,7 @@ use gpui_kit::*;
17
17
18use super::avatar::person_avatar;
18use super::avatar::person_avatar;
19use super::call_extras::{
19use super::call_extras::{
20 BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
20 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
21 room_chip, whiteboard_stage,
21 room_chip, whiteboard_stage,
22};
22};
23use super::call_health::{health_banner, health_indicator};
23use super::call_health::{health_banner, health_indicator};
@@ -1096,7 +1096,7 @@ pub fn render_call_view(
1096 .rounded_full()
1096 .rounded_full()
1097 .bg(theme::surface_raised())
1097 .bg(theme::surface_raised())
1098 .child(camera_button(app, model))
1098 .child(camera_button(app, model))
1099 .children(camera_menu_button(app, model, BackgroundMenu::of(state))),
1099 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1100 )
1100 )
1101 .child(share_button(
1101 .child(share_button(
1102 app,
1102 app,
crates/calling/examples/blur_bench.rs +83 −6
@@ -1,9 +1,16 @@
1 use std::sync::Arc;
1 2 use std::time::Instant;
2 3
3 use calling::blur::{BackgroundBlur, Segmenter};
4 use calling::blur::{BlurSettings, MaskSource, Segmenter, compose};
5 use calling::effects::{CameraEffects, EffectsStage};
6 use calling::framing::{Crop, crop_and_scale};
7 use calling::luma_effects::soften_luma;
8 use libwebrtc::video_frame::I420Buffer;
4 9
5 10 const WIDTH: usize = 640;
6 11 const HEIGHT: usize = 360;
12 const SEND_WIDTH: u32 = 1280;
13 const SEND_HEIGHT: u32 = 720;
7 14 const FRAMES: usize = 200;
8 15 const WARMUP: usize = 10;
9 16
@@ -11,30 +18,100 @@ fn synthetic() -> Vec<u8> {
11 18 (0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()
12 19 }
13 20
21 fn send_frame() -> I420Buffer {
22 let mut buffer = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
23 let stride = buffer.strides().0 as usize;
24 let (plane_y, plane_u, plane_v) = buffer.data_mut();
25 for (index, value) in plane_y.iter_mut().enumerate() {
26 *value = (((index % stride) + index / stride) * 255 / (SEND_WIDTH as usize + SEND_HEIGHT as usize)) as u8;
27 }
28 plane_u.fill(128);
29 plane_v.fill(128);
30 buffer
31 }
32
33 fn milliseconds_per_frame(started: Instant) -> f64 {
34 started.elapsed().as_secs_f64() * 1000. / FRAMES as f64
35 }
36
37 fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {
38 let settings = Arc::new(BlurSettings::default());
39 settings.set_enabled(blur);
40 settings.set_effects(effects);
41 let mut stage = EffectsStage::new(settings);
42 let source = send_frame();
43 let run = |stage: &mut EffectsStage| {
44 let mut frame = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
45 let (source_y, source_u, source_v) = source.data();
46 let (target_y, target_u, target_v) = frame.data_mut();
47 target_y.copy_from_slice(source_y);
48 target_u.copy_from_slice(source_u);
49 target_v.copy_from_slice(source_v);
50 stage.apply_i420(frame)
51 };
52 for _ in 0..WARMUP {
53 run(&mut stage);
54 }
55 let started = Instant::now();
56 for _ in 0..FRAMES {
57 run(&mut stage);
58 }
59 println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
60 }
61
14 62 fn main() {
15 63 let mut arguments = std::env::args().skip(1);
16 64 let input = arguments.next();
17 65 let output = arguments.next();
18 66 let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
19 67 assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");
20 let mut blur = BackgroundBlur::new().expect("model");
68 let mut masks = MaskSource::new().expect("model");
21 69 let segmenter = Segmenter::new().expect("model");
22 70 for _ in 0..WARMUP {
23 blur.apply(&mut frame.clone(), WIDTH, HEIGHT, None);
71 masks.refresh(|| (frame.clone(), WIDTH, HEIGHT));
24 72 }
25 73 let started = Instant::now();
26 74 for _ in 0..FRAMES {
27 75 segmenter.mask(&frame, WIDTH, HEIGHT).expect("mask");
28 76 }
29 println!("segmentation only: {:.2} ms/frame", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64);
77 println!("segmentation only: {:.2} ms/frame", milliseconds_per_frame(started));
30 78 let started = Instant::now();
31 79 let mut result = frame.clone();
32 80 for _ in 0..FRAMES {
33 81 result.copy_from_slice(&frame);
34 blur.apply(&mut result, WIDTH, HEIGHT, None);
82 masks.refresh(|| (frame.clone(), WIDTH, HEIGHT));
83 compose(&mut result, WIDTH, HEIGHT, masks.mask());
35 84 }
36 println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());
85 println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
37 86 if let Some(path) = output {
38 87 std::fs::write(path, &result).expect("output");
39 88 }
89 let off = CameraEffects::default();
90 let all = CameraEffects { auto_framing: true, adjust_brightness: true, soft_focus: true, ..off };
91 stage_cost("stage, brightness", false, CameraEffects { adjust_brightness: true, ..off });
92 stage_cost("stage, soft focus", false, CameraEffects { soft_focus: true, ..off });
93 stage_cost("stage, auto framing", false, CameraEffects { auto_framing: true, ..off });
94 stage_cost("stage, all three", false, all);
95 stage_cost("stage, all three + blur", true, all);
96 stage_cost("stage, blur only", true, off);
97 let mut frame = send_frame();
98 let stride = frame.strides().0 as usize;
99 let oval: Vec<f32> = (0..calling::blur::MASK_WIDTH * calling::blur::MASK_HEIGHT)
100 .map(|index| {
101 let (x, y) = ((index % calling::blur::MASK_WIDTH) as f32 / calling::blur::MASK_WIDTH as f32 - 0.5, (index / calling::blur::MASK_WIDTH) as f32 / calling::blur::MASK_HEIGHT as f32 - 0.5);
102 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
103 })
104 .collect();
105 let started = Instant::now();
106 for _ in 0..FRAMES {
107 soften_luma(frame.data_mut().0, stride, SEND_WIDTH as usize, SEND_HEIGHT as usize, &oval, 100);
108 }
109 println!("soft focus only, oval person {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
110 let source = send_frame();
111 let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
112 let started = Instant::now();
113 for _ in 0..FRAMES {
114 std::hint::black_box(crop_and_scale(&source, &crop));
115 }
116 println!("crop and scale {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
40 117 }
@@ -1,9 +1,16 @@
1use std::sync::Arc;
1use std::time::Instant;
2use std::time::Instant;
2
3
3use calling::blur::{BackgroundBlur, Segmenter};
4use calling::blur::{BlurSettings, MaskSource, Segmenter, compose};
5use calling::effects::{CameraEffects, EffectsStage};
6use calling::framing::{Crop, crop_and_scale};
7use calling::luma_effects::soften_luma;
8use libwebrtc::video_frame::I420Buffer;
4
9
5const WIDTH: usize = 640;
10const WIDTH: usize = 640;
6const HEIGHT: usize = 360;
11const HEIGHT: usize = 360;
12const SEND_WIDTH: u32 = 1280;
13const SEND_HEIGHT: u32 = 720;
7const FRAMES: usize = 200;
14const FRAMES: usize = 200;
8const WARMUP: usize = 10;
15const WARMUP: usize = 10;
9
16
@@ -11,30 +18,100 @@ fn synthetic() -> Vec<u8> {
11 (0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()
18 (0..WIDTH * HEIGHT * 4).map(|index| if index % 4 == 3 { 255 } else { ((index / 4 % WIDTH + index / 4 / WIDTH) * 255 / (WIDTH + HEIGHT)) as u8 }).collect()
12}
19}
13
20
21fn send_frame() -> I420Buffer {
22 let mut buffer = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
23 let stride = buffer.strides().0 as usize;
24 let (plane_y, plane_u, plane_v) = buffer.data_mut();
25 for (index, value) in plane_y.iter_mut().enumerate() {
26 *value = (((index % stride) + index / stride) * 255 / (SEND_WIDTH as usize + SEND_HEIGHT as usize)) as u8;
27 }
28 plane_u.fill(128);
29 plane_v.fill(128);
30 buffer
31}
32
33fn milliseconds_per_frame(started: Instant) -> f64 {
34 started.elapsed().as_secs_f64() * 1000. / FRAMES as f64
35}
36
37fn stage_cost(label: &str, blur: bool, effects: CameraEffects) {
38 let settings = Arc::new(BlurSettings::default());
39 settings.set_enabled(blur);
40 settings.set_effects(effects);
41 let mut stage = EffectsStage::new(settings);
42 let source = send_frame();
43 let run = |stage: &mut EffectsStage| {
44 let mut frame = I420Buffer::new(SEND_WIDTH, SEND_HEIGHT);
45 let (source_y, source_u, source_v) = source.data();
46 let (target_y, target_u, target_v) = frame.data_mut();
47 target_y.copy_from_slice(source_y);
48 target_u.copy_from_slice(source_u);
49 target_v.copy_from_slice(source_v);
50 stage.apply_i420(frame)
51 };
52 for _ in 0..WARMUP {
53 run(&mut stage);
54 }
55 let started = Instant::now();
56 for _ in 0..FRAMES {
57 run(&mut stage);
58 }
59 println!("{label} {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
60}
61
14fn main() {
62fn main() {
15 let mut arguments = std::env::args().skip(1);
63 let mut arguments = std::env::args().skip(1);
16 let input = arguments.next();
64 let input = arguments.next();
17 let output = arguments.next();
65 let output = arguments.next();
18 let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
66 let frame = input.map_or_else(synthetic, |path| std::fs::read(path).expect("raw rgba 640x360 input"));
19 assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");
67 assert_eq!(frame.len(), WIDTH * HEIGHT * 4, "input must be raw RGBA {WIDTH}x{HEIGHT}");
20 let mut blur = BackgroundBlur::new().expect("model");
68 let mut masks = MaskSource::new().expect("model");
21 let segmenter = Segmenter::new().expect("model");
69 let segmenter = Segmenter::new().expect("model");
22 for _ in 0..WARMUP {
70 for _ in 0..WARMUP {
23 blur.apply(&mut frame.clone(), WIDTH, HEIGHT, None);
71 masks.refresh(|| (frame.clone(), WIDTH, HEIGHT));
24 }
72 }
25 let started = Instant::now();
73 let started = Instant::now();
26 for _ in 0..FRAMES {
74 for _ in 0..FRAMES {
27 segmenter.mask(&frame, WIDTH, HEIGHT).expect("mask");
75 segmenter.mask(&frame, WIDTH, HEIGHT).expect("mask");
28 }
76 }
29 println!("segmentation only: {:.2} ms/frame", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64);
77 println!("segmentation only: {:.2} ms/frame", milliseconds_per_frame(started));
30 let started = Instant::now();
78 let started = Instant::now();
31 let mut result = frame.clone();
79 let mut result = frame.clone();
32 for _ in 0..FRAMES {
80 for _ in 0..FRAMES {
33 result.copy_from_slice(&frame);
81 result.copy_from_slice(&frame);
34 blur.apply(&mut result, WIDTH, HEIGHT, None);
82 masks.refresh(|| (frame.clone(), WIDTH, HEIGHT));
83 compose(&mut result, WIDTH, HEIGHT, masks.mask());
35 }
84 }
36 println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame (running average {:.2} ms)", started.elapsed().as_secs_f64() * 1000. / FRAMES as f64, blur.average_ms());
85 println!("segment + blur + compose {WIDTH}x{HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
37 if let Some(path) = output {
86 if let Some(path) = output {
38 std::fs::write(path, &result).expect("output");
87 std::fs::write(path, &result).expect("output");
39 }
88 }
89 let off = CameraEffects::default();
90 let all = CameraEffects { auto_framing: true, adjust_brightness: true, soft_focus: true, ..off };
91 stage_cost("stage, brightness", false, CameraEffects { adjust_brightness: true, ..off });
92 stage_cost("stage, soft focus", false, CameraEffects { soft_focus: true, ..off });
93 stage_cost("stage, auto framing", false, CameraEffects { auto_framing: true, ..off });
94 stage_cost("stage, all three", false, all);
95 stage_cost("stage, all three + blur", true, all);
96 stage_cost("stage, blur only", true, off);
97 let mut frame = send_frame();
98 let stride = frame.strides().0 as usize;
99 let oval: Vec<f32> = (0..calling::blur::MASK_WIDTH * calling::blur::MASK_HEIGHT)
100 .map(|index| {
101 let (x, y) = ((index % calling::blur::MASK_WIDTH) as f32 / calling::blur::MASK_WIDTH as f32 - 0.5, (index / calling::blur::MASK_WIDTH) as f32 / calling::blur::MASK_HEIGHT as f32 - 0.5);
102 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
103 })
104 .collect();
105 let started = Instant::now();
106 for _ in 0..FRAMES {
107 soften_luma(frame.data_mut().0, stride, SEND_WIDTH as usize, SEND_HEIGHT as usize, &oval, 100);
108 }
109 println!("soft focus only, oval person {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
110 let source = send_frame();
111 let crop = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
112 let started = Instant::now();
113 for _ in 0..FRAMES {
114 std::hint::black_box(crop_and_scale(&source, &crop));
115 }
116 println!("crop and scale {SEND_WIDTH}x{SEND_HEIGHT}: {:.2} ms/frame", milliseconds_per_frame(started));
40}
117}
crates/calling/src/blur.rs +60 −76
@@ -3,12 +3,10 @@ use std::sync::{Arc, Mutex};
3 3 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
4 4 use std::time::{Duration, Instant};
5 5
6 use libwebrtc::native::yuv_helper::i420_to_abgr;
7 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
8 6 use tract_onnx::prelude::*;
9 7
10 8 use crate::background::BackgroundPicture;
11 use crate::camera::i420_from_rgba;
9 use crate::effects::CameraEffects;
12 10 use crate::error::{Error, Result};
13 11
14 12 const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
@@ -24,7 +22,6 @@ const OPAQUE: f32 = 0.985;
24 22 const MASK_SMOOTHING: f32 = 0.35;
25 23 const SLOW_INFERENCE: Duration = Duration::from_millis(22);
26 24 const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
27 const AVERAGE_WEIGHT: f64 = 0.1;
28 25 const MAX_BANDS: usize = 4;
29 26
30 27 type Plan = std::sync::Arc<TypedRunnableModel>;
@@ -84,13 +81,13 @@ fn smoothstep(value: f32) -> f32 {
84 81 t * t * (3. - 2. * t)
85 82 }
86 83
87 struct Axis {
88 first: Vec<usize>,
89 second: Vec<usize>,
90 weight: Vec<f32>,
84 pub(crate) struct Axis {
85 pub(crate) first: Vec<usize>,
86 pub(crate) second: Vec<usize>,
87 pub(crate) weight: Vec<f32>,
91 88 }
92 89
93 fn axis(output: usize, input: usize) -> Axis {
90 pub(crate) fn axis(output: usize, input: usize) -> Axis {
94 91 let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };
95 92 for index in 0..output {
96 93 let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);
@@ -234,6 +231,7 @@ pub struct BlurSettings {
234 231 enabled: AtomicBool,
235 232 average_micros: AtomicU32,
236 233 picture: Mutex<Option<Arc<BackgroundPicture>>>,
234 effects: Mutex<CameraEffects>,
237 235 }
238 236
239 237 impl BlurSettings {
@@ -253,16 +251,30 @@ impl BlurSettings {
253 251 self.picture.lock().expect("picture lock").clone()
254 252 }
255 253
254 pub fn set_effects(&self, effects: CameraEffects) {
255 *self.effects.lock().expect("effects lock") = effects;
256 }
257
258 pub fn effects(&self) -> CameraEffects {
259 *self.effects.lock().expect("effects lock")
260 }
261
262 pub fn active(&self) -> bool {
263 self.enabled() || self.effects().alters_frame()
264 }
265
256 266 pub fn average_ms(&self) -> f32 {
257 267 self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
258 268 }
269
270 pub fn set_average_ms(&self, average_ms: f64) {
271 self.average_micros.store((average_ms * 1000.) as u32, Ordering::Relaxed);
272 }
259 273 }
260 274
261 /// Runs on the capture thread; loads the model on first use and stays out of the way while the setting is off.
275 /// Replaces the background of a frame; the mask comes from the shared `MaskSource`.
262 276 pub struct BlurStage {
263 277 settings: Arc<BlurSettings>,
264 blur: Option<BackgroundBlur>,
265 unavailable: bool,
266 278 covered: Option<CoveredPicture>,
267 279 }
268 280
@@ -275,7 +287,7 @@ struct CoveredPicture {
275 287
276 288 impl BlurStage {
277 289 pub fn new(settings: Arc<BlurSettings>) -> Self {
278 BlurStage { settings, blur: None, unavailable: false, covered: None }
290 BlurStage { settings, covered: None }
279 291 }
280 292
281 293 fn refresh_covered(&mut self, width: usize, height: usize) {
@@ -290,73 +302,47 @@ impl BlurStage {
290 302 }
291 303 }
292 304
293 pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {
294 if !self.settings.enabled() || self.unavailable {
295 return;
296 }
297 if self.blur.is_none() {
298 match BackgroundBlur::new() {
299 Ok(blur) => self.blur = Some(blur),
300 Err(_) => {
301 self.unavailable = true;
302 return;
303 }
304 }
305 }
305 pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
306 306 self.refresh_covered(width, height);
307 if let Some(blur) = self.blur.as_mut() {
308 blur.apply(rgba, width, height, self.covered.as_ref().map(|covered| covered.rgb.as_slice()));
309 self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);
307 match &self.covered {
308 Some(covered) => compose_image(rgba, width, height, mask, &covered.rgb),
309 None => compose(rgba, width, height, mask),
310 310 }
311 311 }
312
313 pub fn apply_i420(&mut self, buffer: I420Buffer) -> I420Buffer {
314 if !self.settings.enabled() || self.unavailable {
315 return buffer;
316 }
317 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
318 let (stride_y, stride_u, stride_v) = buffer.strides();
319 let (plane_y, plane_u, plane_v) = buffer.data();
320 let mut rgba = vec![0u8; width * height * CHANNELS];
321 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * CHANNELS) as u32, width as i32, height as i32);
322 self.apply_rgba(&mut rgba, width, height);
323 i420_from_rgba(&rgba, width as u32, height as u32)
324 }
325 312 }
326 313
327 /// Background blur for camera frames: segments every `stride` frames and slows down when inference is slow.
328 pub struct BackgroundBlur {
314 /// One segmentation mask for every effect: segments every `stride` frames and slows down when inference is slow.
315 pub struct MaskSource {
329 316 segmenter: Segmenter,
330 317 mask: Vec<f32>,
331 318 frames: u64,
332 319 stride: u64,
333 average_ms: f64,
334 processed: u64,
335 320 }
336 321
337 impl BackgroundBlur {
322 impl MaskSource {
338 323 pub fn new() -> Result<Self> {
339 Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })
324 Ok(MaskSource { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1 })
340 325 }
341 326
342 pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize, covered: Option<&[u8]>) {
343 let started = Instant::now();
344 if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {
345 self.segment(rgba, width, height, started);
346 }
347 self.frames += 1;
348 match covered {
349 Some(covered) => compose_image(rgba, width, height, &self.mask, covered),
350 None => compose(rgba, width, height, &self.mask),
351 }
352 let elapsed = started.elapsed().as_secs_f64() * 1000.;
353 self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };
354 self.processed += 1;
327 pub fn due(&self) -> bool {
328 self.frames.is_multiple_of(self.stride) || self.mask.is_empty()
355 329 }
356 330
357 fn segment(&mut self, rgba: &[u8], width: usize, height: usize, started: Instant) {
358 let Ok(fresh) = self.segmenter.mask(rgba, width, height) else {
359 return;
331 pub fn mask(&self) -> &[f32] {
332 &self.mask
333 }
334
335 /// Call once per frame; `rgba` is only read when `due`. Answers whether the mask changed.
336 pub fn refresh(&mut self, rgba: impl FnOnce() -> (Vec<u8>, usize, usize)) -> bool {
337 let due = self.due();
338 self.frames += 1;
339 if !due {
340 return false;
341 }
342 let (rgba, width, height) = rgba();
343 let started = Instant::now();
344 let Ok(fresh) = self.segmenter.mask(&rgba, width, height) else {
345 return false;
360 346 };
361 347 let inference = started.elapsed();
362 348 self.stride = if inference > VERY_SLOW_INFERENCE {
@@ -368,15 +354,12 @@ impl BackgroundBlur {
368 354 };
369 355 if self.mask.is_empty() {
370 356 self.mask = fresh;
371 return;
357 return true;
372 358 }
373 359 for (current, new) in self.mask.iter_mut().zip(fresh) {
374 360 *current += (new - *current) * (1. - MASK_SMOOTHING);
375 361 }
376 }
377
378 pub fn average_ms(&self) -> f64 {
379 self.average_ms
362 true
380 363 }
381 364 }
382 365
@@ -496,12 +479,13 @@ mod tests {
496 479 }
497 480
498 481 #[test]
499 fn the_blur_keeps_a_running_average_and_a_mask() {
500 let mut blur = BackgroundBlur::new().expect("model loads");
501 let mut frame = checkerboard();
502 blur.apply(&mut frame, WIDTH, HEIGHT, None);
503 blur.apply(&mut frame, WIDTH, HEIGHT, None);
504 assert!(blur.average_ms() > 0.);
505 assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);
482 fn the_mask_source_segments_when_due_and_keeps_one_mask() {
483 let mut source = MaskSource::new().expect("model loads");
484 let frame = || (checkerboard(), WIDTH, HEIGHT);
485 assert!(source.refresh(frame));
486 assert_eq!(source.mask().len(), MASK_WIDTH * MASK_HEIGHT);
487 source.stride = 3;
488 assert!(!source.due());
489 assert!(!source.refresh(|| unreachable!("a skipped frame is not read")));
506 490 }
507 491 }
@@ -3,12 +3,10 @@ use std::sync::{Arc, Mutex};
3use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
3use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
4use std::time::{Duration, Instant};
4use std::time::{Duration, Instant};
5
5
6use libwebrtc::native::yuv_helper::i420_to_abgr;
7use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
8use tract_onnx::prelude::*;
6use tract_onnx::prelude::*;
9
7
10use crate::background::BackgroundPicture;
8use crate::background::BackgroundPicture;
11use crate::camera::i420_from_rgba;
9use crate::effects::CameraEffects;
12use crate::error::{Error, Result};
10use crate::error::{Error, Result};
13
11
14const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
12const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");
@@ -24,7 +22,6 @@ const OPAQUE: f32 = 0.985;
24const MASK_SMOOTHING: f32 = 0.35;
22const MASK_SMOOTHING: f32 = 0.35;
25const SLOW_INFERENCE: Duration = Duration::from_millis(22);
23const SLOW_INFERENCE: Duration = Duration::from_millis(22);
26const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
24const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);
27const AVERAGE_WEIGHT: f64 = 0.1;
28const MAX_BANDS: usize = 4;
25const MAX_BANDS: usize = 4;
29
26
30type Plan = std::sync::Arc<TypedRunnableModel>;
27type Plan = std::sync::Arc<TypedRunnableModel>;
@@ -84,13 +81,13 @@ fn smoothstep(value: f32) -> f32 {
84 t * t * (3. - 2. * t)
81 t * t * (3. - 2. * t)
85}
82}
86
83
87struct Axis {
84pub(crate) struct Axis {
88 first: Vec<usize>,
85 pub(crate) first: Vec<usize>,
89 second: Vec<usize>,
86 pub(crate) second: Vec<usize>,
90 weight: Vec<f32>,
87 pub(crate) weight: Vec<f32>,
91}
88}
92
89
93fn axis(output: usize, input: usize) -> Axis {
90pub(crate) fn axis(output: usize, input: usize) -> Axis {
94 let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };
91 let mut axis = Axis { first: Vec::with_capacity(output), second: Vec::with_capacity(output), weight: Vec::with_capacity(output) };
95 for index in 0..output {
92 for index in 0..output {
96 let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);
93 let position = ((index as f32 + 0.5) * input as f32 / output as f32 - 0.5).clamp(0., (input - 1) as f32);
@@ -234,6 +231,7 @@ pub struct BlurSettings {
234 enabled: AtomicBool,
231 enabled: AtomicBool,
235 average_micros: AtomicU32,
232 average_micros: AtomicU32,
236 picture: Mutex<Option<Arc<BackgroundPicture>>>,
233 picture: Mutex<Option<Arc<BackgroundPicture>>>,
234 effects: Mutex<CameraEffects>,
237}
235}
238
236
239impl BlurSettings {
237impl BlurSettings {
@@ -253,16 +251,30 @@ impl BlurSettings {
253 self.picture.lock().expect("picture lock").clone()
251 self.picture.lock().expect("picture lock").clone()
254 }
252 }
255
253
254 pub fn set_effects(&self, effects: CameraEffects) {
255 *self.effects.lock().expect("effects lock") = effects;
256 }
257
258 pub fn effects(&self) -> CameraEffects {
259 *self.effects.lock().expect("effects lock")
260 }
261
262 pub fn active(&self) -> bool {
263 self.enabled() || self.effects().alters_frame()
264 }
265
256 pub fn average_ms(&self) -> f32 {
266 pub fn average_ms(&self) -> f32 {
257 self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
267 self.average_micros.load(Ordering::Relaxed) as f32 / 1000.
258 }
268 }
269
270 pub fn set_average_ms(&self, average_ms: f64) {
271 self.average_micros.store((average_ms * 1000.) as u32, Ordering::Relaxed);
272 }
259}
273}
260
274
261/// Runs on the capture thread; loads the model on first use and stays out of the way while the setting is off.
275/// Replaces the background of a frame; the mask comes from the shared `MaskSource`.
262pub struct BlurStage {
276pub struct BlurStage {
263 settings: Arc<BlurSettings>,
277 settings: Arc<BlurSettings>,
264 blur: Option<BackgroundBlur>,
265 unavailable: bool,
266 covered: Option<CoveredPicture>,
278 covered: Option<CoveredPicture>,
267}
279}
268
280
@@ -275,7 +287,7 @@ struct CoveredPicture {
275
287
276impl BlurStage {
288impl BlurStage {
277 pub fn new(settings: Arc<BlurSettings>) -> Self {
289 pub fn new(settings: Arc<BlurSettings>) -> Self {
278 BlurStage { settings, blur: None, unavailable: false, covered: None }
290 BlurStage { settings, covered: None }
279 }
291 }
280
292
281 fn refresh_covered(&mut self, width: usize, height: usize) {
293 fn refresh_covered(&mut self, width: usize, height: usize) {
@@ -290,73 +302,47 @@ impl BlurStage {
290 }
302 }
291 }
303 }
292
304
293 pub fn apply_rgba(&mut self, rgba: &mut [u8], width: usize, height: usize) {
305 pub fn compose(&mut self, rgba: &mut [u8], width: usize, height: usize, mask: &[f32]) {
294 if !self.settings.enabled() || self.unavailable {
295 return;
296 }
297 if self.blur.is_none() {
298 match BackgroundBlur::new() {
299 Ok(blur) => self.blur = Some(blur),
300 Err(_) => {
301 self.unavailable = true;
302 return;
303 }
304 }
305 }
306 self.refresh_covered(width, height);
306 self.refresh_covered(width, height);
307 if let Some(blur) = self.blur.as_mut() {
307 match &self.covered {
308 blur.apply(rgba, width, height, self.covered.as_ref().map(|covered| covered.rgb.as_slice()));
308 Some(covered) => compose_image(rgba, width, height, mask, &covered.rgb),
309 self.settings.average_micros.store((blur.average_ms() * 1000.) as u32, Ordering::Relaxed);
309 None => compose(rgba, width, height, mask),
310 }
310 }
311 }
311 }
312
313 pub fn apply_i420(&mut self, buffer: I420Buffer) -> I420Buffer {
314 if !self.settings.enabled() || self.unavailable {
315 return buffer;
316 }
317 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
318 let (stride_y, stride_u, stride_v) = buffer.strides();
319 let (plane_y, plane_u, plane_v) = buffer.data();
320 let mut rgba = vec![0u8; width * height * CHANNELS];
321 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * CHANNELS) as u32, width as i32, height as i32);
322 self.apply_rgba(&mut rgba, width, height);
323 i420_from_rgba(&rgba, width as u32, height as u32)
324 }
325}
312}
326
313
327/// Background blur for camera frames: segments every `stride` frames and slows down when inference is slow.
314/// One segmentation mask for every effect: segments every `stride` frames and slows down when inference is slow.
328pub struct BackgroundBlur {
315pub struct MaskSource {
329 segmenter: Segmenter,
316 segmenter: Segmenter,
330 mask: Vec<f32>,
317 mask: Vec<f32>,
331 frames: u64,
318 frames: u64,
332 stride: u64,
319 stride: u64,
333 average_ms: f64,
334 processed: u64,
335}
320}
336
321
337impl BackgroundBlur {
322impl MaskSource {
338 pub fn new() -> Result<Self> {
323 pub fn new() -> Result<Self> {
339 Ok(BackgroundBlur { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1, average_ms: 0., processed: 0 })
324 Ok(MaskSource { segmenter: Segmenter::new()?, mask: Vec::new(), frames: 0, stride: 1 })
340 }
325 }
341
326
342 pub fn apply(&mut self, rgba: &mut [u8], width: usize, height: usize, covered: Option<&[u8]>) {
327 pub fn due(&self) -> bool {
343 let started = Instant::now();
328 self.frames.is_multiple_of(self.stride) || self.mask.is_empty()
344 if self.frames.is_multiple_of(self.stride) || self.mask.is_empty() {
345 self.segment(rgba, width, height, started);
346 }
347 self.frames += 1;
348 match covered {
349 Some(covered) => compose_image(rgba, width, height, &self.mask, covered),
350 None => compose(rgba, width, height, &self.mask),
351 }
352 let elapsed = started.elapsed().as_secs_f64() * 1000.;
353 self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };
354 self.processed += 1;
355 }
329 }
356
330
357 fn segment(&mut self, rgba: &[u8], width: usize, height: usize, started: Instant) {
331 pub fn mask(&self) -> &[f32] {
358 let Ok(fresh) = self.segmenter.mask(rgba, width, height) else {
332 &self.mask
359 return;
333 }
334
335 /// Call once per frame; `rgba` is only read when `due`. Answers whether the mask changed.
336 pub fn refresh(&mut self, rgba: impl FnOnce() -> (Vec<u8>, usize, usize)) -> bool {
337 let due = self.due();
338 self.frames += 1;
339 if !due {
340 return false;
341 }
342 let (rgba, width, height) = rgba();
343 let started = Instant::now();
344 let Ok(fresh) = self.segmenter.mask(&rgba, width, height) else {
345 return false;
360 };
346 };
361 let inference = started.elapsed();
347 let inference = started.elapsed();
362 self.stride = if inference > VERY_SLOW_INFERENCE {
348 self.stride = if inference > VERY_SLOW_INFERENCE {
@@ -368,15 +354,12 @@ impl BackgroundBlur {
368 };
354 };
369 if self.mask.is_empty() {
355 if self.mask.is_empty() {
370 self.mask = fresh;
356 self.mask = fresh;
371 return;
357 return true;
372 }
358 }
373 for (current, new) in self.mask.iter_mut().zip(fresh) {
359 for (current, new) in self.mask.iter_mut().zip(fresh) {
374 *current += (new - *current) * (1. - MASK_SMOOTHING);
360 *current += (new - *current) * (1. - MASK_SMOOTHING);
375 }
361 }
376 }
362 true
377
378 pub fn average_ms(&self) -> f64 {
379 self.average_ms
380 }
363 }
381}
364}
382
365
@@ -496,12 +479,13 @@ mod tests {
496 }
479 }
497
480
498 #[test]
481 #[test]
499 fn the_blur_keeps_a_running_average_and_a_mask() {
482 fn the_mask_source_segments_when_due_and_keeps_one_mask() {
500 let mut blur = BackgroundBlur::new().expect("model loads");
483 let mut source = MaskSource::new().expect("model loads");
501 let mut frame = checkerboard();
484 let frame = || (checkerboard(), WIDTH, HEIGHT);
502 blur.apply(&mut frame, WIDTH, HEIGHT, None);
485 assert!(source.refresh(frame));
503 blur.apply(&mut frame, WIDTH, HEIGHT, None);
486 assert_eq!(source.mask().len(), MASK_WIDTH * MASK_HEIGHT);
504 assert!(blur.average_ms() > 0.);
487 source.stride = 3;
505 assert_eq!(blur.mask.len(), MASK_WIDTH * MASK_HEIGHT);
488 assert!(!source.due());
489 assert!(!source.refresh(|| unreachable!("a skipped frame is not read")));
506 }
490 }
507}
491}
crates/calling/src/call.rs +1 −0
@@ -1535,6 +1535,7 @@ async fn drive(
1535 1535 send_receive_change(control, video.reselect(&roster));
1536 1536 control.send(CallUpdate::IncomingVideo(enabled));
1537 1537 }
1538 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1538 1539 Some(CallCommand::SendReaction(reaction)) => {
1539 1540 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1540 1541 timeline.record("reaction failed", error.to_string());
@@ -1535,6 +1535,7 @@ async fn drive(
1535 send_receive_change(control, video.reselect(&roster));
1535 send_receive_change(control, video.reselect(&roster));
1536 control.send(CallUpdate::IncomingVideo(enabled));
1536 control.send(CallUpdate::IncomingVideo(enabled));
1537 }
1537 }
1538 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1538 Some(CallCommand::SendReaction(reaction)) => {
1539 Some(CallCommand::SendReaction(reaction)) => {
1539 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1540 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1540 timeline.record("reaction failed", error.to_string());
1541 timeline.record("reaction failed", error.to_string());
crates/calling/src/camera.rs +14 −15
@@ -8,7 +8,8 @@ use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, Requeste
8 8 use nokhwa::{Camera, query};
9 9 use std::sync::atomic::Ordering;
10 10
11 use crate::blur::{BlurSettings, BlurStage};
11 use crate::blur::BlurSettings;
12 use crate::effects::EffectsStage;
12 13 use crate::capture::Capture;
13 14 use crate::devices::{DeviceChoice, DeviceEntry};
14 15 use crate::error::{Error, Result};
@@ -176,7 +177,7 @@ pub fn start_camera(
176 177 Ok(camera) => camera,
177 178 Err(error) => return failed(error.to_string()),
178 179 };
179 let mut blur_stage = BlurStage::new(blur.clone());
180 let mut stage = EffectsStage::new(blur);
180 181 let mut warned_undecodable = false;
181 182 while !stop.load(Ordering::SeqCst) {
182 183 let Ok(frame) = camera.frame() else {
@@ -188,21 +189,19 @@ pub fn start_camera(
188 189 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
189 190 continue;
190 191 }
191 if !blur.enabled()
192 && let Some(buffer) = direct_i420(frame.source_frame_format(), frame.buffer(), width, height)
193 {
194 deliver(buffer);
195 continue;
196 }
197 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
198 if !std::mem::replace(&mut warned_undecodable, true) {
199 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
192 let buffer = match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
193 Some(buffer) => buffer,
194 None => {
195 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
196 if !std::mem::replace(&mut warned_undecodable, true) {
197 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
198 }
199 continue;
200 };
201 i420_from_rgba(&decoded.into_raw(), width, height)
200 202 }
201 continue;
202 203 };
203 let mut rgba = decoded.into_raw();
204 blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
205 deliver(i420_from_rgba(&rgba, width, height));
204 deliver(stage.apply_i420(buffer));
206 205 }
207 206 let _ = camera.stop_stream();
208 207 })
@@ -8,7 +8,8 @@ use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, Requeste
8use nokhwa::{Camera, query};
8use nokhwa::{Camera, query};
9use std::sync::atomic::Ordering;
9use std::sync::atomic::Ordering;
10
10
11use crate::blur::{BlurSettings, BlurStage};
11use crate::blur::BlurSettings;
12use crate::effects::EffectsStage;
12use crate::capture::Capture;
13use crate::capture::Capture;
13use crate::devices::{DeviceChoice, DeviceEntry};
14use crate::devices::{DeviceChoice, DeviceEntry};
14use crate::error::{Error, Result};
15use crate::error::{Error, Result};
@@ -176,7 +177,7 @@ pub fn start_camera(
176 Ok(camera) => camera,
177 Ok(camera) => camera,
177 Err(error) => return failed(error.to_string()),
178 Err(error) => return failed(error.to_string()),
178 };
179 };
179 let mut blur_stage = BlurStage::new(blur.clone());
180 let mut stage = EffectsStage::new(blur);
180 let mut warned_undecodable = false;
181 let mut warned_undecodable = false;
181 while !stop.load(Ordering::SeqCst) {
182 while !stop.load(Ordering::SeqCst) {
182 let Ok(frame) = camera.frame() else {
183 let Ok(frame) = camera.frame() else {
@@ -188,21 +189,19 @@ pub fn start_camera(
188 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
189 if width < 2 || height < 2 || width % 2 != 0 || height % 2 != 0 {
189 continue;
190 continue;
190 }
191 }
191 if !blur.enabled()
192 let buffer = match direct_i420(frame.source_frame_format(), frame.buffer(), width, height) {
192 && let Some(buffer) = direct_i420(frame.source_frame_format(), frame.buffer(), width, height)
193 Some(buffer) => buffer,
193 {
194 None => {
194 deliver(buffer);
195 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
195 continue;
196 if !std::mem::replace(&mut warned_undecodable, true) {
196 }
197 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
197 let Ok(decoded) = frame.decode_image::<RgbAFormat>() else {
198 }
198 if !std::mem::replace(&mut warned_undecodable, true) {
199 continue;
199 eprintln!("calls: camera delivers {} and no decoder is available", frame.source_frame_format());
200 };
201 i420_from_rgba(&decoded.into_raw(), width, height)
200 }
202 }
201 continue;
202 };
203 };
203 let mut rgba = decoded.into_raw();
204 deliver(stage.apply_i420(buffer));
204 blur_stage.apply_rgba(&mut rgba, width as usize, height as usize);
205 deliver(i420_from_rgba(&rgba, width, height));
206 }
205 }
207 let _ = camera.stop_stream();
206 let _ = camera.stop_stream();
208 })
207 })
crates/calling/src/control.rs +2 −0
@@ -4,6 +4,7 @@ use std::sync::Arc;
4 4 use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
5 5
6 6 use crate::background::BackgroundChoice;
7 use crate::effects::CameraEffects;
7 8 use crate::breakout::BreakoutMove;
8 9 use crate::captions::{CaptionEntry, CaptionState};
9 10 use crate::devices::{DeviceChoice, DeviceLists};
@@ -48,6 +49,7 @@ pub enum CallCommand {
48 49 SetCaptions(bool),
49 50 SetBackground(BackgroundChoice),
50 51 SetIncomingVideo(bool),
52 SetCameraEffects(CameraEffects),
51 53 SendReaction(Reaction),
52 54 SetRecording { on: bool, title: String },
53 55 ConsentToRecording,
@@ -4,6 +4,7 @@ use std::sync::Arc;
4use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
4use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
5
5
6use crate::background::BackgroundChoice;
6use crate::background::BackgroundChoice;
7use crate::effects::CameraEffects;
7use crate::breakout::BreakoutMove;
8use crate::breakout::BreakoutMove;
8use crate::captions::{CaptionEntry, CaptionState};
9use crate::captions::{CaptionEntry, CaptionState};
9use crate::devices::{DeviceChoice, DeviceLists};
10use crate::devices::{DeviceChoice, DeviceLists};
@@ -48,6 +49,7 @@ pub enum CallCommand {
48 SetCaptions(bool),
49 SetCaptions(bool),
49 SetBackground(BackgroundChoice),
50 SetBackground(BackgroundChoice),
50 SetIncomingVideo(bool),
51 SetIncomingVideo(bool),
52 SetCameraEffects(CameraEffects),
51 SendReaction(Reaction),
53 SendReaction(Reaction),
52 SetRecording { on: bool, title: String },
54 SetRecording { on: bool, title: String },
53 ConsentToRecording,
55 ConsentToRecording,
crates/calling/src/effects.rs added +284 −0
@@ -0,0 +1,284 @@
1 use std::sync::Arc;
2 use std::time::{Duration, Instant};
3
4 use libwebrtc::native::yuv_helper::i420_to_abgr;
5 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6
7 use crate::blur::{BlurSettings, BlurStage, MASK_HEIGHT, MASK_WIDTH, MaskSource};
8 use crate::camera::i420_from_rgba;
9 use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};
10 use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};
11
12 pub const SOFT_FOCUS_DEFAULT: u8 = 50;
13 const MASK_INPUT_WIDTH: u32 = 512;
14 const RGBA_BYTES: usize = 4;
15 const AVERAGE_WEIGHT: f64 = 0.1;
16 const FIRST_FRAME_GAP: Duration = Duration::from_millis(33);
17 const GAMMA_NEUTRAL: f32 = 1.;
18 const GAMMA_VISIBLE: f32 = 0.01;
19
20 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
21 pub struct CameraEffects {
22 pub mirror: bool,
23 pub auto_framing: bool,
24 pub adjust_brightness: bool,
25 pub soft_focus: bool,
26 pub soft_focus_strength: u8,
27 }
28
29 impl Default for CameraEffects {
30 fn default() -> Self {
31 CameraEffects { mirror: true, auto_framing: false, adjust_brightness: false, soft_focus: false, soft_focus_strength: SOFT_FOCUS_DEFAULT }
32 }
33 }
34
35 impl CameraEffects {
36 pub fn needs_mask(&self) -> bool {
37 self.auto_framing || self.soft_focus
38 }
39
40 pub fn alters_frame(&self) -> bool {
41 self.auto_framing || self.adjust_brightness || self.soft_focus
42 }
43
44 pub fn to_meta(&self) -> String {
45 format!("mirror={},framing={},brightness={},soft_focus={},strength={}", u8::from(self.mirror), u8::from(self.auto_framing), u8::from(self.adjust_brightness), u8::from(self.soft_focus), self.soft_focus_strength)
46 }
47
48 pub fn from_meta(value: &str) -> Self {
49 let mut effects = CameraEffects::default();
50 for (key, setting) in value.split(',').filter_map(|part| part.split_once('=')) {
51 match key {
52 "mirror" => effects.mirror = setting == "1",
53 "framing" => effects.auto_framing = setting == "1",
54 "brightness" => effects.adjust_brightness = setting == "1",
55 "soft_focus" => effects.soft_focus = setting == "1",
56 "strength" => effects.soft_focus_strength = setting.parse().map_or(SOFT_FOCUS_DEFAULT, |strength: u8| strength.min(100)),
57 _ => {}
58 }
59 }
60 effects
61 }
62 }
63
64 /// Runs on the capture thread: brightness, soft focus, background and auto framing share one mask per frame.
65 pub struct EffectsStage {
66 settings: Arc<BlurSettings>,
67 blur: BlurStage,
68 masks: Option<MaskSource>,
69 unavailable: bool,
70 subject: Option<Subject>,
71 planner: CropPlanner,
72 gamma: f32,
73 previous_frame: Option<Instant>,
74 processed: u64,
75 average_ms: f64,
76 }
77
78 impl EffectsStage {
79 pub fn new(settings: Arc<BlurSettings>) -> Self {
80 EffectsStage {
81 blur: BlurStage::new(settings.clone()),
82 settings,
83 masks: None,
84 unavailable: false,
85 subject: None,
86 planner: CropPlanner::default(),
87 gamma: GAMMA_NEUTRAL,
88 previous_frame: None,
89 processed: 0,
90 average_ms: 0.,
91 }
92 }
93
94 pub fn apply_i420(&mut self, mut buffer: I420Buffer) -> I420Buffer {
95 let effects = self.settings.effects();
96 let blur = self.settings.enabled();
97 if !blur && !effects.alters_frame() {
98 self.previous_frame = None;
99 return buffer;
100 }
101 let started = Instant::now();
102 let elapsed = self.previous_frame.replace(started).map_or(FIRST_FRAME_GAP, |previous| started.duration_since(previous));
103 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
104 if effects.adjust_brightness {
105 self.adjust_brightness(&mut buffer, width, height, elapsed);
106 }
107 if (blur || effects.needs_mask()) && self.load_masks() {
108 self.refresh_mask(&mut buffer, effects.auto_framing);
109 if effects.soft_focus {
110 self.soften(&mut buffer, width, height, effects.soft_focus_strength);
111 }
112 if blur {
113 buffer = self.compose_background(buffer, width, height);
114 }
115 }
116 buffer = self.frame(buffer, effects.auto_framing, elapsed);
117 self.record(started);
118 buffer
119 }
120
121 fn adjust_brightness(&mut self, buffer: &mut I420Buffer, width: usize, height: usize, elapsed: Duration) {
122 let stride = buffer.strides().0 as usize;
123 let plane = buffer.data_mut().0;
124 let target = target_gamma(mean_luma(plane, stride, width, height));
125 self.gamma = smooth_gamma(self.gamma, target, elapsed);
126 if (self.gamma - GAMMA_NEUTRAL).abs() > GAMMA_VISIBLE {
127 apply_table(plane, stride, width, height, &gamma_table(self.gamma));
128 }
129 }
130
131 fn load_masks(&mut self) -> bool {
132 if self.masks.is_none() && !self.unavailable {
133 match MaskSource::new() {
134 Ok(masks) => self.masks = Some(masks),
135 Err(_) => self.unavailable = true,
136 }
137 }
138 !self.unavailable
139 }
140
141 fn refresh_mask(&mut self, buffer: &mut I420Buffer, track_subject: bool) {
142 let Some(masks) = self.masks.as_mut() else { return };
143 let fresh = masks.refresh(|| mask_input(buffer));
144 if track_subject && fresh {
145 self.subject = find_subject(masks.mask(), MASK_WIDTH, MASK_HEIGHT);
146 }
147 }
148
149 fn soften(&self, buffer: &mut I420Buffer, width: usize, height: usize, strength: u8) {
150 let Some(masks) = self.masks.as_ref().filter(|masks| !masks.mask().is_empty()) else { return };
151 let stride = buffer.strides().0 as usize;
152 soften_luma(buffer.data_mut().0, stride, width, height, masks.mask(), strength);
153 }
154
155 fn compose_background(&mut self, buffer: I420Buffer, width: usize, height: usize) -> I420Buffer {
156 let Some(masks) = self.masks.as_ref().filter(|masks| !masks.mask().is_empty()) else { return buffer };
157 let (stride_y, stride_u, stride_v) = buffer.strides();
158 let (plane_y, plane_u, plane_v) = buffer.data();
159 let mut rgba = vec![0u8; width * height * RGBA_BYTES];
160 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * RGBA_BYTES) as u32, width as i32, height as i32);
161 self.blur.compose(&mut rgba, width, height, masks.mask());
162 i420_from_rgba(&rgba, width as u32, height as u32)
163 }
164
165 fn frame(&mut self, buffer: I420Buffer, auto_framing: bool, elapsed: Duration) -> I420Buffer {
166 if !auto_framing {
167 self.planner.reset();
168 self.subject = None;
169 return buffer;
170 }
171 let crop = self.planner.advance(self.subject.as_ref(), elapsed);
172 if is_full_frame(&crop) { buffer } else { crop_and_scale(&buffer, &crop) }
173 }
174
175 fn record(&mut self, started: Instant) {
176 let elapsed = started.elapsed().as_secs_f64() * 1000.;
177 self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };
178 self.processed += 1;
179 self.settings.set_average_ms(self.average_ms);
180 }
181 }
182
183 fn mask_input(buffer: &mut I420Buffer) -> (Vec<u8>, usize, usize) {
184 let (width, height) = (buffer.width(), buffer.height());
185 let small_width = width.min(MASK_INPUT_WIDTH) & !1;
186 let small_height = (u64::from(height) * u64::from(small_width) / u64::from(width)) as u32 & !1;
187 let small = if (small_width, small_height) == (width, height) { None } else { Some(buffer.scale(small_width as i32, small_height as i32)) };
188 let source = small.as_ref().unwrap_or(buffer);
189 let (stride_y, stride_u, stride_v) = source.strides();
190 let (plane_y, plane_u, plane_v) = source.data();
191 let mut rgba = vec![0u8; small_width as usize * small_height as usize * RGBA_BYTES];
192 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, small_width * RGBA_BYTES as u32, small_width as i32, small_height as i32);
193 (rgba, small_width as usize, small_height as usize)
194 }
195
196 #[cfg(test)]
197 mod tests {
198 use super::*;
199
200 #[test]
201 fn the_defaults_mirror_the_self_view_and_leave_the_stream_untouched() {
202 let effects = CameraEffects::default();
203 assert!(effects.mirror && !effects.alters_frame() && !effects.needs_mask());
204 assert_eq!(effects.soft_focus_strength, 50);
205 }
206
207 #[test]
208 fn the_effects_survive_a_round_trip_through_the_meta_text() {
209 let effects = CameraEffects { mirror: false, auto_framing: true, adjust_brightness: true, soft_focus: true, soft_focus_strength: 80 };
210 assert_eq!(CameraEffects::from_meta(&effects.to_meta()), effects);
211 assert_eq!(CameraEffects::from_meta(""), CameraEffects::default());
212 assert_eq!(CameraEffects::from_meta("strength=900,junk").soft_focus_strength, SOFT_FOCUS_DEFAULT);
213 }
214
215 #[test]
216 fn only_framing_and_soft_focus_need_the_segmenter() {
217 let framing = CameraEffects { auto_framing: true, ..CameraEffects::default() };
218 let brightness = CameraEffects { adjust_brightness: true, ..CameraEffects::default() };
219 assert!(framing.needs_mask() && framing.alters_frame());
220 assert!(!brightness.needs_mask() && brightness.alters_frame());
221 }
222
223 #[test]
224 fn an_idle_stage_hands_the_frame_back_untouched() {
225 let settings = Arc::new(BlurSettings::default());
226 let mut stage = EffectsStage::new(settings.clone());
227 let mut buffer = I420Buffer::new(64, 36);
228 buffer.data_mut().0.fill(77);
229 let out = stage.apply_i420(buffer);
230 assert!(out.data().0.iter().all(|&value| value == 77));
231 settings.set_effects(CameraEffects { adjust_brightness: true, ..CameraEffects::default() });
232 let mut dark = I420Buffer::new(64, 36);
233 dark.data_mut().0.fill(30);
234 let mut brightened = stage.apply_i420(dark);
235 for _ in 0..200 {
236 let mut again = I420Buffer::new(64, 36);
237 again.data_mut().0.fill(30);
238 brightened = stage.apply_i420(again);
239 }
240 assert!(brightened.data().0[0] > 30);
241 }
242
243 fn timed<T>(label: &str, mut work: impl FnMut() -> T) -> f64 {
244 let runs = 20;
245 let started = Instant::now();
246 for _ in 0..runs {
247 std::hint::black_box(work());
248 }
249 let millis = started.elapsed().as_secs_f64() * 1000. / f64::from(runs);
250 eprintln!("{label}: {millis:.2} ms per 720p frame");
251 millis
252 }
253
254 #[test]
255 #[ignore = "timing, run with --release --ignored --nocapture"]
256 fn every_effect_stays_inside_the_frame_budget_at_720p() {
257 let mut buffer = I420Buffer::new(1280, 720);
258 buffer.data_mut().0.iter_mut().enumerate().for_each(|(index, value)| *value = (index % 200) as u8 + 20);
259 let mask: Vec<f32> = (0..MASK_WIDTH * MASK_HEIGHT)
260 .map(|index| {
261 let (x, y) = ((index % MASK_WIDTH) as f32 / MASK_WIDTH as f32 - 0.5, (index / MASK_WIDTH) as f32 / MASK_HEIGHT as f32 - 0.5);
262 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
263 })
264 .collect();
265 let crop = crate::framing::Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
266 let total = [
267 timed("brightness", || {
268 let mut copy = I420Buffer::new(1280, 720);
269 apply_table(copy.data_mut().0, 1280, 1280, 720, &gamma_table(0.7));
270 }),
271 timed("soft focus", || {
272 let mut copy = I420Buffer::new(1280, 720);
273 soften_luma(copy.data_mut().0, 1280, 1280, 720, &mask, 100);
274 }),
275 timed("mask input", || mask_input(&mut buffer)),
276 timed("subject", || find_subject(&mask, MASK_WIDTH, MASK_HEIGHT)),
277 timed("crop and scale", || crop_and_scale(&buffer, &crop)),
278 ]
279 .iter()
280 .sum::<f64>();
281 eprintln!("sum without segmentation: {total:.2} ms");
282 assert!(total < 33.);
283 }
284 }
@@ -0,0 +1,284 @@
1use std::sync::Arc;
2use std::time::{Duration, Instant};
3
4use libwebrtc::native::yuv_helper::i420_to_abgr;
5use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6
7use crate::blur::{BlurSettings, BlurStage, MASK_HEIGHT, MASK_WIDTH, MaskSource};
8use crate::camera::i420_from_rgba;
9use crate::framing::{CropPlanner, Subject, crop_and_scale, find_subject, is_full_frame};
10use crate::luma_effects::{apply_table, gamma_table, mean_luma, smooth_gamma, soften_luma, target_gamma};
11
12pub const SOFT_FOCUS_DEFAULT: u8 = 50;
13const MASK_INPUT_WIDTH: u32 = 512;
14const RGBA_BYTES: usize = 4;
15const AVERAGE_WEIGHT: f64 = 0.1;
16const FIRST_FRAME_GAP: Duration = Duration::from_millis(33);
17const GAMMA_NEUTRAL: f32 = 1.;
18const GAMMA_VISIBLE: f32 = 0.01;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct CameraEffects {
22 pub mirror: bool,
23 pub auto_framing: bool,
24 pub adjust_brightness: bool,
25 pub soft_focus: bool,
26 pub soft_focus_strength: u8,
27}
28
29impl Default for CameraEffects {
30 fn default() -> Self {
31 CameraEffects { mirror: true, auto_framing: false, adjust_brightness: false, soft_focus: false, soft_focus_strength: SOFT_FOCUS_DEFAULT }
32 }
33}
34
35impl CameraEffects {
36 pub fn needs_mask(&self) -> bool {
37 self.auto_framing || self.soft_focus
38 }
39
40 pub fn alters_frame(&self) -> bool {
41 self.auto_framing || self.adjust_brightness || self.soft_focus
42 }
43
44 pub fn to_meta(&self) -> String {
45 format!("mirror={},framing={},brightness={},soft_focus={},strength={}", u8::from(self.mirror), u8::from(self.auto_framing), u8::from(self.adjust_brightness), u8::from(self.soft_focus), self.soft_focus_strength)
46 }
47
48 pub fn from_meta(value: &str) -> Self {
49 let mut effects = CameraEffects::default();
50 for (key, setting) in value.split(',').filter_map(|part| part.split_once('=')) {
51 match key {
52 "mirror" => effects.mirror = setting == "1",
53 "framing" => effects.auto_framing = setting == "1",
54 "brightness" => effects.adjust_brightness = setting == "1",
55 "soft_focus" => effects.soft_focus = setting == "1",
56 "strength" => effects.soft_focus_strength = setting.parse().map_or(SOFT_FOCUS_DEFAULT, |strength: u8| strength.min(100)),
57 _ => {}
58 }
59 }
60 effects
61 }
62}
63
64/// Runs on the capture thread: brightness, soft focus, background and auto framing share one mask per frame.
65pub struct EffectsStage {
66 settings: Arc<BlurSettings>,
67 blur: BlurStage,
68 masks: Option<MaskSource>,
69 unavailable: bool,
70 subject: Option<Subject>,
71 planner: CropPlanner,
72 gamma: f32,
73 previous_frame: Option<Instant>,
74 processed: u64,
75 average_ms: f64,
76}
77
78impl EffectsStage {
79 pub fn new(settings: Arc<BlurSettings>) -> Self {
80 EffectsStage {
81 blur: BlurStage::new(settings.clone()),
82 settings,
83 masks: None,
84 unavailable: false,
85 subject: None,
86 planner: CropPlanner::default(),
87 gamma: GAMMA_NEUTRAL,
88 previous_frame: None,
89 processed: 0,
90 average_ms: 0.,
91 }
92 }
93
94 pub fn apply_i420(&mut self, mut buffer: I420Buffer) -> I420Buffer {
95 let effects = self.settings.effects();
96 let blur = self.settings.enabled();
97 if !blur && !effects.alters_frame() {
98 self.previous_frame = None;
99 return buffer;
100 }
101 let started = Instant::now();
102 let elapsed = self.previous_frame.replace(started).map_or(FIRST_FRAME_GAP, |previous| started.duration_since(previous));
103 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
104 if effects.adjust_brightness {
105 self.adjust_brightness(&mut buffer, width, height, elapsed);
106 }
107 if (blur || effects.needs_mask()) && self.load_masks() {
108 self.refresh_mask(&mut buffer, effects.auto_framing);
109 if effects.soft_focus {
110 self.soften(&mut buffer, width, height, effects.soft_focus_strength);
111 }
112 if blur {
113 buffer = self.compose_background(buffer, width, height);
114 }
115 }
116 buffer = self.frame(buffer, effects.auto_framing, elapsed);
117 self.record(started);
118 buffer
119 }
120
121 fn adjust_brightness(&mut self, buffer: &mut I420Buffer, width: usize, height: usize, elapsed: Duration) {
122 let stride = buffer.strides().0 as usize;
123 let plane = buffer.data_mut().0;
124 let target = target_gamma(mean_luma(plane, stride, width, height));
125 self.gamma = smooth_gamma(self.gamma, target, elapsed);
126 if (self.gamma - GAMMA_NEUTRAL).abs() > GAMMA_VISIBLE {
127 apply_table(plane, stride, width, height, &gamma_table(self.gamma));
128 }
129 }
130
131 fn load_masks(&mut self) -> bool {
132 if self.masks.is_none() && !self.unavailable {
133 match MaskSource::new() {
134 Ok(masks) => self.masks = Some(masks),
135 Err(_) => self.unavailable = true,
136 }
137 }
138 !self.unavailable
139 }
140
141 fn refresh_mask(&mut self, buffer: &mut I420Buffer, track_subject: bool) {
142 let Some(masks) = self.masks.as_mut() else { return };
143 let fresh = masks.refresh(|| mask_input(buffer));
144 if track_subject && fresh {
145 self.subject = find_subject(masks.mask(), MASK_WIDTH, MASK_HEIGHT);
146 }
147 }
148
149 fn soften(&self, buffer: &mut I420Buffer, width: usize, height: usize, strength: u8) {
150 let Some(masks) = self.masks.as_ref().filter(|masks| !masks.mask().is_empty()) else { return };
151 let stride = buffer.strides().0 as usize;
152 soften_luma(buffer.data_mut().0, stride, width, height, masks.mask(), strength);
153 }
154
155 fn compose_background(&mut self, buffer: I420Buffer, width: usize, height: usize) -> I420Buffer {
156 let Some(masks) = self.masks.as_ref().filter(|masks| !masks.mask().is_empty()) else { return buffer };
157 let (stride_y, stride_u, stride_v) = buffer.strides();
158 let (plane_y, plane_u, plane_v) = buffer.data();
159 let mut rgba = vec![0u8; width * height * RGBA_BYTES];
160 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, (width * RGBA_BYTES) as u32, width as i32, height as i32);
161 self.blur.compose(&mut rgba, width, height, masks.mask());
162 i420_from_rgba(&rgba, width as u32, height as u32)
163 }
164
165 fn frame(&mut self, buffer: I420Buffer, auto_framing: bool, elapsed: Duration) -> I420Buffer {
166 if !auto_framing {
167 self.planner.reset();
168 self.subject = None;
169 return buffer;
170 }
171 let crop = self.planner.advance(self.subject.as_ref(), elapsed);
172 if is_full_frame(&crop) { buffer } else { crop_and_scale(&buffer, &crop) }
173 }
174
175 fn record(&mut self, started: Instant) {
176 let elapsed = started.elapsed().as_secs_f64() * 1000.;
177 self.average_ms = if self.processed == 0 { elapsed } else { self.average_ms * (1. - AVERAGE_WEIGHT) + elapsed * AVERAGE_WEIGHT };
178 self.processed += 1;
179 self.settings.set_average_ms(self.average_ms);
180 }
181}
182
183fn mask_input(buffer: &mut I420Buffer) -> (Vec<u8>, usize, usize) {
184 let (width, height) = (buffer.width(), buffer.height());
185 let small_width = width.min(MASK_INPUT_WIDTH) & !1;
186 let small_height = (u64::from(height) * u64::from(small_width) / u64::from(width)) as u32 & !1;
187 let small = if (small_width, small_height) == (width, height) { None } else { Some(buffer.scale(small_width as i32, small_height as i32)) };
188 let source = small.as_ref().unwrap_or(buffer);
189 let (stride_y, stride_u, stride_v) = source.strides();
190 let (plane_y, plane_u, plane_v) = source.data();
191 let mut rgba = vec![0u8; small_width as usize * small_height as usize * RGBA_BYTES];
192 i420_to_abgr(plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, &mut rgba, small_width * RGBA_BYTES as u32, small_width as i32, small_height as i32);
193 (rgba, small_width as usize, small_height as usize)
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 #[test]
201 fn the_defaults_mirror_the_self_view_and_leave_the_stream_untouched() {
202 let effects = CameraEffects::default();
203 assert!(effects.mirror && !effects.alters_frame() && !effects.needs_mask());
204 assert_eq!(effects.soft_focus_strength, 50);
205 }
206
207 #[test]
208 fn the_effects_survive_a_round_trip_through_the_meta_text() {
209 let effects = CameraEffects { mirror: false, auto_framing: true, adjust_brightness: true, soft_focus: true, soft_focus_strength: 80 };
210 assert_eq!(CameraEffects::from_meta(&effects.to_meta()), effects);
211 assert_eq!(CameraEffects::from_meta(""), CameraEffects::default());
212 assert_eq!(CameraEffects::from_meta("strength=900,junk").soft_focus_strength, SOFT_FOCUS_DEFAULT);
213 }
214
215 #[test]
216 fn only_framing_and_soft_focus_need_the_segmenter() {
217 let framing = CameraEffects { auto_framing: true, ..CameraEffects::default() };
218 let brightness = CameraEffects { adjust_brightness: true, ..CameraEffects::default() };
219 assert!(framing.needs_mask() && framing.alters_frame());
220 assert!(!brightness.needs_mask() && brightness.alters_frame());
221 }
222
223 #[test]
224 fn an_idle_stage_hands_the_frame_back_untouched() {
225 let settings = Arc::new(BlurSettings::default());
226 let mut stage = EffectsStage::new(settings.clone());
227 let mut buffer = I420Buffer::new(64, 36);
228 buffer.data_mut().0.fill(77);
229 let out = stage.apply_i420(buffer);
230 assert!(out.data().0.iter().all(|&value| value == 77));
231 settings.set_effects(CameraEffects { adjust_brightness: true, ..CameraEffects::default() });
232 let mut dark = I420Buffer::new(64, 36);
233 dark.data_mut().0.fill(30);
234 let mut brightened = stage.apply_i420(dark);
235 for _ in 0..200 {
236 let mut again = I420Buffer::new(64, 36);
237 again.data_mut().0.fill(30);
238 brightened = stage.apply_i420(again);
239 }
240 assert!(brightened.data().0[0] > 30);
241 }
242
243 fn timed<T>(label: &str, mut work: impl FnMut() -> T) -> f64 {
244 let runs = 20;
245 let started = Instant::now();
246 for _ in 0..runs {
247 std::hint::black_box(work());
248 }
249 let millis = started.elapsed().as_secs_f64() * 1000. / f64::from(runs);
250 eprintln!("{label}: {millis:.2} ms per 720p frame");
251 millis
252 }
253
254 #[test]
255 #[ignore = "timing, run with --release --ignored --nocapture"]
256 fn every_effect_stays_inside_the_frame_budget_at_720p() {
257 let mut buffer = I420Buffer::new(1280, 720);
258 buffer.data_mut().0.iter_mut().enumerate().for_each(|(index, value)| *value = (index % 200) as u8 + 20);
259 let mask: Vec<f32> = (0..MASK_WIDTH * MASK_HEIGHT)
260 .map(|index| {
261 let (x, y) = ((index % MASK_WIDTH) as f32 / MASK_WIDTH as f32 - 0.5, (index / MASK_WIDTH) as f32 / MASK_HEIGHT as f32 - 0.5);
262 if (x * x) / 0.04 + (y * y) / 0.09 <= 1. { 1. } else { 0. }
263 })
264 .collect();
265 let crop = crate::framing::Crop { center_x: 0.5, center_y: 0.5, zoom: 1.6 };
266 let total = [
267 timed("brightness", || {
268 let mut copy = I420Buffer::new(1280, 720);
269 apply_table(copy.data_mut().0, 1280, 1280, 720, &gamma_table(0.7));
270 }),
271 timed("soft focus", || {
272 let mut copy = I420Buffer::new(1280, 720);
273 soften_luma(copy.data_mut().0, 1280, 1280, 720, &mask, 100);
274 }),
275 timed("mask input", || mask_input(&mut buffer)),
276 timed("subject", || find_subject(&mask, MASK_WIDTH, MASK_HEIGHT)),
277 timed("crop and scale", || crop_and_scale(&buffer, &crop)),
278 ]
279 .iter()
280 .sum::<f64>();
281 eprintln!("sum without segmentation: {total:.2} ms");
282 assert!(total < 33.);
283 }
284}
crates/calling/src/framing.rs added +301 −0
@@ -0,0 +1,301 @@
1 use std::time::Duration;
2
3 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
4
5 const PERSON_THRESHOLD: f32 = 0.5;
6 const MIN_REGION_AREA: f32 = 0.02;
7 const CROP_WIDTH_PER_SUBJECT_WIDTH: f32 = 1.8;
8 const HEADROOM: f32 = 0.12;
9 const MIN_ZOOM: f32 = 1.0;
10 const MAX_ZOOM: f32 = 2.0;
11 const POSITION_DEADBAND: f32 = 0.06;
12 const SIZE_DEADBAND: f32 = 0.10;
13 const PAN_TIME_CONSTANT: f32 = 0.7;
14 const ZOOM_TIME_CONSTANT: f32 = 1.4;
15 const PAN_SPEED_CAP: f32 = 0.25;
16 const ZOOM_SPEED_CAP: f32 = 0.4;
17 const LOST_HOLD: f32 = 1.5;
18 const MAX_STEP: f32 = 0.25;
19 const SETTLED: f32 = 0.001;
20 const FULL_ZOOM_LIMIT: f32 = 1.001;
21
22 #[derive(Debug, Clone, Copy, PartialEq)]
23 pub struct Subject {
24 pub left: f32,
25 pub top: f32,
26 pub right: f32,
27 pub bottom: f32,
28 }
29
30 /// The crop is centered at (`center_x`, `center_y`) in frame fractions and keeps the frame's aspect ratio.
31 #[derive(Debug, Clone, Copy, PartialEq)]
32 pub struct Crop {
33 pub center_x: f32,
34 pub center_y: f32,
35 pub zoom: f32,
36 }
37
38 pub const FULL_FRAME: Crop = Crop { center_x: 0.5, center_y: 0.5, zoom: MIN_ZOOM };
39
40 pub fn find_subject(mask: &[f32], width: usize, height: usize) -> Option<Subject> {
41 let mut visited = vec![false; mask.len()];
42 let mut stack = Vec::new();
43 let mut best: Option<(usize, Subject)> = None;
44 for start in 0..mask.len() {
45 if visited[start] || mask[start] < PERSON_THRESHOLD {
46 continue;
47 }
48 visited[start] = true;
49 stack.push(start);
50 let (mut area, mut left, mut right, mut top, mut bottom) = (0usize, width, 0usize, height, 0usize);
51 while let Some(index) = stack.pop() {
52 let (x, y) = (index % width, index / width);
53 area += 1;
54 (left, right, top, bottom) = (left.min(x), right.max(x), top.min(y), bottom.max(y));
55 let neighbors = [(x > 0).then(|| index - 1), (x + 1 < width).then(|| index + 1), (y > 0).then(|| index - width), (y + 1 < height).then(|| index + width)];
56 for next in neighbors.into_iter().flatten() {
57 if !visited[next] && mask[next] >= PERSON_THRESHOLD {
58 visited[next] = true;
59 stack.push(next);
60 }
61 }
62 }
63 let large_enough = area as f32 >= MIN_REGION_AREA * mask.len() as f32;
64 if large_enough && best.is_none_or(|(largest, _)| area > largest) {
65 let subject = Subject {
66 left: left as f32 / width as f32,
67 top: top as f32 / height as f32,
68 right: (right + 1) as f32 / width as f32,
69 bottom: (bottom + 1) as f32 / height as f32,
70 };
71 best = Some((area, subject));
72 }
73 }
74 best.map(|(_, subject)| subject)
75 }
76
77 fn fit_center(center: f32, size: f32) -> f32 {
78 center.clamp(size / 2., 1. - size / 2.)
79 }
80
81 pub fn crop_for(subject: &Subject) -> Crop {
82 let crop_width = (subject.right - subject.left) * CROP_WIDTH_PER_SUBJECT_WIDTH;
83 let zoom = (1. / crop_width).clamp(MIN_ZOOM, MAX_ZOOM);
84 let size = 1. / zoom;
85 let crop_top = subject.top - HEADROOM * size;
86 Crop {
87 center_x: fit_center((subject.left + subject.right) / 2., size),
88 center_y: fit_center(crop_top + size / 2., size),
89 zoom,
90 }
91 }
92
93 fn ease(current: f32, target: f32, time_constant: f32, speed_cap: f32, seconds: f32) -> f32 {
94 let weight = 1. - (-seconds / time_constant).exp();
95 let cap = speed_cap * seconds;
96 let remaining = target - current;
97 if remaining.abs() < SETTLED {
98 return target;
99 }
100 current + (remaining * weight).clamp(-cap, cap)
101 }
102
103 pub fn step_crop(current: Crop, target: Crop, seconds: f32, deadband: bool) -> Crop {
104 let current_size = 1. / current.zoom;
105 let offset = (target.center_x - current.center_x).abs().max((target.center_y - current.center_y).abs());
106 let resize = (1. / target.zoom - current_size).abs();
107 let pans = !deadband || offset / current_size > POSITION_DEADBAND;
108 let zooms = !deadband || resize / current_size > SIZE_DEADBAND;
109 let zoom = if zooms { ease(current.zoom, target.zoom, ZOOM_TIME_CONSTANT, ZOOM_SPEED_CAP, seconds) } else { current.zoom };
110 let size = 1. / zoom;
111 let (center_x, center_y) = if pans {
112 (ease(current.center_x, target.center_x, PAN_TIME_CONSTANT, PAN_SPEED_CAP, seconds), ease(current.center_y, target.center_y, PAN_TIME_CONSTANT, PAN_SPEED_CAP, seconds))
113 } else {
114 (current.center_x, current.center_y)
115 };
116 Crop { center_x: fit_center(center_x, size), center_y: fit_center(center_y, size), zoom }
117 }
118
119 pub struct CropPlanner {
120 crop: Crop,
121 lost_seconds: f32,
122 }
123
124 impl Default for CropPlanner {
125 fn default() -> Self {
126 CropPlanner { crop: FULL_FRAME, lost_seconds: 0. }
127 }
128 }
129
130 impl CropPlanner {
131 pub fn advance(&mut self, subject: Option<&Subject>, elapsed: Duration) -> Crop {
132 let seconds = elapsed.as_secs_f32().min(MAX_STEP);
133 match subject {
134 Some(subject) => {
135 self.lost_seconds = 0.;
136 self.crop = step_crop(self.crop, crop_for(subject), seconds, true);
137 }
138 None => {
139 self.lost_seconds += seconds;
140 if self.lost_seconds >= LOST_HOLD {
141 self.crop = step_crop(self.crop, FULL_FRAME, seconds, false);
142 }
143 }
144 }
145 self.crop
146 }
147
148 pub fn reset(&mut self) {
149 *self = CropPlanner::default();
150 }
151 }
152
153 pub fn is_full_frame(crop: &Crop) -> bool {
154 crop.zoom < FULL_ZOOM_LIMIT
155 }
156
157 pub fn crop_rectangle(crop: &Crop, width: usize, height: usize) -> (usize, usize, usize, usize) {
158 let even = |value: f32| (value.round() as usize) & !1;
159 let crop_width = even(width as f32 / crop.zoom).clamp(2, width);
160 let crop_height = even(height as f32 / crop.zoom).clamp(2, height);
161 let left = even(crop.center_x * width as f32 - crop_width as f32 / 2.).min(width - crop_width);
162 let top = even(crop.center_y * height as f32 - crop_height as f32 / 2.).min(height - crop_height);
163 (left, top, crop_width, crop_height)
164 }
165
166 fn copy_plane(source: &[u8], source_stride: usize, rectangle: (usize, usize, usize, usize), target: &mut [u8], target_stride: usize) {
167 let (left, top, width, height) = rectangle;
168 for row in 0..height {
169 target[row * target_stride..][..width].copy_from_slice(&source[(top + row) * source_stride + left..][..width]);
170 }
171 }
172
173 pub fn crop_and_scale(buffer: &I420Buffer, crop: &Crop) -> I420Buffer {
174 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
175 let (left, top, crop_width, crop_height) = crop_rectangle(crop, width, height);
176 let mut cropped = I420Buffer::new(crop_width as u32, crop_height as u32);
177 let (source_strides, target_strides) = (buffer.strides(), cropped.strides());
178 let (source_y, source_u, source_v) = buffer.data();
179 let (target_y, target_u, target_v) = cropped.data_mut();
180 copy_plane(source_y, source_strides.0 as usize, (left, top, crop_width, crop_height), target_y, target_strides.0 as usize);
181 copy_plane(source_u, source_strides.1 as usize, (left / 2, top / 2, crop_width / 2, crop_height / 2), target_u, target_strides.1 as usize);
182 copy_plane(source_v, source_strides.2 as usize, (left / 2, top / 2, crop_width / 2, crop_height / 2), target_v, target_strides.2 as usize);
183 cropped.scale(width as i32, height as i32)
184 }
185
186 #[cfg(test)]
187 mod tests {
188 use super::*;
189
190 const WIDTH: usize = 64;
191 const HEIGHT: usize = 36;
192 const FRAME: Duration = Duration::from_millis(33);
193
194 fn mask_with(regions: &[(usize, usize, usize, usize)]) -> Vec<f32> {
195 let mut mask = vec![0.; WIDTH * HEIGHT];
196 for &(left, top, right, bottom) in regions {
197 for y in top..bottom {
198 for x in left..right {
199 mask[y * WIDTH + x] = 0.9;
200 }
201 }
202 }
203 mask
204 }
205
206 fn small_person() -> Subject {
207 Subject { left: 0.4, top: 0.3, right: 0.5, bottom: 0.7 }
208 }
209
210 fn settle(planner: &mut CropPlanner, subject: Option<&Subject>, seconds: u32) -> Crop {
211 let mut crop = planner.crop;
212 for _ in 0..seconds * 30 {
213 crop = planner.advance(subject, FRAME);
214 }
215 crop
216 }
217
218 #[test]
219 fn the_largest_region_wins_and_small_ones_are_dropped() {
220 let mask = mask_with(&[(10, 5, 30, 30), (40, 5, 46, 10), (50, 20, 54, 24)]);
221 let subject = find_subject(&mask, WIDTH, HEIGHT).expect("a person");
222 assert_eq!(subject, Subject { left: 10. / 64., top: 5. / 36., right: 30. / 64., bottom: 30. / 36. });
223 assert!(find_subject(&mask_with(&[(40, 5, 46, 10)]), WIDTH, HEIGHT).is_none());
224 assert!(find_subject(&vec![0.4; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none());
225 assert!(find_subject(&vec![0.6; WIDTH * HEIGHT], WIDTH, HEIGHT).is_some());
226 assert!(find_subject(&vec![0.; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none());
227 }
228
229 #[test]
230 fn the_target_crop_is_wide_enough_has_headroom_and_stays_in_the_frame() {
231 let crop = crop_for(&small_person());
232 assert_eq!(crop.zoom, 2.);
233 let size = 1. / crop.zoom;
234 assert!(crop.center_y - size / 2. <= 0.3 - 0.12 * size + 1e-4);
235 assert!(crop.center_x - size / 2. >= 0. && crop.center_y + size / 2. <= 1.);
236 let wide = Subject { left: 0.1, top: 0.1, right: 0.9, bottom: 0.9 };
237 assert_eq!(crop_for(&wide).zoom, 1.);
238 let medium = Subject { left: 0.3, top: 0.2, right: 0.7, bottom: 0.9 };
239 assert!((crop_for(&medium).zoom - 1. / 0.72).abs() < 1e-4);
240 }
241
242 #[test]
243 fn the_crop_holds_while_the_target_is_inside_the_deadband() {
244 let current = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.5 };
245 let size = 1. / current.zoom;
246 let near = Crop { center_x: 0.5 + 0.05 * size, center_y: 0.5, zoom: 1. / (size * 1.09) };
247 assert_eq!(step_crop(current, near, 0.033, true), current);
248 let far = Crop { center_x: 0.5 + 0.2 * size, ..current };
249 assert!(step_crop(current, far, 0.033, true).center_x > current.center_x);
250 let bigger = Crop { zoom: 1. / (size * 1.2), ..current };
251 assert!(step_crop(current, bigger, 0.033, true).zoom < current.zoom);
252 }
253
254 #[test]
255 fn smoothing_converges_on_the_target_without_overshoot() {
256 let mut planner = CropPlanner::default();
257 let target = crop_for(&small_person());
258 let crop = settle(&mut planner, Some(&small_person()), 20);
259 assert!((crop.zoom - target.zoom).abs() < 0.1 * target.zoom);
260 assert!((crop.center_x - target.center_x).abs() <= POSITION_DEADBAND / crop.zoom + 1e-4);
261 assert!(crop.zoom <= MAX_ZOOM && crop.zoom >= MIN_ZOOM);
262 }
263
264 #[test]
265 fn panning_never_exceeds_the_speed_cap() {
266 let current = Crop { center_x: 0.3, center_y: 0.5, zoom: 2. };
267 let target = Crop { center_x: 0.7, center_y: 0.5, zoom: 2. };
268 let moved = step_crop(current, target, 0.1, true);
269 assert!((moved.center_x - current.center_x) <= PAN_SPEED_CAP * 0.1 + 1e-6);
270 assert!(moved.center_x > current.center_x);
271 let zoomed = step_crop(FULL_FRAME, Crop { zoom: 2., ..FULL_FRAME }, 0.5, true);
272 assert!(zoomed.zoom - 1. <= ZOOM_SPEED_CAP * 0.5 + 1e-6);
273 }
274
275 #[test]
276 fn a_lost_subject_is_held_then_eased_out_to_the_full_frame() {
277 let mut planner = CropPlanner::default();
278 let zoomed = settle(&mut planner, Some(&small_person()), 20);
279 assert!(zoomed.zoom > 1.5);
280 let held = settle(&mut planner, None, 1);
281 assert_eq!(held, zoomed);
282 let easing = settle(&mut planner, None, 2);
283 assert!(easing.zoom < zoomed.zoom);
284 let full = settle(&mut planner, None, 10);
285 assert_eq!(full, FULL_FRAME);
286 planner.advance(Some(&small_person()), FRAME);
287 assert_eq!(planner.lost_seconds, 0.);
288 }
289
290 #[test]
291 fn the_crop_rectangle_is_even_inside_the_frame_and_scales_back() {
292 let (left, top, width, height) = crop_rectangle(&Crop { center_x: 0.9, center_y: 0.1, zoom: 2. }, 1280, 720);
293 assert_eq!((width, height), (640, 360));
294 assert_eq!((left, top), (640, 0));
295 assert!(left % 2 == 0 && top % 2 == 0);
296 assert_eq!(crop_rectangle(&FULL_FRAME, 1280, 720), (0, 0, 1280, 720));
297 let buffer = I420Buffer::new(64, 36);
298 let scaled = crop_and_scale(&buffer, &Crop { center_x: 0.5, center_y: 0.5, zoom: 2. });
299 assert_eq!((scaled.width(), scaled.height()), (64, 36));
300 }
301 }
@@ -0,0 +1,301 @@
1use std::time::Duration;
2
3use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
4
5const PERSON_THRESHOLD: f32 = 0.5;
6const MIN_REGION_AREA: f32 = 0.02;
7const CROP_WIDTH_PER_SUBJECT_WIDTH: f32 = 1.8;
8const HEADROOM: f32 = 0.12;
9const MIN_ZOOM: f32 = 1.0;
10const MAX_ZOOM: f32 = 2.0;
11const POSITION_DEADBAND: f32 = 0.06;
12const SIZE_DEADBAND: f32 = 0.10;
13const PAN_TIME_CONSTANT: f32 = 0.7;
14const ZOOM_TIME_CONSTANT: f32 = 1.4;
15const PAN_SPEED_CAP: f32 = 0.25;
16const ZOOM_SPEED_CAP: f32 = 0.4;
17const LOST_HOLD: f32 = 1.5;
18const MAX_STEP: f32 = 0.25;
19const SETTLED: f32 = 0.001;
20const FULL_ZOOM_LIMIT: f32 = 1.001;
21
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub struct Subject {
24 pub left: f32,
25 pub top: f32,
26 pub right: f32,
27 pub bottom: f32,
28}
29
30/// The crop is centered at (`center_x`, `center_y`) in frame fractions and keeps the frame's aspect ratio.
31#[derive(Debug, Clone, Copy, PartialEq)]
32pub struct Crop {
33 pub center_x: f32,
34 pub center_y: f32,
35 pub zoom: f32,
36}
37
38pub const FULL_FRAME: Crop = Crop { center_x: 0.5, center_y: 0.5, zoom: MIN_ZOOM };
39
40pub fn find_subject(mask: &[f32], width: usize, height: usize) -> Option<Subject> {
41 let mut visited = vec![false; mask.len()];
42 let mut stack = Vec::new();
43 let mut best: Option<(usize, Subject)> = None;
44 for start in 0..mask.len() {
45 if visited[start] || mask[start] < PERSON_THRESHOLD {
46 continue;
47 }
48 visited[start] = true;
49 stack.push(start);
50 let (mut area, mut left, mut right, mut top, mut bottom) = (0usize, width, 0usize, height, 0usize);
51 while let Some(index) = stack.pop() {
52 let (x, y) = (index % width, index / width);
53 area += 1;
54 (left, right, top, bottom) = (left.min(x), right.max(x), top.min(y), bottom.max(y));
55 let neighbors = [(x > 0).then(|| index - 1), (x + 1 < width).then(|| index + 1), (y > 0).then(|| index - width), (y + 1 < height).then(|| index + width)];
56 for next in neighbors.into_iter().flatten() {
57 if !visited[next] && mask[next] >= PERSON_THRESHOLD {
58 visited[next] = true;
59 stack.push(next);
60 }
61 }
62 }
63 let large_enough = area as f32 >= MIN_REGION_AREA * mask.len() as f32;
64 if large_enough && best.is_none_or(|(largest, _)| area > largest) {
65 let subject = Subject {
66 left: left as f32 / width as f32,
67 top: top as f32 / height as f32,
68 right: (right + 1) as f32 / width as f32,
69 bottom: (bottom + 1) as f32 / height as f32,
70 };
71 best = Some((area, subject));
72 }
73 }
74 best.map(|(_, subject)| subject)
75}
76
77fn fit_center(center: f32, size: f32) -> f32 {
78 center.clamp(size / 2., 1. - size / 2.)
79}
80
81pub fn crop_for(subject: &Subject) -> Crop {
82 let crop_width = (subject.right - subject.left) * CROP_WIDTH_PER_SUBJECT_WIDTH;
83 let zoom = (1. / crop_width).clamp(MIN_ZOOM, MAX_ZOOM);
84 let size = 1. / zoom;
85 let crop_top = subject.top - HEADROOM * size;
86 Crop {
87 center_x: fit_center((subject.left + subject.right) / 2., size),
88 center_y: fit_center(crop_top + size / 2., size),
89 zoom,
90 }
91}
92
93fn ease(current: f32, target: f32, time_constant: f32, speed_cap: f32, seconds: f32) -> f32 {
94 let weight = 1. - (-seconds / time_constant).exp();
95 let cap = speed_cap * seconds;
96 let remaining = target - current;
97 if remaining.abs() < SETTLED {
98 return target;
99 }
100 current + (remaining * weight).clamp(-cap, cap)
101}
102
103pub fn step_crop(current: Crop, target: Crop, seconds: f32, deadband: bool) -> Crop {
104 let current_size = 1. / current.zoom;
105 let offset = (target.center_x - current.center_x).abs().max((target.center_y - current.center_y).abs());
106 let resize = (1. / target.zoom - current_size).abs();
107 let pans = !deadband || offset / current_size > POSITION_DEADBAND;
108 let zooms = !deadband || resize / current_size > SIZE_DEADBAND;
109 let zoom = if zooms { ease(current.zoom, target.zoom, ZOOM_TIME_CONSTANT, ZOOM_SPEED_CAP, seconds) } else { current.zoom };
110 let size = 1. / zoom;
111 let (center_x, center_y) = if pans {
112 (ease(current.center_x, target.center_x, PAN_TIME_CONSTANT, PAN_SPEED_CAP, seconds), ease(current.center_y, target.center_y, PAN_TIME_CONSTANT, PAN_SPEED_CAP, seconds))
113 } else {
114 (current.center_x, current.center_y)
115 };
116 Crop { center_x: fit_center(center_x, size), center_y: fit_center(center_y, size), zoom }
117}
118
119pub struct CropPlanner {
120 crop: Crop,
121 lost_seconds: f32,
122}
123
124impl Default for CropPlanner {
125 fn default() -> Self {
126 CropPlanner { crop: FULL_FRAME, lost_seconds: 0. }
127 }
128}
129
130impl CropPlanner {
131 pub fn advance(&mut self, subject: Option<&Subject>, elapsed: Duration) -> Crop {
132 let seconds = elapsed.as_secs_f32().min(MAX_STEP);
133 match subject {
134 Some(subject) => {
135 self.lost_seconds = 0.;
136 self.crop = step_crop(self.crop, crop_for(subject), seconds, true);
137 }
138 None => {
139 self.lost_seconds += seconds;
140 if self.lost_seconds >= LOST_HOLD {
141 self.crop = step_crop(self.crop, FULL_FRAME, seconds, false);
142 }
143 }
144 }
145 self.crop
146 }
147
148 pub fn reset(&mut self) {
149 *self = CropPlanner::default();
150 }
151}
152
153pub fn is_full_frame(crop: &Crop) -> bool {
154 crop.zoom < FULL_ZOOM_LIMIT
155}
156
157pub fn crop_rectangle(crop: &Crop, width: usize, height: usize) -> (usize, usize, usize, usize) {
158 let even = |value: f32| (value.round() as usize) & !1;
159 let crop_width = even(width as f32 / crop.zoom).clamp(2, width);
160 let crop_height = even(height as f32 / crop.zoom).clamp(2, height);
161 let left = even(crop.center_x * width as f32 - crop_width as f32 / 2.).min(width - crop_width);
162 let top = even(crop.center_y * height as f32 - crop_height as f32 / 2.).min(height - crop_height);
163 (left, top, crop_width, crop_height)
164}
165
166fn copy_plane(source: &[u8], source_stride: usize, rectangle: (usize, usize, usize, usize), target: &mut [u8], target_stride: usize) {
167 let (left, top, width, height) = rectangle;
168 for row in 0..height {
169 target[row * target_stride..][..width].copy_from_slice(&source[(top + row) * source_stride + left..][..width]);
170 }
171}
172
173pub fn crop_and_scale(buffer: &I420Buffer, crop: &Crop) -> I420Buffer {
174 let (width, height) = (buffer.width() as usize, buffer.height() as usize);
175 let (left, top, crop_width, crop_height) = crop_rectangle(crop, width, height);
176 let mut cropped = I420Buffer::new(crop_width as u32, crop_height as u32);
177 let (source_strides, target_strides) = (buffer.strides(), cropped.strides());
178 let (source_y, source_u, source_v) = buffer.data();
179 let (target_y, target_u, target_v) = cropped.data_mut();
180 copy_plane(source_y, source_strides.0 as usize, (left, top, crop_width, crop_height), target_y, target_strides.0 as usize);
181 copy_plane(source_u, source_strides.1 as usize, (left / 2, top / 2, crop_width / 2, crop_height / 2), target_u, target_strides.1 as usize);
182 copy_plane(source_v, source_strides.2 as usize, (left / 2, top / 2, crop_width / 2, crop_height / 2), target_v, target_strides.2 as usize);
183 cropped.scale(width as i32, height as i32)
184}
185
186#[cfg(test)]
187mod tests {
188 use super::*;
189
190 const WIDTH: usize = 64;
191 const HEIGHT: usize = 36;
192 const FRAME: Duration = Duration::from_millis(33);
193
194 fn mask_with(regions: &[(usize, usize, usize, usize)]) -> Vec<f32> {
195 let mut mask = vec![0.; WIDTH * HEIGHT];
196 for &(left, top, right, bottom) in regions {
197 for y in top..bottom {
198 for x in left..right {
199 mask[y * WIDTH + x] = 0.9;
200 }
201 }
202 }
203 mask
204 }
205
206 fn small_person() -> Subject {
207 Subject { left: 0.4, top: 0.3, right: 0.5, bottom: 0.7 }
208 }
209
210 fn settle(planner: &mut CropPlanner, subject: Option<&Subject>, seconds: u32) -> Crop {
211 let mut crop = planner.crop;
212 for _ in 0..seconds * 30 {
213 crop = planner.advance(subject, FRAME);
214 }
215 crop
216 }
217
218 #[test]
219 fn the_largest_region_wins_and_small_ones_are_dropped() {
220 let mask = mask_with(&[(10, 5, 30, 30), (40, 5, 46, 10), (50, 20, 54, 24)]);
221 let subject = find_subject(&mask, WIDTH, HEIGHT).expect("a person");
222 assert_eq!(subject, Subject { left: 10. / 64., top: 5. / 36., right: 30. / 64., bottom: 30. / 36. });
223 assert!(find_subject(&mask_with(&[(40, 5, 46, 10)]), WIDTH, HEIGHT).is_none());
224 assert!(find_subject(&vec![0.4; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none());
225 assert!(find_subject(&vec![0.6; WIDTH * HEIGHT], WIDTH, HEIGHT).is_some());
226 assert!(find_subject(&vec![0.; WIDTH * HEIGHT], WIDTH, HEIGHT).is_none());
227 }
228
229 #[test]
230 fn the_target_crop_is_wide_enough_has_headroom_and_stays_in_the_frame() {
231 let crop = crop_for(&small_person());
232 assert_eq!(crop.zoom, 2.);
233 let size = 1. / crop.zoom;
234 assert!(crop.center_y - size / 2. <= 0.3 - 0.12 * size + 1e-4);
235 assert!(crop.center_x - size / 2. >= 0. && crop.center_y + size / 2. <= 1.);
236 let wide = Subject { left: 0.1, top: 0.1, right: 0.9, bottom: 0.9 };
237 assert_eq!(crop_for(&wide).zoom, 1.);
238 let medium = Subject { left: 0.3, top: 0.2, right: 0.7, bottom: 0.9 };
239 assert!((crop_for(&medium).zoom - 1. / 0.72).abs() < 1e-4);
240 }
241
242 #[test]
243 fn the_crop_holds_while_the_target_is_inside_the_deadband() {
244 let current = Crop { center_x: 0.5, center_y: 0.5, zoom: 1.5 };
245 let size = 1. / current.zoom;
246 let near = Crop { center_x: 0.5 + 0.05 * size, center_y: 0.5, zoom: 1. / (size * 1.09) };
247 assert_eq!(step_crop(current, near, 0.033, true), current);
248 let far = Crop { center_x: 0.5 + 0.2 * size, ..current };
249 assert!(step_crop(current, far, 0.033, true).center_x > current.center_x);
250 let bigger = Crop { zoom: 1. / (size * 1.2), ..current };
251 assert!(step_crop(current, bigger, 0.033, true).zoom < current.zoom);
252 }
253
254 #[test]
255 fn smoothing_converges_on_the_target_without_overshoot() {
256 let mut planner = CropPlanner::default();
257 let target = crop_for(&small_person());
258 let crop = settle(&mut planner, Some(&small_person()), 20);
259 assert!((crop.zoom - target.zoom).abs() < 0.1 * target.zoom);
260 assert!((crop.center_x - target.center_x).abs() <= POSITION_DEADBAND / crop.zoom + 1e-4);
261 assert!(crop.zoom <= MAX_ZOOM && crop.zoom >= MIN_ZOOM);
262 }
263
264 #[test]
265 fn panning_never_exceeds_the_speed_cap() {
266 let current = Crop { center_x: 0.3, center_y: 0.5, zoom: 2. };
267 let target = Crop { center_x: 0.7, center_y: 0.5, zoom: 2. };
268 let moved = step_crop(current, target, 0.1, true);
269 assert!((moved.center_x - current.center_x) <= PAN_SPEED_CAP * 0.1 + 1e-6);
270 assert!(moved.center_x > current.center_x);
271 let zoomed = step_crop(FULL_FRAME, Crop { zoom: 2., ..FULL_FRAME }, 0.5, true);
272 assert!(zoomed.zoom - 1. <= ZOOM_SPEED_CAP * 0.5 + 1e-6);
273 }
274
275 #[test]
276 fn a_lost_subject_is_held_then_eased_out_to_the_full_frame() {
277 let mut planner = CropPlanner::default();
278 let zoomed = settle(&mut planner, Some(&small_person()), 20);
279 assert!(zoomed.zoom > 1.5);
280 let held = settle(&mut planner, None, 1);
281 assert_eq!(held, zoomed);
282 let easing = settle(&mut planner, None, 2);
283 assert!(easing.zoom < zoomed.zoom);
284 let full = settle(&mut planner, None, 10);
285 assert_eq!(full, FULL_FRAME);
286 planner.advance(Some(&small_person()), FRAME);
287 assert_eq!(planner.lost_seconds, 0.);
288 }
289
290 #[test]
291 fn the_crop_rectangle_is_even_inside_the_frame_and_scales_back() {
292 let (left, top, width, height) = crop_rectangle(&Crop { center_x: 0.9, center_y: 0.1, zoom: 2. }, 1280, 720);
293 assert_eq!((width, height), (640, 360));
294 assert_eq!((left, top), (640, 0));
295 assert!(left % 2 == 0 && top % 2 == 0);
296 assert_eq!(crop_rectangle(&FULL_FRAME, 1280, 720), (0, 0, 1280, 720));
297 let buffer = I420Buffer::new(64, 36);
298 let scaled = crop_and_scale(&buffer, &Crop { center_x: 0.5, center_y: 0.5, zoom: 2. });
299 assert_eq!((scaled.width(), scaled.height()), (64, 36));
300 }
301}
crates/calling/src/lib.rs +4 −0
@@ -12,12 +12,15 @@ pub mod control;
12 12 pub mod data_channel;
13 13 pub mod devices;
14 14 pub mod engine;
15 pub mod effects;
15 16 pub mod end;
16 17 pub mod error;
17 18 pub mod health;
19 pub mod framing;
18 20 pub mod hold;
19 21 pub mod join;
20 22 pub mod level;
23 pub mod luma_effects;
21 24 #[cfg(windows)]
22 25 mod loopback_windows;
23 26 pub mod meeting;
@@ -53,6 +56,7 @@ pub use audio_io::AudioMode;
53 56 pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
54 57 pub use breakout::BreakoutMove;
55 58 pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
59 pub use effects::CameraEffects;
56 60 pub use hold::HoldState;
57 61 pub use whiteboard::ContentShare;
58 62 pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
@@ -12,12 +12,15 @@ pub mod control;
12pub mod data_channel;
12pub mod data_channel;
13pub mod devices;
13pub mod devices;
14pub mod engine;
14pub mod engine;
15pub mod effects;
15pub mod end;
16pub mod end;
16pub mod error;
17pub mod error;
17pub mod health;
18pub mod health;
19pub mod framing;
18pub mod hold;
20pub mod hold;
19pub mod join;
21pub mod join;
20pub mod level;
22pub mod level;
23pub mod luma_effects;
21#[cfg(windows)]
24#[cfg(windows)]
22mod loopback_windows;
25mod loopback_windows;
23pub mod meeting;
26pub mod meeting;
@@ -53,6 +56,7 @@ pub use audio_io::AudioMode;
53pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
56pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
54pub use breakout::BreakoutMove;
57pub use breakout::BreakoutMove;
55pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
58pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
59pub use effects::CameraEffects;
56pub use hold::HoldState;
60pub use hold::HoldState;
57pub use whiteboard::ContentShare;
61pub use whiteboard::ContentShare;
58pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
62pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
crates/calling/src/luma_effects.rs added +290 −0
@@ -0,0 +1,290 @@
1 use std::time::Duration;
2
3 use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis};
4
5 const DARK_LUMA: f32 = 0.35;
6 const VERY_DARK_LUMA: f32 = 0.05;
7 const GAMMA_AT_DARK: f32 = 0.75;
8 const GAMMA_AT_VERY_DARK: f32 = 0.6;
9 const GAMMA_TIME_CONSTANT: f32 = 1.0;
10 const GAMMA_SETTLED: f32 = 0.005;
11 const LUMA_SAMPLE_STEP: usize = 4;
12 const SOFT_FOCUS_MAX_ALPHA: f32 = 0.7;
13 const CELL: usize = 4;
14 const FILTER_RADIUS: usize = 1;
15 const FILTER_EPSILON: f32 = 100.;
16 const NEAR_WEIGHTS: [f32; CELL] = [0.625, 0.875, 0.875, 0.625];
17 const INSIDE_START: f32 = 0.5;
18 const MAX_BANDS: usize = 4;
19
20 pub fn mean_luma(plane: &[u8], stride: usize, width: usize, height: usize) -> f32 {
21 let (mut sum, mut count) = (0u64, 0u64);
22 for row in (0..height).step_by(LUMA_SAMPLE_STEP) {
23 for &value in plane[row * stride..][..width].iter().step_by(LUMA_SAMPLE_STEP) {
24 sum += u64::from(value);
25 count += 1;
26 }
27 }
28 if count == 0 { 0. } else { sum as f32 / (count as f32 * 255.) }
29 }
30
31 pub fn target_gamma(mean_luma: f32) -> f32 {
32 if mean_luma >= DARK_LUMA {
33 return 1.;
34 }
35 let darkness = ((DARK_LUMA - mean_luma) / (DARK_LUMA - VERY_DARK_LUMA)).clamp(0., 1.);
36 GAMMA_AT_DARK + (GAMMA_AT_VERY_DARK - GAMMA_AT_DARK) * darkness
37 }
38
39 pub fn smooth_gamma(current: f32, target: f32, elapsed: Duration) -> f32 {
40 let next = current + (target - current) * (1. - (-elapsed.as_secs_f32() / GAMMA_TIME_CONSTANT).exp());
41 if (next - target).abs() < GAMMA_SETTLED { target } else { next }
42 }
43
44 pub fn gamma_table(gamma: f32) -> [u8; 256] {
45 std::array::from_fn(|value| (255. * (value as f32 / 255.).powf(gamma)).round() as u8)
46 }
47
48 pub fn apply_table(plane: &mut [u8], stride: usize, width: usize, height: usize, table: &[u8; 256]) {
49 for row in plane.chunks_mut(stride).take(height) {
50 for value in &mut row[..width] {
51 *value = table[usize::from(*value)];
52 }
53 }
54 }
55
56 pub fn inside_person(mask_value: f32) -> f32 {
57 ((mask_value - INSIDE_START) / (1. - INSIDE_START)).clamp(0., 1.)
58 }
59
60 pub fn soft_focus_alpha(strength_percent: u8, inside: f32) -> f32 {
61 f32::from(strength_percent.min(100)) / 100. * SOFT_FOCUS_MAX_ALPHA * inside
62 }
63
64 pub fn blend_coefficients(alpha: f32, slope: f32, offset: f32) -> (f32, f32) {
65 (1. + alpha * (slope - 1.), alpha * offset)
66 }
67
68 pub fn apply_coefficients(value: u8, gain: f32, bias: f32) -> u8 {
69 (f32::from(value) * gain + bias + 0.5) as u8
70 }
71
72 fn box_mean(input: &[f32], width: usize, height: usize) -> Vec<f32> {
73 let mut across = vec![0f32; input.len()];
74 for (line, mean) in input.chunks_exact(width).zip(across.chunks_exact_mut(width)) {
75 for (index, slot) in mean.iter_mut().enumerate() {
76 let (low, high) = (index.saturating_sub(FILTER_RADIUS), (index + FILTER_RADIUS).min(width - 1));
77 *slot = line[low..=high].iter().sum::<f32>() / (high + 1 - low) as f32;
78 }
79 }
80 let mut output = vec![0f32; input.len()];
81 for row in 0..height {
82 let (low, high) = (row.saturating_sub(FILTER_RADIUS), (row + FILTER_RADIUS).min(height - 1));
83 let slot = &mut output[row * width..][..width];
84 for line in low..=high {
85 slot.iter_mut().zip(&across[line * width..][..width]).for_each(|(sum, value)| *sum += value);
86 }
87 let count = (high + 1 - low) as f32;
88 slot.iter_mut().for_each(|sum| *sum /= count);
89 }
90 output
91 }
92
93 struct Cells {
94 gain: Vec<f32>,
95 bias: Vec<f32>,
96 alpha: Vec<f32>,
97 width: usize,
98 height: usize,
99 }
100
101 fn cell_means(plane: &[u8], stride: usize, cell_width: usize, cell_height: usize) -> Vec<f32> {
102 let mut means = vec![0f32; cell_width * cell_height];
103 let mut sums = vec![0u32; cell_width];
104 for (row, mean) in means.chunks_exact_mut(cell_width).enumerate() {
105 sums.fill(0);
106 for line in 0..CELL {
107 let pixels = &plane[(row * CELL + line) * stride..][..cell_width * CELL];
108 for (sum, group) in sums.iter_mut().zip(pixels.as_chunks::<CELL>().0) {
109 *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>();
110 }
111 }
112 mean.iter_mut().zip(&sums).for_each(|(slot, sum)| *slot = *sum as f32 / (CELL * CELL) as f32);
113 }
114 means
115 }
116
117 fn smoothing_cells(plane: &[u8], stride: usize, width: usize, height: usize, mask: &[f32], strength_percent: u8) -> Cells {
118 let (cell_width, cell_height) = (width / CELL, height / CELL);
119 let small = cell_means(plane, stride, cell_width, cell_height);
120 let squared: Vec<f32> = small.iter().map(|value| value * value).collect();
121 let mean = box_mean(&small, cell_width, cell_height);
122 let mean_squared = box_mean(&squared, cell_width, cell_height);
123 let slope: Vec<f32> = mean.iter().zip(&mean_squared).map(|(mean, squared)| {
124 let variance = (squared - mean * mean).max(0.);
125 variance / (variance + FILTER_EPSILON)
126 }).collect();
127 let offset: Vec<f32> = mean.iter().zip(&slope).map(|(mean, slope)| mean * (1. - slope)).collect();
128 let (mean_slope, mean_offset) = (box_mean(&slope, cell_width, cell_height), box_mean(&offset, cell_width, cell_height));
129 let (mask_x, mask_y) = (axis(cell_width, MASK_WIDTH), axis(cell_height, MASK_HEIGHT));
130 let mut cells = Cells { gain: vec![1.; small.len()], bias: vec![0.; small.len()], alpha: vec![0.; small.len()], width: cell_width, height: cell_height };
131 for row in 0..cell_height {
132 let (mask_top, mask_bottom, mask_fraction) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
133 for column in 0..cell_width {
134 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
135 let top = mask[mask_top + left] * (1. - across) + mask[mask_top + right] * across;
136 let bottom = mask[mask_bottom + left] * (1. - across) + mask[mask_bottom + right] * across;
137 let index = row * cell_width + column;
138 let alpha = soft_focus_alpha(strength_percent, inside_person(top * (1. - mask_fraction) + bottom * mask_fraction));
139 (cells.gain[index], cells.bias[index]) = blend_coefficients(alpha, mean_slope[index], mean_offset[index]);
140 cells.alpha[index] = alpha;
141 }
142 }
143 cells
144 }
145
146 fn neighbor(index: usize, step: usize, last: usize) -> usize {
147 if step < CELL / 2 { index.saturating_sub(1) } else { (index + 1).min(last) }
148 }
149
150 fn blend_rows(plane: &mut [u8], stride: usize, first_row: usize, cells: &Cells) {
151 let (mut gain_row, mut bias_row) = (vec![0f32; cells.width], vec![0f32; cells.width]);
152 for (offset, line) in plane.chunks_mut(stride).enumerate() {
153 let row = first_row + offset;
154 if row >= cells.height * CELL {
155 break;
156 }
157 let (near, step) = (row / CELL, row % CELL);
158 let far = neighbor(near, step, cells.height - 1);
159 let (near_start, far_start) = (near * cells.width, far * cells.width);
160 if cells.alpha[near_start..][..cells.width].iter().chain(&cells.alpha[far_start..][..cells.width]).all(|alpha| *alpha <= 0.) {
161 continue;
162 }
163 let (near_weight, far_weight) = (NEAR_WEIGHTS[step], 1. - NEAR_WEIGHTS[step]);
164 for column in 0..cells.width {
165 gain_row[column] = cells.gain[near_start + column] * near_weight + cells.gain[far_start + column] * far_weight;
166 bias_row[column] = cells.bias[near_start + column] * near_weight + cells.bias[far_start + column] * far_weight;
167 }
168 for (column, group) in line[..cells.width * CELL].as_chunks_mut::<CELL>().0.iter_mut().enumerate() {
169 for (step, value) in group.iter_mut().enumerate() {
170 let far = neighbor(column, step, cells.width - 1);
171 let (near_weight, far_weight) = (NEAR_WEIGHTS[step], 1. - NEAR_WEIGHTS[step]);
172 let gain = gain_row[column] * near_weight + gain_row[far] * far_weight;
173 let bias = bias_row[column] * near_weight + bias_row[far] * far_weight;
174 *value = apply_coefficients(*value, gain, bias);
175 }
176 }
177 }
178 }
179
180 /// Edge-preserving smoothing (fast guided filter, radius about 4) of the luma plane, blended in only inside the person mask.
181 pub fn soften_luma(plane: &mut [u8], stride: usize, width: usize, height: usize, mask: &[f32], strength_percent: u8) {
182 if strength_percent == 0 || width < CELL * 2 || height < CELL * 2 {
183 return;
184 }
185 let cells = smoothing_cells(plane, stride, width, height, mask, strength_percent);
186 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
187 let rows_per_band = height.div_ceil(bands).next_multiple_of(CELL);
188 std::thread::scope(|scope| {
189 for (index, band) in plane[..stride * (height - 1) + width].chunks_mut(rows_per_band * stride).enumerate() {
190 let cells = &cells;
191 scope.spawn(move || blend_rows(band, stride, index * rows_per_band, cells));
192 }
193 });
194 }
195
196 #[cfg(test)]
197 mod tests {
198 use super::*;
199
200 const WIDTH: usize = 64;
201 const HEIGHT: usize = 36;
202
203 #[test]
204 fn the_gamma_follows_the_darkness_and_leaves_bright_frames_alone() {
205 assert_eq!(target_gamma(0.5), 1.);
206 assert_eq!(target_gamma(0.35), 1.);
207 assert!((target_gamma(0.3499) - GAMMA_AT_DARK).abs() < 0.001);
208 assert_eq!(target_gamma(0.05), GAMMA_AT_VERY_DARK);
209 assert_eq!(target_gamma(0.), GAMMA_AT_VERY_DARK);
210 let middle = target_gamma(0.2);
211 assert!(middle < GAMMA_AT_DARK && middle > GAMMA_AT_VERY_DARK);
212 }
213
214 #[test]
215 fn the_gamma_glides_instead_of_jumping() {
216 let step = Duration::from_millis(33);
217 let first = smooth_gamma(1., 0.6, step);
218 assert!(first < 1. && first > 0.95);
219 let mut gamma = 1.;
220 for _ in 0..300 {
221 gamma = smooth_gamma(gamma, 0.6, step);
222 }
223 assert_eq!(gamma, 0.6);
224 }
225
226 #[test]
227 fn the_table_brightens_dark_values_and_keeps_the_ends() {
228 let table = gamma_table(0.6);
229 assert_eq!((table[0], table[255]), (0, 255));
230 assert!(table[40] > 40 && table[128] > 128);
231 assert!(table.windows(2).all(|pair| pair[0] <= pair[1]));
232 assert_eq!(gamma_table(1.), std::array::from_fn(|value| value as u8));
233 let mut plane = vec![40u8; WIDTH * HEIGHT];
234 apply_table(&mut plane, WIDTH, WIDTH, HEIGHT, &table);
235 assert!(plane.iter().all(|&value| value == table[40]));
236 }
237
238 #[test]
239 fn the_mean_luma_is_a_fraction_of_full_scale() {
240 assert_eq!(mean_luma(&vec![255; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 1.);
241 assert_eq!(mean_luma(&vec![0; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 0.);
242 assert!((mean_luma(&vec![51; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT) - 0.2).abs() < 1e-3);
243 }
244
245 #[test]
246 fn the_blend_only_acts_inside_the_person_and_scales_with_strength() {
247 assert_eq!(soft_focus_alpha(100, 1.), SOFT_FOCUS_MAX_ALPHA);
248 assert_eq!(soft_focus_alpha(50, 1.), 0.35);
249 assert_eq!(soft_focus_alpha(0, 1.), 0.);
250 assert_eq!(soft_focus_alpha(100, 0.), 0.);
251 assert_eq!(inside_person(0.5), 0.);
252 assert_eq!(inside_person(0.2), 0.);
253 assert_eq!(inside_person(1.), 1.);
254 assert_eq!(blend_coefficients(0., 0.3, 40.), (1., 0.));
255 assert_eq!(blend_coefficients(1., 0.3, 40.), (0.3, 40.));
256 let (gain, bias) = blend_coefficients(0.5, 0.2, 100.);
257 assert_eq!(apply_coefficients(100, gain, bias), 110);
258 }
259
260 fn noisy_plane() -> Vec<u8> {
261 (0..WIDTH * HEIGHT)
262 .map(|index| {
263 let (x, y) = (index % WIDTH, index / WIDTH);
264 let base = if x < WIDTH / 2 { 60 } else { 200 };
265 (base + ((x * 7 + y * 13) % 9) as i32 - 4) as u8
266 })
267 .collect()
268 }
269
270 fn roughness(plane: &[u8], y: usize, from: usize, to: usize) -> i32 {
271 (from..to).map(|x| (i32::from(plane[y * WIDTH + x + 1]) - i32::from(plane[y * WIDTH + x])).abs()).sum()
272 }
273
274 #[test]
275 fn soft_focus_smooths_noise_inside_the_mask_keeps_edges_and_spares_the_outside() {
276 let original = noisy_plane();
277 let mut softened = original.clone();
278 let mut mask = vec![0f32; MASK_WIDTH * MASK_HEIGHT];
279 for row in 0..MASK_HEIGHT {
280 mask[row * MASK_WIDTH..][..MASK_WIDTH / 2 + 20].fill(1.);
281 }
282 soften_luma(&mut softened, WIDTH, WIDTH, HEIGHT, &mask, 100);
283 assert!(roughness(&softened, 18, 2, 20) < roughness(&original, 18, 2, 20));
284 assert!(i32::from(softened[18 * WIDTH + WIDTH / 2 + 2]) - i32::from(softened[18 * WIDTH + WIDTH / 2 - 3]) > 100);
285 assert_eq!(softened[18 * WIDTH + WIDTH - 4], original[18 * WIDTH + WIDTH - 4]);
286 let mut untouched = original.clone();
287 soften_luma(&mut untouched, WIDTH, WIDTH, HEIGHT, &mask, 0);
288 assert_eq!(untouched, original);
289 }
290 }
@@ -0,0 +1,290 @@
1use std::time::Duration;
2
3use crate::blur::{MASK_HEIGHT, MASK_WIDTH, axis};
4
5const DARK_LUMA: f32 = 0.35;
6const VERY_DARK_LUMA: f32 = 0.05;
7const GAMMA_AT_DARK: f32 = 0.75;
8const GAMMA_AT_VERY_DARK: f32 = 0.6;
9const GAMMA_TIME_CONSTANT: f32 = 1.0;
10const GAMMA_SETTLED: f32 = 0.005;
11const LUMA_SAMPLE_STEP: usize = 4;
12const SOFT_FOCUS_MAX_ALPHA: f32 = 0.7;
13const CELL: usize = 4;
14const FILTER_RADIUS: usize = 1;
15const FILTER_EPSILON: f32 = 100.;
16const NEAR_WEIGHTS: [f32; CELL] = [0.625, 0.875, 0.875, 0.625];
17const INSIDE_START: f32 = 0.5;
18const MAX_BANDS: usize = 4;
19
20pub fn mean_luma(plane: &[u8], stride: usize, width: usize, height: usize) -> f32 {
21 let (mut sum, mut count) = (0u64, 0u64);
22 for row in (0..height).step_by(LUMA_SAMPLE_STEP) {
23 for &value in plane[row * stride..][..width].iter().step_by(LUMA_SAMPLE_STEP) {
24 sum += u64::from(value);
25 count += 1;
26 }
27 }
28 if count == 0 { 0. } else { sum as f32 / (count as f32 * 255.) }
29}
30
31pub fn target_gamma(mean_luma: f32) -> f32 {
32 if mean_luma >= DARK_LUMA {
33 return 1.;
34 }
35 let darkness = ((DARK_LUMA - mean_luma) / (DARK_LUMA - VERY_DARK_LUMA)).clamp(0., 1.);
36 GAMMA_AT_DARK + (GAMMA_AT_VERY_DARK - GAMMA_AT_DARK) * darkness
37}
38
39pub fn smooth_gamma(current: f32, target: f32, elapsed: Duration) -> f32 {
40 let next = current + (target - current) * (1. - (-elapsed.as_secs_f32() / GAMMA_TIME_CONSTANT).exp());
41 if (next - target).abs() < GAMMA_SETTLED { target } else { next }
42}
43
44pub fn gamma_table(gamma: f32) -> [u8; 256] {
45 std::array::from_fn(|value| (255. * (value as f32 / 255.).powf(gamma)).round() as u8)
46}
47
48pub fn apply_table(plane: &mut [u8], stride: usize, width: usize, height: usize, table: &[u8; 256]) {
49 for row in plane.chunks_mut(stride).take(height) {
50 for value in &mut row[..width] {
51 *value = table[usize::from(*value)];
52 }
53 }
54}
55
56pub fn inside_person(mask_value: f32) -> f32 {
57 ((mask_value - INSIDE_START) / (1. - INSIDE_START)).clamp(0., 1.)
58}
59
60pub fn soft_focus_alpha(strength_percent: u8, inside: f32) -> f32 {
61 f32::from(strength_percent.min(100)) / 100. * SOFT_FOCUS_MAX_ALPHA * inside
62}
63
64pub fn blend_coefficients(alpha: f32, slope: f32, offset: f32) -> (f32, f32) {
65 (1. + alpha * (slope - 1.), alpha * offset)
66}
67
68pub fn apply_coefficients(value: u8, gain: f32, bias: f32) -> u8 {
69 (f32::from(value) * gain + bias + 0.5) as u8
70}
71
72fn box_mean(input: &[f32], width: usize, height: usize) -> Vec<f32> {
73 let mut across = vec![0f32; input.len()];
74 for (line, mean) in input.chunks_exact(width).zip(across.chunks_exact_mut(width)) {
75 for (index, slot) in mean.iter_mut().enumerate() {
76 let (low, high) = (index.saturating_sub(FILTER_RADIUS), (index + FILTER_RADIUS).min(width - 1));
77 *slot = line[low..=high].iter().sum::<f32>() / (high + 1 - low) as f32;
78 }
79 }
80 let mut output = vec![0f32; input.len()];
81 for row in 0..height {
82 let (low, high) = (row.saturating_sub(FILTER_RADIUS), (row + FILTER_RADIUS).min(height - 1));
83 let slot = &mut output[row * width..][..width];
84 for line in low..=high {
85 slot.iter_mut().zip(&across[line * width..][..width]).for_each(|(sum, value)| *sum += value);
86 }
87 let count = (high + 1 - low) as f32;
88 slot.iter_mut().for_each(|sum| *sum /= count);
89 }
90 output
91}
92
93struct Cells {
94 gain: Vec<f32>,
95 bias: Vec<f32>,
96 alpha: Vec<f32>,
97 width: usize,
98 height: usize,
99}
100
101fn cell_means(plane: &[u8], stride: usize, cell_width: usize, cell_height: usize) -> Vec<f32> {
102 let mut means = vec![0f32; cell_width * cell_height];
103 let mut sums = vec![0u32; cell_width];
104 for (row, mean) in means.chunks_exact_mut(cell_width).enumerate() {
105 sums.fill(0);
106 for line in 0..CELL {
107 let pixels = &plane[(row * CELL + line) * stride..][..cell_width * CELL];
108 for (sum, group) in sums.iter_mut().zip(pixels.as_chunks::<CELL>().0) {
109 *sum += group.iter().map(|&value| u32::from(value)).sum::<u32>();
110 }
111 }
112 mean.iter_mut().zip(&sums).for_each(|(slot, sum)| *slot = *sum as f32 / (CELL * CELL) as f32);
113 }
114 means
115}
116
117fn smoothing_cells(plane: &[u8], stride: usize, width: usize, height: usize, mask: &[f32], strength_percent: u8) -> Cells {
118 let (cell_width, cell_height) = (width / CELL, height / CELL);
119 let small = cell_means(plane, stride, cell_width, cell_height);
120 let squared: Vec<f32> = small.iter().map(|value| value * value).collect();
121 let mean = box_mean(&small, cell_width, cell_height);
122 let mean_squared = box_mean(&squared, cell_width, cell_height);
123 let slope: Vec<f32> = mean.iter().zip(&mean_squared).map(|(mean, squared)| {
124 let variance = (squared - mean * mean).max(0.);
125 variance / (variance + FILTER_EPSILON)
126 }).collect();
127 let offset: Vec<f32> = mean.iter().zip(&slope).map(|(mean, slope)| mean * (1. - slope)).collect();
128 let (mean_slope, mean_offset) = (box_mean(&slope, cell_width, cell_height), box_mean(&offset, cell_width, cell_height));
129 let (mask_x, mask_y) = (axis(cell_width, MASK_WIDTH), axis(cell_height, MASK_HEIGHT));
130 let mut cells = Cells { gain: vec![1.; small.len()], bias: vec![0.; small.len()], alpha: vec![0.; small.len()], width: cell_width, height: cell_height };
131 for row in 0..cell_height {
132 let (mask_top, mask_bottom, mask_fraction) = (mask_y.first[row] * MASK_WIDTH, mask_y.second[row] * MASK_WIDTH, mask_y.weight[row]);
133 for column in 0..cell_width {
134 let (left, right, across) = (mask_x.first[column], mask_x.second[column], mask_x.weight[column]);
135 let top = mask[mask_top + left] * (1. - across) + mask[mask_top + right] * across;
136 let bottom = mask[mask_bottom + left] * (1. - across) + mask[mask_bottom + right] * across;
137 let index = row * cell_width + column;
138 let alpha = soft_focus_alpha(strength_percent, inside_person(top * (1. - mask_fraction) + bottom * mask_fraction));
139 (cells.gain[index], cells.bias[index]) = blend_coefficients(alpha, mean_slope[index], mean_offset[index]);
140 cells.alpha[index] = alpha;
141 }
142 }
143 cells
144}
145
146fn neighbor(index: usize, step: usize, last: usize) -> usize {
147 if step < CELL / 2 { index.saturating_sub(1) } else { (index + 1).min(last) }
148}
149
150fn blend_rows(plane: &mut [u8], stride: usize, first_row: usize, cells: &Cells) {
151 let (mut gain_row, mut bias_row) = (vec![0f32; cells.width], vec![0f32; cells.width]);
152 for (offset, line) in plane.chunks_mut(stride).enumerate() {
153 let row = first_row + offset;
154 if row >= cells.height * CELL {
155 break;
156 }
157 let (near, step) = (row / CELL, row % CELL);
158 let far = neighbor(near, step, cells.height - 1);
159 let (near_start, far_start) = (near * cells.width, far * cells.width);
160 if cells.alpha[near_start..][..cells.width].iter().chain(&cells.alpha[far_start..][..cells.width]).all(|alpha| *alpha <= 0.) {
161 continue;
162 }
163 let (near_weight, far_weight) = (NEAR_WEIGHTS[step], 1. - NEAR_WEIGHTS[step]);
164 for column in 0..cells.width {
165 gain_row[column] = cells.gain[near_start + column] * near_weight + cells.gain[far_start + column] * far_weight;
166 bias_row[column] = cells.bias[near_start + column] * near_weight + cells.bias[far_start + column] * far_weight;
167 }
168 for (column, group) in line[..cells.width * CELL].as_chunks_mut::<CELL>().0.iter_mut().enumerate() {
169 for (step, value) in group.iter_mut().enumerate() {
170 let far = neighbor(column, step, cells.width - 1);
171 let (near_weight, far_weight) = (NEAR_WEIGHTS[step], 1. - NEAR_WEIGHTS[step]);
172 let gain = gain_row[column] * near_weight + gain_row[far] * far_weight;
173 let bias = bias_row[column] * near_weight + bias_row[far] * far_weight;
174 *value = apply_coefficients(*value, gain, bias);
175 }
176 }
177 }
178}
179
180/// Edge-preserving smoothing (fast guided filter, radius about 4) of the luma plane, blended in only inside the person mask.
181pub fn soften_luma(plane: &mut [u8], stride: usize, width: usize, height: usize, mask: &[f32], strength_percent: u8) {
182 if strength_percent == 0 || width < CELL * 2 || height < CELL * 2 {
183 return;
184 }
185 let cells = smoothing_cells(plane, stride, width, height, mask, strength_percent);
186 let bands = std::thread::available_parallelism().map_or(1, usize::from).min(MAX_BANDS);
187 let rows_per_band = height.div_ceil(bands).next_multiple_of(CELL);
188 std::thread::scope(|scope| {
189 for (index, band) in plane[..stride * (height - 1) + width].chunks_mut(rows_per_band * stride).enumerate() {
190 let cells = &cells;
191 scope.spawn(move || blend_rows(band, stride, index * rows_per_band, cells));
192 }
193 });
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 const WIDTH: usize = 64;
201 const HEIGHT: usize = 36;
202
203 #[test]
204 fn the_gamma_follows_the_darkness_and_leaves_bright_frames_alone() {
205 assert_eq!(target_gamma(0.5), 1.);
206 assert_eq!(target_gamma(0.35), 1.);
207 assert!((target_gamma(0.3499) - GAMMA_AT_DARK).abs() < 0.001);
208 assert_eq!(target_gamma(0.05), GAMMA_AT_VERY_DARK);
209 assert_eq!(target_gamma(0.), GAMMA_AT_VERY_DARK);
210 let middle = target_gamma(0.2);
211 assert!(middle < GAMMA_AT_DARK && middle > GAMMA_AT_VERY_DARK);
212 }
213
214 #[test]
215 fn the_gamma_glides_instead_of_jumping() {
216 let step = Duration::from_millis(33);
217 let first = smooth_gamma(1., 0.6, step);
218 assert!(first < 1. && first > 0.95);
219 let mut gamma = 1.;
220 for _ in 0..300 {
221 gamma = smooth_gamma(gamma, 0.6, step);
222 }
223 assert_eq!(gamma, 0.6);
224 }
225
226 #[test]
227 fn the_table_brightens_dark_values_and_keeps_the_ends() {
228 let table = gamma_table(0.6);
229 assert_eq!((table[0], table[255]), (0, 255));
230 assert!(table[40] > 40 && table[128] > 128);
231 assert!(table.windows(2).all(|pair| pair[0] <= pair[1]));
232 assert_eq!(gamma_table(1.), std::array::from_fn(|value| value as u8));
233 let mut plane = vec![40u8; WIDTH * HEIGHT];
234 apply_table(&mut plane, WIDTH, WIDTH, HEIGHT, &table);
235 assert!(plane.iter().all(|&value| value == table[40]));
236 }
237
238 #[test]
239 fn the_mean_luma_is_a_fraction_of_full_scale() {
240 assert_eq!(mean_luma(&vec![255; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 1.);
241 assert_eq!(mean_luma(&vec![0; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT), 0.);
242 assert!((mean_luma(&vec![51; WIDTH * HEIGHT], WIDTH, WIDTH, HEIGHT) - 0.2).abs() < 1e-3);
243 }
244
245 #[test]
246 fn the_blend_only_acts_inside_the_person_and_scales_with_strength() {
247 assert_eq!(soft_focus_alpha(100, 1.), SOFT_FOCUS_MAX_ALPHA);
248 assert_eq!(soft_focus_alpha(50, 1.), 0.35);
249 assert_eq!(soft_focus_alpha(0, 1.), 0.);
250 assert_eq!(soft_focus_alpha(100, 0.), 0.);
251 assert_eq!(inside_person(0.5), 0.);
252 assert_eq!(inside_person(0.2), 0.);
253 assert_eq!(inside_person(1.), 1.);
254 assert_eq!(blend_coefficients(0., 0.3, 40.), (1., 0.));
255 assert_eq!(blend_coefficients(1., 0.3, 40.), (0.3, 40.));
256 let (gain, bias) = blend_coefficients(0.5, 0.2, 100.);
257 assert_eq!(apply_coefficients(100, gain, bias), 110);
258 }
259
260 fn noisy_plane() -> Vec<u8> {
261 (0..WIDTH * HEIGHT)
262 .map(|index| {
263 let (x, y) = (index % WIDTH, index / WIDTH);
264 let base = if x < WIDTH / 2 { 60 } else { 200 };
265 (base + ((x * 7 + y * 13) % 9) as i32 - 4) as u8
266 })
267 .collect()
268 }
269
270 fn roughness(plane: &[u8], y: usize, from: usize, to: usize) -> i32 {
271 (from..to).map(|x| (i32::from(plane[y * WIDTH + x + 1]) - i32::from(plane[y * WIDTH + x])).abs()).sum()
272 }
273
274 #[test]
275 fn soft_focus_smooths_noise_inside_the_mask_keeps_edges_and_spares_the_outside() {
276 let original = noisy_plane();
277 let mut softened = original.clone();
278 let mut mask = vec![0f32; MASK_WIDTH * MASK_HEIGHT];
279 for row in 0..MASK_HEIGHT {
280 mask[row * MASK_WIDTH..][..MASK_WIDTH / 2 + 20].fill(1.);
281 }
282 soften_luma(&mut softened, WIDTH, WIDTH, HEIGHT, &mask, 100);
283 assert!(roughness(&softened, 18, 2, 20) < roughness(&original, 18, 2, 20));
284 assert!(i32::from(softened[18 * WIDTH + WIDTH / 2 + 2]) - i32::from(softened[18 * WIDTH + WIDTH / 2 - 3]) > 100);
285 assert_eq!(softened[18 * WIDTH + WIDTH - 4], original[18 * WIDTH + WIDTH - 4]);
286 let mut untouched = original.clone();
287 soften_luma(&mut untouched, WIDTH, WIDTH, HEIGHT, &mask, 0);
288 assert_eq!(untouched, original);
289 }
290}
crates/calling/src/video_frame.rs +15 −0
@@ -47,6 +47,13 @@ pub struct VideoPicture {
47 47 }
48 48
49 49 impl VideoPicture {
50 pub fn flip_horizontally(&mut self) {
51 for row in self.bgra.chunks_exact_mut(self.width as usize * BYTES_PER_PIXEL) {
52 let (pixels, _) = row.as_chunks_mut::<BYTES_PER_PIXEL>();
53 pixels.reverse();
54 }
55 }
56
50 57 pub fn solid(width: u32, height: u32, blue: u8, green: u8, red: u8) -> Self {
51 58 let pixel = [blue, green, red, u8::MAX];
52 59 VideoPicture {
@@ -151,6 +158,14 @@ pub fn bgra_from_i420(i420: I420Buffer) -> VideoPicture {
151 158 mod tests {
152 159 use super::*;
153 160
161 #[test]
162 fn flipping_mirrors_every_row() {
163 let mut picture = VideoPicture { width: 3, height: 2, bgra: (0u8..24).collect() };
164 picture.flip_horizontally();
165 assert_eq!(&picture.bgra[..12], &[8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3]);
166 assert_eq!(&picture.bgra[12..16], &[20, 21, 22, 23]);
167 }
168
154 169 #[test]
155 170 fn the_gate_caps_a_fast_source_at_thirty_frames_a_second() {
156 171 let mut gate = FrameGate::new(30);
@@ -47,6 +47,13 @@ pub struct VideoPicture {
47}
47}
48
48
49impl VideoPicture {
49impl VideoPicture {
50 pub fn flip_horizontally(&mut self) {
51 for row in self.bgra.chunks_exact_mut(self.width as usize * BYTES_PER_PIXEL) {
52 let (pixels, _) = row.as_chunks_mut::<BYTES_PER_PIXEL>();
53 pixels.reverse();
54 }
55 }
56
50 pub fn solid(width: u32, height: u32, blue: u8, green: u8, red: u8) -> Self {
57 pub fn solid(width: u32, height: u32, blue: u8, green: u8, red: u8) -> Self {
51 let pixel = [blue, green, red, u8::MAX];
58 let pixel = [blue, green, red, u8::MAX];
52 VideoPicture {
59 VideoPicture {
@@ -151,6 +158,14 @@ pub fn bgra_from_i420(i420: I420Buffer) -> VideoPicture {
151mod tests {
158mod tests {
152 use super::*;
159 use super::*;
153
160
161 #[test]
162 fn flipping_mirrors_every_row() {
163 let mut picture = VideoPicture { width: 3, height: 2, bgra: (0u8..24).collect() };
164 picture.flip_horizontally();
165 assert_eq!(&picture.bgra[..12], &[8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3]);
166 assert_eq!(&picture.bgra[12..16], &[20, 21, 22, 23]);
167 }
168
154 #[test]
169 #[test]
155 fn the_gate_caps_a_fast_source_at_thirty_frames_a_second() {
170 fn the_gate_caps_a_fast_source_at_thirty_frames_a_second() {
156 let mut gate = FrameGate::new(30);
171 let mut gate = FrameGate::new(30);
crates/calling/src/video_pattern.rs +3 −3
@@ -4,7 +4,7 @@ use libwebrtc::video_frame::I420Buffer;
4 4 use tokio::task::JoinHandle;
5 5 use tokio::time::interval;
6 6
7 use crate::blur::BlurStage;
7 use crate::effects::EffectsStage;
8 8 use crate::video_send::LocalSink;
9 9
10 10 pub const CAMERA_WIDTH: u32 = 640;
@@ -102,14 +102,14 @@ fn paint_screen(
102 102 v_plane[..(stride_v * height / 2) as usize].fill(128);
103 103 }
104 104
105 pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind, mut blur: Option<BlurStage>) -> JoinHandle<()> {
105 pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind, mut effects: Option<EffectsStage>) -> JoinHandle<()> {
106 106 tokio::spawn(async move {
107 107 let mut ticker = interval(Duration::from_secs(1) / kind.fps());
108 108 let mut tick = 0u32;
109 109 loop {
110 110 ticker.tick().await;
111 111 let frame = pattern_frame(kind, tick);
112 sink.push(match blur.as_mut() {
112 sink.push(match effects.as_mut() {
113 113 Some(stage) => stage.apply_i420(frame),
114 114 None => frame,
115 115 });
@@ -4,7 +4,7 @@ use libwebrtc::video_frame::I420Buffer;
4use tokio::task::JoinHandle;
4use tokio::task::JoinHandle;
5use tokio::time::interval;
5use tokio::time::interval;
6
6
7use crate::blur::BlurStage;
7use crate::effects::EffectsStage;
8use crate::video_send::LocalSink;
8use crate::video_send::LocalSink;
9
9
10pub const CAMERA_WIDTH: u32 = 640;
10pub const CAMERA_WIDTH: u32 = 640;
@@ -102,14 +102,14 @@ fn paint_screen(
102 v_plane[..(stride_v * height / 2) as usize].fill(128);
102 v_plane[..(stride_v * height / 2) as usize].fill(128);
103}
103}
104
104
105pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind, mut blur: Option<BlurStage>) -> JoinHandle<()> {
105pub fn spawn_pattern(mut sink: LocalSink, kind: PatternKind, mut effects: Option<EffectsStage>) -> JoinHandle<()> {
106 tokio::spawn(async move {
106 tokio::spawn(async move {
107 let mut ticker = interval(Duration::from_secs(1) / kind.fps());
107 let mut ticker = interval(Duration::from_secs(1) / kind.fps());
108 let mut tick = 0u32;
108 let mut tick = 0u32;
109 loop {
109 loop {
110 ticker.tick().await;
110 ticker.tick().await;
111 let frame = pattern_frame(kind, tick);
111 let frame = pattern_frame(kind, tick);
112 sink.push(match blur.as_mut() {
112 sink.push(match effects.as_mut() {
113 Some(stage) => stage.apply_i420(frame),
113 Some(stage) => stage.apply_i420(frame),
114 None => frame,
114 None => frame,
115 });
115 });
crates/calling/src/video_send.rs +20 −6
@@ -12,7 +12,8 @@ use libwebrtc::video_track::RtcVideoTrack;
12 12 use tokio::sync::mpsc::UnboundedSender;
13 13
14 14 use crate::background::BackgroundPicture;
15 use crate::blur::{BlurSettings, BlurStage};
15 use crate::blur::BlurSettings;
16 use crate::effects::{CameraEffects, EffectsStage};
16 17 use crate::camera::start_camera;
17 18 use crate::capture::Capture;
18 19 use crate::control::CallUpdate;
@@ -53,6 +54,7 @@ impl VideoMode {
53 54 pub struct LocalSink {
54 55 source: NativeVideoSource,
55 56 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
57 mirror: Option<Arc<BlurSettings>>,
56 58 }
57 59
58 60 impl LocalSink {
@@ -61,7 +63,12 @@ impl LocalSink {
61 63 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
62 64 (hub, key, FrameGate::new(fps))
63 65 });
64 LocalSink { source, self_view }
66 LocalSink { source, self_view, mirror: None }
67 }
68
69 pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
70 self.mirror = Some(settings);
71 self
65 72 }
66 73
67 74 pub fn push(&mut self, buffer: I420Buffer) {
@@ -70,8 +77,11 @@ impl LocalSink {
70 77 self.source.capture_frame(&frame);
71 78 let Some((hub, key, gate)) = &mut self.self_view else { return };
72 79 if gate.admit(Instant::now())
73 && let Some(picture) = picture_from_i420(frame.buffer, key.max_width())
80 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
74 81 {
82 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
83 picture.flip_horizontally();
84 }
75 85 hub.publish(key.clone(), picture);
76 86 }
77 87 }
@@ -121,12 +131,16 @@ impl LocalVideo {
121 131 self.blur.set_enabled(enabled);
122 132 }
123 133
134 pub fn set_effects(&self, effects: CameraEffects) {
135 self.blur.set_effects(effects);
136 }
137
124 138 pub fn camera_track(&self) -> RtcVideoTrack {
125 139 self.camera.track.clone()
126 140 }
127 141
128 142 pub fn blur_average_ms(&self) -> Option<f32> {
129 (self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())
143 (self.camera_on() && self.blur.active()).then(|| self.blur.average_ms())
130 144 }
131 145
132 146 pub fn has_lines(&self) -> bool {
@@ -174,7 +188,7 @@ impl LocalVideo {
174 188 }
175 189
176 190 fn camera_sink(&self) -> LocalSink {
177 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
191 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera))).mirrored_by(self.blur.clone())
178 192 }
179 193
180 194 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -192,7 +206,7 @@ impl LocalVideo {
192 206 self.camera.capture = None;
193 207 let mut sink = self.camera_sink();
194 208 let capture = match self.mode {
195 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),
209 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(EffectsStage::new(self.blur.clone())))),
196 210 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
197 211 };
198 212 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
@@ -12,7 +12,8 @@ use libwebrtc::video_track::RtcVideoTrack;
12use tokio::sync::mpsc::UnboundedSender;
12use tokio::sync::mpsc::UnboundedSender;
13
13
14use crate::background::BackgroundPicture;
14use crate::background::BackgroundPicture;
15use crate::blur::{BlurSettings, BlurStage};
15use crate::blur::BlurSettings;
16use crate::effects::{CameraEffects, EffectsStage};
16use crate::camera::start_camera;
17use crate::camera::start_camera;
17use crate::capture::Capture;
18use crate::capture::Capture;
18use crate::control::CallUpdate;
19use crate::control::CallUpdate;
@@ -53,6 +54,7 @@ impl VideoMode {
53pub struct LocalSink {
54pub struct LocalSink {
54 source: NativeVideoSource,
55 source: NativeVideoSource,
55 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
56 self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
57 mirror: Option<Arc<BlurSettings>>,
56}
58}
57
59
58impl LocalSink {
60impl LocalSink {
@@ -61,7 +63,12 @@ impl LocalSink {
61 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
63 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
62 (hub, key, FrameGate::new(fps))
64 (hub, key, FrameGate::new(fps))
63 });
65 });
64 LocalSink { source, self_view }
66 LocalSink { source, self_view, mirror: None }
67 }
68
69 pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
70 self.mirror = Some(settings);
71 self
65 }
72 }
66
73
67 pub fn push(&mut self, buffer: I420Buffer) {
74 pub fn push(&mut self, buffer: I420Buffer) {
@@ -70,8 +77,11 @@ impl LocalSink {
70 self.source.capture_frame(&frame);
77 self.source.capture_frame(&frame);
71 let Some((hub, key, gate)) = &mut self.self_view else { return };
78 let Some((hub, key, gate)) = &mut self.self_view else { return };
72 if gate.admit(Instant::now())
79 if gate.admit(Instant::now())
73 && let Some(picture) = picture_from_i420(frame.buffer, key.max_width())
80 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
74 {
81 {
82 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
83 picture.flip_horizontally();
84 }
75 hub.publish(key.clone(), picture);
85 hub.publish(key.clone(), picture);
76 }
86 }
77 }
87 }
@@ -121,12 +131,16 @@ impl LocalVideo {
121 self.blur.set_enabled(enabled);
131 self.blur.set_enabled(enabled);
122 }
132 }
123
133
134 pub fn set_effects(&self, effects: CameraEffects) {
135 self.blur.set_effects(effects);
136 }
137
124 pub fn camera_track(&self) -> RtcVideoTrack {
138 pub fn camera_track(&self) -> RtcVideoTrack {
125 self.camera.track.clone()
139 self.camera.track.clone()
126 }
140 }
127
141
128 pub fn blur_average_ms(&self) -> Option<f32> {
142 pub fn blur_average_ms(&self) -> Option<f32> {
129 (self.camera_on() && self.blur.enabled()).then(|| self.blur.average_ms())
143 (self.camera_on() && self.blur.active()).then(|| self.blur.average_ms())
130 }
144 }
131
145
132 pub fn has_lines(&self) -> bool {
146 pub fn has_lines(&self) -> bool {
@@ -174,7 +188,7 @@ impl LocalVideo {
174 }
188 }
175
189
176 fn camera_sink(&self) -> LocalSink {
190 fn camera_sink(&self) -> LocalSink {
177 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
191 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera))).mirrored_by(self.blur.clone())
178 }
192 }
179
193
180 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
194 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -192,7 +206,7 @@ impl LocalVideo {
192 self.camera.capture = None;
206 self.camera.capture = None;
193 let mut sink = self.camera_sink();
207 let mut sink = self.camera_sink();
194 let capture = match self.mode {
208 let capture = match self.mode {
195 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(BlurStage::new(self.blur.clone())))),
209 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(EffectsStage::new(self.blur.clone())))),
196 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
210 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
197 };
211 };
198 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
212 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;