feat(calls): mirror, auto framing, brightness and soft focus camera effects
- Camera menu and Settings > Devices get an Effects section, remembered and live - Mirror flips the self view and camera test only, after all effects - Auto framing: person box from the shared mask, deadband, smoothing, speed cap, hold then ease out - Adjust brightness: gamma table on Y below 0.35 mean luma, smoothed over time - Soft focus: guided filter on Y blended inside the person mask - One MaskSource per frame for blur, picture, framing and soft focus - blur_bench measures the new effects at 720p Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -171,6 +171,7 @@ Feature parity with the Microsoft Teams desktop client.
171
171
| 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
172
| 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
173
| 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
| 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 |
174
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 |
175
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 |
176
177
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |
@@ -171,6 +171,7 @@ Feature parity with the Microsoft Teams desktop client.171
| 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 |171
| 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
| 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 |172
| 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
| 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 |173
| 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
| 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 |174
| 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 |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 |175
| 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 |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 |176
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |177
| Hold, resume, transfer | Partial | 1:1 "..." > Hold renegotiates every line inactive, "On hold" view with Resume, "You're on hold" when the other side holds, Transfer... person picker with Transfer now (blind) and Consult first (second call, first held, Transfer now). Needs a second person; redirect and park not built |@@ -126,6 +126,7 @@ pub struct AppState {
126
126
pub call_share_sound: bool,
127
127
pub call_background: crate::call::BackgroundPick,
128
128
pub call_camera: calling::DeviceChoice,
129
pub call_effects: calling::CameraEffects,
129
130
pub meet_now_pending: bool,
130
131
pub call_backgrounds: crate::call::BackgroundLibrary,
131
132
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
@@ -223,6 +224,7 @@ impl AppState {
223
224
call_share_sound: false,
224
225
call_background: crate::call::BackgroundPick::None,
225
226
call_camera: calling::DeviceChoice::SystemDefault,
227
call_effects: calling::CameraEffects::default(),
226
228
meet_now_pending: false,
227
229
call_backgrounds: if mode.demo {
228
230
crate::call::demo_library()
@@ -241,6 +243,7 @@ impl AppState {
241
243
state.call_share_sound = crate::call::load_share_sound(&state.store);
242
244
state.call_background = crate::call::load_background(&state.store);
243
245
state.call_camera = crate::call::load_camera(&state.store);
246
state.call_effects = crate::call::load_camera_effects(&state.store);
244
247
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
245
248
state.load_cached_translation_settings();
246
249
if !mode.demo {
@@ -126,6 +126,7 @@ pub struct AppState {126
pub call_share_sound: bool,126
pub call_share_sound: bool,127
pub call_background: crate::call::BackgroundPick,127
pub call_background: crate::call::BackgroundPick,128
pub call_camera: calling::DeviceChoice,128
pub call_camera: calling::DeviceChoice,129
pub call_effects: calling::CameraEffects,129
pub meet_now_pending: bool,130
pub meet_now_pending: bool,130
pub call_backgrounds: crate::call::BackgroundLibrary,131
pub call_backgrounds: crate::call::BackgroundLibrary,131
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,132
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,@@ -223,6 +224,7 @@ impl AppState {223
call_share_sound: false,224
call_share_sound: false,224
call_background: crate::call::BackgroundPick::None,225
call_background: crate::call::BackgroundPick::None,225
call_camera: calling::DeviceChoice::SystemDefault,226
call_camera: calling::DeviceChoice::SystemDefault,227
call_effects: calling::CameraEffects::default(),226
meet_now_pending: false,228
meet_now_pending: false,227
call_backgrounds: if mode.demo {229
call_backgrounds: if mode.demo {228
crate::call::demo_library()230
crate::call::demo_library()@@ -241,6 +243,7 @@ impl AppState {241
state.call_share_sound = crate::call::load_share_sound(&state.store);243
state.call_share_sound = crate::call::load_share_sound(&state.store);242
state.call_background = crate::call::load_background(&state.store);244
state.call_background = crate::call::load_background(&state.store);243
state.call_camera = crate::call::load_camera(&state.store);245
state.call_camera = crate::call::load_camera(&state.store);246
state.call_effects = crate::call::load_camera_effects(&state.store);244
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);247
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);245
state.load_cached_translation_settings();248
state.load_cached_translation_settings();246
if !mode.demo {249
if !mode.demo {@@ -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, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6
DeviceChoice, EndReason, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7
7
};
8
8
use gpui_kit::*;
9
9
@@ -37,6 +37,7 @@ const DEMO_LIVE_MINUTES: i64 = 60;
37
37
const ORGID_PREFIX: &str = "8:orgid:";
38
38
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
39
39
const CAMERA_META_KEY: &str = "call_camera";
40
const EFFECTS_META_KEY: &str = "call_camera_effects";
40
41
const DEFAULT_CAMERA_META: &str = "default";
41
42
42
43
pub fn load_share_sound(store: &store::Store) -> bool {
@@ -50,6 +51,16 @@ pub fn load_camera(store: &store::Store) -> DeviceChoice {
50
51
}
51
52
}
52
53
54
pub fn load_camera_effects(store: &store::Store) -> CameraEffects {
55
store
56
.meta(EFFECTS_META_KEY)
57
.ok()
58
.flatten()
59
.map_or_else(CameraEffects::default, |value| {
60
CameraEffects::from_meta(&value)
61
})
62
}
63
53
64
fn camera_meta(choice: &DeviceChoice) -> &str {
54
65
match choice {
55
66
DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
@@ -225,6 +236,7 @@ impl AppState {
225
236
if self.call_background != BackgroundPick::None {
226
237
self.send_background_command(cx);
227
238
}
239
self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));
228
240
self.refresh_call_backgrounds(cx);
229
241
self.new_chat = false;
230
242
self.follow_call(call_id, updates, cx);
@@ -671,6 +683,13 @@ impl AppState {
671
683
self.send_call_command(CallCommand::SetCaptions(on));
672
684
}
673
685
686
pub fn set_call_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
687
let _ = self.store.set_meta(EFFECTS_META_KEY, &effects.to_meta());
688
self.call_effects = effects;
689
self.send_call_command(CallCommand::SetCameraEffects(effects));
690
cx.notify();
691
}
692
674
693
pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
675
694
let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());
676
695
self.call_background = pick.clone();
@@ -1086,13 +1105,13 @@ mod tests {
1086
1105
use std::path::PathBuf;
1087
1106
1088
1107
use calling::{
1089
BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind,
1090
EndReason, EngineEvent, HoldState, Reaction, call_channel,
1108
BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,
1109
DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel,
1091
1110
};
1092
1111
use gpui_kit::{AppContext as _, Entity, TestAppContext};
1093
1112
use store::{ChatRecord, MemberRecord, Store};
1094
1113
1095
use super::{ActiveCall, CallModel, load_camera};
1114
use super::{ActiveCall, CallModel, load_camera, load_camera_effects};
1096
1115
use crate::app_state::{AppEvent, AppState, Mode, Selection};
1097
1116
use crate::call::TransferCandidate;
1098
1117
use crate::call::background::BackgroundPick;
@@ -1238,6 +1257,28 @@ mod tests {
1238
1257
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
1239
1258
}
1240
1259
1260
#[gpui_kit::test]
1261
fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1262
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1263
let store = cx.update(|cx| app.read(cx).store.clone());
1264
assert_eq!(load_camera_effects(&store), CameraEffects::default());
1265
let effects = CameraEffects {
1266
mirror: false,
1267
auto_framing: true,
1268
soft_focus: true,
1269
soft_focus_strength: 75,
1270
..CameraEffects::default()
1271
};
1272
cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));
1273
assert_eq!(
1274
control.try_recv_command(),
1275
Some(CallCommand::SetCameraEffects(effects))
1276
);
1277
assert_eq!(load_camera_effects(&store), effects);
1278
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1279
assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);
1280
}
1281
1241
1282
#[gpui_kit::test]
1242
1283
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1243
1284
cx: &mut TestAppContext,
@@ -2,8 +2,8 @@ use std::time::{Duration, Instant};2
2
3
use calling::meeting::LiveMeeting;3
use calling::meeting::LiveMeeting;4
use calling::{4
use calling::{5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice,5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,6
EndReason, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,6
DeviceChoice, EndReason, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,7
};7
};8
use gpui_kit::*;8
use gpui_kit::*;9
9
@@ -37,6 +37,7 @@ const DEMO_LIVE_MINUTES: i64 = 60;37
const ORGID_PREFIX: &str = "8:orgid:";37
const ORGID_PREFIX: &str = "8:orgid:";38
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";38
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";39
const CAMERA_META_KEY: &str = "call_camera";39
const CAMERA_META_KEY: &str = "call_camera";40
const EFFECTS_META_KEY: &str = "call_camera_effects";40
const DEFAULT_CAMERA_META: &str = "default";41
const DEFAULT_CAMERA_META: &str = "default";41
42
42
pub fn load_share_sound(store: &store::Store) -> bool {43
pub fn load_share_sound(store: &store::Store) -> bool {@@ -50,6 +51,16 @@ pub fn load_camera(store: &store::Store) -> DeviceChoice {50
}51
}51
}52
}52
53
54
pub fn load_camera_effects(store: &store::Store) -> CameraEffects {55
store56
.meta(EFFECTS_META_KEY)57
.ok()58
.flatten()59
.map_or_else(CameraEffects::default, |value| {60
CameraEffects::from_meta(&value)61
})62
}63
53
fn camera_meta(choice: &DeviceChoice) -> &str {64
fn camera_meta(choice: &DeviceChoice) -> &str {54
match choice {65
match choice {55
DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,66
DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,@@ -225,6 +236,7 @@ impl AppState {225
if self.call_background != BackgroundPick::None {236
if self.call_background != BackgroundPick::None {226
self.send_background_command(cx);237
self.send_background_command(cx);227
}238
}239
self.send_call_command(CallCommand::SetCameraEffects(self.call_effects));228
self.refresh_call_backgrounds(cx);240
self.refresh_call_backgrounds(cx);229
self.new_chat = false;241
self.new_chat = false;230
self.follow_call(call_id, updates, cx);242
self.follow_call(call_id, updates, cx);@@ -671,6 +683,13 @@ impl AppState {671
self.send_call_command(CallCommand::SetCaptions(on));683
self.send_call_command(CallCommand::SetCaptions(on));672
}684
}673
685
686
pub fn set_call_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {687
let _ = self.store.set_meta(EFFECTS_META_KEY, &effects.to_meta());688
self.call_effects = effects;689
self.send_call_command(CallCommand::SetCameraEffects(effects));690
cx.notify();691
}692
674
pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {693
pub fn set_call_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {675
let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());694
let _ = self.store.set_meta(BACKGROUND_META_KEY, &pick.to_meta());676
self.call_background = pick.clone();695
self.call_background = pick.clone();@@ -1086,13 +1105,13 @@ mod tests {1086
use std::path::PathBuf;1105
use std::path::PathBuf;1087
1106
1088
use calling::{1107
use calling::{1089
BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind,1108
BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, CameraEffects,1090
EndReason, EngineEvent, HoldState, Reaction, call_channel,1109
DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel,1091
};1110
};1092
use gpui_kit::{AppContext as _, Entity, TestAppContext};1111
use gpui_kit::{AppContext as _, Entity, TestAppContext};1093
use store::{ChatRecord, MemberRecord, Store};1112
use store::{ChatRecord, MemberRecord, Store};1094
1113
1095
use super::{ActiveCall, CallModel, load_camera};1114
use super::{ActiveCall, CallModel, load_camera, load_camera_effects};1096
use crate::app_state::{AppEvent, AppState, Mode, Selection};1115
use crate::app_state::{AppEvent, AppState, Mode, Selection};1097
use crate::call::TransferCandidate;1116
use crate::call::TransferCandidate;1098
use crate::call::background::BackgroundPick;1117
use crate::call::background::BackgroundPick;@@ -1238,6 +1257,28 @@ mod tests {1238
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);1257
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);1239
}1258
}1240
1259
1260
#[gpui_kit::test]1261
fn the_camera_effects_are_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {1262
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1263
let store = cx.update(|cx| app.read(cx).store.clone());1264
assert_eq!(load_camera_effects(&store), CameraEffects::default());1265
let effects = CameraEffects {1266
mirror: false,1267
auto_framing: true,1268
soft_focus: true,1269
soft_focus_strength: 75,1270
..CameraEffects::default()1271
};1272
cx.update(|cx| app.update(cx, |state, cx| state.set_call_effects(effects, cx)));1273
assert_eq!(1274
control.try_recv_command(),1275
Some(CallCommand::SetCameraEffects(effects))1276
);1277
assert_eq!(load_camera_effects(&store), effects);1278
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1279
assert_eq!(cx.update(|cx| reopened.read(cx).call_effects), effects);1280
}1281
1241
#[gpui_kit::test]1282
#[gpui_kit::test]1242
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(1283
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(1243
cx: &mut TestAppContext,1284
cx: &mut TestAppContext,@@ -532,6 +532,7 @@ async fn speak_until_hangup(
532
532
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));
533
533
}
534
534
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,
535
Some(CallCommand::SetCameraEffects(_)) => {}
535
536
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),
536
537
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),
537
538
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),
@@ -532,6 +532,7 @@ async fn speak_until_hangup(532
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));532
control.send(CallUpdate::Captions(if on { CaptionState::On } else { CaptionState::Off }));533
}533
}534
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,534
Some(CallCommand::SetBackground(choice)) => blur = choice != BackgroundChoice::None,535
Some(CallCommand::SetCameraEffects(_)) => {}535
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),536
Some(CallCommand::SetRecording { on, .. }) => control.send(CallUpdate::Recording(on)),536
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),537
Some(CallCommand::ConsentToRecording) => control.send(CallUpdate::ConsentRequired(false)),537
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),538
Some(CallCommand::Hold(hold)) => control.send(CallUpdate::Hold(if hold { HoldState::Local } else { HoldState::Active })),@@ -18,7 +18,7 @@ mod preview;
18
18
mod ring;
19
19
mod target;
20
20
21
pub use actions::{load_camera, load_share_sound};
21
pub use actions::{load_camera, load_camera_effects, load_share_sound};
22
22
pub use agenda::{AgendaRow, fetch_window, join_available};
23
23
pub use background::{
24
24
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
@@ -18,7 +18,7 @@ mod preview;18
mod ring;18
mod ring;19
mod target;19
mod target;20
20
21
pub use actions::{load_camera, load_share_sound};21
pub use actions::{load_camera, load_camera_effects, load_share_sound};22
pub use agenda::{AgendaRow, fetch_window, join_available};22
pub use agenda::{AgendaRow, fetch_window, join_available};23
pub use background::{23
pub use background::{24
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,24
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,@@ -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;7
use calling::camera::start_camera;7
use calling::camera::start_camera;8
use calling::capture::Capture;8
use calling::capture::Capture;9
use calling::video_frame::picture_from_i420;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
use gpui_kit::*;11
use gpui_kit::*;12
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};12
use 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);@@ -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, camera_entries};
4
use calling::{CameraEffects, DeviceChoice, DeviceEntry, camera_entries};
5
5
use gpui_kit::assets::IconName;
6
6
use gpui_kit::component::{
7
7
button::Button,
@@ -27,6 +27,7 @@ const SELECT_WIDTH: f32 = 170.;
27
27
const PREVIEW_WIDTH: f32 = 380.;
28
28
const PREVIEW_HEIGHT: f32 = 214.;
29
29
const PREVIEW_RADIUS: f32 = 10.;
30
const SOFT_FOCUS_LEVELS: [(&str, u8); 3] = [("Low", 25), ("Medium", 50), ("High", 75)];
30
31
const CAMERA_IN_USE: &str = "Camera is in use by the call";
31
32
32
33
fn camera_in_call(state: &AppState) -> bool {
@@ -129,6 +130,7 @@ impl SettingsView {
129
130
let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));
130
131
let state = app.read(cx);
131
132
let camera = state.call_camera.clone();
133
preview.set_effects(state.call_effects);
132
134
let preview_blocked = camera_in_call(state);
133
135
let background = Some(state.call_background.clone())
134
136
.filter(|pick| {
@@ -194,6 +196,8 @@ impl SettingsView {
194
196
Section::Devices => {
195
197
self.load_cameras(cx);
196
198
self.apply_background(cx);
199
self.preview
200
.set_effects(self.center.read(cx).app().read(cx).call_effects);
197
201
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
198
202
self.start_preview();
199
203
}
@@ -248,6 +252,84 @@ impl SettingsView {
248
252
cx.notify();
249
253
}
250
254
255
fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {
256
let app = self.center.read(cx).app().clone();
257
let mut effects = app.read(cx).call_effects;
258
change(&mut effects);
259
self.preview.set_effects(effects);
260
app.update(cx, |state, cx| state.set_call_effects(effects, cx));
261
cx.notify();
262
}
263
264
fn effect_row(
265
&self,
266
id: &'static str,
267
title: &'static str,
268
on: bool,
269
change: fn(&mut CameraEffects),
270
cx: &mut Context<Self>,
271
) -> Stateful<Div> {
272
let view = cx.entity();
273
h_flex()
274
.id(id)
275
.w_full()
276
.px(px(20.))
277
.py(px(6.))
278
.gap(px(12.))
279
.items_center()
280
.cursor_pointer()
281
.hover(|row| row.bg(theme::row_hover()))
282
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.change_effects(change, cx)))
283
.child(
284
div()
285
.flex_1()
286
.text_size(px(14.))
287
.font_weight(FontWeight::SEMIBOLD)
288
.text_color(theme::text())
289
.child(title),
290
)
291
.child(switch(on))
292
}
293
294
fn strength_row(&self, strength: u8, cx: &mut Context<Self>) -> Stateful<Div> {
295
let levels = SOFT_FOCUS_LEVELS.map(|(label, level)| {
296
let view = cx.entity();
297
let app = self.center.read(cx).app().clone();
298
button(label)
299
.when(strength == level, |button| {
300
button.bg(theme::accent()).text_color(theme::on_accent())
301
})
302
.on_click(move |_, _, cx| {
303
app.update(cx, |state, cx| {
304
let effects = CameraEffects {
305
soft_focus_strength: level,
306
..state.call_effects
307
};
308
state.set_call_effects(effects, cx);
309
view.update(cx, |view, cx| {
310
view.preview.set_effects(effects);
311
cx.notify();
312
});
313
})
314
})
315
});
316
h_flex()
317
.id("effect-soft-focus-strength")
318
.w_full()
319
.px(px(20.))
320
.py(px(6.))
321
.gap(px(8.))
322
.items_center()
323
.child(
324
div()
325
.flex_1()
326
.text_size(px(12.))
327
.text_color(theme::text_muted())
328
.child("Soft focus strength"),
329
)
330
.children(levels)
331
}
332
251
333
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
252
334
self.background = pick.clone();
253
335
let app = self.center.read(cx).app().clone();
@@ -422,6 +504,7 @@ impl SettingsView {
422
504
.find(|(pick, _)| *pick == self.background)
423
505
.map_or("None".to_owned(), |(_, label)| label.clone());
424
506
let current_background = self.background.clone();
507
let effects = self.center.read(cx).app().read(cx).call_effects;
425
508
let image = self.preview.image(Instant::now());
426
509
let status = if self.preview_blocked {
427
510
CAMERA_IN_USE.to_owned()
@@ -515,6 +598,43 @@ impl SettingsView {
515
598
.child(status),
516
599
),
517
600
)
601
.child(
602
v_flex()
603
.id("camera-effects")
604
.w_full()
605
.pt(px(8.))
606
.child(self.effect_row(
607
"effect-mirror",
608
"Mirror my video",
609
effects.mirror,
610
|effects| effects.mirror = !effects.mirror,
611
cx,
612
))
613
.child(self.effect_row(
614
"effect-framing",
615
"Auto framing",
616
effects.auto_framing,
617
|effects| effects.auto_framing = !effects.auto_framing,
618
cx,
619
))
620
.child(self.effect_row(
621
"effect-brightness",
622
"Adjust brightness",
623
effects.adjust_brightness,
624
|effects| effects.adjust_brightness = !effects.adjust_brightness,
625
cx,
626
))
627
.child(self.effect_row(
628
"effect-soft-focus",
629
"Soft focus",
630
effects.soft_focus,
631
|effects| effects.soft_focus = !effects.soft_focus,
632
cx,
633
))
634
.when(effects.soft_focus, |column| {
635
column.child(self.strength_row(effects.soft_focus_strength, cx))
636
}),
637
)
518
638
}
519
639
}
520
640
@@ -1,7 +1,7 @@1
use std::time::{Duration, Instant};1
use std::time::{Duration, Instant};2
2
3
use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};3
use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};4
use calling::{DeviceChoice, DeviceEntry, camera_entries};4
use calling::{CameraEffects, DeviceChoice, DeviceEntry, camera_entries};5
use gpui_kit::assets::IconName;5
use gpui_kit::assets::IconName;6
use gpui_kit::component::{6
use gpui_kit::component::{7
button::Button,7
button::Button,@@ -27,6 +27,7 @@ const SELECT_WIDTH: f32 = 170.;27
const PREVIEW_WIDTH: f32 = 380.;27
const PREVIEW_WIDTH: f32 = 380.;28
const PREVIEW_HEIGHT: f32 = 214.;28
const PREVIEW_HEIGHT: f32 = 214.;29
const PREVIEW_RADIUS: f32 = 10.;29
const PREVIEW_RADIUS: f32 = 10.;30
const SOFT_FOCUS_LEVELS: [(&str, u8); 3] = [("Low", 25), ("Medium", 50), ("High", 75)];30
const CAMERA_IN_USE: &str = "Camera is in use by the call";31
const CAMERA_IN_USE: &str = "Camera is in use by the call";31
32
32
fn camera_in_call(state: &AppState) -> bool {33
fn camera_in_call(state: &AppState) -> bool {@@ -129,6 +130,7 @@ impl SettingsView {129
let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));130
let mcp = cx.new(|cx| McpView::new(app.clone(), window, cx));130
let state = app.read(cx);131
let state = app.read(cx);131
let camera = state.call_camera.clone();132
let camera = state.call_camera.clone();133
preview.set_effects(state.call_effects);132
let preview_blocked = camera_in_call(state);134
let preview_blocked = camera_in_call(state);133
let background = Some(state.call_background.clone())135
let background = Some(state.call_background.clone())134
.filter(|pick| {136
.filter(|pick| {@@ -194,6 +196,8 @@ impl SettingsView {194
Section::Devices => {196
Section::Devices => {195
self.load_cameras(cx);197
self.load_cameras(cx);196
self.apply_background(cx);198
self.apply_background(cx);199
self.preview200
.set_effects(self.center.read(cx).app().read(cx).call_effects);197
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));201
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));198
self.start_preview();202
self.start_preview();199
}203
}@@ -248,6 +252,84 @@ impl SettingsView {248
cx.notify();252
cx.notify();249
}253
}250
254
255
fn change_effects(&mut self, change: fn(&mut CameraEffects), cx: &mut Context<Self>) {256
let app = self.center.read(cx).app().clone();257
let mut effects = app.read(cx).call_effects;258
change(&mut effects);259
self.preview.set_effects(effects);260
app.update(cx, |state, cx| state.set_call_effects(effects, cx));261
cx.notify();262
}263
264
fn effect_row(265
&self,266
id: &'static str,267
title: &'static str,268
on: bool,269
change: fn(&mut CameraEffects),270
cx: &mut Context<Self>,271
) -> Stateful<Div> {272
let view = cx.entity();273
h_flex()274
.id(id)275
.w_full()276
.px(px(20.))277
.py(px(6.))278
.gap(px(12.))279
.items_center()280
.cursor_pointer()281
.hover(|row| row.bg(theme::row_hover()))282
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.change_effects(change, cx)))283
.child(284
div()285
.flex_1()286
.text_size(px(14.))287
.font_weight(FontWeight::SEMIBOLD)288
.text_color(theme::text())289
.child(title),290
)291
.child(switch(on))292
}293
294
fn strength_row(&self, strength: u8, cx: &mut Context<Self>) -> Stateful<Div> {295
let levels = SOFT_FOCUS_LEVELS.map(|(label, level)| {296
let view = cx.entity();297
let app = self.center.read(cx).app().clone();298
button(label)299
.when(strength == level, |button| {300
button.bg(theme::accent()).text_color(theme::on_accent())301
})302
.on_click(move |_, _, cx| {303
app.update(cx, |state, cx| {304
let effects = CameraEffects {305
soft_focus_strength: level,306
..state.call_effects307
};308
state.set_call_effects(effects, cx);309
view.update(cx, |view, cx| {310
view.preview.set_effects(effects);311
cx.notify();312
});313
})314
})315
});316
h_flex()317
.id("effect-soft-focus-strength")318
.w_full()319
.px(px(20.))320
.py(px(6.))321
.gap(px(8.))322
.items_center()323
.child(324
div()325
.flex_1()326
.text_size(px(12.))327
.text_color(theme::text_muted())328
.child("Soft focus strength"),329
)330
.children(levels)331
}332
251
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {333
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {252
self.background = pick.clone();334
self.background = pick.clone();253
let app = self.center.read(cx).app().clone();335
let app = self.center.read(cx).app().clone();@@ -422,6 +504,7 @@ impl SettingsView {422
.find(|(pick, _)| *pick == self.background)504
.find(|(pick, _)| *pick == self.background)423
.map_or("None".to_owned(), |(_, label)| label.clone());505
.map_or("None".to_owned(), |(_, label)| label.clone());424
let current_background = self.background.clone();506
let current_background = self.background.clone();507
let effects = self.center.read(cx).app().read(cx).call_effects;425
let image = self.preview.image(Instant::now());508
let image = self.preview.image(Instant::now());426
let status = if self.preview_blocked {509
let status = if self.preview_blocked {427
CAMERA_IN_USE.to_owned()510
CAMERA_IN_USE.to_owned()@@ -515,6 +598,43 @@ impl SettingsView {515
.child(status),598
.child(status),516
),599
),517
)600
)601
.child(602
v_flex()603
.id("camera-effects")604
.w_full()605
.pt(px(8.))606
.child(self.effect_row(607
"effect-mirror",608
"Mirror my video",609
effects.mirror,610
|effects| effects.mirror = !effects.mirror,611
cx,612
))613
.child(self.effect_row(614
"effect-framing",615
"Auto framing",616
effects.auto_framing,617
|effects| effects.auto_framing = !effects.auto_framing,618
cx,619
))620
.child(self.effect_row(621
"effect-brightness",622
"Adjust brightness",623
effects.adjust_brightness,624
|effects| effects.adjust_brightness = !effects.adjust_brightness,625
cx,626
))627
.child(self.effect_row(628
"effect-soft-focus",629
"Soft focus",630
effects.soft_focus,631
|effects| effects.soft_focus = !effects.soft_focus,632
cx,633
))634
.when(effects.soft_focus, |column| {635
column.child(self.strength_row(effects.soft_focus_strength, cx))636
}),637
)518
}638
}519
}639
}520
640
@@ -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(
399
PopupMenuItem::new("Mirror my video")
400
.checked(effects.mirror)
401
.on_click(effect_change(app, |effects| {
402
effects.mirror = !effects.mirror
403
})),
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 @@1
use std::path::PathBuf;1
use std::path::PathBuf;2
2
3
use calling::HoldState;3
use calling::{CameraEffects, HoldState};4
use gpui_kit::assets::IconName;4
use gpui_kit::assets::IconName;5
use gpui_kit::component::button::{Button, ButtonVariants as _};5
use gpui_kit::component::button::{Button, ButtonVariants as _};6
use gpui_kit::component::dialog::DialogFooter;6
use gpui_kit::component::dialog::DialogFooter;7
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};7
use gpui_kit::component::menu::{PopupMenu, PopupMenuItem};8
use gpui_kit::component::switch::Switch;8
use gpui_kit::component::tooltip::Tooltip;9
use gpui_kit::component::tooltip::Tooltip;9
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};10
use gpui_kit::component::{WindowExt as _, h_flex, v_flex};10
use gpui_kit::*;11
use gpui_kit::*;@@ -288,16 +289,17 @@ pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mu288
}289
}289
290
290
#[derive(Clone)]291
#[derive(Clone)]291
pub struct BackgroundMenu {292
pub 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
297
impl BackgroundMenu {299
impl 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: library304
images: library303
.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
357
pub fn background_items(360
fn 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
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
popup396
.separator()397
.item(PopupMenuItem::label("Effects"))398
.item(399
PopupMenuItem::new("Mirror my video")400
.checked(effects.mirror)401
.on_click(effect_change(app, |effects| {402
effects.mirror = !effects.mirror403
})),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
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();@@ -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;
@@ -475,7 +475,7 @@ pub fn chevron_button(button_id: &'static str, face_id: &'static str) -> Button
475
475
pub fn camera_menu_button(
476
476
app: &Entity<AppState>,
477
477
model: &CallModel,
478
backgrounds: BackgroundMenu,
478
backgrounds: CameraMenu,
479
479
) -> Option<AnyElement> {
480
480
if !model.can_use_camera() {
481
481
return None;
@@ -495,7 +495,7 @@ fn camera_menu(
495
495
popup: PopupMenu,
496
496
app: &Entity<AppState>,
497
497
model: &CallModel,
498
backgrounds: &BackgroundMenu,
498
backgrounds: &CameraMenu,
499
499
) -> PopupMenu {
500
500
let camera_app = app.clone();
501
501
let cameras = super::call_view::device_items(
@@ -511,7 +511,11 @@ fn camera_menu(
511
511
for item in cameras {
512
512
popup = popup.item(item);
513
513
}
514
background_items(popup, app, backgrounds)
514
background_items(
515
effect_items(popup, app, backgrounds.effects),
516
app,
517
backgrounds,
518
)
515
519
}
516
520
517
521
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
@@ -13,7 +13,7 @@ use gpui_kit::*;13
13
14
use super::avatar::person_avatar;14
use super::avatar::person_avatar;15
use super::call_extras::{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
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};18
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};19
use super::widgets::icon;19
use super::widgets::icon;@@ -475,7 +475,7 @@ pub fn chevron_button(button_id: &'static str, face_id: &'static str) -> Button475
pub fn camera_menu_button(475
pub fn camera_menu_button(476
app: &Entity<AppState>,476
app: &Entity<AppState>,477
model: &CallModel,477
model: &CallModel,478
backgrounds: BackgroundMenu,478
backgrounds: CameraMenu,479
) -> Option<AnyElement> {479
) -> Option<AnyElement> {480
if !model.can_use_camera() {480
if !model.can_use_camera() {481
return None;481
return None;@@ -495,7 +495,7 @@ fn camera_menu(495
popup: PopupMenu,495
popup: PopupMenu,496
app: &Entity<AppState>,496
app: &Entity<AppState>,497
model: &CallModel,497
model: &CallModel,498
backgrounds: &BackgroundMenu,498
backgrounds: &CameraMenu,499
) -> PopupMenu {499
) -> PopupMenu {500
let camera_app = app.clone();500
let camera_app = app.clone();501
let cameras = super::call_view::device_items(501
let cameras = super::call_view::device_items(@@ -511,7 +511,11 @@ fn camera_menu(511
for item in cameras {511
for item in cameras {512
popup = popup.item(item);512
popup = popup.item(item);513
}513
}514
background_items(popup, app, backgrounds)514
background_items(515
effect_items(popup, app, backgrounds.effects),516
app,517
backgrounds,518
)515
}519
}516
520
517
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {521
pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {@@ -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_organizer::{
@@ -1092,7 +1092,7 @@ pub fn render_call_view(
1092
1092
.rounded_full()
1093
1093
.bg(theme::surface_raised())
1094
1094
.child(camera_button(app, model))
1095
.children(camera_menu_button(app, model, BackgroundMenu::of(state))),
1095
.children(camera_menu_button(app, model, CameraMenu::of(state))),
1096
1096
)
1097
1097
.child(share_button(app, model, state.call_share_sound))
1098
1098
.when(model.has_reaction_controls(), |row| {
@@ -17,7 +17,7 @@ use gpui_kit::*;17
17
18
use super::avatar::person_avatar;18
use super::avatar::person_avatar;19
use super::call_extras::{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
room_chip, whiteboard_stage,21
room_chip, whiteboard_stage,22
};22
};23
use super::call_organizer::{23
use super::call_organizer::{@@ -1092,7 +1092,7 @@ pub fn render_call_view(1092
.rounded_full()1092
.rounded_full()1093
.bg(theme::surface_raised())1093
.bg(theme::surface_raised())1094
.child(camera_button(app, model))1094
.child(camera_button(app, model))1095
.children(camera_menu_button(app, model, BackgroundMenu::of(state))),1095
.children(camera_menu_button(app, model, CameraMenu::of(state))),1096
)1096
)1097
.child(share_button(app, model, state.call_share_sound))1097
.child(share_button(app, model, state.call_share_sound))1098
.when(model.has_reaction_controls(), |row| {1098
.when(model.has_reaction_controls(), |row| {@@ -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 @@1
use std::sync::Arc;1
use std::time::Instant;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
const WIDTH: usize = 640;10
const WIDTH: usize = 640;6
const HEIGHT: usize = 360;11
const HEIGHT: usize = 360;12
const SEND_WIDTH: u32 = 1280;13
const SEND_HEIGHT: u32 = 720;7
const FRAMES: usize = 200;14
const FRAMES: usize = 200;8
const WARMUP: usize = 10;15
const 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
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
buffer31
}32
33
fn milliseconds_per_frame(started: Instant) -> f64 {34
started.elapsed().as_secs_f64() * 1000. / FRAMES as f6435
}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
fn main() {62
fn 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
}@@ -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};3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};3
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};4
use std::time::{Duration, Instant};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
use tract_onnx::prelude::*;6
use tract_onnx::prelude::*;9
7
10
use crate::background::BackgroundPicture;8
use crate::background::BackgroundPicture;11
use crate::camera::i420_from_rgba;9
use crate::effects::CameraEffects;12
use crate::error::{Error, Result};10
use crate::error::{Error, Result};13
11
14
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");12
const MODEL: &[u8] = include_bytes!("../assets/selfie_segmentation_landscape.onnx");@@ -24,7 +22,6 @@ const OPAQUE: f32 = 0.985;24
const MASK_SMOOTHING: f32 = 0.35;22
const MASK_SMOOTHING: f32 = 0.35;25
const SLOW_INFERENCE: Duration = Duration::from_millis(22);23
const SLOW_INFERENCE: Duration = Duration::from_millis(22);26
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);24
const VERY_SLOW_INFERENCE: Duration = Duration::from_millis(45);27
const AVERAGE_WEIGHT: f64 = 0.1;28
const MAX_BANDS: usize = 4;25
const MAX_BANDS: usize = 4;29
26
30
type Plan = std::sync::Arc<TypedRunnableModel>;27
type 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
87
struct Axis {84
pub(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
93
fn axis(output: usize, input: usize) -> Axis {90
pub(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
239
impl BlurSettings {237
impl 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`.262
pub struct BlurStage {276
pub 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
276
impl BlurStage {288
impl 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.328
pub struct BackgroundBlur {315
pub 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
337
impl BackgroundBlur {322
impl 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.mask359
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
true377
378
pub fn average_ms(&self) -> f64 {379
self.average_ms380
}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
}@@ -1517,6 +1517,7 @@ async fn drive(
1517
1517
});
1518
1518
}
1519
1519
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,
1520
Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
1520
1521
Some(CallCommand::SendReaction(reaction)) => {
1521
1522
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
1522
1523
timeline.record("reaction failed", error.to_string());
@@ -1517,6 +1517,7 @@ async fn drive(1517
});1517
});1518
}1518
}1519
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,1519
Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,1520
Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),1520
Some(CallCommand::SendReaction(reaction)) => {1521
Some(CallCommand::SendReaction(reaction)) => {1521
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1522
if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {1522
timeline.record("reaction failed", error.to_string());1523
timeline.record("reaction failed", error.to_string());@@ -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, Requeste8
use nokhwa::{Camera, query};8
use nokhwa::{Camera, query};9
use std::sync::atomic::Ordering;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
use crate::capture::Capture;13
use crate::capture::Capture;13
use crate::devices::{DeviceChoice, DeviceEntry};14
use crate::devices::{DeviceChoice, DeviceEntry};14
use crate::error::{Error, Result};15
use 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
})@@ -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};
@@ -44,6 +45,7 @@ pub enum CallCommand {
44
45
RemoveParticipant { mri: String },
45
46
SetCaptions(bool),
46
47
SetBackground(BackgroundChoice),
48
SetCameraEffects(CameraEffects),
47
49
SendReaction(Reaction),
48
50
SetRecording { on: bool, title: String },
49
51
ConsentToRecording,
@@ -4,6 +4,7 @@ use std::sync::Arc;4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};4
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};5
5
6
use crate::background::BackgroundChoice;6
use crate::background::BackgroundChoice;7
use crate::effects::CameraEffects;7
use crate::breakout::BreakoutMove;8
use crate::breakout::BreakoutMove;8
use crate::captions::{CaptionEntry, CaptionState};9
use crate::captions::{CaptionEntry, CaptionState};9
use crate::devices::{DeviceChoice, DeviceLists};10
use crate::devices::{DeviceChoice, DeviceLists};@@ -44,6 +45,7 @@ pub enum CallCommand {44
RemoveParticipant { mri: String },45
RemoveParticipant { mri: String },45
SetCaptions(bool),46
SetCaptions(bool),46
SetBackground(BackgroundChoice),47
SetBackground(BackgroundChoice),48
SetCameraEffects(CameraEffects),47
SendReaction(Reaction),49
SendReaction(Reaction),48
SetRecording { on: bool, title: String },50
SetRecording { on: bool, title: String },49
ConsentToRecording,51
ConsentToRecording,@@ -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 @@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_focus38
}39
40
pub fn alters_frame(&self) -> bool {41
self.auto_framing || self.adjust_brightness || self.soft_focus42
}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
effects61
}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
buffer119
}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.unavailable139
}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
millis252
}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,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 @@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.crop146
}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_LIMIT155
}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
mask204
}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
crop216
}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
}@@ -12,11 +12,14 @@ 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;
18
pub mod framing;
17
19
pub mod hold;
18
20
pub mod join;
19
21
pub mod level;
22
pub mod luma_effects;
20
23
#[cfg(windows)]
21
24
mod loopback_windows;
22
25
pub mod meeting;
@@ -50,6 +53,7 @@ pub mod whiteboard;
50
53
pub use audio_io::AudioMode;
51
54
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
52
55
pub use breakout::BreakoutMove;
56
pub use effects::CameraEffects;
53
57
pub use hold::HoldState;
54
58
pub use whiteboard::ContentShare;
55
59
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
@@ -12,11 +12,14 @@ pub mod control;12
pub mod data_channel;12
pub mod data_channel;13
pub mod devices;13
pub mod devices;14
pub mod engine;14
pub mod engine;15
pub mod effects;15
pub mod end;16
pub mod end;16
pub mod error;17
pub mod error;18
pub mod framing;17
pub mod hold;19
pub mod hold;18
pub mod join;20
pub mod join;19
pub mod level;21
pub mod level;22
pub mod luma_effects;20
#[cfg(windows)]23
#[cfg(windows)]21
mod loopback_windows;24
mod loopback_windows;22
pub mod meeting;25
pub mod meeting;@@ -50,6 +53,7 @@ pub mod whiteboard;50
pub use audio_io::AudioMode;53
pub use audio_io::AudioMode;51
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};54
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};52
pub use breakout::BreakoutMove;55
pub use breakout::BreakoutMove;56
pub use effects::CameraEffects;53
pub use hold::HoldState;57
pub use hold::HoldState;54
pub use whiteboard::ContentShare;58
pub use whiteboard::ContentShare;55
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};59
pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};@@ -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 @@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) * darkness37
}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 * inside62
}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 u870
}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
output91
}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
means115
}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
cells144
}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 u8266
})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
}@@ -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
49
impl VideoPicture {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
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 {151
mod tests {158
mod 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);@@ -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;4
use tokio::task::JoinHandle;4
use tokio::task::JoinHandle;5
use tokio::time::interval;5
use tokio::time::interval;6
6
7
use crate::blur::BlurStage;7
use crate::effects::EffectsStage;8
use crate::video_send::LocalSink;8
use crate::video_send::LocalSink;9
9
10
pub const CAMERA_WIDTH: u32 = 640;10
pub 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
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
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
});@@ -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;12
use tokio::sync::mpsc::UnboundedSender;12
use tokio::sync::mpsc::UnboundedSender;13
13
14
use crate::background::BackgroundPicture;14
use crate::background::BackgroundPicture;15
use crate::blur::{BlurSettings, BlurStage};15
use crate::blur::BlurSettings;16
use crate::effects::{CameraEffects, EffectsStage};16
use crate::camera::start_camera;17
use crate::camera::start_camera;17
use crate::capture::Capture;18
use crate::capture::Capture;18
use crate::control::CallUpdate;19
use crate::control::CallUpdate;@@ -53,6 +54,7 @@ impl VideoMode {53
pub struct LocalSink {54
pub 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
58
impl LocalSink {60
impl 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
self65
}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)?;