BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / settings / devices.rs

devices.rs

devices.rs 17.9 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use calling::camera::{DEFAULT_CAMERA_LABEL, list_cameras};
4use calling::devices::{DeviceLists, list_devices, shared_factory};
5use calling::{
6 CameraEffects, DeviceChoice, DeviceEntry, MicSettings, NoiseSuppression, camera_entries,
7};
8use gpui_kit::component::{h_flex, v_flex};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11
12use super::rows::{Choice, caption, control_row, row, select, text_button, toggle_row};
13use crate::app_state::AppState;
14use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
15use crate::theme;
16use crate::views::prejoin_view::demo_devices;
17
18const FPS_TICK: Duration = Duration::from_millis(500);
19const PREVIEW_WIDTH: f32 = 288.;
20const PREVIEW_HEIGHT: f32 = 162.;
21const PREVIEW_RADIUS: f32 = 10.;
22const SOFT_FOCUS_LEVELS: [(&str, u8); 3] = [("Low", 25), ("Medium", 50), ("High", 75)];
23const CAMERA_IN_USE: &str = "Camera is in use by the call";
24const DEFAULT_DEVICE_LABEL: &str = "Default device";
25
26struct Effect {
27 id: &'static str,
28 title: &'static str,
29 read: fn(&CameraEffects) -> bool,
30 flip: fn(&mut CameraEffects),
31}
32
33const EFFECTS: [Effect; 4] = [
34 Effect {
35 id: "effect-mirror",
36 title: "Mirror my video",
37 read: |effects| effects.mirror,
38 flip: |effects| effects.mirror = !effects.mirror,
39 },
40 Effect {
41 id: "effect-framing",
42 title: "Auto framing",
43 read: |effects| effects.auto_framing,
44 flip: |effects| effects.auto_framing = !effects.auto_framing,
45 },
46 Effect {
47 id: "effect-brightness",
48 title: "Adjust brightness",
49 read: |effects| effects.adjust_brightness,
50 flip: |effects| effects.adjust_brightness = !effects.adjust_brightness,
51 },
52 Effect {
53 id: "effect-soft-focus",
54 title: "Soft focus",
55 read: |effects| effects.soft_focus,
56 flip: |effects| effects.soft_focus = !effects.soft_focus,
57 },
58];
59
60fn camera_in_call(state: &AppState) -> bool {
61 state.call.is_some()
62}
63
64fn label_of(entries: &[DeviceEntry], choice: &DeviceChoice, fallback: &str) -> String {
65 entries
66 .iter()
67 .find(|entry| &entry.choice == choice)
68 .map_or_else(|| fallback.to_owned(), |entry| entry.label.clone())
69}
70
71pub struct DevicesView {
72 app: Entity<AppState>,
73 preview: CameraPreview,
74 cameras: Vec<DeviceEntry>,
75 audio_devices: DeviceLists,
76 camera: DeviceChoice,
77 background: BackgroundPick,
78 preview_blocked: bool,
79 _app_subscription: Subscription,
80 _release: Subscription,
81}
82
83impl DevicesView {
84 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
85 let app_subscription = cx.observe(&app, |view, _, cx| view.sync_preview_block(cx));
86 let release = cx.on_release(|view, cx| view.preview.stop(cx));
87 let (preview, mut updates) = CameraPreview::new();
88 let state = app.read(cx);
89 let demo = state.mode.demo;
90 let camera = state.call_camera.clone();
91 preview.set_effects(state.call_effects);
92 let preview_blocked = camera_in_call(state);
93 let background = Some(state.call_background.clone())
94 .filter(|pick| {
95 preview_backgrounds(&state.call_backgrounds)
96 .iter()
97 .any(|(known, _)| known == pick)
98 })
99 .unwrap_or_default();
100 cx.spawn(async move |this, cx| {
101 while updates.recv().await.is_some() {
102 if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
103 return;
104 }
105 }
106 })
107 .detach();
108 cx.spawn(async move |this, cx| {
109 loop {
110 cx.background_executor().timer(FPS_TICK).await;
111 let ticked = this.update(cx, |view, cx| {
112 view.preview.tick(Instant::now());
113 cx.notify();
114 });
115 if ticked.is_err() {
116 break;
117 }
118 }
119 })
120 .detach();
121 let mut view = DevicesView {
122 app,
123 preview,
124 cameras: camera_entries(&[]),
125 audio_devices: if demo {
126 demo_devices()
127 } else {
128 DeviceLists::default()
129 },
130 camera,
131 background,
132 preview_blocked,
133 _app_subscription: app_subscription,
134 _release: release,
135 };
136 view.load_devices(demo, cx);
137 view.apply_background(cx);
138 view.start_preview();
139 view
140 }
141
142 fn take_frames(&mut self, cx: &mut Context<Self>) {
143 self.preview.take_frames(cx);
144 cx.notify();
145 }
146
147 fn load_devices(&mut self, demo: bool, cx: &mut Context<Self>) {
148 cx.spawn(async move |this, cx| {
149 let (cameras, audio_devices) = cx
150 .background_executor()
151 .spawn(async move {
152 let audio_devices = (!demo).then(|| list_devices(&shared_factory()));
153 (list_cameras(), audio_devices)
154 })
155 .await;
156 this.update(cx, |view, cx| {
157 view.cameras = camera_entries(&cameras);
158 if let Some(audio_devices) = audio_devices {
159 view.audio_devices = audio_devices;
160 }
161 cx.notify();
162 })
163 .ok();
164 })
165 .detach();
166 }
167
168 fn start_preview(&mut self) {
169 if !self.preview_blocked {
170 self.preview.start(&self.camera);
171 }
172 }
173
174 fn sync_preview_block(&mut self, cx: &mut Context<Self>) {
175 let blocked = camera_in_call(self.app.read(cx));
176 if blocked == self.preview_blocked {
177 return;
178 }
179 self.preview_blocked = blocked;
180 if blocked {
181 self.preview.stop(cx);
182 } else {
183 self.start_preview();
184 }
185 cx.notify();
186 }
187
188 fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {
189 self.camera = camera.clone();
190 self.app
191 .update(cx, |state, cx| state.select_call_camera(camera, cx));
192 self.start_preview();
193 cx.notify();
194 }
195
196 fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
197 self.background = pick.clone();
198 self.app
199 .update(cx, |state, cx| state.set_call_background(pick, cx));
200 self.apply_background(cx);
201 cx.notify();
202 }
203
204 fn apply_background(&self, cx: &App) {
205 let state = self.app.read(cx);
206 if let Some(choice) = state.call_backgrounds.choice_for(&self.background) {
207 self.preview.set_background(choice);
208 }
209 }
210
211 fn set_mic(&mut self, settings: MicSettings, cx: &mut Context<Self>) {
212 self.app
213 .update(cx, |state, cx| state.set_call_mic(settings, cx));
214 cx.notify();
215 }
216
217 fn set_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
218 self.preview.set_effects(effects);
219 self.app
220 .update(cx, |state, cx| state.set_call_effects(effects, cx));
221 cx.notify();
222 }
223
224 fn preview_status(&self) -> String {
225 if self.preview_blocked {
226 return CAMERA_IN_USE.to_owned();
227 }
228 match self.preview.failure() {
229 Some(reason) => format!("Camera could not start: {reason}"),
230 None => self
231 .preview
232 .fps()
233 .map_or("Starting camera...".to_owned(), |fps| {
234 format!("{fps:.0} fps")
235 }),
236 }
237 }
238
239 fn audio_rows(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
240 let view = cx.entity();
241 let state = self.app.read(cx);
242 let (input, output, mic) = (
243 state.call_input.clone(),
244 state.call_output.clone(),
245 state.call_mic,
246 );
247 let device_choices = |entries: Vec<DeviceEntry>, current: &DeviceChoice, output: bool| {
248 entries
249 .into_iter()
250 .map(|entry| {
251 let (app, choice) = (self.app.clone(), entry.choice.clone());
252 Choice::new(entry.label, &entry.choice == current, move |cx| {
253 let choice = choice.clone();
254 app.update(cx, |state, cx| {
255 if output {
256 state.select_call_output(choice, cx)
257 } else {
258 state.select_call_input(choice, cx)
259 }
260 })
261 })
262 })
263 .collect::<Vec<_>>()
264 };
265 let (outputs, inputs) = (
266 self.audio_devices.output_entries(),
267 self.audio_devices.input_entries(),
268 );
269 let speaker_label = label_of(&outputs, &output, DEFAULT_DEVICE_LABEL);
270 let microphone_label = label_of(&inputs, &input, DEFAULT_DEVICE_LABEL);
271 let noise_choices = NoiseSuppression::ALL
272 .iter()
273 .map(|level| {
274 let (view, level) = (view.clone(), *level);
275 Choice::new(level.label(), level == mic.noise_suppression, move |cx| {
276 view.update(cx, |view, cx| {
277 view.set_mic(
278 MicSettings {
279 noise_suppression: level,
280 ..mic
281 },
282 cx,
283 )
284 })
285 })
286 })
287 .collect();
288 let music_view = view.clone();
289 let call_app = self.app.clone();
290 vec![
291 control_row(
292 "Speaker",
293 "",
294 select(
295 "settings-speaker",
296 speaker_label,
297 false,
298 device_choices(outputs, &output, true),
299 ),
300 )
301 .into_any_element(),
302 control_row(
303 "Microphone",
304 "",
305 select(
306 "settings-microphone",
307 microphone_label,
308 false,
309 device_choices(inputs, &input, false),
310 ),
311 )
312 .into_any_element(),
313 control_row(
314 "Noise suppression",
315 if mic.music_mode {
316 "Off while music mode is on"
317 } else {
318 "Echo, hum and background noise"
319 },
320 select(
321 "noise-suppression-select",
322 mic.noise_suppression.label(),
323 mic.music_mode,
324 noise_choices,
325 ),
326 )
327 .into_any_element(),
328 toggle_row(
329 "music-mode-row",
330 "Music mode",
331 "Keeps echo cancellation, turns off the rest",
332 theme::text_muted(),
333 mic.music_mode,
334 )
335 .on_click(move |_, _, cx| {
336 music_view.update(cx, |view, cx| {
337 view.set_mic(
338 MicSettings {
339 music_mode: !mic.music_mode,
340 ..mic
341 },
342 cx,
343 )
344 })
345 })
346 .into_any_element(),
347 control_row(
348 "Make a test call",
349 "Echo bot, checks your speaker and microphone",
350 text_button("settings-test-call", "Make a test call").on_click(move |_, _, cx| {
351 call_app.update(cx, |state, cx| state.start_test_call(cx))
352 }),
353 )
354 .into_any_element(),
355 ]
356 }
357
358 fn camera_block(&self, cx: &mut Context<Self>) -> Div {
359 let view = cx.entity();
360 let camera_label = label_of(&self.cameras, &self.camera, DEFAULT_CAMERA_LABEL);
361 let camera_choices = self
362 .cameras
363 .iter()
364 .map(|entry| {
365 let (view, choice) = (view.clone(), entry.choice.clone());
366 Choice::new(
367 entry.label.clone(),
368 entry.choice == self.camera,
369 move |cx| view.update(cx, |view, cx| view.select_camera(choice.clone(), cx)),
370 )
371 })
372 .collect();
373 let backgrounds = preview_backgrounds(&self.app.read(cx).call_backgrounds);
374 let background_label = backgrounds
375 .iter()
376 .find(|(pick, _)| *pick == self.background)
377 .map_or("None".to_owned(), |(_, label)| label.clone());
378 let background_choices = backgrounds
379 .into_iter()
380 .map(|(pick, label)| {
381 let view = view.clone();
382 let checked = pick == self.background;
383 Choice::new(label, checked, move |cx| {
384 view.update(cx, |view, cx| view.select_background(pick.clone(), cx))
385 })
386 })
387 .collect();
388 let image = self.preview.image(Instant::now());
389 v_flex()
390 .w_full()
391 .child(
392 row()
393 .items_start()
394 .flex_wrap()
395 .child(
396 div()
397 .w(px(PREVIEW_WIDTH))
398 .h(px(PREVIEW_HEIGHT))
399 .flex_none()
400 .flex()
401 .items_center()
402 .justify_center()
403 .overflow_hidden()
404 .rounded(px(PREVIEW_RADIUS))
405 .bg(theme::surface())
406 .children(image.map(|image| {
407 img(ImageSource::Render(image))
408 .size_full()
409 .object_fit(ObjectFit::Cover)
410 .rounded(px(PREVIEW_RADIUS))
411 })),
412 )
413 .child(
414 v_flex()
415 .gap(px(12.))
416 .child(device_label("Camera"))
417 .child(select("camera-select", camera_label, false, camera_choices))
418 .child(device_label("Background"))
419 .child(select(
420 "background-select",
421 background_label,
422 false,
423 background_choices,
424 )),
425 ),
426 )
427 .child(
428 div()
429 .px(px(super::rows::ROW_INSET))
430 .text_size(px(12.))
431 .text_color(theme::text_muted())
432 .child(self.preview_status()),
433 )
434 }
435
436 fn effect_rows(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
437 let effects = self.app.read(cx).call_effects;
438 let mut rows: Vec<AnyElement> = EFFECTS
439 .iter()
440 .map(|effect| {
441 let view = cx.entity();
442 let flip = effect.flip;
443 toggle_row(
444 effect.id,
445 effect.title,
446 "",
447 theme::text_muted(),
448 (effect.read)(&effects),
449 )
450 .on_click(move |_, _, cx| {
451 view.update(cx, |view, cx| {
452 let mut changed = view.app.read(cx).call_effects;
453 flip(&mut changed);
454 view.set_effects(changed, cx)
455 })
456 })
457 .into_any_element()
458 })
459 .collect();
460 if effects.soft_focus {
461 rows.push(self.strength_row(effects, cx).into_any_element());
462 }
463 rows
464 }
465
466 fn strength_row(&self, effects: CameraEffects, cx: &mut Context<Self>) -> Div {
467 let levels = SOFT_FOCUS_LEVELS.map(|(label, level)| {
468 let view = cx.entity();
469 text_button(label, label)
470 .when(effects.soft_focus_strength == level, |button| {
471 button.bg(theme::accent()).text_color(theme::on_accent())
472 })
473 .on_click(move |_, _, cx| {
474 view.update(cx, |view, cx| {
475 let changed = CameraEffects {
476 soft_focus_strength: level,
477 ..view.app.read(cx).call_effects
478 };
479 view.set_effects(changed, cx)
480 })
481 })
482 });
483 control_row(
484 "Soft focus strength",
485 "",
486 h_flex().gap(px(8.)).children(levels),
487 )
488 }
489}
490
491fn device_label(text: &'static str) -> Div {
492 div()
493 .text_size(px(12.))
494 .text_color(theme::text_muted())
495 .child(text)
496}
497
498impl Render for DevicesView {
499 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
500 let report_on = self.app.read(cx).call_report_enabled;
501 let report_app = self.app.clone();
502 v_flex()
503 .w_full()
504 .child(caption("AUDIO DEVICES"))
505 .children(self.audio_rows(cx))
506 .child(caption("CAMERA"))
507 .child(self.camera_block(cx))
508 .children(self.effect_rows(cx))
509 .child(caption("DIAGNOSTICS"))
510 .child(
511 toggle_row(
512 "call-report-row",
513 "Save a test report after each call",
514 "Pseudonymized, stays on this computer",
515 theme::text_muted(),
516 report_on,
517 )
518 .on_click(move |_, _, cx| {
519 report_app.update(cx, |state, cx| {
520 state.set_call_report_enabled(!report_on, cx)
521 })
522 }),
523 )
524 }
525}