BlueGit

ict rusty-teams

Files

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

devices.rs

039de50c History
devices.rs 18.0 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(cx);
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, cx: &Context<Self>) {
169 if !self.preview_blocked {
170 let quality = self.app.read(cx).call_video_quality;
171 self.preview.start(&self.camera, quality);
172 }
173 }
174
175 fn sync_preview_block(&mut self, cx: &mut Context<Self>) {
176 let blocked = camera_in_call(self.app.read(cx));
177 if blocked == self.preview_blocked {
178 return;
179 }
180 self.preview_blocked = blocked;
181 if blocked {
182 self.preview.stop(cx);
183 } else {
184 self.start_preview(cx);
185 }
186 cx.notify();
187 }
188
189 fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {
190 self.camera = camera.clone();
191 self.app
192 .update(cx, |state, cx| state.select_call_camera(camera, cx));
193 self.start_preview(cx);
194 cx.notify();
195 }
196
197 fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
198 self.background = pick.clone();
199 self.app
200 .update(cx, |state, cx| state.set_call_background(pick, cx));
201 self.apply_background(cx);
202 cx.notify();
203 }
204
205 fn apply_background(&self, cx: &App) {
206 let state = self.app.read(cx);
207 if let Some(choice) = state.call_backgrounds.choice_for(&self.background) {
208 self.preview.set_background(choice);
209 }
210 }
211
212 fn set_mic(&mut self, settings: MicSettings, cx: &mut Context<Self>) {
213 self.app
214 .update(cx, |state, cx| state.set_call_mic(settings, cx));
215 cx.notify();
216 }
217
218 fn set_effects(&mut self, effects: CameraEffects, cx: &mut Context<Self>) {
219 self.preview.set_effects(effects);
220 self.app
221 .update(cx, |state, cx| state.set_call_effects(effects, cx));
222 cx.notify();
223 }
224
225 fn preview_status(&self) -> String {
226 if self.preview_blocked {
227 return CAMERA_IN_USE.to_owned();
228 }
229 match self.preview.failure() {
230 Some(reason) => format!("Camera could not start: {reason}"),
231 None => self
232 .preview
233 .fps()
234 .map_or("Starting camera...".to_owned(), |fps| {
235 format!("{fps:.0} fps")
236 }),
237 }
238 }
239
240 fn audio_rows(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
241 let view = cx.entity();
242 let state = self.app.read(cx);
243 let (input, output, mic) = (
244 state.call_input.clone(),
245 state.call_output.clone(),
246 state.call_mic,
247 );
248 let device_choices = |entries: Vec<DeviceEntry>, current: &DeviceChoice, output: bool| {
249 entries
250 .into_iter()
251 .map(|entry| {
252 let (app, choice) = (self.app.clone(), entry.choice.clone());
253 Choice::new(entry.label, &entry.choice == current, move |cx| {
254 let choice = choice.clone();
255 app.update(cx, |state, cx| {
256 if output {
257 state.select_call_output(choice, cx)
258 } else {
259 state.select_call_input(choice, cx)
260 }
261 })
262 })
263 })
264 .collect::<Vec<_>>()
265 };
266 let (outputs, inputs) = (
267 self.audio_devices.output_entries(),
268 self.audio_devices.input_entries(),
269 );
270 let speaker_label = label_of(&outputs, &output, DEFAULT_DEVICE_LABEL);
271 let microphone_label = label_of(&inputs, &input, DEFAULT_DEVICE_LABEL);
272 let noise_choices = NoiseSuppression::ALL
273 .iter()
274 .map(|level| {
275 let (view, level) = (view.clone(), *level);
276 Choice::new(level.label(), level == mic.noise_suppression, move |cx| {
277 view.update(cx, |view, cx| {
278 view.set_mic(
279 MicSettings {
280 noise_suppression: level,
281 ..mic
282 },
283 cx,
284 )
285 })
286 })
287 })
288 .collect();
289 let music_view = view.clone();
290 let call_app = self.app.clone();
291 vec![
292 control_row(
293 "Speaker",
294 "",
295 select(
296 "settings-speaker",
297 speaker_label,
298 false,
299 device_choices(outputs, &output, true),
300 ),
301 )
302 .into_any_element(),
303 control_row(
304 "Microphone",
305 "",
306 select(
307 "settings-microphone",
308 microphone_label,
309 false,
310 device_choices(inputs, &input, false),
311 ),
312 )
313 .into_any_element(),
314 control_row(
315 "Noise suppression",
316 if mic.music_mode {
317 "Off while music mode is on"
318 } else {
319 "Echo, hum and background noise"
320 },
321 select(
322 "noise-suppression-select",
323 mic.noise_suppression.label(),
324 mic.music_mode,
325 noise_choices,
326 ),
327 )
328 .into_any_element(),
329 toggle_row(
330 "music-mode-row",
331 "Music mode",
332 "Keeps echo cancellation, turns off the rest",
333 theme::text_muted(),
334 mic.music_mode,
335 )
336 .on_click(move |_, _, cx| {
337 music_view.update(cx, |view, cx| {
338 view.set_mic(
339 MicSettings {
340 music_mode: !mic.music_mode,
341 ..mic
342 },
343 cx,
344 )
345 })
346 })
347 .into_any_element(),
348 control_row(
349 "Make a test call",
350 "Echo bot, checks your speaker and microphone",
351 text_button("settings-test-call", "Make a test call").on_click(move |_, _, cx| {
352 call_app.update(cx, |state, cx| state.start_test_call(cx))
353 }),
354 )
355 .into_any_element(),
356 ]
357 }
358
359 fn camera_block(&self, cx: &mut Context<Self>) -> Div {
360 let view = cx.entity();
361 let camera_label = label_of(&self.cameras, &self.camera, DEFAULT_CAMERA_LABEL);
362 let camera_choices = self
363 .cameras
364 .iter()
365 .map(|entry| {
366 let (view, choice) = (view.clone(), entry.choice.clone());
367 Choice::new(
368 entry.label.clone(),
369 entry.choice == self.camera,
370 move |cx| view.update(cx, |view, cx| view.select_camera(choice.clone(), cx)),
371 )
372 })
373 .collect();
374 let backgrounds = preview_backgrounds(&self.app.read(cx).call_backgrounds);
375 let background_label = backgrounds
376 .iter()
377 .find(|(pick, _)| *pick == self.background)
378 .map_or("None".to_owned(), |(_, label)| label.clone());
379 let background_choices = backgrounds
380 .into_iter()
381 .map(|(pick, label)| {
382 let view = view.clone();
383 let checked = pick == self.background;
384 Choice::new(label, checked, move |cx| {
385 view.update(cx, |view, cx| view.select_background(pick.clone(), cx))
386 })
387 })
388 .collect();
389 let image = self.preview.image(Instant::now());
390 v_flex()
391 .w_full()
392 .child(
393 row()
394 .items_start()
395 .flex_wrap()
396 .child(
397 div()
398 .w(px(PREVIEW_WIDTH))
399 .h(px(PREVIEW_HEIGHT))
400 .flex_none()
401 .flex()
402 .items_center()
403 .justify_center()
404 .overflow_hidden()
405 .rounded(px(PREVIEW_RADIUS))
406 .bg(theme::surface())
407 .children(image.map(|image| {
408 img(ImageSource::Render(image))
409 .size_full()
410 .object_fit(ObjectFit::Cover)
411 .rounded(px(PREVIEW_RADIUS))
412 })),
413 )
414 .child(
415 v_flex()
416 .gap(px(12.))
417 .child(device_label("Camera"))
418 .child(select("camera-select", camera_label, false, camera_choices))
419 .child(device_label("Background"))
420 .child(select(
421 "background-select",
422 background_label,
423 false,
424 background_choices,
425 )),
426 ),
427 )
428 .child(
429 div()
430 .px(px(super::rows::ROW_INSET))
431 .text_size(px(12.))
432 .text_color(theme::text_muted())
433 .child(self.preview_status()),
434 )
435 }
436
437 fn effect_rows(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
438 let effects = self.app.read(cx).call_effects;
439 let mut rows: Vec<AnyElement> = EFFECTS
440 .iter()
441 .map(|effect| {
442 let view = cx.entity();
443 let flip = effect.flip;
444 toggle_row(
445 effect.id,
446 effect.title,
447 "",
448 theme::text_muted(),
449 (effect.read)(&effects),
450 )
451 .on_click(move |_, _, cx| {
452 view.update(cx, |view, cx| {
453 let mut changed = view.app.read(cx).call_effects;
454 flip(&mut changed);
455 view.set_effects(changed, cx)
456 })
457 })
458 .into_any_element()
459 })
460 .collect();
461 if effects.soft_focus {
462 rows.push(self.strength_row(effects, cx).into_any_element());
463 }
464 rows
465 }
466
467 fn strength_row(&self, effects: CameraEffects, cx: &mut Context<Self>) -> Div {
468 let levels = SOFT_FOCUS_LEVELS.map(|(label, level)| {
469 let view = cx.entity();
470 text_button(label, label)
471 .when(effects.soft_focus_strength == level, |button| {
472 button.bg(theme::accent()).text_color(theme::on_accent())
473 })
474 .on_click(move |_, _, cx| {
475 view.update(cx, |view, cx| {
476 let changed = CameraEffects {
477 soft_focus_strength: level,
478 ..view.app.read(cx).call_effects
479 };
480 view.set_effects(changed, cx)
481 })
482 })
483 });
484 control_row(
485 "Soft focus strength",
486 "",
487 h_flex().gap(px(8.)).children(levels),
488 )
489 }
490}
491
492fn device_label(text: &'static str) -> Div {
493 div()
494 .text_size(px(12.))
495 .text_color(theme::text_muted())
496 .child(text)
497}
498
499impl Render for DevicesView {
500 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
501 let report_on = self.app.read(cx).call_report_enabled;
502 let report_app = self.app.clone();
503 v_flex()
504 .w_full()
505 .child(caption("AUDIO DEVICES"))
506 .children(self.audio_rows(cx))
507 .child(caption("CAMERA"))
508 .child(self.camera_block(cx))
509 .children(self.effect_rows(cx))
510 .child(caption("DIAGNOSTICS"))
511 .child(
512 toggle_row(
513 "call-report-row",
514 "Save a test report after each call",
515 "Pseudonymized, stays on this computer",
516 theme::text_muted(),
517 report_on,
518 )
519 .on_click(move |_, _, cx| {
520 report_app.update(cx, |state, cx| {
521 state.set_call_report_enabled(!report_on, cx)
522 })
523 }),
524 )
525 }
526}