Add screen sharing with simulcast, hardware codecs and share audio
Browse files at this commite06b4eff8348b0de8e4e902281916fbd262b1fdcParent: d40b0b3- feat
- add screen sharing with simulcast, hardware codecs and share audio
43 changed files +4851 -247
- crates/client/Cargo.toml +5 -0
- crates/client/src/gui.rs +7 -0
- crates/client/src/gui/chat.rs +81 -8
- crates/client/src/gui/media_view.rs +1 -1
- crates/client/src/gui/settings_page.rs +3 -3
- crates/client/src/gui/share_view.rs +762 -0
- crates/client/src/gui/sidebar.rs +4 -3
- crates/client/src/gui/voice_stats.rs +232 -60
- crates/client/src/lib.rs +1 -0
- crates/client/src/media/convert.rs +5 -3
- crates/client/src/media/decode.rs +184 -17
- crates/client/src/media/mod.rs +24 -16
- crates/client/src/media/resample.rs +19 -4
- crates/client/src/network.rs +244 -4
- crates/client/src/settings.rs +137 -2
- crates/client/src/share/audio_capture.rs +477 -0
- crates/client/src/share/capture.rs +324 -0
- crates/client/src/share/convert.rs +88 -0
- crates/client/src/share/encode.rs +343 -0
- crates/client/src/share/frame.rs +19 -0
- crates/client/src/share/mod.rs +9 -0
- crates/client/src/share/reassembly.rs +148 -0
- crates/client/src/share/session.rs +769 -0
- crates/client/src/voice/audio.rs +15 -13
- crates/client/src/voice/audio/coreaudio.rs +7 -4
- crates/client/src/voice/audio/pipewire.rs +3 -3
- crates/client/src/voice/audio/wasapi.rs +4 -4
- crates/client/src/voice/engine.rs +8 -4
- crates/client/src/voice/mod.rs +13 -8
- crates/common/src/constant.rs +4 -0
- crates/common/src/datagram.rs +216 -0
- crates/common/src/event.rs +14 -1
- crates/common/src/lib.rs +2 -1
- crates/common/src/permission.rs +4 -0
- crates/common/src/request.rs +22 -1
- crates/common/src/response.rs +2 -0
- crates/common/src/share.rs +243 -0
- crates/common/src/voice.rs +0 -54
- crates/server/src/lib.rs +1 -0
- crates/server/src/network.rs +14 -6
- crates/server/src/request.rs +134 -24
- crates/server/src/share.rs +249 -0
- crates/server/src/voice.rs +10 -3
crates/client/Cargo.tomlmodified+5 -0
| @@ -21,6 +21,8 @@ ec-aac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e844 | |||
| 21 | ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | 21 | ec-mp3 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } |
| 22 | ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | 22 | ec-vorbis = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } |
| 23 | ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | 23 | ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } |
| 24 | +ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | ||
| 25 | +ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | ||
| 24 | ureq = "3.5.2" | 26 | ureq = "3.5.2" |
| 25 | bytes = "1.12.2" | 27 | bytes = "1.12.2" |
| 26 | tracing = "0.1.44" | 28 | tracing = "0.1.44" |
| @@ -34,6 +36,9 @@ rtrb = "0.4.1" | |||
| 34 | [target.'cfg(target_os = "linux")'.dependencies] | 36 | [target.'cfg(target_os = "linux")'.dependencies] |
| 35 | pipewire = { version = "0.10.1", features = ["v0_3_49"] } | 37 | pipewire = { version = "0.10.1", features = ["v0_3_49"] } |
| 36 | ksni = "0.3.7" | 38 | ksni = "0.3.7" |
| 39 | +ashpd = { version = "0.14.3", default-features = false, features = ["tokio", "screencast"] } | ||
| 40 | +ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | ||
| 41 | +ec-va = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "e84467678af472c83966325ec66cfc8f46083dc1" } | ||
| 37 | 42 | ||
| 38 | [target.'cfg(target_os = "windows")'.dependencies] | 43 | [target.'cfg(target_os = "windows")'.dependencies] |
| 39 | wasapi = "0.27.0" | 44 | wasapi = "0.27.0" |
crates/client/src/gui.rsmodified+7 -0
| @@ -52,6 +52,7 @@ mod message_actions; | |||
| 52 | mod poll; | 52 | mod poll; |
| 53 | mod profile; | 53 | mod profile; |
| 54 | mod settings_page; | 54 | mod settings_page; |
| 55 | +mod share_view; | ||
| 55 | mod sidebar; | 56 | mod sidebar; |
| 56 | mod snippet; | 57 | mod snippet; |
| 57 | mod social; | 58 | mod social; |
| @@ -601,6 +602,7 @@ pub struct Yumush { | |||
| 601 | deferred: Vec<NetworkEvent>, | 602 | deferred: Vec<NetworkEvent>, |
| 602 | backups: Vec<BackupInfo>, | 603 | backups: Vec<BackupInfo>, |
| 603 | pending_backup_delete: Option<String>, | 604 | pending_backup_delete: Option<String>, |
| 605 | + share_apps: Vec<crate::share::audio_capture::AudioApp>, | ||
| 604 | } | 606 | } |
| 605 | 607 | ||
| 606 | impl Yumush { | 608 | impl Yumush { |
| @@ -612,6 +614,7 @@ impl Yumush { | |||
| 612 | cx: &mut Context<Self>, | 614 | cx: &mut Context<Self>, |
| 613 | ) -> Self { | 615 | ) -> Self { |
| 614 | network.set_voice_settings(settings.voice.clone()); | 616 | network.set_voice_settings(settings.voice.clone()); |
| 617 | + network.set_share_settings(settings.share.clone()); | ||
| 615 | 618 | ||
| 616 | cx.spawn(async move |this, cx| { | 619 | cx.spawn(async move |this, cx| { |
| 617 | while let Some(event) = network_event_receiver.recv().await { | 620 | while let Some(event) = network_event_receiver.recv().await { |
| @@ -660,6 +663,7 @@ impl Yumush { | |||
| 660 | deferred: Vec::new(), | 663 | deferred: Vec::new(), |
| 661 | backups: Vec::new(), | 664 | backups: Vec::new(), |
| 662 | pending_backup_delete: None, | 665 | pending_backup_delete: None, |
| 666 | + share_apps: Vec::new(), | ||
| 663 | } | 667 | } |
| 664 | } | 668 | } |
| 665 | 669 | ||
| @@ -951,6 +955,9 @@ impl Yumush { | |||
| 951 | user_id, | 955 | user_id, |
| 952 | muted: true, | 956 | muted: true, |
| 953 | } if self.is_me(user_id) => self.set_muted(true, cx), | 957 | } if self.is_me(user_id) => self.set_muted(true, cx), |
| 958 | + Event::ShareStopped { user_id, .. } if self.is_watching(user_id) => { | ||
| 959 | + self.close_viewer(cx) | ||
| 960 | + } | ||
| 954 | Event::Typing { .. } => { | 961 | Event::Typing { .. } => { |
| 955 | cx.spawn(async move |this, cx| { | 962 | cx.spawn(async move |this, cx| { |
| 956 | cx.background_executor().timer(chat::TYPING_TTL).await; | 963 | cx.background_executor().timer(chat::TYPING_TTL).await; |
crates/client/src/gui/chat.rsmodified+81 -8
| @@ -7,7 +7,8 @@ use std::{ | |||
| 7 | }; | 7 | }; |
| 8 | 8 | ||
| 9 | use crate::gui::social::InviteLookup; | 9 | use crate::gui::social::InviteLookup; |
| 10 | -use crate::gui::voice_stats::SAMPLE_HISTORY; | 10 | +use crate::gui::voice_stats::{SAMPLE_HISTORY, StatsTab}; |
| 11 | +use crate::share::session::ShareSample; | ||
| 11 | use crate::gui::{ | 12 | use crate::gui::{ |
| 12 | FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, | 13 | FIND_HINT, Palette, Tooltip as _, Yumush, avatar, badge, |
| 13 | builder::{BuilderTab, Transfer}, | 14 | builder::{BuilderTab, Transfer}, |
| @@ -20,6 +21,7 @@ use crate::gui::{ | |||
| 20 | primary_button, | 21 | primary_button, |
| 21 | profile::profile_popover, | 22 | profile::profile_popover, |
| 22 | rank_tag, | 23 | rank_tag, |
| 24 | + share_view::{self, Viewer}, | ||
| 23 | sidebar::SidebarTab, | 25 | sidebar::SidebarTab, |
| 24 | snippet, | 26 | snippet, |
| 25 | voice_note::{self, VoiceNote}, | 27 | voice_note::{self, VoiceNote}, |
| @@ -34,6 +36,7 @@ use common::{ | |||
| 34 | ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, | 36 | ServerBan, SessionInfo, Unread, Usage, User, VoiceRoom, mentions, |
| 35 | }, | 37 | }, |
| 36 | permission, | 38 | permission, |
| 39 | + share::Share, | ||
| 37 | }; | 40 | }; |
| 38 | use gpui_kit::{ | 41 | use gpui_kit::{ |
| 39 | Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, | 42 | Anchor, AnyElement, App, AppContext, Context, Div, Entity, FontWeight, Image, |
| @@ -230,9 +233,14 @@ pub struct Chat { | |||
| 230 | pub(super) builder_voice_rooms: Vec<VoiceRoom>, | 233 | pub(super) builder_voice_rooms: Vec<VoiceRoom>, |
| 231 | pub(super) voice_task: Option<Task<()>>, | 234 | pub(super) voice_task: Option<Task<()>>, |
| 232 | pub(super) voice_samples: VecDeque<crate::voice::VoiceSample>, | 235 | pub(super) voice_samples: VecDeque<crate::voice::VoiceSample>, |
| 236 | + pub(super) share_sample: ShareSample, | ||
| 237 | + pub(super) share_loss: HashMap<String, VecDeque<f32>>, | ||
| 238 | + pub(super) stats_tab: StatsTab, | ||
| 233 | pub(super) ringing: HashSet<String>, | 239 | pub(super) ringing: HashSet<String>, |
| 234 | pub(super) ring_task: Option<Task<()>>, | 240 | pub(super) ring_task: Option<Task<()>>, |
| 235 | pub(super) media: Media, | 241 | pub(super) media: Media, |
| 242 | + pub(super) shares: HashMap<String, Vec<Share>>, | ||
| 243 | + pub(super) viewer: Option<Viewer>, | ||
| 236 | pub(super) typing: HashMap<String, HashMap<String, Instant>>, | 244 | pub(super) typing: HashMap<String, HashMap<String, Instant>>, |
| 237 | pub(super) typing_sent: HashMap<String, Instant>, | 245 | pub(super) typing_sent: HashMap<String, Instant>, |
| 238 | } | 246 | } |
| @@ -442,11 +450,16 @@ impl Chat { | |||
| 442 | builder_voice_rooms: Vec::new(), | 450 | builder_voice_rooms: Vec::new(), |
| 443 | voice_task: None, | 451 | voice_task: None, |
| 444 | voice_samples: VecDeque::new(), | 452 | voice_samples: VecDeque::new(), |
| 453 | + share_sample: ShareSample::default(), | ||
| 454 | + share_loss: HashMap::new(), | ||
| 455 | + stats_tab: StatsTab::Voice, | ||
| 445 | ringing: HashSet::new(), | 456 | ringing: HashSet::new(), |
| 446 | ring_task: None, | 457 | ring_task: None, |
| 447 | typing: HashMap::new(), | 458 | typing: HashMap::new(), |
| 448 | typing_sent: HashMap::new(), | 459 | typing_sent: HashMap::new(), |
| 449 | media: Media::default(), | 460 | media: Media::default(), |
| 461 | + shares: HashMap::new(), | ||
| 462 | + viewer: None, | ||
| 450 | composer: Composer::Compose { reply: None }, | 463 | composer: Composer::Compose { reply: None }, |
| 451 | } | 464 | } |
| 452 | } | 465 | } |
| @@ -588,6 +601,23 @@ impl Chat { | |||
| 588 | .or_default() | 601 | .or_default() |
| 589 | .insert(user_id, Instant::now()); | 602 | .insert(user_id, Instant::now()); |
| 590 | } | 603 | } |
| 604 | + Event::ShareStarted { | ||
| 605 | + community_id, | ||
| 606 | + share, | ||
| 607 | + } => { | ||
| 608 | + let shares = self.shares.entry(community_id).or_default(); | ||
| 609 | + shares.retain(|existing| existing.user_id != share.user_id); | ||
| 610 | + shares.push(share); | ||
| 611 | + } | ||
| 612 | + Event::ShareStopped { | ||
| 613 | + community_id, | ||
| 614 | + user_id, | ||
| 615 | + } => { | ||
| 616 | + if let Some(shares) = self.shares.get_mut(&community_id) { | ||
| 617 | + shares.retain(|share| share.user_id != user_id); | ||
| 618 | + } | ||
| 619 | + } | ||
| 620 | + Event::ShareLayers(_) | Event::KeyframeWanted(_) => {} | ||
| 591 | Event::ReportCreated | Event::Announcement { .. } => {} | 621 | Event::ReportCreated | Event::Announcement { .. } => {} |
| 592 | } | 622 | } |
| 593 | } | 623 | } |
| @@ -1039,6 +1069,12 @@ impl Chat { | |||
| 1039 | .any(|community| community.id == community_id && community.voice_enabled) | 1069 | .any(|community| community.id == community_id && community.voice_enabled) |
| 1040 | } | 1070 | } |
| 1041 | 1071 | ||
| 1072 | + pub fn is_sharing(&self, community_id: &str, user_id: &str) -> bool { | ||
| 1073 | + self.shares | ||
| 1074 | + .get(community_id) | ||
| 1075 | + .is_some_and(|shares| shares.iter().any(|share| share.user_id == user_id)) | ||
| 1076 | + } | ||
| 1077 | + | ||
| 1042 | pub fn voice_ids(&self, community_id: &str) -> &[String] { | 1078 | pub fn voice_ids(&self, community_id: &str) -> &[String] { |
| 1043 | self.voice | 1079 | self.voice |
| 1044 | .get(community_id) | 1080 | .get(community_id) |
| @@ -1051,6 +1087,21 @@ impl Chat { | |||
| 1051 | self.speaking.clear(); | 1087 | self.speaking.clear(); |
| 1052 | self.voice_task = None; | 1088 | self.voice_task = None; |
| 1053 | self.voice_samples.clear(); | 1089 | self.voice_samples.clear(); |
| 1090 | + self.share_sample = ShareSample::default(); | ||
| 1091 | + self.share_loss.clear(); | ||
| 1092 | + } | ||
| 1093 | + | ||
| 1094 | + pub fn record_share(&mut self, sample: ShareSample) { | ||
| 1095 | + self.share_loss | ||
| 1096 | + .retain(|user_id, _| sample.watching.iter().any(|(id, _)| id == user_id)); | ||
| 1097 | + for (user_id, stats) in &sample.watching { | ||
| 1098 | + let history = self.share_loss.entry(user_id.clone()).or_default(); | ||
| 1099 | + history.push_back(stats.loss); | ||
| 1100 | + while history.len() > SAMPLE_HISTORY { | ||
| 1101 | + history.pop_front(); | ||
| 1102 | + } | ||
| 1103 | + } | ||
| 1104 | + self.share_sample = sample; | ||
| 1054 | } | 1105 | } |
| 1055 | } | 1106 | } |
| 1056 | 1107 | ||
| @@ -1160,6 +1211,7 @@ impl Yumush { | |||
| 1160 | .size_full() | 1211 | .size_full() |
| 1161 | .child(self.sidebar(&entity, &self.search_query(cx), palette)) | 1212 | .child(self.sidebar(&entity, &self.search_query(cx), palette)) |
| 1162 | .child(self.main_panel(&entity, palette, cx)) | 1213 | .child(self.main_panel(&entity, palette, cx)) |
| 1214 | + .children(self.fullscreen_viewer(&entity, palette)) | ||
| 1163 | } | 1215 | } |
| 1164 | 1216 | ||
| 1165 | fn main_panel(&self, entity: &Entity<Self>, palette: Palette, cx: &App) -> impl IntoElement { | 1217 | fn main_panel(&self, entity: &Entity<Self>, palette: Palette, cx: &App) -> impl IntoElement { |
| @@ -1191,8 +1243,12 @@ impl Yumush { | |||
| 1191 | .child(self.header(entity, themed)) | 1243 | .child(self.header(entity, themed)) |
| 1192 | .children(self.unread_bar(entity, themed)) | 1244 | .children(self.unread_bar(entity, themed)) |
| 1193 | .children(self.poll_banner(entity, themed)) | 1245 | .children(self.poll_banner(entity, themed)) |
| 1194 | - .child(self.message_area(entity, themed)) | 1246 | + .map(|panel| match self.inline_viewer(entity, themed) { |
| 1195 | - .child(self.composer(entity, themed)), | 1247 | + Some(viewer) => panel.child(viewer), |
| 1248 | + None => panel | ||
| 1249 | + .child(self.message_area(entity, themed)) | ||
| 1250 | + .child(self.composer(entity, themed)), | ||
| 1251 | + }), | ||
| 1196 | None => panel.child(empty_state(palette)), | 1252 | None => panel.child(empty_state(palette)), |
| 1197 | }, | 1253 | }, |
| 1198 | }) | 1254 | }) |
| @@ -1504,6 +1560,7 @@ impl Yumush { | |||
| 1504 | self.load_members(window, cx); | 1560 | self.load_members(window, cx); |
| 1505 | self.load_pins(window, cx); | 1561 | self.load_pins(window, cx); |
| 1506 | self.load_voice(window, cx); | 1562 | self.load_voice(window, cx); |
| 1563 | + self.load_shares(community_id, cx); | ||
| 1507 | self.load_messages(None, window, cx); | 1564 | self.load_messages(None, window, cx); |
| 1508 | cx.notify(); | 1565 | cx.notify(); |
| 1509 | } | 1566 | } |
| @@ -1913,6 +1970,7 @@ impl Yumush { | |||
| 1913 | muted || yumush.is_server_muted() || yumush.hidden_in(&community_id); | 1970 | muted || yumush.is_server_muted() || yumush.hidden_in(&community_id); |
| 1914 | yumush.network.set_muted(muted); | 1971 | yumush.network.set_muted(muted); |
| 1915 | yumush.chat.voice.insert(community_id.clone(), participants); | 1972 | yumush.chat.voice.insert(community_id.clone(), participants); |
| 1973 | + yumush.load_shares(community_id.clone(), cx); | ||
| 1916 | yumush.chat.voice_state = VoiceState::In { | 1974 | yumush.chat.voice_state = VoiceState::In { |
| 1917 | community_id, | 1975 | community_id, |
| 1918 | muted, | 1976 | muted, |
| @@ -2086,12 +2144,12 @@ impl Yumush { | |||
| 2086 | .timer(Duration::from_millis(150)) | 2144 | .timer(Duration::from_millis(150)) |
| 2087 | .await; | 2145 | .await; |
| 2088 | let speaking = network.speaking(); | 2146 | let speaking = network.speaking(); |
| 2089 | - let sample = (sampled.elapsed() >= VOICE_SAMPLE_INTERVAL) | 2147 | + let due = sampled.elapsed() >= VOICE_SAMPLE_INTERVAL; |
| 2090 | - .then(|| network.voice_sample()) | 2148 | + if due { |
| 2091 | - .flatten(); | ||
| 2092 | - if sample.is_some() { | ||
| 2093 | sampled = Instant::now(); | 2149 | sampled = Instant::now(); |
| 2094 | } | 2150 | } |
| 2151 | + let sample = due.then(|| network.voice_sample()).flatten(); | ||
| 2152 | + let share = due.then(|| network.share_sample()); | ||
| 2095 | let polling = this.update(cx, |yumush, cx| { | 2153 | let polling = this.update(cx, |yumush, cx| { |
| 2096 | if yumush.chat.voice_community().is_none() { | 2154 | if yumush.chat.voice_community().is_none() { |
| 2097 | return false; | 2155 | return false; |
| @@ -2104,6 +2162,10 @@ impl Yumush { | |||
| 2104 | } | 2162 | } |
| 2105 | cx.notify(); | 2163 | cx.notify(); |
| 2106 | } | 2164 | } |
| 2165 | + if let Some(share) = share { | ||
| 2166 | + yumush.chat.record_share(share); | ||
| 2167 | + cx.notify(); | ||
| 2168 | + } | ||
| 2107 | yumush.update_speaking(speaking, cx); | 2169 | yumush.update_speaking(speaking, cx); |
| 2108 | true | 2170 | true |
| 2109 | }); | 2171 | }); |
| @@ -2337,10 +2399,16 @@ impl Yumush { | |||
| 2337 | if users.is_empty() { | 2399 | if users.is_empty() { |
| 2338 | return None; | 2400 | return None; |
| 2339 | } | 2401 | } |
| 2402 | + let sharers: Vec<String> = users | ||
| 2403 | + .iter() | ||
| 2404 | + .filter(|user| self.chat.is_sharing(community_id, &user.id)) | ||
| 2405 | + .map(|user| user.id.clone()) | ||
| 2406 | + .collect(); | ||
| 2340 | 2407 | ||
| 2341 | Some( | 2408 | Some( |
| 2342 | div() | 2409 | div() |
| 2343 | .flex() | 2410 | .flex() |
| 2411 | + .items_center() | ||
| 2344 | .children(users.into_iter().take(3).enumerate().map(|(index, user)| { | 2412 | .children(users.into_iter().take(3).enumerate().map(|(index, user)| { |
| 2345 | let ring = if self.chat.speaking.contains(&user.id) { | 2413 | let ring = if self.chat.speaking.contains(&user.id) { |
| 2346 | palette.ok | 2414 | palette.ok |
| @@ -2360,7 +2428,12 @@ impl Yumush { | |||
| 2360 | .hover(move |style| style.border_color(palette.accent)) | 2428 | .hover(move |style| style.border_color(palette.accent)) |
| 2361 | .when(index > 0, |this| this.ml(px(-6.))), | 2429 | .when(index > 0, |this| this.ml(px(-6.))), |
| 2362 | ) | 2430 | ) |
| 2363 | - })), | 2431 | + })) |
| 2432 | + .children( | ||
| 2433 | + sharers | ||
| 2434 | + .iter() | ||
| 2435 | + .map(|user_id| share_view::share_badge(entity, user_id, palette)), | ||
| 2436 | + ), | ||
| 2364 | ) | 2437 | ) |
| 2365 | } | 2438 | } |
| 2366 | 2439 | ||
crates/client/src/gui/media_view.rsmodified+1 -1
| @@ -165,7 +165,7 @@ pub(super) async fn upload_file( | |||
| 165 | uploaded | 165 | uploaded |
| 166 | } | 166 | } |
| 167 | 167 | ||
| 168 | -fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> { | 168 | +pub(super) fn to_render_image(frame: &crate::media::Frame) -> Option<Arc<RenderImage>> { |
| 169 | let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; | 169 | let buffer = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra.to_vec())?; |
| 170 | Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) | 170 | Some(Arc::new(RenderImage::new(vec![image::Frame::new(buffer)]))) |
| 171 | } | 171 | } |
crates/client/src/gui/settings_page.rsmodified+3 -3
| @@ -614,14 +614,14 @@ pub(super) fn segment<E: Styled>(item: E, active: bool, palette: Palette) -> E { | |||
| 614 | .text_color(text) | 614 | .text_color(text) |
| 615 | } | 615 | } |
| 616 | 616 | ||
| 617 | -pub(super) fn segmented<T: Copy + PartialEq + 'static, const N: usize>( | 617 | +pub(super) fn segmented<T: Copy + PartialEq + 'static>( |
| 618 | - options: [(T, &'static str); N], | 618 | + options: impl IntoIterator<Item = (T, &'static str)>, |
| 619 | selected: T, | 619 | selected: T, |
| 620 | entity: &Entity<Yumush>, | 620 | entity: &Entity<Yumush>, |
| 621 | palette: Palette, | 621 | palette: Palette, |
| 622 | select: fn(&mut Yumush, T, &mut Context<Yumush>), | 622 | select: fn(&mut Yumush, T, &mut Context<Yumush>), |
| 623 | ) -> impl IntoElement { | 623 | ) -> impl IntoElement { |
| 624 | - segment_track(palette).children(options.map(|(choice, label)| { | 624 | + segment_track(palette).children(options.into_iter().map(|(choice, label)| { |
| 625 | let entity = entity.clone(); | 625 | let entity = entity.clone(); |
| 626 | 626 | ||
| 627 | segment( | 627 | segment( |
crates/client/src/gui/share_view.rsadded+762 -0
| @@ -0,0 +1,762 @@ | |||
| 1 | +use std::{sync::Arc, time::Duration}; | ||
| 2 | + | ||
| 3 | +use common::share::{Codec, Fps, Quality, Resolution}; | ||
| 4 | +use gpui_kit::{ | ||
| 5 | + Anchor, AnyElement, AppContext, Context, Div, Entity, FontWeight, InteractiveElement, | ||
| 6 | + IntoElement, MouseButton, ObjectFit, ParentElement, RenderImage, Styled, StyledImage, | ||
| 7 | + StatefulInteractiveElement, Subscription, Task, Window, | ||
| 8 | + assets::IconName, | ||
| 9 | + component::{ | ||
| 10 | + Icon, | ||
| 11 | + popover::Popover, | ||
| 12 | + slider::{Slider, SliderEvent, SliderState}, | ||
| 13 | + switch::Switch, | ||
| 14 | + }, | ||
| 15 | + div, img, px, | ||
| 16 | +}; | ||
| 17 | + | ||
| 18 | +use super::{ | ||
| 19 | + Palette, Tooltip as _, Trigger, Yumush, chat::View, clickable, entity_action, | ||
| 20 | + media_view::to_render_image, notify_error, pop_in, settings_page::segmented, | ||
| 21 | + sidebar::icon_button, text, | ||
| 22 | +}; | ||
| 23 | +use crate::{ | ||
| 24 | + settings::{self, SHARE_QUALITY, ShareAudio, ShareCodec, ShareSettings}, | ||
| 25 | + share::{ | ||
| 26 | + audio_capture::{AudioApp, AudioKind}, | ||
| 27 | + encode::capabilities, | ||
| 28 | + session::WatchQuality, | ||
| 29 | + }, | ||
| 30 | +}; | ||
| 31 | + | ||
| 32 | +const FRAME_TICK: Duration = Duration::from_millis(16); | ||
| 33 | +const RESOLUTIONS: [(Resolution, &str); 6] = [ | ||
| 34 | + (Resolution::P360, "360"), | ||
| 35 | + (Resolution::P480, "480"), | ||
| 36 | + (Resolution::P720, "720"), | ||
| 37 | + (Resolution::P1080, "1080"), | ||
| 38 | + (Resolution::P1440, "1440"), | ||
| 39 | + (Resolution::P2160, "2160"), | ||
| 40 | +]; | ||
| 41 | +const FPS: [(Fps, &str); 3] = [(Fps::F15, "15"), (Fps::F30, "30"), (Fps::F60, "60")]; | ||
| 42 | + | ||
| 43 | +const CODECS: [(ShareCodec, &str); 4] = [ | ||
| 44 | + (ShareCodec::Auto, "Auto"), | ||
| 45 | + (ShareCodec::Only(Codec::Av1), "AV1"), | ||
| 46 | + (ShareCodec::Only(Codec::H265), "H265"), | ||
| 47 | + (ShareCodec::Only(Codec::H264), "H264"), | ||
| 48 | +]; | ||
| 49 | + | ||
| 50 | +#[derive(Clone, Copy, PartialEq, Eq)] | ||
| 51 | +pub(super) enum AudioMode { | ||
| 52 | + Off, | ||
| 53 | + Everything, | ||
| 54 | + App, | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +impl AudioMode { | ||
| 58 | + const ALL: [(Self, &'static str); 3] = [ | ||
| 59 | + (Self::Off, "Off"), | ||
| 60 | + (Self::Everything, "All"), | ||
| 61 | + (Self::App, "Pick"), | ||
| 62 | + ]; | ||
| 63 | + | ||
| 64 | + fn of(audio: &ShareAudio) -> Self { | ||
| 65 | + match audio { | ||
| 66 | + ShareAudio::Off => Self::Off, | ||
| 67 | + ShareAudio::Everything => Self::Everything, | ||
| 68 | + ShareAudio::Source(_) => Self::App, | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + fn audio(self, first: String) -> ShareAudio { | ||
| 73 | + match self { | ||
| 74 | + Self::Off => ShareAudio::Off, | ||
| 75 | + Self::Everything => ShareAudio::Everything, | ||
| 76 | + Self::App => ShareAudio::Source(first), | ||
| 77 | + } | ||
| 78 | + } | ||
| 79 | +} | ||
| 80 | + | ||
| 81 | +pub(super) struct Viewer { | ||
| 82 | + user_id: String, | ||
| 83 | + generation: Option<u64>, | ||
| 84 | + frame: Option<Arc<RenderImage>>, | ||
| 85 | + fullscreen: bool, | ||
| 86 | + volume: Entity<SliderState>, | ||
| 87 | + _subscriptions: Vec<Subscription>, | ||
| 88 | + _tick: Task<()>, | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +impl Yumush { | ||
| 92 | + pub(super) fn load_shares(&self, community_id: String, cx: &mut Context<Self>) { | ||
| 93 | + let network = self.network.clone(); | ||
| 94 | + | ||
| 95 | + cx.spawn(async move |this, cx| { | ||
| 96 | + let Ok(shares) = network.shares(&community_id).await else { | ||
| 97 | + return; | ||
| 98 | + }; | ||
| 99 | + let _ = this.update(cx, |yumush, cx| { | ||
| 100 | + yumush.chat.shares.insert(community_id, shares); | ||
| 101 | + cx.notify(); | ||
| 102 | + }); | ||
| 103 | + }) | ||
| 104 | + .detach(); | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context<Self>) { | ||
| 108 | + let network = self.network.clone(); | ||
| 109 | + let sharing = network.sharing(); | ||
| 110 | + | ||
| 111 | + cx.spawn_in(window, async move |this, cx| { | ||
| 112 | + if sharing { | ||
| 113 | + let _ = network.stop_share().await; | ||
| 114 | + } else if let Err(error) = network.start_share().await { | ||
| 115 | + notify_error(&this, cx, error); | ||
| 116 | + } | ||
| 117 | + let _ = this.update(cx, |_, cx| cx.notify()); | ||
| 118 | + }) | ||
| 119 | + .detach(); | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + fn update_share(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut ShareSettings)) { | ||
| 123 | + change(&mut self.settings.share); | ||
| 124 | + settings::save(&self.settings); | ||
| 125 | + self.network.set_share_settings(self.settings.share.clone()); | ||
| 126 | + cx.notify(); | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + pub(super) fn refresh_share_apps(&self, cx: &mut Context<Self>) { | ||
| 130 | + let network = self.network.clone(); | ||
| 131 | + | ||
| 132 | + cx.spawn(async move |this, cx| { | ||
| 133 | + let apps = cx | ||
| 134 | + .background_executor() | ||
| 135 | + .spawn(async move { network.audio_apps() }) | ||
| 136 | + .await; | ||
| 137 | + let _ = this.update(cx, |yumush, cx| { | ||
| 138 | + yumush.share_apps = apps; | ||
| 139 | + cx.notify(); | ||
| 140 | + }); | ||
| 141 | + }) | ||
| 142 | + .detach(); | ||
| 143 | + } | ||
| 144 | + | ||
| 145 | + pub(super) fn set_share_resolution(&mut self, resolution: Resolution, cx: &mut Context<Self>) { | ||
| 146 | + self.update_share(cx, |settings| settings.top.resolution = resolution); | ||
| 147 | + } | ||
| 148 | + | ||
| 149 | + pub(super) fn set_share_codec(&mut self, codec: ShareCodec, cx: &mut Context<Self>) { | ||
| 150 | + self.update_share(cx, |settings| settings.codec = codec); | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + pub(super) fn set_share_fps(&mut self, fps: Fps, cx: &mut Context<Self>) { | ||
| 154 | + self.update_share(cx, |settings| settings.top.fps = fps); | ||
| 155 | + } | ||
| 156 | + | ||
| 157 | + pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context<Self>) { | ||
| 158 | + let first = self | ||
| 159 | + .share_apps | ||
| 160 | + .first() | ||
| 161 | + .map(|app| app.node.clone()) | ||
| 162 | + .unwrap_or_default(); | ||
| 163 | + self.update_share(cx, |settings| settings.audio = mode.audio(first)); | ||
| 164 | + self.refresh_share_apps(cx); | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + pub(super) fn set_share_source(&mut self, node: String, cx: &mut Context<Self>) { | ||
| 168 | + self.update_share(cx, |settings| settings.audio = ShareAudio::Source(node)); | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + pub(super) fn set_share_excluded( | ||
| 172 | + &mut self, | ||
| 173 | + name: String, | ||
| 174 | + excluded: bool, | ||
| 175 | + cx: &mut Context<Self>, | ||
| 176 | + ) { | ||
| 177 | + self.update_share(cx, |settings| { | ||
| 178 | + settings.excluded.retain(|app| *app != name); | ||
| 179 | + if excluded { | ||
| 180 | + settings.excluded.push(name); | ||
| 181 | + } | ||
| 182 | + }); | ||
| 183 | + } | ||
| 184 | + | ||
| 185 | + pub(super) fn set_share_watch(&mut self, watch: WatchQuality, cx: &mut Context<Self>) { | ||
| 186 | + self.update_share(cx, |settings| settings.watch = watch); | ||
| 187 | + } | ||
| 188 | + | ||
| 189 | + pub(super) fn is_watching(&self, user_id: &str) -> bool { | ||
| 190 | + self.chat | ||
| 191 | + .viewer | ||
| 192 | + .as_ref() | ||
| 193 | + .is_some_and(|viewer| viewer.user_id == user_id) | ||
| 194 | + } | ||
| 195 | + | ||
| 196 | + pub(super) fn toggle_viewer( | ||
| 197 | + &mut self, | ||
| 198 | + user_id: String, | ||
| 199 | + window: &mut Window, | ||
| 200 | + cx: &mut Context<Self>, | ||
| 201 | + ) { | ||
| 202 | + let watching = self.is_watching(&user_id); | ||
| 203 | + self.close_viewer(cx); | ||
| 204 | + if watching { | ||
| 205 | + return; | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + let volume_level = self.settings.share.volume; | ||
| 209 | + let volume = cx.new(|_| { | ||
| 210 | + SliderState::new() | ||
| 211 | + .min(0.) | ||
| 212 | + .max(100.) | ||
| 213 | + .default_value(volume_level) | ||
| 214 | + }); | ||
| 215 | + let subscriptions = vec![cx.subscribe(&volume, |this, _, event: &SliderEvent, cx| { | ||
| 216 | + if let SliderEvent::Change(value) = event { | ||
| 217 | + let volume = value.start(); | ||
| 218 | + this.update_share(cx, |settings| settings.volume = volume); | ||
| 219 | + } | ||
| 220 | + })]; | ||
| 221 | + let tick = cx.spawn(async move |this, cx| { | ||
| 222 | + loop { | ||
| 223 | + cx.background_executor().timer(FRAME_TICK).await; | ||
| 224 | + if this | ||
| 225 | + .update(cx, |yumush, cx| yumush.tick_viewer(cx)) | ||
| 226 | + .is_err() | ||
| 227 | + { | ||
| 228 | + break; | ||
| 229 | + } | ||
| 230 | + } | ||
| 231 | + }); | ||
| 232 | + | ||
| 233 | + self.chat.viewer = Some(Viewer { | ||
| 234 | + user_id: user_id.clone(), | ||
| 235 | + generation: None, | ||
| 236 | + frame: None, | ||
| 237 | + fullscreen: false, | ||
| 238 | + volume, | ||
| 239 | + _subscriptions: subscriptions, | ||
| 240 | + _tick: tick, | ||
| 241 | + }); | ||
| 242 | + | ||
| 243 | + let network = self.network.clone(); | ||
| 244 | + cx.spawn_in(window, async move |this, cx| { | ||
| 245 | + if let Err(error) = network.watch_share(&user_id).await { | ||
| 246 | + notify_error(&this, cx, error); | ||
| 247 | + } | ||
| 248 | + }) | ||
| 249 | + .detach(); | ||
| 250 | + cx.notify(); | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + pub(super) fn close_viewer(&mut self, cx: &mut Context<Self>) { | ||
| 254 | + let Some(viewer) = self.chat.viewer.take() else { | ||
| 255 | + return; | ||
| 256 | + }; | ||
| 257 | + let user_id = viewer.user_id.clone(); | ||
| 258 | + if let Some(frame) = viewer.frame { | ||
| 259 | + cx.drop_image(frame, None); | ||
| 260 | + } | ||
| 261 | + let network = self.network.clone(); | ||
| 262 | + cx.spawn(async move |_, _| { | ||
| 263 | + let _ = network.unwatch_share(&user_id).await; | ||
| 264 | + }) | ||
| 265 | + .detach(); | ||
| 266 | + cx.notify(); | ||
| 267 | + } | ||
| 268 | + | ||
| 269 | + fn tick_viewer(&mut self, cx: &mut Context<Self>) { | ||
| 270 | + let Some(viewer) = self.chat.viewer.as_mut() else { | ||
| 271 | + return; | ||
| 272 | + }; | ||
| 273 | + let Some(frame) = self.network.share_frame(&viewer.user_id) else { | ||
| 274 | + return; | ||
| 275 | + }; | ||
| 276 | + if viewer.generation == Some(frame.generation) { | ||
| 277 | + return; | ||
| 278 | + } | ||
| 279 | + viewer.generation = Some(frame.generation); | ||
| 280 | + let next = to_render_image(&frame); | ||
| 281 | + if let Some(old) = std::mem::replace(&mut viewer.frame, next) { | ||
| 282 | + cx.drop_image(old, None); | ||
| 283 | + } | ||
| 284 | + cx.notify(); | ||
| 285 | + } | ||
| 286 | + | ||
| 287 | + pub(super) fn toggle_fullscreen(&mut self, cx: &mut Context<Self>) { | ||
| 288 | + if let Some(viewer) = self.chat.viewer.as_mut() { | ||
| 289 | + viewer.fullscreen = !viewer.fullscreen; | ||
| 290 | + } | ||
| 291 | + cx.notify(); | ||
| 292 | + } | ||
| 293 | + | ||
| 294 | + pub(super) fn share_controls( | ||
| 295 | + &self, | ||
| 296 | + entity: &Entity<Self>, | ||
| 297 | + palette: Palette, | ||
| 298 | + ) -> impl IntoElement { | ||
| 299 | + let sharing = self.network.sharing(); | ||
| 300 | + let toggle = entity.clone(); | ||
| 301 | + let refresh = entity.clone(); | ||
| 302 | + let settings = entity.clone(); | ||
| 303 | + | ||
| 304 | + div() | ||
| 305 | + .flex() | ||
| 306 | + .items_center() | ||
| 307 | + .gap(px(2.)) | ||
| 308 | + .child( | ||
| 309 | + clickable("share_toggle", palette, move |window, cx| { | ||
| 310 | + toggle.update(cx, |yumush, cx| yumush.toggle_share(window, cx)); | ||
| 311 | + }) | ||
| 312 | + .tip(if sharing { | ||
| 313 | + "Stop sharing" | ||
| 314 | + } else { | ||
| 315 | + "Share screen" | ||
| 316 | + }) | ||
| 317 | + .size(px(26.)) | ||
| 318 | + .flex() | ||
| 319 | + .items_center() | ||
| 320 | + .justify_center() | ||
| 321 | + .rounded(px(6.)) | ||
| 322 | + .text_color(if sharing { palette.ok } else { palette.muted }) | ||
| 323 | + .child( | ||
| 324 | + Icon::new(if sharing { | ||
| 325 | + IconName::ScreenShareOff | ||
| 326 | + } else { | ||
| 327 | + IconName::ScreenShare | ||
| 328 | + }) | ||
| 329 | + .w(px(14.)) | ||
| 330 | + .h(px(14.)), | ||
| 331 | + ), | ||
| 332 | + ) | ||
| 333 | + .child( | ||
| 334 | + Popover::new("share_settings") | ||
| 335 | + .anchor(Anchor::BottomLeft) | ||
| 336 | + .appearance(false) | ||
| 337 | + .trigger(Trigger::new( | ||
| 338 | + div() | ||
| 339 | + .id("share_settings_button") | ||
| 340 | + .on_mouse_down(MouseButton::Left, move |_, _, cx| { | ||
| 341 | + refresh.update(cx, |yumush, cx| yumush.refresh_share_apps(cx)); | ||
| 342 | + }) | ||
| 343 | + .tip("Share settings") | ||
| 344 | + .size(px(26.)) | ||
| 345 | + .flex() | ||
| 346 | + .items_center() | ||
| 347 | + .justify_center() | ||
| 348 | + .rounded(px(6.)) | ||
| 349 | + .text_color(palette.muted) | ||
| 350 | + .child(Icon::new(IconName::SlidersHorizontal).w(px(14.)).h(px(14.))), | ||
| 351 | + )) | ||
| 352 | + .content(move |_, _, cx| { | ||
| 353 | + let entity = settings.clone(); | ||
| 354 | + pop_in( | ||
| 355 | + "share_settings_card", | ||
| 356 | + settings_card(&entity, entity.read(cx), palette), | ||
| 357 | + Anchor::BottomLeft, | ||
| 358 | + ) | ||
| 359 | + }), | ||
| 360 | + ) | ||
| 361 | + } | ||
| 362 | + | ||
| 363 | + pub(super) fn inline_viewer(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> { | ||
| 364 | + let viewer = self | ||
| 365 | + .chat | ||
| 366 | + .viewer | ||
| 367 | + .as_ref() | ||
| 368 | + .filter(|viewer| !viewer.fullscreen)?; | ||
| 369 | + Some(self.viewer_pane(viewer, entity, palette)) | ||
| 370 | + } | ||
| 371 | + | ||
| 372 | + pub(super) fn fullscreen_viewer(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> { | ||
| 373 | + let viewer = self | ||
| 374 | + .chat | ||
| 375 | + .viewer | ||
| 376 | + .as_ref() | ||
| 377 | + .filter(|viewer| viewer.fullscreen && self.chat.view == View::Chat)?; | ||
| 378 | + Some( | ||
| 379 | + self.viewer_pane(viewer, entity, palette) | ||
| 380 | + .absolute() | ||
| 381 | + .inset_0(), | ||
| 382 | + ) | ||
| 383 | + } | ||
| 384 | + | ||
| 385 | + fn share_top(&self, user_id: &str) -> Quality { | ||
| 386 | + self.chat | ||
| 387 | + .selected_community_id | ||
| 388 | + .as_ref() | ||
| 389 | + .and_then(|community_id| self.chat.shares.get(community_id)) | ||
| 390 | + .and_then(|shares| shares.iter().find(|share| share.user_id == user_id)) | ||
| 391 | + .map_or(SHARE_QUALITY, |share| share.source.top) | ||
| 392 | + } | ||
| 393 | + | ||
| 394 | + fn viewer_pane(&self, viewer: &Viewer, entity: &Entity<Self>, palette: Palette) -> Div { | ||
| 395 | + let (fullscreen_icon, fullscreen_tip) = if viewer.fullscreen { | ||
| 396 | + (IconName::Minimize, "Exit fullscreen") | ||
| 397 | + } else { | ||
| 398 | + (IconName::Maximize, "Fullscreen") | ||
| 399 | + }; | ||
| 400 | + let top = self.share_top(&viewer.user_id); | ||
| 401 | + | ||
| 402 | + div() | ||
| 403 | + .flex_1() | ||
| 404 | + .min_h_0() | ||
| 405 | + .relative() | ||
| 406 | + .occlude() | ||
| 407 | + .bg(gpui_kit::black()) | ||
| 408 | + .children( | ||
| 409 | + viewer | ||
| 410 | + .frame | ||
| 411 | + .clone() | ||
| 412 | + .map(|frame| img(frame).size_full().object_fit(ObjectFit::Contain)), | ||
| 413 | + ) | ||
| 414 | + .child( | ||
| 415 | + div() | ||
| 416 | + .absolute() | ||
| 417 | + .left(px(10.)) | ||
| 418 | + .right(px(10.)) | ||
| 419 | + .bottom(px(10.)) | ||
| 420 | + .p(px(6.)) | ||
| 421 | + .flex() | ||
| 422 | + .items_center() | ||
| 423 | + .gap(px(8.)) | ||
| 424 | + .rounded(px(8.)) | ||
| 425 | + .border_1() | ||
| 426 | + .border_color(palette.border) | ||
| 427 | + .bg(palette.panel) | ||
| 428 | + .occlude() | ||
| 429 | + .text_size(text(12.)) | ||
| 430 | + .child(quality_chips( | ||
| 431 | + entity, | ||
| 432 | + self.settings.share.watch, | ||
| 433 | + top, | ||
| 434 | + palette, | ||
| 435 | + )) | ||
| 436 | + .child(div().flex_1()) | ||
| 437 | + .child( | ||
| 438 | + Icon::new(IconName::Volume2) | ||
| 439 | + .w(px(14.)) | ||
| 440 | + .h(px(14.)) | ||
| 441 | + .text_color(palette.muted), | ||
| 442 | + ) | ||
| 443 | + .child(Slider::new(&viewer.volume).bg(palette.muted).w(px(80.))) | ||
| 444 | + .child(icon_button( | ||
| 445 | + "share_fullscreen".to_string(), | ||
| 446 | + palette, | ||
| 447 | + fullscreen_icon, | ||
| 448 | + fullscreen_tip, | ||
| 449 | + entity_action(entity, |yumush, _, cx| yumush.toggle_fullscreen(cx)), | ||
| 450 | + )) | ||
| 451 | + .child(icon_button( | ||
| 452 | + "share_close".to_string(), | ||
| 453 | + palette, | ||
| 454 | + IconName::X, | ||
| 455 | + "Close", | ||
| 456 | + entity_action(entity, |yumush, _, cx| yumush.close_viewer(cx)), | ||
| 457 | + )), | ||
| 458 | + ) | ||
| 459 | + } | ||
| 460 | +} | ||
| 461 | + | ||
| 462 | +fn quality_chips( | ||
| 463 | + entity: &Entity<Yumush>, | ||
| 464 | + watch: WatchQuality, | ||
| 465 | + top: Quality, | ||
| 466 | + palette: Palette, | ||
| 467 | +) -> Div { | ||
| 468 | + let fps = match watch { | ||
| 469 | + WatchQuality::Auto => top.fps, | ||
| 470 | + WatchQuality::Fixed(quality) => quality.fps, | ||
| 471 | + }; | ||
| 472 | + let resolutions = std::iter::once((WatchQuality::Auto, "Auto")).chain( | ||
| 473 | + RESOLUTIONS | ||
| 474 | + .into_iter() | ||
| 475 | + .filter(|(resolution, _)| resolution.height() <= top.resolution.height()) | ||
| 476 | + .map(|(resolution, label)| (WatchQuality::Fixed(Quality { resolution, fps }), label)), | ||
| 477 | + ); | ||
| 478 | + let row = div().flex().items_center().gap(px(6.)).child(segmented( | ||
| 479 | + resolutions, | ||
| 480 | + watch, | ||
| 481 | + entity, | ||
| 482 | + palette, | ||
| 483 | + Yumush::set_share_watch, | ||
| 484 | + )); | ||
| 485 | + | ||
| 486 | + match watch { | ||
| 487 | + WatchQuality::Auto => row, | ||
| 488 | + WatchQuality::Fixed(quality) => { | ||
| 489 | + let fps = FPS | ||
| 490 | + .into_iter() | ||
| 491 | + .filter(|(fps, _)| fps.value() <= top.fps.value()) | ||
| 492 | + .map(|(fps, label)| { | ||
| 493 | + ( | ||
| 494 | + WatchQuality::Fixed(Quality { | ||
| 495 | + resolution: quality.resolution, | ||
| 496 | + fps, | ||
| 497 | + }), | ||
| 498 | + label, | ||
| 499 | + ) | ||
| 500 | + }); | ||
| 501 | + row.child(segmented( | ||
| 502 | + fps, | ||
| 503 | + watch, | ||
| 504 | + entity, | ||
| 505 | + palette, | ||
| 506 | + Yumush::set_share_watch, | ||
| 507 | + )) | ||
| 508 | + } | ||
| 509 | + } | ||
| 510 | +} | ||
| 511 | + | ||
| 512 | +pub(super) fn share_badge( | ||
| 513 | + entity: &Entity<Yumush>, | ||
| 514 | + user_id: &str, | ||
| 515 | + palette: Palette, | ||
| 516 | +) -> impl IntoElement { | ||
| 517 | + let entity = entity.clone(); | ||
| 518 | + let user_id = user_id.to_string(); | ||
| 519 | + | ||
| 520 | + clickable( | ||
| 521 | + format!("share_badge_{user_id}"), | ||
| 522 | + palette, | ||
| 523 | + move |window, cx| { | ||
| 524 | + let user_id = user_id.clone(); | ||
| 525 | + entity.update(cx, |yumush, cx| yumush.toggle_viewer(user_id, window, cx)); | ||
| 526 | + }, | ||
| 527 | + ) | ||
| 528 | + .tip("Watch") | ||
| 529 | + .ml(px(6.)) | ||
| 530 | + .h(px(18.)) | ||
| 531 | + .px(px(5.)) | ||
| 532 | + .flex() | ||
| 533 | + .items_center() | ||
| 534 | + .gap(px(3.)) | ||
| 535 | + .rounded(px(4.)) | ||
| 536 | + .bg(palette.alert) | ||
| 537 | + .text_color(palette.on_accent) | ||
| 538 | + .text_size(text(10.)) | ||
| 539 | + .font_weight(FontWeight::SEMIBOLD) | ||
| 540 | + .child(Icon::new(IconName::ScreenShare).w(px(10.)).h(px(10.))) | ||
| 541 | + .child("Live") | ||
| 542 | +} | ||
| 543 | + | ||
| 544 | +fn settings_card(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Div { | ||
| 545 | + let settings = &yumush.settings.share; | ||
| 546 | + | ||
| 547 | + div() | ||
| 548 | + .w(px(320.)) | ||
| 549 | + .p(px(10.)) | ||
| 550 | + .flex() | ||
| 551 | + .flex_col() | ||
| 552 | + .gap(px(12.)) | ||
| 553 | + .text_size(text(12.)) | ||
| 554 | + .rounded(px(8.)) | ||
| 555 | + .border_1() | ||
| 556 | + .border_color(palette.border) | ||
| 557 | + .bg(palette.panel) | ||
| 558 | + .child(field( | ||
| 559 | + "Resolution", | ||
| 560 | + segmented( | ||
| 561 | + RESOLUTIONS, | ||
| 562 | + settings.top.resolution, | ||
| 563 | + entity, | ||
| 564 | + palette, | ||
| 565 | + Yumush::set_share_resolution, | ||
| 566 | + ), | ||
| 567 | + palette, | ||
| 568 | + )) | ||
| 569 | + .child(field( | ||
| 570 | + "FPS", | ||
| 571 | + segmented( | ||
| 572 | + FPS, | ||
| 573 | + settings.top.fps, | ||
| 574 | + entity, | ||
| 575 | + palette, | ||
| 576 | + Yumush::set_share_fps, | ||
| 577 | + ), | ||
| 578 | + palette, | ||
| 579 | + )) | ||
| 580 | + .child(field( | ||
| 581 | + "Codec", | ||
| 582 | + segmented( | ||
| 583 | + CODECS.into_iter().filter(|(codec, _)| match codec { | ||
| 584 | + ShareCodec::Auto => true, | ||
| 585 | + ShareCodec::Only(codec) => capabilities().encode.contains(codec), | ||
| 586 | + }), | ||
| 587 | + settings.codec, | ||
| 588 | + entity, | ||
| 589 | + palette, | ||
| 590 | + Yumush::set_share_codec, | ||
| 591 | + ), | ||
| 592 | + palette, | ||
| 593 | + )) | ||
| 594 | + .child(field( | ||
| 595 | + "Audio", | ||
| 596 | + segmented( | ||
| 597 | + AudioMode::ALL, | ||
| 598 | + AudioMode::of(&settings.audio), | ||
| 599 | + entity, | ||
| 600 | + palette, | ||
| 601 | + Yumush::set_share_audio_mode, | ||
| 602 | + ), | ||
| 603 | + palette, | ||
| 604 | + )) | ||
| 605 | + .children(audio_list(entity, yumush, palette)) | ||
| 606 | +} | ||
| 607 | + | ||
| 608 | +fn audio_list(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Option<AnyElement> { | ||
| 609 | + let settings = &yumush.settings.share; | ||
| 610 | + | ||
| 611 | + match &settings.audio { | ||
| 612 | + ShareAudio::Off => None, | ||
| 613 | + ShareAudio::Everything => { | ||
| 614 | + let rows = div() | ||
| 615 | + .flex() | ||
| 616 | + .flex_col() | ||
| 617 | + .gap(px(2.)) | ||
| 618 | + .children( | ||
| 619 | + yumush | ||
| 620 | + .share_apps | ||
| 621 | + .iter() | ||
| 622 | + .filter(|app| app.kind == AudioKind::App) | ||
| 623 | + .map(|app| exclude_row(entity, settings, app)), | ||
| 624 | + ); | ||
| 625 | + Some(field("Exclude", app_list(rows), palette).into_any_element()) | ||
| 626 | + } | ||
| 627 | + ShareAudio::Source(selected) => Some( | ||
| 628 | + app_list(pick_list( | ||
| 629 | + entity, | ||
| 630 | + selected.as_str(), | ||
| 631 | + &yumush.share_apps, | ||
| 632 | + palette, | ||
| 633 | + )) | ||
| 634 | + .into_any_element(), | ||
| 635 | + ), | ||
| 636 | + } | ||
| 637 | +} | ||
| 638 | + | ||
| 639 | +fn app_list(rows: impl IntoElement) -> impl IntoElement { | ||
| 640 | + div() | ||
| 641 | + .id("share_apps") | ||
| 642 | + .max_h(px(160.)) | ||
| 643 | + .overflow_y_scroll() | ||
| 644 | + .child(rows) | ||
| 645 | +} | ||
| 646 | + | ||
| 647 | +fn pick_list( | ||
| 648 | + entity: &Entity<Yumush>, | ||
| 649 | + selected: &str, | ||
| 650 | + apps: &[AudioApp], | ||
| 651 | + palette: Palette, | ||
| 652 | +) -> Div { | ||
| 653 | + let groups = [ | ||
| 654 | + (AudioKind::App, "Apps"), | ||
| 655 | + (AudioKind::Output, "Outputs"), | ||
| 656 | + (AudioKind::Input, "Inputs"), | ||
| 657 | + ]; | ||
| 658 | + | ||
| 659 | + div() | ||
| 660 | + .flex() | ||
| 661 | + .flex_col() | ||
| 662 | + .gap(px(8.)) | ||
| 663 | + .children(groups.into_iter().filter_map(|(kind, label)| { | ||
| 664 | + let rows: Vec<_> = apps | ||
| 665 | + .iter() | ||
| 666 | + .filter(|app| app.kind == kind) | ||
| 667 | + .map(|app| pick_row(entity, selected == app.node, app, palette)) | ||
| 668 | + .collect(); | ||
| 669 | + (!rows.is_empty()).then(|| group(label, rows, palette)) | ||
| 670 | + })) | ||
| 671 | +} | ||
| 672 | + | ||
| 673 | +fn group(label: &'static str, rows: Vec<impl IntoElement>, palette: Palette) -> Div { | ||
| 674 | + div() | ||
| 675 | + .flex() | ||
| 676 | + .flex_col() | ||
| 677 | + .gap(px(2.)) | ||
| 678 | + .child( | ||
| 679 | + div() | ||
| 680 | + .px(px(8.)) | ||
| 681 | + .text_size(text(11.)) | ||
| 682 | + .text_color(palette.muted) | ||
| 683 | + .child(label), | ||
| 684 | + ) | ||
| 685 | + .children(rows) | ||
| 686 | +} | ||
| 687 | + | ||
| 688 | +fn field(label: &'static str, control: impl IntoElement, palette: Palette) -> Div { | ||
| 689 | + div() | ||
| 690 | + .flex() | ||
| 691 | + .flex_col() | ||
| 692 | + .gap(px(6.)) | ||
| 693 | + .child( | ||
| 694 | + div() | ||
| 695 | + .text_size(text(11.)) | ||
| 696 | + .text_color(palette.muted) | ||
| 697 | + .child(label), | ||
| 698 | + ) | ||
| 699 | + .child(control) | ||
| 700 | +} | ||
| 701 | + | ||
| 702 | +fn row_style<E: Styled>(item: E) -> E { | ||
| 703 | + item.h(px(28.)) | ||
| 704 | + .px(px(8.)) | ||
| 705 | + .flex() | ||
| 706 | + .items_center() | ||
| 707 | + .gap(px(8.)) | ||
| 708 | + .rounded(px(6.)) | ||
| 709 | +} | ||
| 710 | + | ||
| 711 | +fn name_cell(name: String) -> Div { | ||
| 712 | + div().flex_1().min_w_0().truncate().child(name) | ||
| 713 | +} | ||
| 714 | + | ||
| 715 | +fn exclude_row(entity: &Entity<Yumush>, settings: &ShareSettings, app: &AudioApp) -> impl IntoElement { | ||
| 716 | + let entity = entity.clone(); | ||
| 717 | + let name = app.name.clone(); | ||
| 718 | + let included = !settings.excluded.contains(&app.name); | ||
| 719 | + | ||
| 720 | + row_style(div()) | ||
| 721 | + .child(name_cell(app.name.clone())) | ||
| 722 | + .child( | ||
| 723 | + div().flex_shrink_0().child( | ||
| 724 | + Switch::new(format!("share_app_{}", app.node)) | ||
| 725 | + .checked(included) | ||
| 726 | + .on_change(move |checked, _, cx| { | ||
| 727 | + let name = name.clone(); | ||
| 728 | + let included = *checked; | ||
| 729 | + entity.update(cx, |yumush, cx| { | ||
| 730 | + yumush.set_share_excluded(name, !included, cx) | ||
| 731 | + }); | ||
| 732 | + }), | ||
| 733 | + ), | ||
| 734 | + ) | ||
| 735 | +} | ||
| 736 | + | ||
| 737 | +fn pick_row( | ||
| 738 | + entity: &Entity<Yumush>, | ||
| 739 | + chosen: bool, | ||
| 740 | + app: &AudioApp, | ||
| 741 | + palette: Palette, | ||
| 742 | +) -> impl IntoElement { | ||
| 743 | + let entity = entity.clone(); | ||
| 744 | + let node = app.node.clone(); | ||
| 745 | + | ||
| 746 | + row_style(clickable( | ||
| 747 | + format!("share_app_{}", app.node), | ||
| 748 | + palette, | ||
| 749 | + move |_, cx| { | ||
| 750 | + let node = node.clone(); | ||
| 751 | + entity.update(cx, |yumush, cx| yumush.set_share_source(node, cx)); | ||
| 752 | + }, | ||
| 753 | + )) | ||
| 754 | + .child(name_cell(app.name.clone())) | ||
| 755 | + .children(chosen.then(|| { | ||
| 756 | + Icon::new(IconName::Check) | ||
| 757 | + .w(px(14.)) | ||
| 758 | + .h(px(14.)) | ||
| 759 | + .flex_shrink_0() | ||
| 760 | + .text_color(palette.ok) | ||
| 761 | + })) | ||
| 762 | +} | ||
crates/client/src/gui/sidebar.rsmodified+4 -3
| @@ -187,6 +187,7 @@ impl Yumush { | |||
| 187 | ), | 187 | ), |
| 188 | ), | 188 | ), |
| 189 | ) | 189 | ) |
| 190 | + .child(self.share_controls(entity, palette)) | ||
| 190 | .child(icon_button( | 191 | .child(icon_button( |
| 191 | "voice_panel_leave".to_string(), | 192 | "voice_panel_leave".to_string(), |
| 192 | palette, | 193 | palette, |
| @@ -205,10 +206,10 @@ impl Yumush { | |||
| 205 | .appearance(false) | 206 | .appearance(false) |
| 206 | .trigger(Trigger::new(panel)) | 207 | .trigger(Trigger::new(panel)) |
| 207 | .content(move |_, _, cx| { | 208 | .content(move |_, _, cx| { |
| 208 | - let samples = &stats_entity.read(cx).chat.voice_samples; | 209 | + let chat = &stats_entity.read(cx).chat; |
| 209 | pop_in( | 210 | pop_in( |
| 210 | "voice_stats_card", | 211 | "voice_stats_card", |
| 211 | - voice_stats::stats_card(samples, palette), | 212 | + voice_stats::stats_card(chat, &stats_entity, palette), |
| 212 | Anchor::BottomLeft, | 213 | Anchor::BottomLeft, |
| 213 | ) | 214 | ) |
| 214 | }), | 215 | }), |
| @@ -995,7 +996,7 @@ fn entry( | |||
| 995 | .children(trailing) | 996 | .children(trailing) |
| 996 | } | 997 | } |
| 997 | 998 | ||
| 998 | -fn icon_button( | 999 | +pub(super) fn icon_button( |
| 999 | id: String, | 1000 | id: String, |
| 1000 | palette: Palette, | 1001 | palette: Palette, |
| 1001 | icon: IconName, | 1002 | icon: IconName, |
crates/client/src/gui/voice_stats.rsmodified+232 -60
| @@ -1,16 +1,29 @@ | |||
| 1 | use std::collections::VecDeque; | 1 | use std::collections::VecDeque; |
| 2 | 2 | ||
| 3 | +use common::share::Layer; | ||
| 3 | use gpui_kit::{ | 4 | use gpui_kit::{ |
| 4 | - Div, FontWeight, Hsla, ParentElement, Styled, div, hsla, prelude::FluentBuilder as _, px, | 5 | + Context, Div, Entity, FontWeight, Hsla, ParentElement, Styled, div, hsla, |
| 6 | + prelude::FluentBuilder as _, px, | ||
| 5 | }; | 7 | }; |
| 6 | 8 | ||
| 7 | -use super::{Palette, text}; | 9 | +use super::{Palette, Yumush, chat::Chat, settings_page::segmented, text}; |
| 10 | +use crate::media::decode::Engine; | ||
| 11 | +use crate::share::session::{LayerStats, WatchStats}; | ||
| 8 | use crate::voice::VoiceSample; | 12 | use crate::voice::VoiceSample; |
| 9 | 13 | ||
| 10 | pub const SAMPLE_HISTORY: usize = 60; | 14 | pub const SAMPLE_HISTORY: usize = 60; |
| 11 | const GRAPH_HEIGHT: f32 = 32.; | 15 | const GRAPH_HEIGHT: f32 = 32.; |
| 12 | const PING_SCALE: f32 = 150.; | 16 | const PING_SCALE: f32 = 150.; |
| 13 | const LOSS_SCALE: f32 = 10.; | 17 | const LOSS_SCALE: f32 = 10.; |
| 18 | +const GOOD_LOSS: f32 = 2.; | ||
| 19 | +const FAIR_LOSS: f32 = 8.; | ||
| 20 | + | ||
| 21 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 22 | +pub enum StatsTab { | ||
| 23 | + Voice, | ||
| 24 | + Sharing, | ||
| 25 | + Watching, | ||
| 26 | +} | ||
| 14 | 27 | ||
| 15 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] | 28 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 16 | pub enum Quality { | 29 | pub enum Quality { |
| @@ -23,9 +36,19 @@ impl Quality { | |||
| 23 | pub fn of(sample: &VoiceSample) -> Self { | 36 | pub fn of(sample: &VoiceSample) -> Self { |
| 24 | let loss = sample.traffic.loss * 100.; | 37 | let loss = sample.traffic.loss * 100.; |
| 25 | let jitter = sample.traffic.jitter_ms; | 38 | let jitter = sample.traffic.jitter_ms; |
| 26 | - if sample.ping_ms < 100. && loss < 2. && jitter < 30. { | 39 | + if sample.ping_ms < 100. && loss < GOOD_LOSS && jitter < 30. { |
| 40 | + Self::Good | ||
| 41 | + } else if sample.ping_ms < 200. && loss < FAIR_LOSS && jitter < 60. { | ||
| 42 | + Self::Fair | ||
| 43 | + } else { | ||
| 44 | + Self::Poor | ||
| 45 | + } | ||
| 46 | + } | ||
| 47 | + | ||
| 48 | + fn of_loss(percent: f32) -> Self { | ||
| 49 | + if percent < GOOD_LOSS { | ||
| 27 | Self::Good | 50 | Self::Good |
| 28 | - } else if sample.ping_ms < 200. && loss < 8. && jitter < 60. { | 51 | + } else if percent < FAIR_LOSS { |
| 29 | Self::Fair | 52 | Self::Fair |
| 30 | } else { | 53 | } else { |
| 31 | Self::Poor | 54 | Self::Poor |
| @@ -53,7 +76,79 @@ pub fn quality(samples: &VecDeque<VoiceSample>) -> Option<Quality> { | |||
| 53 | samples.back().map(Quality::of) | 76 | samples.back().map(Quality::of) |
| 54 | } | 77 | } |
| 55 | 78 | ||
| 56 | -pub fn stats_card(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div { | 79 | +pub fn stats_card(chat: &Chat, entity: &Entity<Yumush>, palette: Palette) -> Div { |
| 80 | + let share = &chat.share_sample; | ||
| 81 | + let mut tabs = vec![(StatsTab::Voice, "Voice")]; | ||
| 82 | + if !share.sending.is_empty() { | ||
| 83 | + tabs.push((StatsTab::Sharing, "Sharing")); | ||
| 84 | + } | ||
| 85 | + if !share.watching.is_empty() { | ||
| 86 | + tabs.push((StatsTab::Watching, "Watching")); | ||
| 87 | + } | ||
| 88 | + let selected = if tabs.iter().any(|(tab, _)| *tab == chat.stats_tab) { | ||
| 89 | + chat.stats_tab | ||
| 90 | + } else { | ||
| 91 | + StatsTab::Voice | ||
| 92 | + }; | ||
| 93 | + | ||
| 94 | + let body = match selected { | ||
| 95 | + StatsTab::Voice => voice_body(&chat.voice_samples, palette), | ||
| 96 | + StatsTab::Sharing => sharing_body(&share.sending, palette), | ||
| 97 | + StatsTab::Watching => watching_body(&share.watching, chat, palette), | ||
| 98 | + }; | ||
| 99 | + let latest = chat.voice_samples.back(); | ||
| 100 | + | ||
| 101 | + div() | ||
| 102 | + .w(px(280.)) | ||
| 103 | + .p(px(14.)) | ||
| 104 | + .flex() | ||
| 105 | + .flex_col() | ||
| 106 | + .gap(px(12.)) | ||
| 107 | + .rounded(px(8.)) | ||
| 108 | + .border_1() | ||
| 109 | + .border_color(palette.border) | ||
| 110 | + .bg(palette.panel) | ||
| 111 | + .shadow_lg() | ||
| 112 | + .child( | ||
| 113 | + div() | ||
| 114 | + .flex() | ||
| 115 | + .items_center() | ||
| 116 | + .justify_between() | ||
| 117 | + .child( | ||
| 118 | + div() | ||
| 119 | + .font_weight(FontWeight::SEMIBOLD) | ||
| 120 | + .text_color(palette.text) | ||
| 121 | + .child("Connection"), | ||
| 122 | + ) | ||
| 123 | + .children( | ||
| 124 | + (selected == StatsTab::Voice) | ||
| 125 | + .then_some(latest) | ||
| 126 | + .flatten() | ||
| 127 | + .map(|sample| { | ||
| 128 | + let quality = Quality::of(sample); | ||
| 129 | + let color = quality.color(palette); | ||
| 130 | + div() | ||
| 131 | + .px(px(8.)) | ||
| 132 | + .py(px(2.)) | ||
| 133 | + .rounded_full() | ||
| 134 | + .bg(color.opacity(0.15)) | ||
| 135 | + .text_size(text(11.)) | ||
| 136 | + .font_weight(FontWeight::MEDIUM) | ||
| 137 | + .text_color(color) | ||
| 138 | + .child(quality.label()) | ||
| 139 | + }), | ||
| 140 | + ), | ||
| 141 | + ) | ||
| 142 | + .children((tabs.len() > 1).then(|| segmented(tabs, selected, entity, palette, select_tab))) | ||
| 143 | + .child(body) | ||
| 144 | +} | ||
| 145 | + | ||
| 146 | +fn select_tab(yumush: &mut Yumush, tab: StatsTab, cx: &mut Context<Yumush>) { | ||
| 147 | + yumush.chat.stats_tab = tab; | ||
| 148 | + cx.notify(); | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +fn voice_body(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div { | ||
| 57 | let latest = samples.back(); | 152 | let latest = samples.back(); |
| 58 | let value = |format: fn(&VoiceSample) -> String| latest.map_or("…".to_string(), format); | 153 | let value = |format: fn(&VoiceSample) -> String| latest.map_or("…".to_string(), format); |
| 59 | let tiles = [ | 154 | let tiles = [ |
| @@ -80,42 +175,7 @@ pub fn stats_card(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div { | |||
| 80 | ), | 175 | ), |
| 81 | ]; | 176 | ]; |
| 82 | 177 | ||
| 83 | - div() | 178 | + column() |
| 84 | - .w(px(280.)) | ||
| 85 | - .p(px(14.)) | ||
| 86 | - .flex() | ||
| 87 | - .flex_col() | ||
| 88 | - .gap(px(12.)) | ||
| 89 | - .rounded(px(8.)) | ||
| 90 | - .border_1() | ||
| 91 | - .border_color(palette.border) | ||
| 92 | - .bg(palette.panel) | ||
| 93 | - .shadow_lg() | ||
| 94 | - .child( | ||
| 95 | - div() | ||
| 96 | - .flex() | ||
| 97 | - .items_center() | ||
| 98 | - .justify_between() | ||
| 99 | - .child( | ||
| 100 | - div() | ||
| 101 | - .font_weight(FontWeight::SEMIBOLD) | ||
| 102 | - .text_color(palette.text) | ||
| 103 | - .child("Connection"), | ||
| 104 | - ) | ||
| 105 | - .children(latest.map(|sample| { | ||
| 106 | - let quality = Quality::of(sample); | ||
| 107 | - let color = quality.color(palette); | ||
| 108 | - div() | ||
| 109 | - .px(px(8.)) | ||
| 110 | - .py(px(2.)) | ||
| 111 | - .rounded_full() | ||
| 112 | - .bg(color.opacity(0.15)) | ||
| 113 | - .text_size(text(11.)) | ||
| 114 | - .font_weight(FontWeight::MEDIUM) | ||
| 115 | - .text_color(color) | ||
| 116 | - .child(quality.label()) | ||
| 117 | - })), | ||
| 118 | - ) | ||
| 119 | .child( | 179 | .child( |
| 120 | div() | 180 | div() |
| 121 | .flex() | 181 | .flex() |
| @@ -125,14 +185,28 @@ pub fn stats_card(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div { | |||
| 125 | ) | 185 | ) |
| 126 | .child(graph( | 186 | .child(graph( |
| 127 | "Ping", | 187 | "Ping", |
| 128 | - samples, | 188 | + samples |
| 129 | - |sample| sample.ping_ms / PING_SCALE, | 189 | + .iter() |
| 190 | + .map(|sample| { | ||
| 191 | + ( | ||
| 192 | + sample.ping_ms / PING_SCALE, | ||
| 193 | + Quality::of(sample).color(palette), | ||
| 194 | + ) | ||
| 195 | + }) | ||
| 196 | + .collect(), | ||
| 130 | palette, | 197 | palette, |
| 131 | )) | 198 | )) |
| 132 | .child(graph( | 199 | .child(graph( |
| 133 | "Loss", | 200 | "Loss", |
| 134 | - samples, | 201 | + samples |
| 135 | - |sample| sample.traffic.loss * 100. / LOSS_SCALE, | 202 | + .iter() |
| 203 | + .map(|sample| { | ||
| 204 | + ( | ||
| 205 | + sample.traffic.loss * 100. / LOSS_SCALE, | ||
| 206 | + Quality::of(sample).color(palette), | ||
| 207 | + ) | ||
| 208 | + }) | ||
| 209 | + .collect(), | ||
| 136 | palette, | 210 | palette, |
| 137 | )) | 211 | )) |
| 138 | .children(latest.map(|sample| { | 212 | .children(latest.map(|sample| { |
| @@ -143,6 +217,112 @@ pub fn stats_card(samples: &VecDeque<VoiceSample>, palette: Palette) -> Div { | |||
| 143 | })) | 217 | })) |
| 144 | } | 218 | } |
| 145 | 219 | ||
| 220 | +fn sharing_body(layers: &[LayerStats], palette: Palette) -> Div { | ||
| 221 | + let upload: u32 = layers.iter().map(|layer| layer.kbps).sum(); | ||
| 222 | + column() | ||
| 223 | + .child(div().flex().flex_wrap().gap(px(6.)).child(tile( | ||
| 224 | + "Upload", | ||
| 225 | + format!("{upload} kbps"), | ||
| 226 | + palette, | ||
| 227 | + ))) | ||
| 228 | + .children(layers.iter().map(|stat| { | ||
| 229 | + row_line( | ||
| 230 | + describe(Some(stat.layer), Some(stat.engine)), | ||
| 231 | + format!("{} kbps · {:.0} fps", stat.kbps, stat.fps), | ||
| 232 | + palette, | ||
| 233 | + ) | ||
| 234 | + })) | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +fn watching_body(watching: &[(String, WatchStats)], chat: &Chat, palette: Palette) -> Div { | ||
| 238 | + column().children(watching.iter().map(|(user_id, stats)| { | ||
| 239 | + let name = chat.users.get(user_id).map_or_else( | ||
| 240 | + || user_id.chars().take(8).collect(), | ||
| 241 | + |user| user.username.clone(), | ||
| 242 | + ); | ||
| 243 | + let tiles = [ | ||
| 244 | + ("Bitrate", format!("{} kbps", stats.kbps)), | ||
| 245 | + ("FPS", format!("{:.0}", stats.fps)), | ||
| 246 | + ("Loss", format!("{:.1} %", stats.loss * 100.)), | ||
| 247 | + ("Delay", format!("{} ms", stats.delay_ms)), | ||
| 248 | + ("Keyframes", stats.keyframes.to_string()), | ||
| 249 | + ]; | ||
| 250 | + column() | ||
| 251 | + .child(row_line(name, describe(stats.layer, stats.engine), palette)) | ||
| 252 | + .child( | ||
| 253 | + div() | ||
| 254 | + .flex() | ||
| 255 | + .flex_wrap() | ||
| 256 | + .gap(px(6.)) | ||
| 257 | + .children(tiles.map(|(label, value)| tile(label, value, palette))), | ||
| 258 | + ) | ||
| 259 | + .child(graph( | ||
| 260 | + "Loss", | ||
| 261 | + chat.share_loss | ||
| 262 | + .get(user_id) | ||
| 263 | + .into_iter() | ||
| 264 | + .flatten() | ||
| 265 | + .map(|loss| { | ||
| 266 | + ( | ||
| 267 | + loss * 100. / LOSS_SCALE, | ||
| 268 | + Quality::of_loss(loss * 100.).color(palette), | ||
| 269 | + ) | ||
| 270 | + }) | ||
| 271 | + .collect(), | ||
| 272 | + palette, | ||
| 273 | + )) | ||
| 274 | + })) | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +fn column() -> Div { | ||
| 278 | + div().flex().flex_col().gap(px(8.)) | ||
| 279 | +} | ||
| 280 | + | ||
| 281 | +fn describe(layer: Option<Layer>, engine: Option<Engine>) -> String { | ||
| 282 | + match (layer, engine) { | ||
| 283 | + (Some(layer), Some(engine)) => format!( | ||
| 284 | + "{} · {}p{} · {}", | ||
| 285 | + layer.codec.name(), | ||
| 286 | + layer.quality.resolution.height(), | ||
| 287 | + layer.quality.fps.value(), | ||
| 288 | + match engine { | ||
| 289 | + Engine::Hardware => "HW", | ||
| 290 | + Engine::Software => "SW", | ||
| 291 | + } | ||
| 292 | + ), | ||
| 293 | + _ => "…".to_string(), | ||
| 294 | + } | ||
| 295 | +} | ||
| 296 | + | ||
| 297 | +fn row_line(left: String, right: String, palette: Palette) -> Div { | ||
| 298 | + div() | ||
| 299 | + .flex() | ||
| 300 | + .items_center() | ||
| 301 | + .justify_between() | ||
| 302 | + .gap(px(6.)) | ||
| 303 | + .px(px(8.)) | ||
| 304 | + .py(px(4.)) | ||
| 305 | + .rounded(px(6.)) | ||
| 306 | + .bg(palette.window) | ||
| 307 | + .child( | ||
| 308 | + div() | ||
| 309 | + .flex_1() | ||
| 310 | + .min_w_0() | ||
| 311 | + .truncate() | ||
| 312 | + .text_size(text(11.)) | ||
| 313 | + .font_weight(FontWeight::MEDIUM) | ||
| 314 | + .text_color(palette.text) | ||
| 315 | + .child(left), | ||
| 316 | + ) | ||
| 317 | + .child( | ||
| 318 | + div() | ||
| 319 | + .flex_none() | ||
| 320 | + .text_size(text(11.)) | ||
| 321 | + .text_color(palette.muted) | ||
| 322 | + .child(right), | ||
| 323 | + ) | ||
| 324 | +} | ||
| 325 | + | ||
| 146 | fn tile(label: &'static str, value: String, palette: Palette) -> Div { | 326 | fn tile(label: &'static str, value: String, palette: Palette) -> Div { |
| 147 | div() | 327 | div() |
| 148 | .w(px(80.)) | 328 | .w(px(80.)) |
| @@ -167,20 +347,12 @@ fn tile(label: &'static str, value: String, palette: Palette) -> Div { | |||
| 167 | ) | 347 | ) |
| 168 | } | 348 | } |
| 169 | 349 | ||
| 170 | -fn graph( | 350 | +fn graph(label: &'static str, bars: Vec<(f32, Hsla)>, palette: Palette) -> Div { |
| 171 | - label: &'static str, | 351 | + let empty = SAMPLE_HISTORY.saturating_sub(bars.len()); |
| 172 | - samples: &VecDeque<VoiceSample>, | 352 | + let empty_bars = bars.is_empty(); |
| 173 | - level: fn(&VoiceSample) -> f32, | 353 | + let bars = bars.into_iter().map(|(level, color)| { |
| 174 | - palette: Palette, | 354 | + let height = level.clamp(0.04, 1.) * GRAPH_HEIGHT; |
| 175 | -) -> Div { | 355 | + div().flex_1().h(px(height)).rounded_t(px(1.)).bg(color) |
| 176 | - let empty = SAMPLE_HISTORY.saturating_sub(samples.len()); | ||
| 177 | - let bars = samples.iter().map(|sample| { | ||
| 178 | - let height = level(sample).clamp(0.04, 1.) * GRAPH_HEIGHT; | ||
| 179 | - div() | ||
| 180 | - .flex_1() | ||
| 181 | - .h(px(height)) | ||
| 182 | - .rounded_t(px(1.)) | ||
| 183 | - .bg(Quality::of(sample).color(palette)) | ||
| 184 | }); | 356 | }); |
| 185 | 357 | ||
| 186 | div() | 358 | div() |
| @@ -204,6 +376,6 @@ fn graph( | |||
| 204 | .bg(palette.window) | 376 | .bg(palette.window) |
| 205 | .children((0..empty).map(|_| div().flex_1())) | 377 | .children((0..empty).map(|_| div().flex_1())) |
| 206 | .children(bars) | 378 | .children(bars) |
| 207 | - .when(samples.is_empty(), |this| this.opacity(0.5)), | 379 | + .when(empty_bars, |this| this.opacity(0.5)), |
| 208 | ) | 380 | ) |
| 209 | } | 381 | } |
crates/client/src/lib.rsmodified+1 -0
| @@ -10,6 +10,7 @@ pub mod media; | |||
| 10 | pub mod mutes; | 10 | pub mod mutes; |
| 11 | pub mod network; | 11 | pub mod network; |
| 12 | pub mod settings; | 12 | pub mod settings; |
| 13 | +pub mod share; | ||
| 13 | pub mod tray; | 14 | pub mod tray; |
| 14 | pub mod voice; | 15 | pub mod voice; |
| 15 | 16 | ||
crates/client/src/media/convert.rsmodified+5 -3
| @@ -1,4 +1,5 @@ | |||
| 1 | -const MAX_WIDTH: u32 = 1280; | 1 | +pub const ATTACHMENT_WIDTH: u32 = 1280; |
| 2 | +pub const SHARE_WIDTH: u32 = 1920; | ||
| 2 | 3 | ||
| 3 | pub fn yuv_to_bgra( | 4 | pub fn yuv_to_bgra( |
| 4 | y: &[u8], | 5 | y: &[u8], |
| @@ -8,11 +9,12 @@ pub fn yuv_to_bgra( | |||
| 8 | uv_stride: usize, | 9 | uv_stride: usize, |
| 9 | width: u32, | 10 | width: u32, |
| 10 | height: u32, | 11 | height: u32, |
| 12 | + max_width: u32, | ||
| 11 | ) -> Option<(u32, u32, Vec<u8>)> { | 13 | ) -> Option<(u32, u32, Vec<u8>)> { |
| 12 | if width == 0 || height == 0 { | 14 | if width == 0 || height == 0 { |
| 13 | return None; | 15 | return None; |
| 14 | } | 16 | } |
| 15 | - let step = width.div_ceil(MAX_WIDTH); | 17 | + let step = width.div_ceil(max_width); |
| 16 | let out_width = width.div_ceil(step); | 18 | let out_width = width.div_ceil(step); |
| 17 | let out_height = height.div_ceil(step); | 19 | let out_height = height.div_ceil(step); |
| 18 | let mut out = Vec::with_capacity(out_width as usize * out_height as usize * 4); | 20 | let mut out = Vec::with_capacity(out_width as usize * out_height as usize * 4); |
| @@ -48,7 +50,7 @@ mod tests { | |||
| 48 | use super::*; | 50 | use super::*; |
| 49 | 51 | ||
| 50 | fn bgra(luma: u8) -> Option<(u32, u32, Vec<u8>)> { | 52 | fn bgra(luma: u8) -> Option<(u32, u32, Vec<u8>)> { |
| 51 | - yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2) | 53 | + yuv_to_bgra(&[luma; 4], 2, &[128], &[128], 1, 2, 2, ATTACHMENT_WIDTH) |
| 52 | } | 54 | } |
| 53 | 55 | ||
| 54 | #[test] | 56 | #[test] |
crates/client/src/media/decode.rsmodified+184 -17
| @@ -8,7 +8,7 @@ use std::{ | |||
| 8 | time::{Duration, Instant}, | 8 | time::{Duration, Instant}, |
| 9 | }; | 9 | }; |
| 10 | 10 | ||
| 11 | -use common::constant::VOICE_SAMPLE_RATE; | 11 | +use common::{constant::VOICE_SAMPLE_RATE, share::Codec}; |
| 12 | use ec_core::frame::{Frame as CodecFrame, PixelFormat, VideoFrame}; | 12 | use ec_core::frame::{Frame as CodecFrame, PixelFormat, VideoFrame}; |
| 13 | use ec_core::packet::Packet; | 13 | use ec_core::packet::Packet; |
| 14 | use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekMode}; | 14 | use ec_core::registry::{CodecId, CodecParameters, Decoder as CodecDecoder, SeekMode}; |
| @@ -20,11 +20,12 @@ use tracing::warn; | |||
| 20 | 20 | ||
| 21 | use super::{ | 21 | use super::{ |
| 22 | Frame, Tracks, convert, | 22 | Frame, Tracks, convert, |
| 23 | - resample::{self, Resampler}, | 23 | + resample::{self, Resampler, Stereo}, |
| 24 | }; | 24 | }; |
| 25 | -use crate::voice::Playback; | 25 | +use crate::voice::{PLAYBACK_CHANNELS, Playback}; |
| 26 | 26 | ||
| 27 | -pub const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 4; | 27 | +pub const RING_FRAMES: usize = VOICE_SAMPLE_RATE as usize / 4; |
| 28 | +pub const RING_SAMPLES: usize = RING_FRAMES * PLAYBACK_CHANNELS; | ||
| 28 | const QUEUE_LIMIT: usize = 8; | 29 | const QUEUE_LIMIT: usize = 8; |
| 29 | const BACKLOG_LIMIT: usize = 600; | 30 | const BACKLOG_LIMIT: usize = 600; |
| 30 | const LATE: f64 = 0.1; | 31 | const LATE: f64 = 0.1; |
| @@ -100,7 +101,7 @@ pub struct Shared { | |||
| 100 | pub seek: Mutex<Option<f64>>, | 101 | pub seek: Mutex<Option<f64>>, |
| 101 | pub clock: Mutex<Clock>, | 102 | pub clock: Mutex<Clock>, |
| 102 | pub video: Mutex<Video>, | 103 | pub video: Mutex<Video>, |
| 103 | - pub stash: Mutex<VecDeque<f32>>, | 104 | + pub stash: Mutex<VecDeque<Stereo>>, |
| 104 | } | 105 | } |
| 105 | 106 | ||
| 106 | impl Shared { | 107 | impl Shared { |
| @@ -133,9 +134,19 @@ pub struct Picture { | |||
| 133 | pub height: u32, | 134 | pub height: u32, |
| 134 | } | 135 | } |
| 135 | 136 | ||
| 137 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 138 | +pub enum Engine { | ||
| 139 | + Hardware, | ||
| 140 | + Software, | ||
| 141 | +} | ||
| 142 | + | ||
| 136 | pub enum VideoDecoder { | 143 | pub enum VideoDecoder { |
| 137 | H264(Box<H264Decoder>), | 144 | H264(Box<H264Decoder>), |
| 138 | Vp8(Box<ec_vp8::decode::Decoder>), | 145 | Vp8(Box<ec_vp8::decode::Decoder>), |
| 146 | + H265(Box<ec_h265::Decoder>), | ||
| 147 | + Vp9(Box<ec_vp9::decode::Decoder>), | ||
| 148 | + #[cfg(target_os = "linux")] | ||
| 149 | + Hardware(Box<ec_hw::Decoder>), | ||
| 139 | } | 150 | } |
| 140 | 151 | ||
| 141 | impl VideoDecoder { | 152 | impl VideoDecoder { |
| @@ -154,7 +165,31 @@ impl VideoDecoder { | |||
| 154 | } | 165 | } |
| 155 | } | 166 | } |
| 156 | 167 | ||
| 168 | + pub fn for_codec(codec: Codec) -> Option<VideoDecoder> { | ||
| 169 | + hardware(codec).or_else(|| software(codec)) | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + pub fn engine(&self) -> Engine { | ||
| 173 | + match self { | ||
| 174 | + #[cfg(target_os = "linux")] | ||
| 175 | + VideoDecoder::Hardware(_) => Engine::Hardware, | ||
| 176 | + _ => Engine::Software, | ||
| 177 | + } | ||
| 178 | + } | ||
| 179 | + | ||
| 180 | + pub fn decode(&mut self, data: &[u8], timestamp_ms: u32) -> Vec<Picture> { | ||
| 181 | + let mut packet = Packet::new(0, TimeBase::MILLIS, data); | ||
| 182 | + packet.pts = Some(i64::from(timestamp_ms)); | ||
| 183 | + self.send(&packet) | ||
| 184 | + .into_iter() | ||
| 185 | + .map(|(_, picture)| picture) | ||
| 186 | + .collect() | ||
| 187 | + } | ||
| 188 | + | ||
| 157 | pub fn send(&mut self, packet: &Packet) -> Vec<(f64, Picture)> { | 189 | pub fn send(&mut self, packet: &Packet) -> Vec<(f64, Picture)> { |
| 190 | + let seconds = packet.pts.map_or(0.0, |ticks| { | ||
| 191 | + Timestamp::new(ticks, packet.time_base).as_secs_f64() | ||
| 192 | + }); | ||
| 158 | match self { | 193 | match self { |
| 159 | VideoDecoder::H264(decoder) => { | 194 | VideoDecoder::H264(decoder) => { |
| 160 | if let Err(error) = decoder.send_packet(packet) { | 195 | if let Err(error) = decoder.send_packet(packet) { |
| @@ -190,6 +225,29 @@ impl VideoDecoder { | |||
| 190 | } | 225 | } |
| 191 | } | 226 | } |
| 192 | } | 227 | } |
| 228 | + VideoDecoder::H265(decoder) => { | ||
| 229 | + if let Err(error) = decoder.decode_annex_b(&packet.data) { | ||
| 230 | + warn!("video packet skipped: {error}"); | ||
| 231 | + return Vec::new(); | ||
| 232 | + } | ||
| 233 | + drain_h265(decoder, seconds) | ||
| 234 | + } | ||
| 235 | + VideoDecoder::Vp9(decoder) => match decoder.decode(&packet.data) { | ||
| 236 | + Ok(Some(picture)) => vec![(seconds, vp9_picture(picture))], | ||
| 237 | + Ok(None) => Vec::new(), | ||
| 238 | + Err(error) => { | ||
| 239 | + warn!("video packet skipped: {error}"); | ||
| 240 | + Vec::new() | ||
| 241 | + } | ||
| 242 | + }, | ||
| 243 | + #[cfg(target_os = "linux")] | ||
| 244 | + VideoDecoder::Hardware(decoder) => { | ||
| 245 | + if let Err(error) = decoder.decode(&packet.data, packet.pts.unwrap_or(0)) { | ||
| 246 | + warn!("video packet skipped: {error}"); | ||
| 247 | + return Vec::new(); | ||
| 248 | + } | ||
| 249 | + hardware_pictures(decoder) | ||
| 250 | + } | ||
| 193 | } | 251 | } |
| 194 | } | 252 | } |
| 195 | 253 | ||
| @@ -199,7 +257,16 @@ impl VideoDecoder { | |||
| 199 | let _ = CodecDecoder::flush(decoder.as_mut()); | 257 | let _ = CodecDecoder::flush(decoder.as_mut()); |
| 200 | drain_h264(decoder) | 258 | drain_h264(decoder) |
| 201 | } | 259 | } |
| 202 | - VideoDecoder::Vp8(_) => Vec::new(), | 260 | + VideoDecoder::H265(decoder) => { |
| 261 | + let _ = decoder.flush(); | ||
| 262 | + drain_h265(decoder, 0.0) | ||
| 263 | + } | ||
| 264 | + VideoDecoder::Vp8(_) | VideoDecoder::Vp9(_) => Vec::new(), | ||
| 265 | + #[cfg(target_os = "linux")] | ||
| 266 | + VideoDecoder::Hardware(decoder) => { | ||
| 267 | + let _ = decoder.flush(); | ||
| 268 | + hardware_pictures(decoder) | ||
| 269 | + } | ||
| 203 | } | 270 | } |
| 204 | } | 271 | } |
| 205 | 272 | ||
| @@ -207,10 +274,107 @@ impl VideoDecoder { | |||
| 207 | match self { | 274 | match self { |
| 208 | VideoDecoder::H264(decoder) => CodecDecoder::reset(decoder.as_mut()), | 275 | VideoDecoder::H264(decoder) => CodecDecoder::reset(decoder.as_mut()), |
| 209 | VideoDecoder::Vp8(decoder) => **decoder = ec_vp8::decode::Decoder::new(), | 276 | VideoDecoder::Vp8(decoder) => **decoder = ec_vp8::decode::Decoder::new(), |
| 277 | + VideoDecoder::H265(decoder) => **decoder = ec_h265::Decoder::new(), | ||
| 278 | + VideoDecoder::Vp9(decoder) => **decoder = ec_vp9::decode::Decoder::new(), | ||
| 279 | + #[cfg(target_os = "linux")] | ||
| 280 | + VideoDecoder::Hardware(decoder) => decoder.reset(), | ||
| 210 | } | 281 | } |
| 211 | } | 282 | } |
| 212 | } | 283 | } |
| 213 | 284 | ||
| 285 | +#[cfg(target_os = "linux")] | ||
| 286 | +fn hardware(codec: Codec) -> Option<VideoDecoder> { | ||
| 287 | + let codec = match codec { | ||
| 288 | + Codec::H264 => ec_hw::Codec::H264, | ||
| 289 | + Codec::H265 => ec_hw::Codec::H265, | ||
| 290 | + Codec::Vp9 => ec_hw::Codec::Vp9, | ||
| 291 | + Codec::Av1 => ec_hw::Codec::Av1, | ||
| 292 | + Codec::Vp8 => return None, | ||
| 293 | + }; | ||
| 294 | + let display = ec_va::open().ok()?; | ||
| 295 | + let decoder = ec_hw::Decoder::new(&display, codec).ok()?; | ||
| 296 | + Some(VideoDecoder::Hardware(Box::new(decoder))) | ||
| 297 | +} | ||
| 298 | + | ||
| 299 | +#[cfg(not(target_os = "linux"))] | ||
| 300 | +fn hardware(_: Codec) -> Option<VideoDecoder> { | ||
| 301 | + None | ||
| 302 | +} | ||
| 303 | + | ||
| 304 | +fn software(codec: Codec) -> Option<VideoDecoder> { | ||
| 305 | + match codec { | ||
| 306 | + Codec::H264 => H264Decoder::new(CodecParameters::new(CodecId::H264)) | ||
| 307 | + .ok() | ||
| 308 | + .map(|decoder| VideoDecoder::H264(Box::new(decoder))), | ||
| 309 | + Codec::Vp8 => Some(VideoDecoder::Vp8(Box::new(ec_vp8::decode::Decoder::new()))), | ||
| 310 | + Codec::H265 => Some(VideoDecoder::H265(Box::new(ec_h265::Decoder::new()))), | ||
| 311 | + Codec::Vp9 => Some(VideoDecoder::Vp9(Box::new(ec_vp9::decode::Decoder::new()))), | ||
| 312 | + Codec::Av1 => None, | ||
| 313 | + } | ||
| 314 | +} | ||
| 315 | + | ||
| 316 | +fn plane(samples: &[u16], shift: u32) -> Vec<u8> { | ||
| 317 | + samples | ||
| 318 | + .iter() | ||
| 319 | + .map(|sample| (sample >> shift) as u8) | ||
| 320 | + .collect() | ||
| 321 | +} | ||
| 322 | + | ||
| 323 | +fn drain_h265(decoder: &mut ec_h265::Decoder, pts: f64) -> Vec<(f64, Picture)> { | ||
| 324 | + std::iter::from_fn(|| decoder.next_frame()) | ||
| 325 | + .map(|frame| (pts, h265_picture(&frame.picture))) | ||
| 326 | + .collect() | ||
| 327 | +} | ||
| 328 | + | ||
| 329 | +fn h265_picture(picture: &ec_h265::decode::DecodedPicture) -> Picture { | ||
| 330 | + let shift = picture.bit_depth.saturating_sub(8); | ||
| 331 | + let (uv_width, _) = picture.chroma_dims(); | ||
| 332 | + Picture { | ||
| 333 | + y: plane(&picture.y, shift), | ||
| 334 | + y_stride: picture.width, | ||
| 335 | + u: plane(&picture.cb, shift), | ||
| 336 | + v: plane(&picture.cr, shift), | ||
| 337 | + uv_stride: uv_width, | ||
| 338 | + width: picture.width as u32, | ||
| 339 | + height: picture.height as u32, | ||
| 340 | + } | ||
| 341 | +} | ||
| 342 | + | ||
| 343 | +fn vp9_picture(picture: ec_vp9::decode::Picture) -> Picture { | ||
| 344 | + let shift = u32::from(picture.bit_depth.saturating_sub(8)); | ||
| 345 | + Picture { | ||
| 346 | + y: plane(&picture.y, shift), | ||
| 347 | + y_stride: picture.stride, | ||
| 348 | + u: plane(&picture.u, shift), | ||
| 349 | + v: plane(&picture.v, shift), | ||
| 350 | + uv_stride: picture.uv_stride, | ||
| 351 | + width: u32::from(picture.width), | ||
| 352 | + height: u32::from(picture.height), | ||
| 353 | + } | ||
| 354 | +} | ||
| 355 | + | ||
| 356 | +#[cfg(target_os = "linux")] | ||
| 357 | +fn hardware_pictures(decoder: &mut ec_hw::Decoder) -> Vec<(f64, Picture)> { | ||
| 358 | + std::iter::from_fn(|| decoder.next_frame()) | ||
| 359 | + .filter_map(|frame| { | ||
| 360 | + let pts = Timestamp::new(frame.timestamp, TimeBase::MILLIS).as_secs_f64(); | ||
| 361 | + let i420 = frame.to_i420().ok()?; | ||
| 362 | + Some(( | ||
| 363 | + pts, | ||
| 364 | + Picture { | ||
| 365 | + y: i420.y, | ||
| 366 | + y_stride: i420.width as usize, | ||
| 367 | + u: i420.u, | ||
| 368 | + v: i420.v, | ||
| 369 | + uv_stride: i420.width.div_ceil(2) as usize, | ||
| 370 | + width: i420.width, | ||
| 371 | + height: i420.height, | ||
| 372 | + }, | ||
| 373 | + )) | ||
| 374 | + }) | ||
| 375 | + .collect() | ||
| 376 | +} | ||
| 377 | + | ||
| 214 | enum Queued { | 378 | enum Queued { |
| 215 | Packet(Packet), | 379 | Packet(Packet), |
| 216 | Flush, | 380 | Flush, |
| @@ -227,7 +391,7 @@ pub struct Worker { | |||
| 227 | backlog: VecDeque<Queued>, | 391 | backlog: VecDeque<Queued>, |
| 228 | audio_index: Option<u32>, | 392 | audio_index: Option<u32>, |
| 229 | audio: Option<AudioDecoder>, | 393 | audio: Option<AudioDecoder>, |
| 230 | - pending: VecDeque<f32>, | 394 | + pending: VecDeque<Stereo>, |
| 231 | resampler: Resampler, | 395 | resampler: Resampler, |
| 232 | align: Option<f64>, | 396 | align: Option<f64>, |
| 233 | skip: usize, | 397 | skip: usize, |
| @@ -301,7 +465,7 @@ impl Worker { | |||
| 301 | } | 465 | } |
| 302 | 466 | ||
| 303 | fn buffered(&self) -> bool { | 467 | fn buffered(&self) -> bool { |
| 304 | - self.pending.len() >= RING_SAMPLES | 468 | + self.pending.len() >= RING_FRAMES |
| 305 | } | 469 | } |
| 306 | 470 | ||
| 307 | fn fill(&mut self) { | 471 | fn fill(&mut self) { |
| @@ -338,14 +502,16 @@ impl Worker { | |||
| 338 | return; | 502 | return; |
| 339 | } | 503 | } |
| 340 | let mut stash = lock(&self.shared.stash); | 504 | let mut stash = lock(&self.shared.stash); |
| 341 | - while let Some(sample) = stash.pop_back() { | 505 | + while let Some(frame) = stash.pop_back() { |
| 342 | - self.pending.push_front(sample); | 506 | + self.pending.push_front(frame); |
| 343 | } | 507 | } |
| 344 | drop(stash); | 508 | drop(stash); |
| 345 | - while let Some(&sample) = self.pending.front() { | 509 | + while let Some(&[left, right]) = self.pending.front() { |
| 346 | - if producer.push(sample).is_err() { | 510 | + if producer.slots() < PLAYBACK_CHANNELS { |
| 347 | break; | 511 | break; |
| 348 | } | 512 | } |
| 513 | + let _ = producer.push(left); | ||
| 514 | + let _ = producer.push(right); | ||
| 349 | self.pending.pop_front(); | 515 | self.pending.pop_front(); |
| 350 | clock.written += 1; | 516 | clock.written += 1; |
| 351 | } | 517 | } |
| @@ -432,8 +598,8 @@ impl Worker { | |||
| 432 | if rate == 0 { | 598 | if rate == 0 { |
| 433 | return; | 599 | return; |
| 434 | } | 600 | } |
| 435 | - let mono = resample::downmix(interleaved, channels); | 601 | + let frames = resample::stereo(interleaved, channels); |
| 436 | - let mut out = self.resampler.process(&mono, rate); | 602 | + let mut out = self.resampler.process(&frames, rate); |
| 437 | if let Some(target) = self.align.filter(|_| !out.is_empty()) { | 603 | if let Some(target) = self.align.filter(|_| !out.is_empty()) { |
| 438 | self.align = None; | 604 | self.align = None; |
| 439 | self.align_to(&mut out, target, pts.unwrap_or(target)); | 605 | self.align_to(&mut out, target, pts.unwrap_or(target)); |
| @@ -444,13 +610,13 @@ impl Worker { | |||
| 444 | self.pending.extend(out); | 610 | self.pending.extend(out); |
| 445 | } | 611 | } |
| 446 | 612 | ||
| 447 | - fn align_to(&mut self, out: &mut Vec<f32>, target: f64, pts: f64) { | 613 | + fn align_to(&mut self, out: &mut Vec<Stereo>, target: f64, pts: f64) { |
| 448 | let shift = ((target - pts) * f64::from(VOICE_SAMPLE_RATE)).round() as i64; | 614 | let shift = ((target - pts) * f64::from(VOICE_SAMPLE_RATE)).round() as i64; |
| 449 | if shift > 0 { | 615 | if shift > 0 { |
| 450 | self.skip = shift as usize; | 616 | self.skip = shift as usize; |
| 451 | } else if shift < 0 { | 617 | } else if shift < 0 { |
| 452 | let pad = ((-shift) as usize).min(MAX_PAD); | 618 | let pad = ((-shift) as usize).min(MAX_PAD); |
| 453 | - out.splice(0..0, std::iter::repeat_n(0.0, pad)); | 619 | + out.splice(0..0, std::iter::repeat_n([0.0; 2], pad)); |
| 454 | } | 620 | } |
| 455 | } | 621 | } |
| 456 | 622 | ||
| @@ -519,7 +685,7 @@ impl Worker { | |||
| 519 | pub fn position(shared: &Shared, playback: &Playback) -> f64 { | 685 | pub fn position(shared: &Shared, playback: &Playback) -> f64 { |
| 520 | let clock = lock(&shared.clock); | 686 | let clock = lock(&shared.clock); |
| 521 | let queued = if clock.audio { | 687 | let queued = if clock.audio { |
| 522 | - lock(playback).slots() | 688 | + lock(playback).slots() / PLAYBACK_CHANNELS |
| 523 | } else { | 689 | } else { |
| 524 | 0 | 690 | 0 |
| 525 | }; | 691 | }; |
| @@ -535,6 +701,7 @@ fn show(shared: &Shared, pts: f64, picture: Picture) { | |||
| 535 | picture.uv_stride, | 701 | picture.uv_stride, |
| 536 | picture.width, | 702 | picture.width, |
| 537 | picture.height, | 703 | picture.height, |
| 704 | + convert::ATTACHMENT_WIDTH, | ||
| 538 | ) else { | 705 | ) else { |
| 539 | return; | 706 | return; |
| 540 | }; | 707 | }; |
crates/client/src/media/mod.rsmodified+24 -16
| @@ -1,5 +1,5 @@ | |||
| 1 | -mod convert; | 1 | +pub mod convert; |
| 2 | -mod decode; | 2 | +pub mod decode; |
| 3 | mod resample; | 3 | mod resample; |
| 4 | pub mod voice_note; | 4 | pub mod voice_note; |
| 5 | 5 | ||
| @@ -172,27 +172,35 @@ pub struct Player { | |||
| 172 | 172 | ||
| 173 | impl Player { | 173 | impl Player { |
| 174 | pub fn open(path: &Path, choice: Choice) -> Result<Player, MediaError> { | 174 | pub fn open(path: &Path, choice: Choice) -> Result<Player, MediaError> { |
| 175 | - let (reader, tracks, info) = open_tracks(path)?; | 175 | + let info = probe(path)?; |
| 176 | let (producer, consumer) = RingBuffer::new(RING_SAMPLES); | 176 | let (producer, consumer) = RingBuffer::new(RING_SAMPLES); |
| 177 | let playback: Playback = Arc::new(Mutex::new(consumer)); | 177 | let playback: Playback = Arc::new(Mutex::new(consumer)); |
| 178 | - let audio = if tracks.audio.is_some() { | 178 | + let audio = if info.audio { |
| 179 | audio::start(None, playback.clone(), choice) | 179 | audio::start(None, playback.clone(), choice) |
| 180 | } else { | 180 | } else { |
| 181 | Audio::Silent | 181 | Audio::Silent |
| 182 | }; | 182 | }; |
| 183 | - let audio_on = tracks.audio.is_some() && !matches!(audio, Audio::Silent); | 183 | + let audio_on = info.audio && !matches!(audio, Audio::Silent); |
| 184 | let shared = Arc::new(Shared::new(audio_on)); | 184 | let shared = Arc::new(Shared::new(audio_on)); |
| 185 | - let worker = Worker::new( | 185 | + let worker_shared = shared.clone(); |
| 186 | - shared.clone(), | 186 | + let worker_path = path.to_path_buf(); |
| 187 | - path.to_path_buf(), | 187 | + let worker_playback = playback.clone(); |
| 188 | - reader, | ||
| 189 | - playback.clone(), | ||
| 190 | - audio_on.then_some(producer), | ||
| 191 | - tracks, | ||
| 192 | - ); | ||
| 193 | let handle = std::thread::Builder::new() | 188 | let handle = std::thread::Builder::new() |
| 194 | .name("media-decode".to_string()) | 189 | .name("media-decode".to_string()) |
| 195 | - .spawn(move || worker.run())?; | 190 | + .spawn(move || { |
| 191 | + let Ok((reader, tracks, _)) = open_tracks(&worker_path) else { | ||
| 192 | + return; | ||
| 193 | + }; | ||
| 194 | + Worker::new( | ||
| 195 | + worker_shared, | ||
| 196 | + worker_path, | ||
| 197 | + reader, | ||
| 198 | + worker_playback, | ||
| 199 | + audio_on.then_some(producer), | ||
| 200 | + tracks, | ||
| 201 | + ) | ||
| 202 | + .run() | ||
| 203 | + })?; | ||
| 196 | Ok(Player { | 204 | Ok(Player { |
| 197 | info, | 205 | info, |
| 198 | shared, | 206 | shared, |
| @@ -220,8 +228,8 @@ impl Player { | |||
| 220 | if clock.audio { | 228 | if clock.audio { |
| 221 | let mut playback = lock(&self.playback); | 229 | let mut playback = lock(&self.playback); |
| 222 | let mut stash = lock(&self.shared.stash); | 230 | let mut stash = lock(&self.shared.stash); |
| 223 | - while let Ok(sample) = playback.pop() { | 231 | + while let (Ok(left), Ok(right)) = (playback.pop(), playback.pop()) { |
| 224 | - stash.push_back(sample); | 232 | + stash.push_back([left, right]); |
| 225 | clock.written = clock.written.saturating_sub(1); | 233 | clock.written = clock.written.saturating_sub(1); |
| 226 | } | 234 | } |
| 227 | } | 235 | } |
crates/client/src/media/resample.rsmodified+19 -4
| @@ -1,5 +1,18 @@ | |||
| 1 | use common::constant::VOICE_SAMPLE_RATE; | 1 | use common::constant::VOICE_SAMPLE_RATE; |
| 2 | 2 | ||
| 3 | +pub type Stereo = [f32; 2]; | ||
| 4 | + | ||
| 5 | +pub fn stereo(interleaved: &[f32], channels: usize) -> Vec<Stereo> { | ||
| 6 | + interleaved | ||
| 7 | + .chunks(channels.max(1)) | ||
| 8 | + .map(|frame| match frame { | ||
| 9 | + [mono] => [*mono; 2], | ||
| 10 | + [left, right] => [*left, *right], | ||
| 11 | + _ => [frame.iter().sum::<f32>() / frame.len() as f32; 2], | ||
| 12 | + }) | ||
| 13 | + .collect() | ||
| 14 | +} | ||
| 15 | + | ||
| 3 | pub fn downmix(interleaved: &[f32], channels: usize) -> Vec<f32> { | 16 | pub fn downmix(interleaved: &[f32], channels: usize) -> Vec<f32> { |
| 4 | interleaved | 17 | interleaved |
| 5 | .chunks(channels.max(1)) | 18 | .chunks(channels.max(1)) |
| @@ -9,12 +22,12 @@ pub fn downmix(interleaved: &[f32], channels: usize) -> Vec<f32> { | |||
| 9 | 22 | ||
| 10 | #[derive(Debug, Default)] | 23 | #[derive(Debug, Default)] |
| 11 | pub struct Resampler { | 24 | pub struct Resampler { |
| 12 | - last: f32, | 25 | + last: Stereo, |
| 13 | position: f64, | 26 | position: f64, |
| 14 | } | 27 | } |
| 15 | 28 | ||
| 16 | impl Resampler { | 29 | impl Resampler { |
| 17 | - pub fn process(&mut self, input: &[f32], rate: u32) -> Vec<f32> { | 30 | + pub fn process(&mut self, input: &[Stereo], rate: u32) -> Vec<Stereo> { |
| 18 | let step = f64::from(rate) / f64::from(VOICE_SAMPLE_RATE); | 31 | let step = f64::from(rate) / f64::from(VOICE_SAMPLE_RATE); |
| 19 | let count = input.len() as f64; | 32 | let count = input.len() as f64; |
| 20 | let mut out = Vec::new(); | 33 | let mut out = Vec::new(); |
| @@ -24,7 +37,9 @@ impl Resampler { | |||
| 24 | let fraction = (position - index as f64) as f32; | 37 | let fraction = (position - index as f64) as f32; |
| 25 | let before = at(self.last, input, index); | 38 | let before = at(self.last, input, index); |
| 26 | let after = at(self.last, input, index + 1); | 39 | let after = at(self.last, input, index + 1); |
| 27 | - out.push(before + (after - before) * fraction); | 40 | + out.push(std::array::from_fn(|channel| { |
| 41 | + before[channel] + (after[channel] - before[channel]) * fraction | ||
| 42 | + })); | ||
| 28 | position += step; | 43 | position += step; |
| 29 | } | 44 | } |
| 30 | self.position = position - count; | 45 | self.position = position - count; |
| @@ -35,6 +50,6 @@ impl Resampler { | |||
| 35 | } | 50 | } |
| 36 | } | 51 | } |
| 37 | 52 | ||
| 38 | -fn at(last: f32, input: &[f32], index: usize) -> f32 { | 53 | +fn at(last: Stereo, input: &[Stereo], index: usize) -> Stereo { |
| 39 | if index == 0 { last } else { input[index - 1] } | 54 | if index == 0 { last } else { input[index - 1] } |
| 40 | } | 55 | } |
crates/client/src/network.rsmodified+244 -4
| @@ -1,4 +1,5 @@ | |||
| 1 | use std::{ | 1 | use std::{ |
| 2 | + collections::HashMap, | ||
| 2 | path::{Path, PathBuf}, | 3 | path::{Path, PathBuf}, |
| 3 | sync::{Arc, Mutex}, | 4 | sync::{Arc, Mutex}, |
| 4 | time::Duration, | 5 | time::Duration, |
| @@ -9,6 +10,7 @@ use common::{ | |||
| 9 | ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES, MAXIMUM_AVATAR_BYTES, | 10 | ATTACHMENT_CHUNK_BYTES, MAXIMUM_ATTACHMENT_LIMIT_BYTES, MAXIMUM_AVATAR_BYTES, |
| 10 | MAXIMUM_MESSAGE_LENGTH, | 11 | MAXIMUM_MESSAGE_LENGTH, |
| 11 | }, | 12 | }, |
| 13 | + datagram::decode_relay, | ||
| 12 | error::Error, | 14 | error::Error, |
| 13 | event::Event, | 15 | event::Event, |
| 14 | model::{ | 16 | model::{ |
| @@ -45,7 +47,12 @@ use tracing::{info, warn}; | |||
| 45 | 47 | ||
| 46 | use crate::{ | 48 | use crate::{ |
| 47 | ClientConfig, | 49 | ClientConfig, |
| 48 | - settings::VoiceSettings, | 50 | + settings::{SHARE_QUALITY, ShareSettings, VoiceSettings}, |
| 51 | + share::{ | ||
| 52 | + audio_capture::{self, AudioApp}, | ||
| 53 | + encode::capabilities, | ||
| 54 | + session::{ShareSample, Sharing, Tick, WatchQuality, Watching}, | ||
| 55 | + }, | ||
| 49 | voice::{self, Voice, VoiceSample}, | 56 | voice::{self, Voice, VoiceSample}, |
| 50 | }; | 57 | }; |
| 51 | 58 | ||
| @@ -67,8 +74,65 @@ const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(3); | |||
| 67 | const CHANNEL_SIZE: usize = 32; | 74 | const CHANNEL_SIZE: usize = 32; |
| 68 | const RECONNECT_DELAY: Duration = Duration::from_secs(1); | 75 | const RECONNECT_DELAY: Duration = Duration::from_secs(1); |
| 69 | 76 | ||
| 77 | +const SHARE_TICK: Duration = Duration::from_secs(1); | ||
| 78 | + | ||
| 70 | type SharedVoice = Arc<Mutex<Option<Voice>>>; | 79 | type SharedVoice = Arc<Mutex<Option<Voice>>>; |
| 71 | type SharedSettings = Arc<Mutex<VoiceSettings>>; | 80 | type SharedSettings = Arc<Mutex<VoiceSettings>>; |
| 81 | +type SharedShare = Arc<Mutex<Share>>; | ||
| 82 | +type SharedShareSettings = Arc<Mutex<ShareSettings>>; | ||
| 83 | + | ||
| 84 | +#[derive(Default)] | ||
| 85 | +struct Share { | ||
| 86 | + sharing: Option<Sharing>, | ||
| 87 | + watching: HashMap<String, Watching>, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +impl Share { | ||
| 91 | + fn clear(shared: &SharedShare) { | ||
| 92 | + *shared.lock().unwrap() = Share::default(); | ||
| 93 | + } | ||
| 94 | + | ||
| 95 | + fn event(&mut self, event: &Event) { | ||
| 96 | + match event { | ||
| 97 | + Event::ShareLayers(layers) => { | ||
| 98 | + if let Some(sharing) = self.sharing.as_mut() { | ||
| 99 | + sharing.set_layers(layers); | ||
| 100 | + } | ||
| 101 | + } | ||
| 102 | + Event::KeyframeWanted(layer) => { | ||
| 103 | + if let Some(sharing) = self.sharing.as_ref() { | ||
| 104 | + sharing.keyframe(*layer); | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | + Event::ShareStopped { user_id, .. } => { | ||
| 108 | + self.watching.remove(user_id); | ||
| 109 | + } | ||
| 110 | + _ => {} | ||
| 111 | + } | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + fn ticks(&mut self) -> Vec<Request> { | ||
| 115 | + self.watching | ||
| 116 | + .iter_mut() | ||
| 117 | + .flat_map(|(user_id, watching)| { | ||
| 118 | + watching | ||
| 119 | + .tick() | ||
| 120 | + .into_iter() | ||
| 121 | + .map(move |tick| match tick { | ||
| 122 | + Tick::Quality(quality) => Request::WatchShare { | ||
| 123 | + user_id: user_id.clone(), | ||
| 124 | + quality, | ||
| 125 | + decode: capabilities().decode.clone(), | ||
| 126 | + }, | ||
| 127 | + Tick::Keyframe => Request::RequestKeyframe { | ||
| 128 | + user_id: user_id.clone(), | ||
| 129 | + }, | ||
| 130 | + }) | ||
| 131 | + .collect::<Vec<_>>() | ||
| 132 | + }) | ||
| 133 | + .collect() | ||
| 134 | + } | ||
| 135 | +} | ||
| 72 | 136 | ||
| 73 | #[derive(Debug)] | 137 | #[derive(Debug)] |
| 74 | pub enum NetworkEvent { | 138 | pub enum NetworkEvent { |
| @@ -100,6 +164,10 @@ enum Command { | |||
| 100 | path: PathBuf, | 164 | path: PathBuf, |
| 101 | reply: oneshot::Sender<Result<(), Error>>, | 165 | reply: oneshot::Sender<Result<(), Error>>, |
| 102 | }, | 166 | }, |
| 167 | + StartShare { | ||
| 168 | + settings: ShareSettings, | ||
| 169 | + reply: oneshot::Sender<Result<(), Error>>, | ||
| 170 | + }, | ||
| 103 | } | 171 | } |
| 104 | 172 | ||
| 105 | #[derive(Clone)] | 173 | #[derive(Clone)] |
| @@ -108,6 +176,8 @@ pub struct NetworkHandle { | |||
| 108 | voice: SharedVoice, | 176 | voice: SharedVoice, |
| 109 | mic_test: SharedVoice, | 177 | mic_test: SharedVoice, |
| 110 | voice_settings: SharedSettings, | 178 | voice_settings: SharedSettings, |
| 179 | + share: SharedShare, | ||
| 180 | + share_settings: SharedShareSettings, | ||
| 111 | } | 181 | } |
| 112 | 182 | ||
| 113 | impl NetworkHandle { | 183 | impl NetworkHandle { |
| @@ -1294,6 +1364,101 @@ impl NetworkHandle { | |||
| 1294 | pub fn speaking(&self) -> Vec<String> { | 1364 | pub fn speaking(&self) -> Vec<String> { |
| 1295 | self.with_voice(Voice::speaking).unwrap_or_default() | 1365 | self.with_voice(Voice::speaking).unwrap_or_default() |
| 1296 | } | 1366 | } |
| 1367 | + | ||
| 1368 | + pub async fn start_share(&self) -> Result<(), Error> { | ||
| 1369 | + let settings = self.share_settings.lock().unwrap().clone(); | ||
| 1370 | + self.ask(|reply| Command::StartShare { settings, reply }) | ||
| 1371 | + .await | ||
| 1372 | + } | ||
| 1373 | + | ||
| 1374 | + pub async fn stop_share(&self) -> Result<(), Error> { | ||
| 1375 | + let result = self.done(Request::StopShare).await; | ||
| 1376 | + self.share.lock().unwrap().sharing.take(); | ||
| 1377 | + result | ||
| 1378 | + } | ||
| 1379 | + | ||
| 1380 | + pub fn sharing(&self) -> bool { | ||
| 1381 | + self.share.lock().unwrap().sharing.is_some() | ||
| 1382 | + } | ||
| 1383 | + | ||
| 1384 | + pub async fn shares(&self, community_id: &str) -> Result<Vec<common::share::Share>, Error> { | ||
| 1385 | + match self | ||
| 1386 | + .request(Request::Shares { | ||
| 1387 | + community_id: community_id.to_string(), | ||
| 1388 | + }) | ||
| 1389 | + .await? | ||
| 1390 | + { | ||
| 1391 | + Response::Shares(shares) => Ok(shares), | ||
| 1392 | + _ => Err(Error::Server), | ||
| 1393 | + } | ||
| 1394 | + } | ||
| 1395 | + | ||
| 1396 | + pub async fn watch_share(&self, user_id: &str) -> Result<(), Error> { | ||
| 1397 | + let settings = self.share_settings.lock().unwrap().clone(); | ||
| 1398 | + let quality = match settings.watch { | ||
| 1399 | + WatchQuality::Fixed(quality) => quality, | ||
| 1400 | + WatchQuality::Auto => SHARE_QUALITY, | ||
| 1401 | + }; | ||
| 1402 | + let choice = self.voice_settings.lock().unwrap().choice.clone(); | ||
| 1403 | + let watching = Watching::new(settings.watch, settings.volume, choice); | ||
| 1404 | + self.share | ||
| 1405 | + .lock() | ||
| 1406 | + .unwrap() | ||
| 1407 | + .watching | ||
| 1408 | + .insert(user_id.to_string(), watching); | ||
| 1409 | + | ||
| 1410 | + let result = self | ||
| 1411 | + .done(Request::WatchShare { | ||
| 1412 | + user_id: user_id.to_string(), | ||
| 1413 | + quality, | ||
| 1414 | + decode: capabilities().decode.clone(), | ||
| 1415 | + }) | ||
| 1416 | + .await; | ||
| 1417 | + if result.is_err() { | ||
| 1418 | + self.share.lock().unwrap().watching.remove(user_id); | ||
| 1419 | + } | ||
| 1420 | + result | ||
| 1421 | + } | ||
| 1422 | + | ||
| 1423 | + pub async fn unwatch_share(&self, user_id: &str) -> Result<(), Error> { | ||
| 1424 | + self.share.lock().unwrap().watching.remove(user_id); | ||
| 1425 | + self.done(Request::UnwatchShare { | ||
| 1426 | + user_id: user_id.to_string(), | ||
| 1427 | + }) | ||
| 1428 | + .await | ||
| 1429 | + } | ||
| 1430 | + | ||
| 1431 | + pub fn share_sample(&self) -> ShareSample { | ||
| 1432 | + let mut share = self.share.lock().unwrap(); | ||
| 1433 | + ShareSample { | ||
| 1434 | + sending: share | ||
| 1435 | + .sharing | ||
| 1436 | + .as_ref() | ||
| 1437 | + .map(Sharing::stats) | ||
| 1438 | + .unwrap_or_default(), | ||
| 1439 | + watching: share | ||
| 1440 | + .watching | ||
| 1441 | + .iter_mut() | ||
| 1442 | + .map(|(user_id, watching)| (user_id.clone(), watching.stats())) | ||
| 1443 | + .collect(), | ||
| 1444 | + } | ||
| 1445 | + } | ||
| 1446 | + | ||
| 1447 | + pub fn share_frame(&self, user_id: &str) -> Option<crate::media::Frame> { | ||
| 1448 | + self.share.lock().unwrap().watching.get(user_id)?.frame() | ||
| 1449 | + } | ||
| 1450 | + | ||
| 1451 | + pub fn set_share_settings(&self, settings: ShareSettings) { | ||
| 1452 | + *self.share_settings.lock().unwrap() = settings.clone(); | ||
| 1453 | + for watching in self.share.lock().unwrap().watching.values_mut() { | ||
| 1454 | + watching.set_volume(settings.volume); | ||
| 1455 | + watching.set_quality(settings.watch); | ||
| 1456 | + } | ||
| 1457 | + } | ||
| 1458 | + | ||
| 1459 | + pub fn audio_apps(&self) -> Vec<AudioApp> { | ||
| 1460 | + audio_capture::apps() | ||
| 1461 | + } | ||
| 1297 | } | 1462 | } |
| 1298 | 1463 | ||
| 1299 | pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) { | 1464 | pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<NetworkEvent>) { |
| @@ -1302,6 +1467,8 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw | |||
| 1302 | let voice: SharedVoice = Arc::new(Mutex::new(None)); | 1467 | let voice: SharedVoice = Arc::new(Mutex::new(None)); |
| 1303 | let mic_test: SharedVoice = Arc::new(Mutex::new(None)); | 1468 | let mic_test: SharedVoice = Arc::new(Mutex::new(None)); |
| 1304 | let voice_settings: SharedSettings = Arc::new(Mutex::new(VoiceSettings::default())); | 1469 | let voice_settings: SharedSettings = Arc::new(Mutex::new(VoiceSettings::default())); |
| 1470 | + let share: SharedShare = Arc::new(Mutex::new(Share::default())); | ||
| 1471 | + let share_settings: SharedShareSettings = Arc::new(Mutex::new(ShareSettings::default())); | ||
| 1305 | 1472 | ||
| 1306 | std::thread::Builder::new() | 1473 | std::thread::Builder::new() |
| 1307 | .name("network".to_string()) | 1474 | .name("network".to_string()) |
| @@ -1309,6 +1476,7 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw | |||
| 1309 | let voice = voice.clone(); | 1476 | let voice = voice.clone(); |
| 1310 | let mic_test = mic_test.clone(); | 1477 | let mic_test = mic_test.clone(); |
| 1311 | let voice_settings = voice_settings.clone(); | 1478 | let voice_settings = voice_settings.clone(); |
| 1479 | + let share = share.clone(); | ||
| 1312 | move || { | 1480 | move || { |
| 1313 | tokio::runtime::Builder::new_current_thread() | 1481 | tokio::runtime::Builder::new_current_thread() |
| 1314 | .enable_all() | 1482 | .enable_all() |
| @@ -1321,6 +1489,7 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw | |||
| 1321 | voice, | 1489 | voice, |
| 1322 | mic_test, | 1490 | mic_test, |
| 1323 | voice_settings, | 1491 | voice_settings, |
| 1492 | + share, | ||
| 1324 | )); | 1493 | )); |
| 1325 | } | 1494 | } |
| 1326 | }) | 1495 | }) |
| @@ -1332,6 +1501,8 @@ pub fn start(client_config: ClientConfig) -> (NetworkHandle, mpsc::Receiver<Netw | |||
| 1332 | voice, | 1501 | voice, |
| 1333 | mic_test, | 1502 | mic_test, |
| 1334 | voice_settings, | 1503 | voice_settings, |
| 1504 | + share, | ||
| 1505 | + share_settings, | ||
| 1335 | }, | 1506 | }, |
| 1336 | event_receiver, | 1507 | event_receiver, |
| 1337 | ) | 1508 | ) |
| @@ -1566,6 +1737,7 @@ async fn actor( | |||
| 1566 | voice: SharedVoice, | 1737 | voice: SharedVoice, |
| 1567 | mic_test: SharedVoice, | 1738 | mic_test: SharedVoice, |
| 1568 | voice_settings: SharedSettings, | 1739 | voice_settings: SharedSettings, |
| 1740 | + share: SharedShare, | ||
| 1569 | ) { | 1741 | ) { |
| 1570 | let mut token: Option<String> = None; | 1742 | let mut token: Option<String> = None; |
| 1571 | let mut token_epoch = 0; | 1743 | let mut token_epoch = 0; |
| @@ -1610,8 +1782,17 @@ async fn actor( | |||
| 1610 | return; | 1782 | return; |
| 1611 | } | 1783 | } |
| 1612 | 1784 | ||
| 1613 | - tokio::spawn(event_receive_loop(connection.clone(), event_sender.clone())); | 1785 | + tokio::spawn(event_receive_loop( |
| 1614 | - tokio::spawn(datagram_receive_loop(connection.clone(), voice.clone())); | 1786 | + connection.clone(), |
| 1787 | + event_sender.clone(), | ||
| 1788 | + share.clone(), | ||
| 1789 | + )); | ||
| 1790 | + tokio::spawn(datagram_receive_loop( | ||
| 1791 | + connection.clone(), | ||
| 1792 | + voice.clone(), | ||
| 1793 | + share.clone(), | ||
| 1794 | + )); | ||
| 1795 | + let mut ticker = tokio::time::interval(SHARE_TICK); | ||
| 1615 | 1796 | ||
| 1616 | loop { | 1797 | loop { |
| 1617 | tokio::select! { | 1798 | tokio::select! { |
| @@ -1619,6 +1800,7 @@ async fn actor( | |||
| 1619 | Some(Command::Request { request, reply }) => match &request { | 1800 | Some(Command::Request { request, reply }) => match &request { |
| 1620 | Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { | 1801 | Request::Register { .. } | Request::Login { .. } | Request::Resume { .. } => { |
| 1621 | voice.lock().unwrap().take(); | 1802 | voice.lock().unwrap().take(); |
| 1803 | + Share::clear(&share); | ||
| 1622 | let token_sender = token_sender.clone(); | 1804 | let token_sender = token_sender.clone(); |
| 1623 | let epoch = token_epoch; | 1805 | let epoch = token_epoch; |
| 1624 | let connection = connection.clone(); | 1806 | let connection = connection.clone(); |
| @@ -1636,6 +1818,7 @@ async fn actor( | |||
| 1636 | token = None; | 1818 | token = None; |
| 1637 | token_epoch += 1; | 1819 | token_epoch += 1; |
| 1638 | voice.lock().unwrap().take(); | 1820 | voice.lock().unwrap().take(); |
| 1821 | + Share::clear(&share); | ||
| 1639 | 1822 | ||
| 1640 | tokio::spawn(dispatch(connection.clone(), request, reply)); | 1823 | tokio::spawn(dispatch(connection.clone(), request, reply)); |
| 1641 | } | 1824 | } |
| @@ -1658,6 +1841,7 @@ async fn actor( | |||
| 1658 | } | 1841 | } |
| 1659 | Request::LeaveVoice => { | 1842 | Request::LeaveVoice => { |
| 1660 | voice.lock().unwrap().take(); | 1843 | voice.lock().unwrap().take(); |
| 1844 | + Share::clear(&share); | ||
| 1661 | 1845 | ||
| 1662 | tokio::spawn(dispatch(connection.clone(), request, reply)); | 1846 | tokio::spawn(dispatch(connection.clone(), request, reply)); |
| 1663 | } | 1847 | } |
| @@ -1665,6 +1849,14 @@ async fn actor( | |||
| 1665 | tokio::spawn(dispatch(connection.clone(), request, reply)); | 1849 | tokio::spawn(dispatch(connection.clone(), request, reply)); |
| 1666 | } | 1850 | } |
| 1667 | }, | 1851 | }, |
| 1852 | + Some(Command::StartShare { settings, reply }) => { | ||
| 1853 | + let connection = connection.clone(); | ||
| 1854 | + let share = share.clone(); | ||
| 1855 | + | ||
| 1856 | + tokio::spawn(async move { | ||
| 1857 | + let _ = reply.send(start_share(&connection, &share, &settings).await); | ||
| 1858 | + }); | ||
| 1859 | + } | ||
| 1668 | Some(Command::Upload { community_id, path, maximum, reply }) => { | 1860 | Some(Command::Upload { community_id, path, maximum, reply }) => { |
| 1669 | let connection = connection.clone(); | 1861 | let connection = connection.clone(); |
| 1670 | 1862 | ||
| @@ -1694,9 +1886,20 @@ async fn actor( | |||
| 1694 | } | 1886 | } |
| 1695 | } | 1887 | } |
| 1696 | 1888 | ||
| 1889 | + _ = ticker.tick() => { | ||
| 1890 | + let requests = share.lock().unwrap().ticks(); | ||
| 1891 | + for request in requests { | ||
| 1892 | + let connection = connection.clone(); | ||
| 1893 | + tokio::spawn(async move { | ||
| 1894 | + let _ = send(&connection, &request).await; | ||
| 1895 | + }); | ||
| 1896 | + } | ||
| 1897 | + } | ||
| 1898 | + | ||
| 1697 | error = connection.closed() => { | 1899 | error = connection.closed() => { |
| 1698 | warn!("disconnected: {error}"); | 1900 | warn!("disconnected: {error}"); |
| 1699 | voice.lock().unwrap().take(); | 1901 | voice.lock().unwrap().take(); |
| 1902 | + Share::clear(&share); | ||
| 1700 | 1903 | ||
| 1701 | if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { | 1904 | if event_sender.send(NetworkEvent::Disconnected(error.into())).await.is_err() { |
| 1702 | return; | 1905 | return; |
| @@ -1709,15 +1912,43 @@ async fn actor( | |||
| 1709 | } | 1912 | } |
| 1710 | } | 1913 | } |
| 1711 | 1914 | ||
| 1915 | +async fn start_share( | ||
| 1916 | + connection: &quinn::Connection, | ||
| 1917 | + share: &SharedShare, | ||
| 1918 | + settings: &ShareSettings, | ||
| 1919 | +) -> Result<(), Error> { | ||
| 1920 | + let (sharing, source) = Sharing::start( | ||
| 1921 | + connection.clone(), | ||
| 1922 | + settings.top, | ||
| 1923 | + settings.encode(), | ||
| 1924 | + settings.audio_mode(), | ||
| 1925 | + ) | ||
| 1926 | + .await | ||
| 1927 | + .map_err(Error::Network)?; | ||
| 1928 | + share.lock().unwrap().sharing = Some(sharing); | ||
| 1929 | + | ||
| 1930 | + let result = match send(connection, &Request::StartShare { source }).await { | ||
| 1931 | + Ok(Response::Done) => Ok(()), | ||
| 1932 | + Ok(_) => Err(Error::Server), | ||
| 1933 | + Err(error) => Err(error), | ||
| 1934 | + }; | ||
| 1935 | + if result.is_err() { | ||
| 1936 | + share.lock().unwrap().sharing.take(); | ||
| 1937 | + } | ||
| 1938 | + result | ||
| 1939 | +} | ||
| 1940 | + | ||
| 1712 | async fn event_receive_loop( | 1941 | async fn event_receive_loop( |
| 1713 | connection: quinn::Connection, | 1942 | connection: quinn::Connection, |
| 1714 | event_sender: mpsc::Sender<NetworkEvent>, | 1943 | event_sender: mpsc::Sender<NetworkEvent>, |
| 1944 | + share: SharedShare, | ||
| 1715 | ) { | 1945 | ) { |
| 1716 | let Ok(mut receive_stream) = connection.accept_uni().await else { | 1946 | let Ok(mut receive_stream) = connection.accept_uni().await else { |
| 1717 | return; | 1947 | return; |
| 1718 | }; | 1948 | }; |
| 1719 | 1949 | ||
| 1720 | while let Ok(event) = receive_event(&mut receive_stream).await { | 1950 | while let Ok(event) = receive_event(&mut receive_stream).await { |
| 1951 | + share.lock().unwrap().event(&event); | ||
| 1721 | if event_sender | 1952 | if event_sender |
| 1722 | .send(NetworkEvent::Pushed(Box::new(event))) | 1953 | .send(NetworkEvent::Pushed(Box::new(event))) |
| 1723 | .await | 1954 | .await |
| @@ -1728,10 +1959,19 @@ async fn event_receive_loop( | |||
| 1728 | } | 1959 | } |
| 1729 | } | 1960 | } |
| 1730 | 1961 | ||
| 1731 | -async fn datagram_receive_loop(connection: quinn::Connection, voice: SharedVoice) { | 1962 | +async fn datagram_receive_loop( |
| 1963 | + connection: quinn::Connection, | ||
| 1964 | + voice: SharedVoice, | ||
| 1965 | + share: SharedShare, | ||
| 1966 | +) { | ||
| 1732 | while let Ok(datagram) = connection.read_datagram().await { | 1967 | while let Ok(datagram) = connection.read_datagram().await { |
| 1733 | if let Some(voice) = voice.lock().unwrap().as_ref() { | 1968 | if let Some(voice) = voice.lock().unwrap().as_ref() { |
| 1734 | voice.receive(&datagram); | 1969 | voice.receive(&datagram); |
| 1735 | } | 1970 | } |
| 1971 | + if let Some((user_id, packet)) = decode_relay(&datagram) { | ||
| 1972 | + if let Some(watching) = share.lock().unwrap().watching.get(&user_id) { | ||
| 1973 | + watching.receive(packet); | ||
| 1974 | + } | ||
| 1975 | + } | ||
| 1736 | } | 1976 | } |
| 1737 | } | 1977 | } |
crates/client/src/settings.rsmodified+137 -2
| @@ -1,6 +1,10 @@ | |||
| 1 | use std::{fmt::Display, fs, ops::RangeInclusive}; | 1 | use std::{fmt::Display, fs, ops::RangeInclusive}; |
| 2 | 2 | ||
| 3 | -use common::{config::Config, string_enum}; | 3 | +use common::{ |
| 4 | + config::Config, | ||
| 5 | + share::{Codec, Fps, Quality, Resolution}, | ||
| 6 | + string_enum, | ||
| 7 | +}; | ||
| 4 | use gpui_kit::{ | 8 | use gpui_kit::{ |
| 5 | App, Global, Pixels, | 9 | App, Global, Pixels, |
| 6 | component::{Theme, ThemeMode}, | 10 | component::{Theme, ThemeMode}, |
| @@ -8,7 +12,16 @@ use gpui_kit::{ | |||
| 8 | }; | 12 | }; |
| 9 | use tracing::warn; | 13 | use tracing::warn; |
| 10 | 14 | ||
| 11 | -use crate::{config_file, voice::audio::Choice}; | 15 | +use crate::{ |
| 16 | + config_file, | ||
| 17 | + share::{audio_capture::AudioMode, encode::capabilities, session::WatchQuality}, | ||
| 18 | + voice::audio::Choice, | ||
| 19 | +}; | ||
| 20 | + | ||
| 21 | +pub const SHARE_QUALITY: Quality = Quality { | ||
| 22 | + resolution: Resolution::P1080, | ||
| 23 | + fps: Fps::F30, | ||
| 24 | +}; | ||
| 12 | 25 | ||
| 13 | pub const SENSITIVITY_DB: RangeInclusive<f32> = -80.0..=0.0; | 26 | pub const SENSITIVITY_DB: RangeInclusive<f32> = -80.0..=0.0; |
| 14 | pub const VOLUME: RangeInclusive<f32> = 0.0..=200.0; | 27 | pub const VOLUME: RangeInclusive<f32> = 0.0..=200.0; |
| @@ -110,14 +123,88 @@ impl Default for VoiceSettings { | |||
| 110 | } | 123 | } |
| 111 | } | 124 | } |
| 112 | 125 | ||
| 126 | +#[derive(Debug, Clone, PartialEq)] | ||
| 127 | +pub enum ShareAudio { | ||
| 128 | + Off, | ||
| 129 | + Everything, | ||
| 130 | + Source(String), | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 134 | +pub enum ShareCodec { | ||
| 135 | + Auto, | ||
| 136 | + Only(Codec), | ||
| 137 | +} | ||
| 138 | + | ||
| 139 | +#[derive(Debug, Clone, PartialEq)] | ||
| 140 | +pub struct ShareSettings { | ||
| 141 | + pub top: Quality, | ||
| 142 | + pub codec: ShareCodec, | ||
| 143 | + pub audio: ShareAudio, | ||
| 144 | + pub excluded: Vec<String>, | ||
| 145 | + pub watch: WatchQuality, | ||
| 146 | + pub volume: f32, | ||
| 147 | +} | ||
| 148 | + | ||
| 149 | +impl Default for ShareSettings { | ||
| 150 | + fn default() -> Self { | ||
| 151 | + Self { | ||
| 152 | + top: SHARE_QUALITY, | ||
| 153 | + codec: ShareCodec::Auto, | ||
| 154 | + audio: ShareAudio::Everything, | ||
| 155 | + excluded: Vec::new(), | ||
| 156 | + watch: WatchQuality::Auto, | ||
| 157 | + volume: 100.0, | ||
| 158 | + } | ||
| 159 | + } | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +impl ShareSettings { | ||
| 163 | + pub fn encode(&self) -> Vec<Codec> { | ||
| 164 | + let capable = &capabilities().encode; | ||
| 165 | + match self.codec { | ||
| 166 | + ShareCodec::Auto => capable.clone(), | ||
| 167 | + ShareCodec::Only(codec) => capable.iter().copied().filter(|c| *c == codec).collect(), | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + pub fn audio_mode(&self) -> Option<AudioMode> { | ||
| 172 | + match &self.audio { | ||
| 173 | + ShareAudio::Off => None, | ||
| 174 | + ShareAudio::Everything => Some(AudioMode::Everything { | ||
| 175 | + excluded: self.excluded.clone(), | ||
| 176 | + }), | ||
| 177 | + ShareAudio::Source(name) => Some(AudioMode::Source(name.clone())), | ||
| 178 | + } | ||
| 179 | + } | ||
| 180 | +} | ||
| 181 | + | ||
| 113 | #[derive(Debug, Clone, PartialEq)] | 182 | #[derive(Debug, Clone, PartialEq)] |
| 114 | pub struct Settings { | 183 | pub struct Settings { |
| 115 | pub theme: ThemeChoice, | 184 | pub theme: ThemeChoice, |
| 116 | pub font_size: FontSize, | 185 | pub font_size: FontSize, |
| 117 | pub voice: VoiceSettings, | 186 | pub voice: VoiceSettings, |
| 187 | + pub share: ShareSettings, | ||
| 118 | pub close_to_tray: bool, | 188 | pub close_to_tray: bool, |
| 119 | } | 189 | } |
| 120 | 190 | ||
| 191 | +fn quality_text(quality: Quality) -> String { | ||
| 192 | + format!("{}p{}", quality.resolution.height(), quality.fps.value()) | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +fn parse_quality(text: &str) -> Option<Quality> { | ||
| 196 | + let (height, fps) = text.split_once('p')?; | ||
| 197 | + let height: u32 = height.parse().ok()?; | ||
| 198 | + let fps: u32 = fps.parse().ok()?; | ||
| 199 | + | ||
| 200 | + Some(Quality { | ||
| 201 | + resolution: Resolution::ALL | ||
| 202 | + .into_iter() | ||
| 203 | + .find(|resolution| resolution.height() == height)?, | ||
| 204 | + fps: Fps::ALL.into_iter().find(|rate| rate.value() == fps)?, | ||
| 205 | + }) | ||
| 206 | +} | ||
| 207 | + | ||
| 121 | pub fn load() -> Settings { | 208 | pub fn load() -> Settings { |
| 122 | let config = config_file("settings") | 209 | let config = config_file("settings") |
| 123 | .and_then(|path| fs::read_to_string(path).ok()) | 210 | .and_then(|path| fs::read_to_string(path).ok()) |
| @@ -157,6 +244,30 @@ pub fn load() -> Settings { | |||
| 157 | push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), | 244 | push_to_talk_key: text("voice.push_to_talk").unwrap_or_default(), |
| 158 | }; | 245 | }; |
| 159 | 246 | ||
| 247 | + let share_defaults = ShareSettings::default(); | ||
| 248 | + let share = ShareSettings { | ||
| 249 | + top: text("share.top") | ||
| 250 | + .and_then(|value| parse_quality(&value)) | ||
| 251 | + .unwrap_or(share_defaults.top), | ||
| 252 | + codec: text("share.codec") | ||
| 253 | + .and_then(|value| Codec::parse(&value)) | ||
| 254 | + .map_or(ShareCodec::Auto, ShareCodec::Only), | ||
| 255 | + audio: match text("share.audio").as_deref() { | ||
| 256 | + Some("off") => ShareAudio::Off, | ||
| 257 | + Some("source") => { | ||
| 258 | + text("share.audio_source").map_or(ShareAudio::Everything, ShareAudio::Source) | ||
| 259 | + } | ||
| 260 | + _ => ShareAudio::Everything, | ||
| 261 | + }, | ||
| 262 | + excluded: text("share.excluded") | ||
| 263 | + .map(|value| value.split(',').map(str::to_string).collect()) | ||
| 264 | + .unwrap_or_default(), | ||
| 265 | + watch: text("share.watch") | ||
| 266 | + .and_then(|value| parse_quality(&value)) | ||
| 267 | + .map_or(WatchQuality::Auto, WatchQuality::Fixed), | ||
| 268 | + volume: number("share.volume", share_defaults.volume, &VOLUME), | ||
| 269 | + }; | ||
| 270 | + | ||
| 160 | Settings { | 271 | Settings { |
| 161 | theme: text("theme") | 272 | theme: text("theme") |
| 162 | .and_then(|value| ThemeChoice::parse(&value)) | 273 | .and_then(|value| ThemeChoice::parse(&value)) |
| @@ -165,6 +276,7 @@ pub fn load() -> Settings { | |||
| 165 | .and_then(|value| FontSize::parse(&value)) | 276 | .and_then(|value| FontSize::parse(&value)) |
| 166 | .unwrap_or(FontSize::Medium), | 277 | .unwrap_or(FontSize::Medium), |
| 167 | voice, | 278 | voice, |
| 279 | + share, | ||
| 168 | close_to_tray: text("close_to_tray").is_none_or(|value| value != "false"), | 280 | close_to_tray: text("close_to_tray").is_none_or(|value| value != "false"), |
| 169 | } | 281 | } |
| 170 | } | 282 | } |
| @@ -180,6 +292,16 @@ pub fn save(settings: &Settings) { | |||
| 180 | 292 | ||
| 181 | let voice = &settings.voice; | 293 | let voice = &settings.voice; |
| 182 | let key = voice.push_to_talk_key.as_str(); | 294 | let key = voice.push_to_talk_key.as_str(); |
| 295 | + let share = &settings.share; | ||
| 296 | + let (audio, source) = match &share.audio { | ||
| 297 | + ShareAudio::Off => ("off", ""), | ||
| 298 | + ShareAudio::Everything => ("everything", ""), | ||
| 299 | + ShareAudio::Source(name) => ("source", name.as_str()), | ||
| 300 | + }; | ||
| 301 | + let watch = match share.watch { | ||
| 302 | + WatchQuality::Auto => "auto".to_string(), | ||
| 303 | + WatchQuality::Fixed(quality) => quality_text(quality), | ||
| 304 | + }; | ||
| 183 | let content = [ | 305 | let content = [ |
| 184 | line("theme", settings.theme.as_str()), | 306 | line("theme", settings.theme.as_str()), |
| 185 | line("font_size", settings.font_size.as_str()), | 307 | line("font_size", settings.font_size.as_str()), |
| @@ -198,6 +320,19 @@ pub fn save(settings: &Settings) { | |||
| 198 | line("voice.activation", voice.activation.as_str()), | 320 | line("voice.activation", voice.activation.as_str()), |
| 199 | line("voice.profile", voice.profile.as_str()), | 321 | line("voice.profile", voice.profile.as_str()), |
| 200 | line("voice.push_to_talk", key), | 322 | line("voice.push_to_talk", key), |
| 323 | + line("share.top", quality_text(share.top)), | ||
| 324 | + line( | ||
| 325 | + "share.codec", | ||
| 326 | + match share.codec { | ||
| 327 | + ShareCodec::Auto => "auto", | ||
| 328 | + ShareCodec::Only(codec) => codec.name(), | ||
| 329 | + }, | ||
| 330 | + ), | ||
| 331 | + line("share.audio", audio), | ||
| 332 | + line("share.audio_source", source), | ||
| 333 | + line("share.excluded", share.excluded.join(",")), | ||
| 334 | + line("share.watch", watch), | ||
| 335 | + line("share.volume", share.volume), | ||
| 201 | ] | 336 | ] |
| 202 | .concat(); | 337 | .concat(); |
| 203 | 338 | ||
crates/client/src/share/audio_capture.rsadded+477 -0
| @@ -0,0 +1,477 @@ | |||
| 1 | +use std::{ | ||
| 2 | + cell::{Cell, RefCell}, | ||
| 3 | + collections::{HashMap, HashSet}, | ||
| 4 | + error::Error, | ||
| 5 | + process, | ||
| 6 | + rc::Rc, | ||
| 7 | + sync::{ | ||
| 8 | + Arc, | ||
| 9 | + atomic::{AtomicBool, Ordering}, | ||
| 10 | + }, | ||
| 11 | + thread::JoinHandle, | ||
| 12 | + time::Duration, | ||
| 13 | +}; | ||
| 14 | + | ||
| 15 | +use common::constant::{SHARE_AUDIO_CHANNELS, VOICE_SAMPLE_RATE}; | ||
| 16 | +use pipewire as pw; | ||
| 17 | +use pw::{ | ||
| 18 | + core::CoreRc, | ||
| 19 | + link::Link, | ||
| 20 | + loop_::Timeout, | ||
| 21 | + properties::properties, | ||
| 22 | + registry::GlobalObject, | ||
| 23 | + spa, | ||
| 24 | + stream::{StreamBox, StreamFlags, StreamState}, | ||
| 25 | + types::ObjectType, | ||
| 26 | +}; | ||
| 27 | +use spa::{pod::Pod, utils::dict::DictRef}; | ||
| 28 | +use tracing::warn; | ||
| 29 | + | ||
| 30 | +const STOP_CHECK: Duration = Duration::from_millis(100); | ||
| 31 | +const RETRY_AFTER_ERROR: Duration = Duration::from_secs(1); | ||
| 32 | +const OWN_PREFIX: &str = "yumush"; | ||
| 33 | +const APP_CLASS: &str = "Stream/Output/Audio"; | ||
| 34 | +const SKIPPED_ROLES: [&str; 2] = ["Communication", "Phone"]; | ||
| 35 | + | ||
| 36 | +pub enum AudioMode { | ||
| 37 | + Everything { excluded: Vec<String> }, | ||
| 38 | + Source(String), | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 42 | +pub enum AudioKind { | ||
| 43 | + App, | ||
| 44 | + Output, | ||
| 45 | + Input, | ||
| 46 | +} | ||
| 47 | + | ||
| 48 | +impl AudioKind { | ||
| 49 | + fn of(class: &str) -> Option<Self> { | ||
| 50 | + match class { | ||
| 51 | + APP_CLASS => Some(Self::App), | ||
| 52 | + "Audio/Sink" => Some(Self::Output), | ||
| 53 | + "Audio/Source" => Some(Self::Input), | ||
| 54 | + _ => None, | ||
| 55 | + } | ||
| 56 | + } | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +#[derive(Debug, Clone)] | ||
| 60 | +pub struct AudioApp { | ||
| 61 | + pub name: String, | ||
| 62 | + pub node: String, | ||
| 63 | + pub kind: AudioKind, | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +pub struct AudioCapture { | ||
| 67 | + stop: Arc<AtomicBool>, | ||
| 68 | + thread: Option<JoinHandle<()>>, | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +impl Drop for AudioCapture { | ||
| 72 | + fn drop(&mut self) { | ||
| 73 | + self.stop.store(true, Ordering::Relaxed); | ||
| 74 | + if let Some(thread) = self.thread.take() { | ||
| 75 | + let _ = thread.join(); | ||
| 76 | + } | ||
| 77 | + } | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +#[derive(Default)] | ||
| 81 | +struct Node { | ||
| 82 | + id: u32, | ||
| 83 | + name: String, | ||
| 84 | + class: String, | ||
| 85 | + role: String, | ||
| 86 | + process: String, | ||
| 87 | + app: String, | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +struct Port { | ||
| 91 | + node: u32, | ||
| 92 | + channel: String, | ||
| 93 | + output: bool, | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +#[derive(Default)] | ||
| 97 | +struct Routing { | ||
| 98 | + streams: HashMap<u32, Node>, | ||
| 99 | + ports: HashMap<u32, Port>, | ||
| 100 | + links: HashMap<(u32, u32), Link>, | ||
| 101 | + failed: HashSet<(u32, u32)>, | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +pub fn apps() -> Vec<AudioApp> { | ||
| 105 | + let mut apps: Vec<AudioApp> = nodes() | ||
| 106 | + .unwrap_or_default() | ||
| 107 | + .into_iter() | ||
| 108 | + .filter(|node| !node.name.starts_with(OWN_PREFIX)) | ||
| 109 | + .filter_map(|node| { | ||
| 110 | + Some(AudioApp { | ||
| 111 | + kind: AudioKind::of(&node.class)?, | ||
| 112 | + name: node.app, | ||
| 113 | + node: node.name, | ||
| 114 | + }) | ||
| 115 | + }) | ||
| 116 | + .collect(); | ||
| 117 | + apps.sort_by(|a, b| (a.kind as u8, &a.name).cmp(&(b.kind as u8, &b.name))); | ||
| 118 | + apps.dedup_by(|a, b| a.kind == AudioKind::App && a.kind == b.kind && a.name == b.name); | ||
| 119 | + apps | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +pub fn start(mode: AudioMode, output: rtrb::Producer<f32>) -> AudioCapture { | ||
| 123 | + let stop = Arc::new(AtomicBool::new(false)); | ||
| 124 | + let thread = { | ||
| 125 | + let stop = stop.clone(); | ||
| 126 | + std::thread::Builder::new() | ||
| 127 | + .name("share-audio".to_string()) | ||
| 128 | + .spawn(move || { | ||
| 129 | + let output = Rc::new(RefCell::new(output)); | ||
| 130 | + while !stop.load(Ordering::Relaxed) { | ||
| 131 | + if let Err(error) = run(&mode, &output, &stop) { | ||
| 132 | + warn!("share audio: {error}, retrying"); | ||
| 133 | + std::thread::sleep(RETRY_AFTER_ERROR); | ||
| 134 | + } | ||
| 135 | + } | ||
| 136 | + }) | ||
| 137 | + .inspect_err(|error| warn!("share audio not started: {error}")) | ||
| 138 | + .ok() | ||
| 139 | + }; | ||
| 140 | + | ||
| 141 | + AudioCapture { stop, thread } | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +fn nodes() -> Result<Vec<Node>, Box<dyn Error>> { | ||
| 145 | + pw::init(); | ||
| 146 | + let mainloop = pw::main_loop::MainLoopRc::new(None)?; | ||
| 147 | + let context = pw::context::ContextRc::new(&mainloop, None)?; | ||
| 148 | + let core = context.connect_rc(None)?; | ||
| 149 | + let registry = core.get_registry_rc()?; | ||
| 150 | + | ||
| 151 | + let found = Rc::new(RefCell::new(Vec::new())); | ||
| 152 | + let done = Rc::new(Cell::new(false)); | ||
| 153 | + let failed = Rc::new(Cell::new(false)); | ||
| 154 | + | ||
| 155 | + let pending = core.sync(0)?; | ||
| 156 | + | ||
| 157 | + let _core_listener = core | ||
| 158 | + .add_listener_local() | ||
| 159 | + .done({ | ||
| 160 | + let done = done.clone(); | ||
| 161 | + let mainloop = mainloop.clone(); | ||
| 162 | + move |id, seq| { | ||
| 163 | + if id == pw::core::PW_ID_CORE && seq == pending { | ||
| 164 | + done.set(true); | ||
| 165 | + mainloop.quit(); | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + }) | ||
| 169 | + .error({ | ||
| 170 | + let done = done.clone(); | ||
| 171 | + let failed = failed.clone(); | ||
| 172 | + let mainloop = mainloop.clone(); | ||
| 173 | + move |_, _, _, _| { | ||
| 174 | + failed.set(true); | ||
| 175 | + done.set(true); | ||
| 176 | + mainloop.quit(); | ||
| 177 | + } | ||
| 178 | + }) | ||
| 179 | + .register(); | ||
| 180 | + | ||
| 181 | + let _registry_listener = registry | ||
| 182 | + .add_listener_local() | ||
| 183 | + .global({ | ||
| 184 | + let found = found.clone(); | ||
| 185 | + move |global| { | ||
| 186 | + if let Some(node) = node_of(global) { | ||
| 187 | + found.borrow_mut().push(node); | ||
| 188 | + } | ||
| 189 | + } | ||
| 190 | + }) | ||
| 191 | + .register(); | ||
| 192 | + | ||
| 193 | + while !done.get() { | ||
| 194 | + mainloop.run(); | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + if failed.get() { | ||
| 198 | + return Err("pipewire share scan".into()); | ||
| 199 | + } | ||
| 200 | + Ok(found.take()) | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +fn node_of(global: &GlobalObject<&DictRef>) -> Option<Node> { | ||
| 204 | + if !matches!(global.type_, ObjectType::Node) { | ||
| 205 | + return None; | ||
| 206 | + } | ||
| 207 | + let props = global.props?; | ||
| 208 | + let name = props.get(*pw::keys::NODE_NAME)?; | ||
| 209 | + let description = props.get(*pw::keys::NODE_DESCRIPTION).unwrap_or(name); | ||
| 210 | + Some(Node { | ||
| 211 | + id: global.id, | ||
| 212 | + name: name.to_string(), | ||
| 213 | + class: props | ||
| 214 | + .get(*pw::keys::MEDIA_CLASS) | ||
| 215 | + .unwrap_or_default() | ||
| 216 | + .to_string(), | ||
| 217 | + role: props | ||
| 218 | + .get(*pw::keys::MEDIA_ROLE) | ||
| 219 | + .unwrap_or_default() | ||
| 220 | + .to_string(), | ||
| 221 | + process: props | ||
| 222 | + .get(*pw::keys::APP_PROCESS_ID) | ||
| 223 | + .unwrap_or_default() | ||
| 224 | + .to_string(), | ||
| 225 | + app: props | ||
| 226 | + .get(*pw::keys::APP_NAME) | ||
| 227 | + .unwrap_or(description) | ||
| 228 | + .to_string(), | ||
| 229 | + }) | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +fn port_of(global: &GlobalObject<&DictRef>) -> Option<Port> { | ||
| 233 | + if !matches!(global.type_, ObjectType::Port) { | ||
| 234 | + return None; | ||
| 235 | + } | ||
| 236 | + let props = global.props?; | ||
| 237 | + Some(Port { | ||
| 238 | + node: props.get(*pw::keys::NODE_ID)?.parse().ok()?, | ||
| 239 | + channel: props.get(*pw::keys::AUDIO_CHANNEL)?.to_string(), | ||
| 240 | + output: props.get(*pw::keys::PORT_DIRECTION)? == "out", | ||
| 241 | + }) | ||
| 242 | +} | ||
| 243 | + | ||
| 244 | +impl Routing { | ||
| 245 | + fn add(&mut self, global: &GlobalObject<&DictRef>) { | ||
| 246 | + if let Some(node) = node_of(global).filter(|node| node.class == APP_CLASS) { | ||
| 247 | + self.streams.insert(node.id, node); | ||
| 248 | + } | ||
| 249 | + if let Some(port) = port_of(global) { | ||
| 250 | + self.ports.insert(global.id, port); | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + fn remove(&mut self, id: u32) { | ||
| 255 | + self.streams.remove(&id); | ||
| 256 | + self.ports.remove(&id); | ||
| 257 | + } | ||
| 258 | + | ||
| 259 | + fn sync(&mut self, own: u32, excluded: &[String], core: &CoreRc) { | ||
| 260 | + self.links.retain(|(output, input), _| { | ||
| 261 | + self.ports.contains_key(output) && self.ports.contains_key(input) | ||
| 262 | + }); | ||
| 263 | + | ||
| 264 | + let mut wanted = Vec::new(); | ||
| 265 | + for (output_id, output) in self.ports.iter().filter(|(_, port)| port.output) { | ||
| 266 | + let eligible = self | ||
| 267 | + .streams | ||
| 268 | + .get(&output.node) | ||
| 269 | + .is_some_and(|node| eligible(node, excluded)); | ||
| 270 | + if !eligible { | ||
| 271 | + continue; | ||
| 272 | + } | ||
| 273 | + for (input_id, input) in self | ||
| 274 | + .ports | ||
| 275 | + .iter() | ||
| 276 | + .filter(|(_, port)| port.node == own && !port.output) | ||
| 277 | + { | ||
| 278 | + let key = (*output_id, *input_id); | ||
| 279 | + if matches_channel(output, input) | ||
| 280 | + && !self.links.contains_key(&key) | ||
| 281 | + && !self.failed.contains(&key) | ||
| 282 | + { | ||
| 283 | + wanted.push((key, output.node)); | ||
| 284 | + } | ||
| 285 | + } | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + for ((output_id, input_id), output_node) in wanted { | ||
| 289 | + match create_link(core, output_node, output_id, own, input_id) { | ||
| 290 | + Ok(link) => { | ||
| 291 | + self.links.insert((output_id, input_id), link); | ||
| 292 | + } | ||
| 293 | + Err(error) => { | ||
| 294 | + warn!("share audio link: {error}"); | ||
| 295 | + self.failed.insert((output_id, input_id)); | ||
| 296 | + } | ||
| 297 | + } | ||
| 298 | + } | ||
| 299 | + } | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +fn eligible(node: &Node, excluded: &[String]) -> bool { | ||
| 303 | + let own_process = process::id().to_string(); | ||
| 304 | + !(SKIPPED_ROLES.contains(&node.role.as_str()) | ||
| 305 | + || node.process == own_process | ||
| 306 | + || node.name.starts_with(OWN_PREFIX) | ||
| 307 | + || node.name.contains("echo-cancel") | ||
| 308 | + || excluded.contains(&node.app)) | ||
| 309 | +} | ||
| 310 | + | ||
| 311 | +fn matches_channel(output: &Port, input: &Port) -> bool { | ||
| 312 | + output.channel == input.channel | ||
| 313 | + || (output.channel == "MONO" && (input.channel == "FL" || input.channel == "FR")) | ||
| 314 | +} | ||
| 315 | + | ||
| 316 | +fn create_link( | ||
| 317 | + core: &CoreRc, | ||
| 318 | + output_node: u32, | ||
| 319 | + output_port: u32, | ||
| 320 | + input_node: u32, | ||
| 321 | + input_port: u32, | ||
| 322 | +) -> Result<Link, Box<dyn Error>> { | ||
| 323 | + let output_node = output_node.to_string(); | ||
| 324 | + let output_port = output_port.to_string(); | ||
| 325 | + let input_node = input_node.to_string(); | ||
| 326 | + let input_port = input_port.to_string(); | ||
| 327 | + let props = properties! { | ||
| 328 | + *pw::keys::LINK_OUTPUT_NODE => output_node.as_str(), | ||
| 329 | + *pw::keys::LINK_OUTPUT_PORT => output_port.as_str(), | ||
| 330 | + *pw::keys::LINK_INPUT_NODE => input_node.as_str(), | ||
| 331 | + *pw::keys::LINK_INPUT_PORT => input_port.as_str(), | ||
| 332 | + }; | ||
| 333 | + Ok(core.create_object::<Link>("link-factory", &props)?) | ||
| 334 | +} | ||
| 335 | + | ||
| 336 | +fn format_values() -> Option<Vec<u8>> { | ||
| 337 | + let mut info = spa::param::audio::AudioInfoRaw::new(); | ||
| 338 | + info.set_format(spa::param::audio::AudioFormat::F32LE); | ||
| 339 | + info.set_rate(VOICE_SAMPLE_RATE); | ||
| 340 | + info.set_channels(SHARE_AUDIO_CHANNELS as u32); | ||
| 341 | + let mut position = [0; spa::sys::SPA_AUDIO_MAX_CHANNELS as usize]; | ||
| 342 | + position[0] = spa::sys::SPA_AUDIO_CHANNEL_FL; | ||
| 343 | + position[1] = spa::sys::SPA_AUDIO_CHANNEL_FR; | ||
| 344 | + info.set_position(position); | ||
| 345 | + | ||
| 346 | + let object = spa::pod::Object { | ||
| 347 | + type_: spa::utils::SpaTypes::ObjectParamFormat.as_raw(), | ||
| 348 | + id: spa::param::ParamType::EnumFormat.as_raw(), | ||
| 349 | + properties: info.into(), | ||
| 350 | + }; | ||
| 351 | + let (cursor, _) = spa::pod::serialize::PodSerializer::serialize( | ||
| 352 | + std::io::Cursor::new(Vec::new()), | ||
| 353 | + &spa::pod::Value::Object(object), | ||
| 354 | + ) | ||
| 355 | + .ok()?; | ||
| 356 | + | ||
| 357 | + Some(cursor.into_inner()) | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +fn run( | ||
| 361 | + mode: &AudioMode, | ||
| 362 | + output: &Rc<RefCell<rtrb::Producer<f32>>>, | ||
| 363 | + stop: &AtomicBool, | ||
| 364 | +) -> Result<(), Box<dyn Error>> { | ||
| 365 | + pw::init(); | ||
| 366 | + let mainloop = pw::main_loop::MainLoopRc::new(None)?; | ||
| 367 | + let context = pw::context::ContextRc::new(&mainloop, None)?; | ||
| 368 | + let core = context.connect_rc(None)?; | ||
| 369 | + let registry = core.get_registry_rc()?; | ||
| 370 | + let failed = Rc::new(Cell::new(false)); | ||
| 371 | + | ||
| 372 | + let error_failed = failed.clone(); | ||
| 373 | + let _core_listener = core | ||
| 374 | + .add_listener_local() | ||
| 375 | + .error(move |_, _, _, message| { | ||
| 376 | + warn!("pipewire: {message}"); | ||
| 377 | + error_failed.set(true); | ||
| 378 | + }) | ||
| 379 | + .register(); | ||
| 380 | + | ||
| 381 | + let routing = Rc::new(RefCell::new(Routing::default())); | ||
| 382 | + let _registry_listener = registry | ||
| 383 | + .add_listener_local() | ||
| 384 | + .global({ | ||
| 385 | + let routing = routing.clone(); | ||
| 386 | + move |global| routing.borrow_mut().add(global) | ||
| 387 | + }) | ||
| 388 | + .global_remove({ | ||
| 389 | + let routing = routing.clone(); | ||
| 390 | + move |id| routing.borrow_mut().remove(id) | ||
| 391 | + }) | ||
| 392 | + .register(); | ||
| 393 | + | ||
| 394 | + let target = match mode { | ||
| 395 | + AudioMode::Everything { .. } => None, | ||
| 396 | + AudioMode::Source(name) => Some(name.as_str()), | ||
| 397 | + }; | ||
| 398 | + let is_sink = target.is_some_and(|target| { | ||
| 399 | + nodes() | ||
| 400 | + .unwrap_or_default() | ||
| 401 | + .iter() | ||
| 402 | + .any(|node| node.name == target && node.class == "Audio/Sink") | ||
| 403 | + }); | ||
| 404 | + | ||
| 405 | + let mut props = properties! { | ||
| 406 | + *pw::keys::MEDIA_TYPE => "Audio", | ||
| 407 | + *pw::keys::MEDIA_CATEGORY => "Capture", | ||
| 408 | + *pw::keys::MEDIA_ROLE => "Screen", | ||
| 409 | + *pw::keys::NODE_NAME => "yumush-share", | ||
| 410 | + }; | ||
| 411 | + let mut flags = StreamFlags::MAP_BUFFERS | StreamFlags::RT_PROCESS; | ||
| 412 | + if let Some(target) = target { | ||
| 413 | + props.insert(*pw::keys::TARGET_OBJECT, target); | ||
| 414 | + flags |= StreamFlags::AUTOCONNECT; | ||
| 415 | + if is_sink { | ||
| 416 | + props.insert(*pw::keys::STREAM_CAPTURE_SINK, "true"); | ||
| 417 | + } | ||
| 418 | + } | ||
| 419 | + | ||
| 420 | + let stream = StreamBox::new(&core, "yumush-share", props)?; | ||
| 421 | + let samples = output.clone(); | ||
| 422 | + let _stream_listener = stream | ||
| 423 | + .add_local_listener_with_user_data(()) | ||
| 424 | + .state_changed(state_watch(&failed)) | ||
| 425 | + .process(move |stream, _| { | ||
| 426 | + let Some(mut buffer) = stream.dequeue_buffer() else { | ||
| 427 | + return; | ||
| 428 | + }; | ||
| 429 | + let Some(data) = buffer.datas_mut().first_mut() else { | ||
| 430 | + return; | ||
| 431 | + }; | ||
| 432 | + let size = data.chunk().size() as usize; | ||
| 433 | + let Some(bytes) = data.data() else { | ||
| 434 | + return; | ||
| 435 | + }; | ||
| 436 | + let bytes = &bytes[..size.min(bytes.len())]; | ||
| 437 | + let mut samples = samples.borrow_mut(); | ||
| 438 | + for sample in bytes | ||
| 439 | + .as_chunks::<4>() | ||
| 440 | + .0 | ||
| 441 | + .iter() | ||
| 442 | + .copied() | ||
| 443 | + .map(f32::from_le_bytes) | ||
| 444 | + { | ||
| 445 | + let _ = samples.push(sample); | ||
| 446 | + } | ||
| 447 | + }) | ||
| 448 | + .register()?; | ||
| 449 | + | ||
| 450 | + let values = format_values().ok_or("pipewire format")?; | ||
| 451 | + let mut params = [Pod::from_bytes(&values).ok_or("pipewire format")?]; | ||
| 452 | + stream.connect(spa::utils::Direction::Input, None, flags, &mut params)?; | ||
| 453 | + | ||
| 454 | + while !stop.load(Ordering::Relaxed) { | ||
| 455 | + if failed.get() { | ||
| 456 | + return Err("pipewire connection lost".into()); | ||
| 457 | + } | ||
| 458 | + if let AudioMode::Everything { excluded } = mode { | ||
| 459 | + routing.borrow_mut().sync(stream.node_id(), excluded, &core); | ||
| 460 | + } | ||
| 461 | + mainloop.loop_().iterate(Timeout::Finite(STOP_CHECK)); | ||
| 462 | + } | ||
| 463 | + | ||
| 464 | + Ok(()) | ||
| 465 | +} | ||
| 466 | + | ||
| 467 | +fn state_watch( | ||
| 468 | + failed: &Rc<Cell<bool>>, | ||
| 469 | +) -> impl FnMut(&pw::stream::Stream, &mut (), StreamState, StreamState) + 'static { | ||
| 470 | + let failed = failed.clone(); | ||
| 471 | + move |_, _, _, new| { | ||
| 472 | + if let StreamState::Error(message) = new { | ||
| 473 | + warn!("share audio stream: {message}"); | ||
| 474 | + failed.set(true); | ||
| 475 | + } | ||
| 476 | + } | ||
| 477 | +} | ||
crates/client/src/share/capture.rsadded+324 -0
| @@ -0,0 +1,324 @@ | |||
| 1 | +use std::{ | ||
| 2 | + cell::Cell, | ||
| 3 | + error::Error, | ||
| 4 | + io::Cursor, | ||
| 5 | + os::fd::OwnedFd, | ||
| 6 | + rc::Rc, | ||
| 7 | + sync::{ | ||
| 8 | + Arc, | ||
| 9 | + atomic::{AtomicBool, Ordering}, | ||
| 10 | + mpsc::{Receiver, SyncSender, sync_channel}, | ||
| 11 | + }, | ||
| 12 | + thread::JoinHandle, | ||
| 13 | + time::{Duration, Instant}, | ||
| 14 | +}; | ||
| 15 | + | ||
| 16 | +use ashpd::desktop::{ | ||
| 17 | + PersistMode, Session, | ||
| 18 | + screencast::{CursorMode, Screencast, SelectSourcesOptions, SourceType}, | ||
| 19 | +}; | ||
| 20 | +use pipewire as pw; | ||
| 21 | +use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState}; | ||
| 22 | +use spa::{ | ||
| 23 | + param::{ | ||
| 24 | + ParamType, | ||
| 25 | + format::{FormatProperties, MediaSubtype, MediaType}, | ||
| 26 | + format_utils, | ||
| 27 | + video::{VideoFormat, VideoInfoRaw}, | ||
| 28 | + }, | ||
| 29 | + pod::{Pod, Value, object, property, serialize::PodSerializer}, | ||
| 30 | + utils::{Direction, Fraction, Rectangle, SpaTypes}, | ||
| 31 | +}; | ||
| 32 | + | ||
| 33 | +use super::frame::Frame; | ||
| 34 | + | ||
| 35 | +const NEGOTIATE_TIMEOUT: Duration = Duration::from_secs(10); | ||
| 36 | +const STOP_CHECK: Duration = Duration::from_millis(100); | ||
| 37 | +const DEFAULT_REFRESH: u32 = 60; | ||
| 38 | +const FRAME_QUEUE: usize = 2; | ||
| 39 | +const BYTES_PER_PIXEL: usize = 4; | ||
| 40 | + | ||
| 41 | +type Negotiated = (u32, u32, u32); | ||
| 42 | + | ||
| 43 | +pub struct Capture { | ||
| 44 | + pub width: u32, | ||
| 45 | + pub height: u32, | ||
| 46 | + pub refresh: u32, | ||
| 47 | + pub frames: Receiver<Frame>, | ||
| 48 | + stop: Arc<AtomicBool>, | ||
| 49 | + thread: Option<JoinHandle<()>>, | ||
| 50 | + _session: Session<Screencast>, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +impl Drop for Capture { | ||
| 54 | + fn drop(&mut self) { | ||
| 55 | + self.stop.store(true, Ordering::Relaxed); | ||
| 56 | + if let Some(thread) = self.thread.take() { | ||
| 57 | + let _ = thread.join(); | ||
| 58 | + } | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +pub async fn open() -> Result<Capture, String> { | ||
| 63 | + let screencast = Screencast::new().await.map_err(text)?; | ||
| 64 | + let session = screencast | ||
| 65 | + .create_session(Default::default()) | ||
| 66 | + .await | ||
| 67 | + .map_err(text)?; | ||
| 68 | + screencast | ||
| 69 | + .select_sources( | ||
| 70 | + &session, | ||
| 71 | + SelectSourcesOptions::default() | ||
| 72 | + .set_cursor_mode(CursorMode::EMBEDDED) | ||
| 73 | + .set_sources(SourceType::MONITOR | SourceType::WINDOW) | ||
| 74 | + .set_multiple(false) | ||
| 75 | + .set_persist_mode(PersistMode::DoNot), | ||
| 76 | + ) | ||
| 77 | + .await | ||
| 78 | + .map_err(text)? | ||
| 79 | + .response() | ||
| 80 | + .map_err(text)?; | ||
| 81 | + let streams = screencast | ||
| 82 | + .start(&session, None, Default::default()) | ||
| 83 | + .await | ||
| 84 | + .map_err(text)? | ||
| 85 | + .response() | ||
| 86 | + .map_err(text)?; | ||
| 87 | + let stream = streams.streams().first().ok_or("no screen stream")?; | ||
| 88 | + let node_id = stream.pipe_wire_node_id(); | ||
| 89 | + let (portal_width, portal_height) = stream.size().unwrap_or((0, 0)); | ||
| 90 | + let fd = screencast | ||
| 91 | + .open_pipe_wire_remote(&session, Default::default()) | ||
| 92 | + .await | ||
| 93 | + .map_err(text)?; | ||
| 94 | + | ||
| 95 | + let (negotiated_tx, negotiated_rx) = sync_channel::<Negotiated>(1); | ||
| 96 | + let (frames_tx, frames_rx) = sync_channel(FRAME_QUEUE); | ||
| 97 | + let stop = Arc::new(AtomicBool::new(false)); | ||
| 98 | + let thread = { | ||
| 99 | + let stop = stop.clone(); | ||
| 100 | + std::thread::Builder::new() | ||
| 101 | + .name("share-capture".to_string()) | ||
| 102 | + .spawn(move || { | ||
| 103 | + if let Err(error) = run(fd, node_id, negotiated_tx, frames_tx, &stop) { | ||
| 104 | + tracing::warn!("share capture: {error}"); | ||
| 105 | + } | ||
| 106 | + }) | ||
| 107 | + .map_err(text)? | ||
| 108 | + }; | ||
| 109 | + | ||
| 110 | + let negotiated = | ||
| 111 | + tokio::task::spawn_blocking(move || negotiated_rx.recv_timeout(NEGOTIATE_TIMEOUT).ok()) | ||
| 112 | + .await | ||
| 113 | + .ok() | ||
| 114 | + .flatten(); | ||
| 115 | + let (width, height, refresh) = | ||
| 116 | + negotiated.unwrap_or((portal_width as u32, portal_height as u32, DEFAULT_REFRESH)); | ||
| 117 | + | ||
| 118 | + Ok(Capture { | ||
| 119 | + width, | ||
| 120 | + height, | ||
| 121 | + refresh, | ||
| 122 | + frames: frames_rx, | ||
| 123 | + stop, | ||
| 124 | + thread: Some(thread), | ||
| 125 | + _session: session, | ||
| 126 | + }) | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +fn text(error: impl std::fmt::Display) -> String { | ||
| 130 | + error.to_string() | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +struct State { | ||
| 134 | + format: VideoInfoRaw, | ||
| 135 | + size: (u32, u32), | ||
| 136 | + started: Instant, | ||
| 137 | + negotiated: SyncSender<Negotiated>, | ||
| 138 | + frames: SyncSender<Frame>, | ||
| 139 | +} | ||
| 140 | + | ||
| 141 | +fn run( | ||
| 142 | + fd: OwnedFd, | ||
| 143 | + node_id: u32, | ||
| 144 | + negotiated: SyncSender<Negotiated>, | ||
| 145 | + frames: SyncSender<Frame>, | ||
| 146 | + stop: &AtomicBool, | ||
| 147 | +) -> Result<(), Box<dyn Error>> { | ||
| 148 | + pw::init(); | ||
| 149 | + let mainloop = pw::main_loop::MainLoopRc::new(None)?; | ||
| 150 | + let context = pw::context::ContextRc::new(&mainloop, None)?; | ||
| 151 | + let core = context.connect_fd_rc(fd, None)?; | ||
| 152 | + let failed = Rc::new(Cell::new(false)); | ||
| 153 | + | ||
| 154 | + let core_failed = failed.clone(); | ||
| 155 | + let _core_listener = core | ||
| 156 | + .add_listener_local() | ||
| 157 | + .error(move |_, _, _, message| { | ||
| 158 | + tracing::warn!("pipewire: {message}"); | ||
| 159 | + core_failed.set(true); | ||
| 160 | + }) | ||
| 161 | + .register(); | ||
| 162 | + | ||
| 163 | + let stream = pw::stream::StreamBox::new( | ||
| 164 | + &core, | ||
| 165 | + "yumush-share", | ||
| 166 | + properties! { | ||
| 167 | + *pw::keys::MEDIA_TYPE => "Video", | ||
| 168 | + *pw::keys::MEDIA_CATEGORY => "Capture", | ||
| 169 | + *pw::keys::MEDIA_ROLE => "Screen", | ||
| 170 | + }, | ||
| 171 | + )?; | ||
| 172 | + let state = State { | ||
| 173 | + format: VideoInfoRaw::new(), | ||
| 174 | + size: (0, 0), | ||
| 175 | + started: Instant::now(), | ||
| 176 | + negotiated, | ||
| 177 | + frames, | ||
| 178 | + }; | ||
| 179 | + let stream_failed = failed.clone(); | ||
| 180 | + let _stream_listener = stream | ||
| 181 | + .add_local_listener_with_user_data(state) | ||
| 182 | + .state_changed(move |_, _, _, new| { | ||
| 183 | + if let StreamState::Error(message) = new { | ||
| 184 | + tracing::warn!("pipewire stream: {message}"); | ||
| 185 | + stream_failed.set(true); | ||
| 186 | + } | ||
| 187 | + }) | ||
| 188 | + .param_changed(on_param) | ||
| 189 | + .process(on_process) | ||
| 190 | + .register()?; | ||
| 191 | + | ||
| 192 | + let values = format_values().ok_or("share format")?; | ||
| 193 | + let mut params = [Pod::from_bytes(&values).ok_or("share format")?]; | ||
| 194 | + stream.connect( | ||
| 195 | + Direction::Input, | ||
| 196 | + Some(node_id), | ||
| 197 | + pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS, | ||
| 198 | + &mut params, | ||
| 199 | + )?; | ||
| 200 | + | ||
| 201 | + while !stop.load(Ordering::Relaxed) { | ||
| 202 | + if failed.get() { | ||
| 203 | + return Err("pipewire connection lost".into()); | ||
| 204 | + } | ||
| 205 | + mainloop.loop_().iterate(Timeout::Finite(STOP_CHECK)); | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + Ok(()) | ||
| 209 | +} | ||
| 210 | + | ||
| 211 | +fn format_values() -> Option<Vec<u8>> { | ||
| 212 | + let object = object! { | ||
| 213 | + SpaTypes::ObjectParamFormat, | ||
| 214 | + ParamType::EnumFormat, | ||
| 215 | + property!(FormatProperties::MediaType, Id, MediaType::Video), | ||
| 216 | + property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw), | ||
| 217 | + property!( | ||
| 218 | + FormatProperties::VideoFormat, | ||
| 219 | + Choice, | ||
| 220 | + Enum, | ||
| 221 | + Id, | ||
| 222 | + VideoFormat::BGRx, | ||
| 223 | + VideoFormat::BGRA | ||
| 224 | + ), | ||
| 225 | + property!( | ||
| 226 | + FormatProperties::VideoSize, | ||
| 227 | + Choice, | ||
| 228 | + Range, | ||
| 229 | + Rectangle, | ||
| 230 | + Rectangle { width: 1920, height: 1080 }, | ||
| 231 | + Rectangle { width: 1, height: 1 }, | ||
| 232 | + Rectangle { width: 8192, height: 8192 } | ||
| 233 | + ), | ||
| 234 | + property!( | ||
| 235 | + FormatProperties::VideoFramerate, | ||
| 236 | + Choice, | ||
| 237 | + Range, | ||
| 238 | + Fraction, | ||
| 239 | + Fraction { num: 60, denom: 1 }, | ||
| 240 | + Fraction { num: 0, denom: 1 }, | ||
| 241 | + Fraction { num: 240, denom: 1 } | ||
| 242 | + ), | ||
| 243 | + }; | ||
| 244 | + let (cursor, _) = | ||
| 245 | + PodSerializer::serialize(Cursor::new(Vec::new()), &Value::Object(object)).ok()?; | ||
| 246 | + | ||
| 247 | + Some(cursor.into_inner()) | ||
| 248 | +} | ||
| 249 | + | ||
| 250 | +fn on_param(_: &pw::stream::Stream, state: &mut State, id: u32, param: Option<&Pod>) { | ||
| 251 | + let Some(param) = param else { | ||
| 252 | + return; | ||
| 253 | + }; | ||
| 254 | + if id != ParamType::Format.as_raw() { | ||
| 255 | + return; | ||
| 256 | + } | ||
| 257 | + let Ok((media_type, media_subtype)) = format_utils::parse_format(param) else { | ||
| 258 | + return; | ||
| 259 | + }; | ||
| 260 | + if media_type != MediaType::Video || media_subtype != MediaSubtype::Raw { | ||
| 261 | + return; | ||
| 262 | + } | ||
| 263 | + if state.format.parse(param).is_err() { | ||
| 264 | + return; | ||
| 265 | + } | ||
| 266 | + | ||
| 267 | + let size = state.format.size(); | ||
| 268 | + let fps = state.format.max_framerate(); | ||
| 269 | + let refresh = fps | ||
| 270 | + .num | ||
| 271 | + .checked_div(fps.denom) | ||
| 272 | + .filter(|refresh| *refresh > 0) | ||
| 273 | + .unwrap_or(DEFAULT_REFRESH); | ||
| 274 | + state.size = (size.width, size.height); | ||
| 275 | + let _ = state | ||
| 276 | + .negotiated | ||
| 277 | + .try_send((size.width, size.height, refresh)); | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +fn on_process(stream: &pw::stream::Stream, state: &mut State) { | ||
| 281 | + let (width, height) = state.size; | ||
| 282 | + if width == 0 || height == 0 { | ||
| 283 | + return; | ||
| 284 | + } | ||
| 285 | + let Some(mut buffer) = stream.dequeue_buffer() else { | ||
| 286 | + return; | ||
| 287 | + }; | ||
| 288 | + let Some(plane) = buffer.datas_mut().first_mut() else { | ||
| 289 | + return; | ||
| 290 | + }; | ||
| 291 | + | ||
| 292 | + let row = width as usize * BYTES_PER_PIXEL; | ||
| 293 | + let (offset, stride) = { | ||
| 294 | + let chunk = plane.chunk(); | ||
| 295 | + ( | ||
| 296 | + chunk.offset() as usize, | ||
| 297 | + usize::try_from(chunk.stride()).unwrap_or(0), | ||
| 298 | + ) | ||
| 299 | + }; | ||
| 300 | + let stride = stride.max(row); | ||
| 301 | + let Some(data) = plane.data() else { | ||
| 302 | + return; | ||
| 303 | + }; | ||
| 304 | + let Some(source) = data.get(offset..) else { | ||
| 305 | + return; | ||
| 306 | + }; | ||
| 307 | + | ||
| 308 | + let mut bgra = Vec::with_capacity(row * height as usize); | ||
| 309 | + for line in 0..height as usize { | ||
| 310 | + let Some(pixels) = source.get(line * stride..line * stride + row) else { | ||
| 311 | + return; | ||
| 312 | + }; | ||
| 313 | + bgra.extend_from_slice(pixels); | ||
| 314 | + } | ||
| 315 | + | ||
| 316 | + let frame = Frame { | ||
| 317 | + width, | ||
| 318 | + height, | ||
| 319 | + stride: row as u32, | ||
| 320 | + timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX), | ||
| 321 | + bgra, | ||
| 322 | + }; | ||
| 323 | + let _ = state.frames.try_send(frame); | ||
| 324 | +} | ||
crates/client/src/share/convert.rsadded+88 -0
| @@ -0,0 +1,88 @@ | |||
| 1 | +use std::ops::Range; | ||
| 2 | + | ||
| 3 | +use super::frame::Frame; | ||
| 4 | + | ||
| 5 | +pub struct I420 { | ||
| 6 | + pub y: Vec<u8>, | ||
| 7 | + pub u: Vec<u8>, | ||
| 8 | + pub v: Vec<u8>, | ||
| 9 | + pub width: u32, | ||
| 10 | + pub height: u32, | ||
| 11 | +} | ||
| 12 | + | ||
| 13 | +pub fn bgra_to_i420(frame: &Frame, width: u32, height: u32) -> I420 { | ||
| 14 | + let (w, h) = (width as usize, height as usize); | ||
| 15 | + let mut y = vec![0; w * h]; | ||
| 16 | + let mut cb_full = vec![0; w * h]; | ||
| 17 | + let mut cr_full = vec![0; w * h]; | ||
| 18 | + for dy in 0..h { | ||
| 19 | + let rows = span(dy, h, frame.height as usize); | ||
| 20 | + for dx in 0..w { | ||
| 21 | + let columns = span(dx, w, frame.width as usize); | ||
| 22 | + let (r, g, b) = average(frame, columns, rows.clone()); | ||
| 23 | + let index = dy * w + dx; | ||
| 24 | + y[index] = luma(r, g, b); | ||
| 25 | + cb_full[index] = chroma_blue(r, g, b); | ||
| 26 | + cr_full[index] = chroma_red(r, g, b); | ||
| 27 | + } | ||
| 28 | + } | ||
| 29 | + I420 { | ||
| 30 | + y, | ||
| 31 | + u: subsample(&cb_full, w, h), | ||
| 32 | + v: subsample(&cr_full, w, h), | ||
| 33 | + width, | ||
| 34 | + height, | ||
| 35 | + } | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +fn span(index: usize, target: usize, source: usize) -> Range<usize> { | ||
| 39 | + let start = index * source / target; | ||
| 40 | + let end = ((index + 1) * source / target).max(start + 1); | ||
| 41 | + start..end | ||
| 42 | +} | ||
| 43 | + | ||
| 44 | +fn average(frame: &Frame, columns: Range<usize>, rows: Range<usize>) -> (i32, i32, i32) { | ||
| 45 | + let stride = frame.stride as usize; | ||
| 46 | + let (mut r, mut g, mut b, mut count) = (0u32, 0u32, 0u32, 0u32); | ||
| 47 | + for y in rows { | ||
| 48 | + for x in columns.clone() { | ||
| 49 | + let pixel = y * stride + x * 4; | ||
| 50 | + b += u32::from(frame.bgra[pixel]); | ||
| 51 | + g += u32::from(frame.bgra[pixel + 1]); | ||
| 52 | + r += u32::from(frame.bgra[pixel + 2]); | ||
| 53 | + count += 1; | ||
| 54 | + } | ||
| 55 | + } | ||
| 56 | + ((r / count) as i32, (g / count) as i32, (b / count) as i32) | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +fn luma(r: i32, g: i32, b: i32) -> u8 { | ||
| 60 | + (((47 * r + 157 * g + 16 * b + 128) >> 8) + 16) as u8 | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +fn chroma_blue(r: i32, g: i32, b: i32) -> u8 { | ||
| 64 | + (((-26 * r - 86 * g + 112 * b + 128) >> 8) + 128) as u8 | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +fn chroma_red(r: i32, g: i32, b: i32) -> u8 { | ||
| 68 | + (((112 * r - 102 * g - 10 * b + 128) >> 8) + 128) as u8 | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +fn subsample(plane: &[u8], width: usize, height: usize) -> Vec<u8> { | ||
| 72 | + let mut out = Vec::with_capacity(width / 2 * height / 2); | ||
| 73 | + for y in (0..height).step_by(2) { | ||
| 74 | + for x in (0..width).step_by(2) { | ||
| 75 | + let sum: u32 = [ | ||
| 76 | + plane[y * width + x], | ||
| 77 | + plane[y * width + x + 1], | ||
| 78 | + plane[(y + 1) * width + x], | ||
| 79 | + plane[(y + 1) * width + x + 1], | ||
| 80 | + ] | ||
| 81 | + .into_iter() | ||
| 82 | + .map(u32::from) | ||
| 83 | + .sum(); | ||
| 84 | + out.push(((sum + 2) / 4) as u8); | ||
| 85 | + } | ||
| 86 | + } | ||
| 87 | + out | ||
| 88 | +} | ||
crates/client/src/share/encode.rsadded+343 -0
| @@ -0,0 +1,343 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | +use std::sync::atomic::{AtomicBool, Ordering}; | ||
| 3 | +use std::sync::mpsc::{Receiver, Sender, SyncSender, sync_channel}; | ||
| 4 | +use std::sync::{Arc, OnceLock}; | ||
| 5 | +use std::thread; | ||
| 6 | + | ||
| 7 | +use common::share::{Codec, Layer}; | ||
| 8 | + | ||
| 9 | +use super::convert::{self, I420}; | ||
| 10 | +use super::frame::{Encoded, Frame}; | ||
| 11 | +use crate::media::decode::{Engine, VideoDecoder}; | ||
| 12 | + | ||
| 13 | +const SOFTWARE: Codec = Codec::H264; | ||
| 14 | +const DEFAULT_MAX_HEIGHT: u32 = 2160; | ||
| 15 | +const KEYFRAME_SECONDS: u32 = 2; | ||
| 16 | + | ||
| 17 | +pub struct Capabilities { | ||
| 18 | + pub encode: Vec<Codec>, | ||
| 19 | + pub decode: Vec<Codec>, | ||
| 20 | + pub max_height: u32, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +struct Probe { | ||
| 24 | + capabilities: Capabilities, | ||
| 25 | + hardware: Vec<Codec>, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +fn probe() -> &'static Probe { | ||
| 29 | + static PROBE: OnceLock<Probe> = OnceLock::new(); | ||
| 30 | + PROBE.get_or_init(|| { | ||
| 31 | + let hardware = hardware::probe(); | ||
| 32 | + let codecs: Vec<Codec> = hardware.iter().map(|(codec, _)| *codec).collect(); | ||
| 33 | + let max_height = hardware | ||
| 34 | + .iter() | ||
| 35 | + .map(|(_, height)| *height) | ||
| 36 | + .max() | ||
| 37 | + .unwrap_or(DEFAULT_MAX_HEIGHT); | ||
| 38 | + let encode = Codec::ALL | ||
| 39 | + .into_iter() | ||
| 40 | + .filter(|codec| *codec == SOFTWARE || codecs.contains(codec)) | ||
| 41 | + .collect(); | ||
| 42 | + Probe { | ||
| 43 | + capabilities: Capabilities { | ||
| 44 | + encode, | ||
| 45 | + decode: Codec::ALL | ||
| 46 | + .into_iter() | ||
| 47 | + .filter(|codec| VideoDecoder::for_codec(*codec).is_some()) | ||
| 48 | + .collect(), | ||
| 49 | + max_height, | ||
| 50 | + }, | ||
| 51 | + hardware: codecs, | ||
| 52 | + } | ||
| 53 | + }) | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +pub fn capabilities() -> &'static Capabilities { | ||
| 57 | + &probe().capabilities | ||
| 58 | +} | ||
| 59 | + | ||
| 60 | +struct Settings { | ||
| 61 | + codec: Codec, | ||
| 62 | + width: u32, | ||
| 63 | + height: u32, | ||
| 64 | + fps: u32, | ||
| 65 | + bitrate: u32, | ||
| 66 | + gop: u32, | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +enum Backend { | ||
| 70 | + Hardware(hardware::Encoder), | ||
| 71 | + H264(ec_h264::Encoder), | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +impl Backend { | ||
| 75 | + fn open(settings: &Settings) -> Option<Self> { | ||
| 76 | + let hardware = if probe().hardware.contains(&settings.codec) { | ||
| 77 | + hardware::open(settings) | ||
| 78 | + } else { | ||
| 79 | + None | ||
| 80 | + }; | ||
| 81 | + hardware.map(Self::Hardware).or_else(|| { | ||
| 82 | + tracing::warn!(codec = ?settings.codec, "share encode falls back to software"); | ||
| 83 | + Self::software(settings) | ||
| 84 | + }) | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + fn software(settings: &Settings) -> Option<Self> { | ||
| 88 | + let (width, height) = (settings.width, settings.height); | ||
| 89 | + match settings.codec { | ||
| 90 | + Codec::H264 => { | ||
| 91 | + let mut config = ec_h264::EncoderConfig::new(width, height); | ||
| 92 | + config.framerate = settings.fps as f32; | ||
| 93 | + config.bitrate = settings.bitrate; | ||
| 94 | + config.gop_size = settings.gop; | ||
| 95 | + report(ec_h264::Encoder::new(config)).map(Self::H264) | ||
| 96 | + } | ||
| 97 | + Codec::H265 | Codec::Av1 | Codec::Vp8 | Codec::Vp9 => None, | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + fn engine(&self) -> Engine { | ||
| 102 | + match self { | ||
| 103 | + Self::Hardware(_) => Engine::Hardware, | ||
| 104 | + Self::H264(_) => Engine::Software, | ||
| 105 | + } | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + fn encode(&mut self, planes: I420, timestamp_ms: u32, force: bool) -> Option<(Vec<u8>, bool)> { | ||
| 109 | + match self { | ||
| 110 | + Self::Hardware(encoder) => encoder.encode(planes, timestamp_ms, force), | ||
| 111 | + Self::H264(encoder) => { | ||
| 112 | + let picture = ec_h264::PictureView::i420( | ||
| 113 | + planes.width, | ||
| 114 | + planes.height, | ||
| 115 | + &planes.y, | ||
| 116 | + &planes.u, | ||
| 117 | + &planes.v, | ||
| 118 | + ); | ||
| 119 | + report(encoder.encode(&picture)).map(|picture| (picture.au, picture.key_frame)) | ||
| 120 | + } | ||
| 121 | + } | ||
| 122 | + } | ||
| 123 | +} | ||
| 124 | + | ||
| 125 | +fn report<T, E: std::fmt::Debug>(result: Result<T, E>) -> Option<T> { | ||
| 126 | + result | ||
| 127 | + .inspect_err(|error| tracing::warn!(?error, "share encoder failed")) | ||
| 128 | + .ok() | ||
| 129 | +} | ||
| 130 | + | ||
| 131 | +#[cfg(target_os = "linux")] | ||
| 132 | +mod hardware { | ||
| 133 | + use common::share::Codec; | ||
| 134 | + use ec_va::CapReport; | ||
| 135 | + use ec_va::caps::{Entrypoint, Profile}; | ||
| 136 | + | ||
| 137 | + use super::{Settings, report}; | ||
| 138 | + use crate::share::convert::I420; | ||
| 139 | + | ||
| 140 | + const PAIRS: [(Codec, Profile); 3] = [ | ||
| 141 | + (Codec::H264, Profile::H264High), | ||
| 142 | + (Codec::H265, Profile::HEVCMain), | ||
| 143 | + (Codec::Av1, Profile::AV1Profile0), | ||
| 144 | + ]; | ||
| 145 | + | ||
| 146 | + pub struct Encoder(ec_hw::Encoder); | ||
| 147 | + | ||
| 148 | + impl Encoder { | ||
| 149 | + pub fn encode( | ||
| 150 | + &mut self, | ||
| 151 | + planes: I420, | ||
| 152 | + timestamp_ms: u32, | ||
| 153 | + force: bool, | ||
| 154 | + ) -> Option<(Vec<u8>, bool)> { | ||
| 155 | + let frame = ec_hw::I420 { | ||
| 156 | + y: planes.y, | ||
| 157 | + u: planes.u, | ||
| 158 | + v: planes.v, | ||
| 159 | + width: planes.width, | ||
| 160 | + height: planes.height, | ||
| 161 | + }; | ||
| 162 | + let meta = ec_hw::FrameMetadata { | ||
| 163 | + timestamp: i64::from(timestamp_ms), | ||
| 164 | + force_keyframe: force, | ||
| 165 | + }; | ||
| 166 | + report(self.0.encode(&frame, meta)).map(|coded| (coded.data, coded.is_keyframe)) | ||
| 167 | + } | ||
| 168 | + } | ||
| 169 | + | ||
| 170 | + pub fn probe() -> Vec<(Codec, u32)> { | ||
| 171 | + let Ok(display) = ec_va::open() else { | ||
| 172 | + return Vec::new(); | ||
| 173 | + }; | ||
| 174 | + let Ok(caps) = CapReport::probe(&display) else { | ||
| 175 | + return Vec::new(); | ||
| 176 | + }; | ||
| 177 | + PAIRS | ||
| 178 | + .into_iter() | ||
| 179 | + .filter(|(_, profile)| caps.supports(*profile, Entrypoint::EncSlice)) | ||
| 180 | + .map(|(codec, profile)| { | ||
| 181 | + let height = caps | ||
| 182 | + .entry(profile, Entrypoint::EncSlice) | ||
| 183 | + .and_then(|entry| entry.surfaces.as_ref()) | ||
| 184 | + .and_then(|surfaces| surfaces.max_height) | ||
| 185 | + .unwrap_or(super::DEFAULT_MAX_HEIGHT); | ||
| 186 | + (codec, height) | ||
| 187 | + }) | ||
| 188 | + .collect() | ||
| 189 | + } | ||
| 190 | + | ||
| 191 | + pub fn open(settings: &Settings) -> Option<Encoder> { | ||
| 192 | + let codec = match settings.codec { | ||
| 193 | + Codec::H264 => ec_hw::EncCodec::H264, | ||
| 194 | + Codec::H265 => ec_hw::EncCodec::H265, | ||
| 195 | + Codec::Av1 => ec_hw::EncCodec::Av1, | ||
| 196 | + Codec::Vp8 | Codec::Vp9 => return None, | ||
| 197 | + }; | ||
| 198 | + let display = ec_va::open().ok()?; | ||
| 199 | + let mut config = ec_hw::EncoderConfig::new(codec, settings.width, settings.height); | ||
| 200 | + config.framerate = (settings.fps, 1); | ||
| 201 | + config.bitrate = settings.bitrate; | ||
| 202 | + config.gop_size = settings.gop; | ||
| 203 | + config.rate_control = ec_hw::RateControlMode::ConstantBitrate; | ||
| 204 | + report(ec_hw::Encoder::new(&display, config)).map(Encoder) | ||
| 205 | + } | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +#[cfg(not(target_os = "linux"))] | ||
| 209 | +mod hardware { | ||
| 210 | + use common::share::Codec; | ||
| 211 | + | ||
| 212 | + use super::Settings; | ||
| 213 | + use crate::share::convert::I420; | ||
| 214 | + | ||
| 215 | + pub enum Encoder {} | ||
| 216 | + | ||
| 217 | + impl Encoder { | ||
| 218 | + pub fn encode(&mut self, _: I420, _: u32, _: bool) -> Option<(Vec<u8>, bool)> { | ||
| 219 | + match *self {} | ||
| 220 | + } | ||
| 221 | + } | ||
| 222 | + | ||
| 223 | + pub fn probe() -> Vec<(Codec, u32)> { | ||
| 224 | + Vec::new() | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + pub fn open(_: &Settings) -> Option<Encoder> { | ||
| 228 | + None | ||
| 229 | + } | ||
| 230 | +} | ||
| 231 | + | ||
| 232 | +fn run( | ||
| 233 | + layer: Layer, | ||
| 234 | + settings: Settings, | ||
| 235 | + input: Receiver<Arc<Frame>>, | ||
| 236 | + request: Arc<AtomicBool>, | ||
| 237 | + output: Sender<Encoded>, | ||
| 238 | +) { | ||
| 239 | + let Some(mut backend) = Backend::open(&settings) else { | ||
| 240 | + return; | ||
| 241 | + }; | ||
| 242 | + let interval = 1000 / settings.fps; | ||
| 243 | + let mut last: Option<u32> = None; | ||
| 244 | + for frame in input { | ||
| 245 | + if last.is_some_and(|last| frame.timestamp_ms.wrapping_sub(last) < interval) { | ||
| 246 | + continue; | ||
| 247 | + } | ||
| 248 | + last = Some(frame.timestamp_ms); | ||
| 249 | + let force = request.swap(false, Ordering::Relaxed); | ||
| 250 | + if force | ||
| 251 | + && matches!(backend, Backend::H264(_)) | ||
| 252 | + && let Some(fresh) = Backend::software(&settings) | ||
| 253 | + { | ||
| 254 | + backend = fresh; | ||
| 255 | + } | ||
| 256 | + let planes = convert::bgra_to_i420(&frame, settings.width, settings.height); | ||
| 257 | + let Some((data, keyframe)) = backend.encode(planes, frame.timestamp_ms, force) else { | ||
| 258 | + continue; | ||
| 259 | + }; | ||
| 260 | + let encoded = Encoded { | ||
| 261 | + layer, | ||
| 262 | + engine: backend.engine(), | ||
| 263 | + data, | ||
| 264 | + keyframe, | ||
| 265 | + timestamp_ms: frame.timestamp_ms, | ||
| 266 | + }; | ||
| 267 | + if output.send(encoded).is_err() { | ||
| 268 | + break; | ||
| 269 | + } | ||
| 270 | + } | ||
| 271 | +} | ||
| 272 | + | ||
| 273 | +struct Lane { | ||
| 274 | + input: SyncSender<Arc<Frame>>, | ||
| 275 | + request: Arc<AtomicBool>, | ||
| 276 | +} | ||
| 277 | + | ||
| 278 | +pub struct Encoders { | ||
| 279 | + source_width: u32, | ||
| 280 | + source_height: u32, | ||
| 281 | + output: Sender<Encoded>, | ||
| 282 | + lanes: HashMap<Layer, Lane>, | ||
| 283 | +} | ||
| 284 | + | ||
| 285 | +impl Encoders { | ||
| 286 | + pub fn new(source_width: u32, source_height: u32, output: Sender<Encoded>) -> Self { | ||
| 287 | + Self { | ||
| 288 | + source_width, | ||
| 289 | + source_height, | ||
| 290 | + output, | ||
| 291 | + lanes: HashMap::new(), | ||
| 292 | + } | ||
| 293 | + } | ||
| 294 | + | ||
| 295 | + pub fn set_layers(&mut self, layers: &[Layer]) { | ||
| 296 | + self.lanes.retain(|layer, _| layers.contains(layer)); | ||
| 297 | + for &layer in layers { | ||
| 298 | + if !self.lanes.contains_key(&layer) { | ||
| 299 | + let lane = self.spawn(layer); | ||
| 300 | + self.lanes.insert(layer, lane); | ||
| 301 | + } | ||
| 302 | + } | ||
| 303 | + } | ||
| 304 | + | ||
| 305 | + pub fn keyframe(&self, layer: Layer) { | ||
| 306 | + if let Some(lane) = self.lanes.get(&layer) { | ||
| 307 | + lane.request.store(true, Ordering::Relaxed); | ||
| 308 | + } | ||
| 309 | + } | ||
| 310 | + | ||
| 311 | + pub fn push(&self, frame: Arc<Frame>) { | ||
| 312 | + for lane in self.lanes.values() { | ||
| 313 | + let _ = lane.input.try_send(Arc::clone(&frame)); | ||
| 314 | + } | ||
| 315 | + } | ||
| 316 | + | ||
| 317 | + fn spawn(&self, layer: Layer) -> Lane { | ||
| 318 | + let (width, height) = layer | ||
| 319 | + .quality | ||
| 320 | + .resolution | ||
| 321 | + .size(self.source_width, self.source_height); | ||
| 322 | + let fps = layer.quality.fps.value(); | ||
| 323 | + let settings = Settings { | ||
| 324 | + codec: layer.codec, | ||
| 325 | + width, | ||
| 326 | + height, | ||
| 327 | + fps, | ||
| 328 | + bitrate: layer.bitrate(self.source_width, self.source_height), | ||
| 329 | + gop: fps * KEYFRAME_SECONDS, | ||
| 330 | + }; | ||
| 331 | + let (input, receiver) = sync_channel(1); | ||
| 332 | + let request = Arc::new(AtomicBool::new(false)); | ||
| 333 | + let thread_request = Arc::clone(&request); | ||
| 334 | + let output = self.output.clone(); | ||
| 335 | + let spawned = thread::Builder::new() | ||
| 336 | + .name("share-encode".into()) | ||
| 337 | + .spawn(move || run(layer, settings, receiver, thread_request, output)); | ||
| 338 | + if let Err(error) = spawned { | ||
| 339 | + tracing::warn!(?error, "share encode thread failed to start"); | ||
| 340 | + } | ||
| 341 | + Lane { input, request } | ||
| 342 | + } | ||
| 343 | +} | ||
crates/client/src/share/frame.rsadded+19 -0
| @@ -0,0 +1,19 @@ | |||
| 1 | +use common::share::Layer; | ||
| 2 | + | ||
| 3 | +use crate::media::decode::Engine; | ||
| 4 | + | ||
| 5 | +pub struct Frame { | ||
| 6 | + pub width: u32, | ||
| 7 | + pub height: u32, | ||
| 8 | + pub stride: u32, | ||
| 9 | + pub timestamp_ms: u32, | ||
| 10 | + pub bgra: Vec<u8>, | ||
| 11 | +} | ||
| 12 | + | ||
| 13 | +pub struct Encoded { | ||
| 14 | + pub layer: Layer, | ||
| 15 | + pub engine: Engine, | ||
| 16 | + pub data: Vec<u8>, | ||
| 17 | + pub keyframe: bool, | ||
| 18 | + pub timestamp_ms: u32, | ||
| 19 | +} | ||
crates/client/src/share/mod.rsadded+9 -0
| @@ -0,0 +1,9 @@ | |||
| 1 | +#[cfg(target_os = "linux")] | ||
| 2 | +pub mod audio_capture; | ||
| 3 | +#[cfg(target_os = "linux")] | ||
| 4 | +pub mod capture; | ||
| 5 | +pub mod convert; | ||
| 6 | +pub mod encode; | ||
| 7 | +pub mod frame; | ||
| 8 | +pub mod reassembly; | ||
| 9 | +pub mod session; | ||
crates/client/src/share/reassembly.rsadded+148 -0
| @@ -0,0 +1,148 @@ | |||
| 1 | +use std::collections::HashMap; | ||
| 2 | + | ||
| 3 | +use common::{datagram::Fragment, share::Layer}; | ||
| 4 | + | ||
| 5 | +const PENDING_LIMIT: usize = 8; | ||
| 6 | + | ||
| 7 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 8 | +enum Phase { | ||
| 9 | + WaitingKeyframe, | ||
| 10 | + Streaming, | ||
| 11 | +} | ||
| 12 | + | ||
| 13 | +#[derive(Debug)] | ||
| 14 | +pub struct Assembled { | ||
| 15 | + pub layer: Layer, | ||
| 16 | + pub data: Vec<u8>, | ||
| 17 | + pub keyframe: bool, | ||
| 18 | + pub timestamp_ms: u32, | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +struct Pending { | ||
| 22 | + layer: Layer, | ||
| 23 | + keyframe: bool, | ||
| 24 | + timestamp_ms: u32, | ||
| 25 | + parts: Vec<Option<Vec<u8>>>, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl Pending { | ||
| 29 | + fn new(fragment: Fragment<'_>) -> Pending { | ||
| 30 | + Pending { | ||
| 31 | + layer: fragment.layer, | ||
| 32 | + keyframe: fragment.keyframe, | ||
| 33 | + timestamp_ms: fragment.timestamp_ms, | ||
| 34 | + parts: vec![None; usize::from(fragment.count)], | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + fn insert(&mut self, fragment: Fragment<'_>) { | ||
| 39 | + if let Some(part) = self.parts.get_mut(usize::from(fragment.index)) { | ||
| 40 | + part.get_or_insert_with(|| fragment.payload.to_vec()); | ||
| 41 | + } | ||
| 42 | + } | ||
| 43 | + | ||
| 44 | + fn is_complete(&self) -> bool { | ||
| 45 | + self.parts.iter().all(Option::is_some) | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | + | ||
| 49 | +fn is_newer(frame: u32, than: u32) -> bool { | ||
| 50 | + let distance = frame.wrapping_sub(than); | ||
| 51 | + distance != 0 && distance < u32::MAX / 2 | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +pub struct Reassembler { | ||
| 55 | + layer: Option<Layer>, | ||
| 56 | + pending: HashMap<u32, Pending>, | ||
| 57 | + last: Option<u32>, | ||
| 58 | + phase: Phase, | ||
| 59 | + lost: bool, | ||
| 60 | + received_frames: u32, | ||
| 61 | + lost_frames: u32, | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +impl Reassembler { | ||
| 65 | + pub fn new() -> Reassembler { | ||
| 66 | + Reassembler { | ||
| 67 | + layer: None, | ||
| 68 | + pending: HashMap::new(), | ||
| 69 | + last: None, | ||
| 70 | + phase: Phase::WaitingKeyframe, | ||
| 71 | + lost: false, | ||
| 72 | + received_frames: 0, | ||
| 73 | + lost_frames: 0, | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + pub fn push(&mut self, fragment: Fragment<'_>) -> Option<Assembled> { | ||
| 78 | + if self.layer != Some(fragment.layer) { | ||
| 79 | + self.layer = Some(fragment.layer); | ||
| 80 | + self.pending.clear(); | ||
| 81 | + self.last = None; | ||
| 82 | + self.phase = Phase::WaitingKeyframe; | ||
| 83 | + } | ||
| 84 | + if self | ||
| 85 | + .last | ||
| 86 | + .is_some_and(|last| !is_newer(fragment.frame, last)) | ||
| 87 | + { | ||
| 88 | + return None; | ||
| 89 | + } | ||
| 90 | + if !self.pending.contains_key(&fragment.frame) && self.pending.len() >= PENDING_LIMIT { | ||
| 91 | + self.pending.clear(); | ||
| 92 | + self.lost = true; | ||
| 93 | + self.phase = Phase::WaitingKeyframe; | ||
| 94 | + } | ||
| 95 | + let pending = self | ||
| 96 | + .pending | ||
| 97 | + .entry(fragment.frame) | ||
| 98 | + .or_insert_with(|| Pending::new(fragment)); | ||
| 99 | + pending.insert(fragment); | ||
| 100 | + if !pending.is_complete() { | ||
| 101 | + return None; | ||
| 102 | + } | ||
| 103 | + let complete = self.pending.remove(&fragment.frame)?; | ||
| 104 | + self.deliver(fragment.frame, complete) | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + fn deliver(&mut self, frame: u32, complete: Pending) -> Option<Assembled> { | ||
| 108 | + self.received_frames += 1; | ||
| 109 | + let skipped = self | ||
| 110 | + .last | ||
| 111 | + .map_or(0, |last| frame.wrapping_sub(last).wrapping_sub(1)); | ||
| 112 | + if skipped > 0 { | ||
| 113 | + self.lost_frames += skipped; | ||
| 114 | + self.lost = true; | ||
| 115 | + self.phase = Phase::WaitingKeyframe; | ||
| 116 | + self.pending.retain(|&older, _| is_newer(older, frame)); | ||
| 117 | + } | ||
| 118 | + self.last = Some(frame); | ||
| 119 | + if complete.keyframe { | ||
| 120 | + self.phase = Phase::Streaming; | ||
| 121 | + } | ||
| 122 | + if self.phase == Phase::WaitingKeyframe { | ||
| 123 | + return None; | ||
| 124 | + } | ||
| 125 | + Some(Assembled { | ||
| 126 | + layer: complete.layer, | ||
| 127 | + data: complete.parts.into_iter().flatten().flatten().collect(), | ||
| 128 | + keyframe: complete.keyframe, | ||
| 129 | + timestamp_ms: complete.timestamp_ms, | ||
| 130 | + }) | ||
| 131 | + } | ||
| 132 | + | ||
| 133 | + pub fn take_lost(&mut self) -> bool { | ||
| 134 | + std::mem::take(&mut self.lost) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + pub fn loss_ratio(&mut self) -> f32 { | ||
| 138 | + let total = self.received_frames + self.lost_frames; | ||
| 139 | + let ratio = if total == 0 { | ||
| 140 | + 0.0 | ||
| 141 | + } else { | ||
| 142 | + self.lost_frames as f32 / total as f32 | ||
| 143 | + }; | ||
| 144 | + self.received_frames = 0; | ||
| 145 | + self.lost_frames = 0; | ||
| 146 | + ratio | ||
| 147 | + } | ||
| 148 | +} | ||
crates/client/src/share/session.rsadded+769 -0
| @@ -0,0 +1,769 @@ | |||
| 1 | +use std::{ | ||
| 2 | + cmp::Reverse, | ||
| 3 | + collections::{HashMap, VecDeque}, | ||
| 4 | + sync::{ | ||
| 5 | + Arc, Mutex, | ||
| 6 | + atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, Ordering}, | ||
| 7 | + mpsc::{self, Receiver, RecvTimeoutError, Sender}, | ||
| 8 | + }, | ||
| 9 | + time::{Duration, Instant}, | ||
| 10 | +}; | ||
| 11 | + | ||
| 12 | +use bytes::Bytes; | ||
| 13 | +use common::{ | ||
| 14 | + constant::{ | ||
| 15 | + SHARE_AUDIO_BITRATE, SHARE_AUDIO_CHANNELS, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, | ||
| 16 | + VOICE_SAMPLE_RATE, | ||
| 17 | + }, | ||
| 18 | + datagram::{Datagram, fragments}, | ||
| 19 | + share::{Codec, Fps, Layer, Quality, Resolution, Source, options}, | ||
| 20 | +}; | ||
| 21 | +use ec_opus::{Application, Decoder, Encoder}; | ||
| 22 | +use quinn::Connection; | ||
| 23 | +use rtrb::{Consumer, Producer, RingBuffer}; | ||
| 24 | +use tracing::warn; | ||
| 25 | + | ||
| 26 | +use super::{ | ||
| 27 | + audio_capture::{self, AudioCapture, AudioMode}, | ||
| 28 | + capture::{self, Capture}, | ||
| 29 | + encode::{self, Encoders}, | ||
| 30 | + frame::{Encoded, Frame}, | ||
| 31 | + reassembly::{Assembled, Reassembler}, | ||
| 32 | +}; | ||
| 33 | +use crate::media::{ | ||
| 34 | + self, | ||
| 35 | + decode::{Engine, Picture, VideoDecoder, lock}, | ||
| 36 | +}; | ||
| 37 | +use crate::settings::SHARE_QUALITY; | ||
| 38 | +use crate::voice::{ | ||
| 39 | + Playback, | ||
| 40 | + audio::{self, Audio, Choice, Worker, wait}, | ||
| 41 | +}; | ||
| 42 | + | ||
| 43 | +const CHUNK_MS: u32 = VOICE_FRAME_SAMPLES as u32 * 1000 / VOICE_SAMPLE_RATE; | ||
| 44 | +const STOP_CHECK: Duration = Duration::from_millis(100); | ||
| 45 | +const AUDIO_STEP: Duration = Duration::from_millis(5); | ||
| 46 | +const SAMPLE: Duration = Duration::from_secs(1); | ||
| 47 | +const DELAY_MS: i64 = 100; | ||
| 48 | +const LATE_MS: i64 = 200; | ||
| 49 | +const QUEUE_LIMIT: usize = 8; | ||
| 50 | +const LOSS_LIMIT: f32 = 0.05; | ||
| 51 | +const CLEAN_SECONDS: u32 = 10; | ||
| 52 | +const CHUNK_SAMPLES: usize = VOICE_FRAME_SAMPLES * SHARE_AUDIO_CHANNELS; | ||
| 53 | +const DECODE_SAMPLES: usize = VOICE_SAMPLE_RATE as usize * 120 / 1000 * SHARE_AUDIO_CHANNELS; | ||
| 54 | +const AUDIO_RING: usize = VOICE_SAMPLE_RATE as usize * SHARE_AUDIO_CHANNELS / 2; | ||
| 55 | + | ||
| 56 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 57 | +pub enum WatchQuality { | ||
| 58 | + Auto, | ||
| 59 | + Fixed(Quality), | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 63 | +pub enum Tick { | ||
| 64 | + Quality(Quality), | ||
| 65 | + Keyframe, | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +pub struct LayerStats { | ||
| 69 | + pub layer: Layer, | ||
| 70 | + pub engine: Engine, | ||
| 71 | + pub kbps: u32, | ||
| 72 | + pub fps: f32, | ||
| 73 | +} | ||
| 74 | + | ||
| 75 | +#[derive(Default)] | ||
| 76 | +pub struct WatchStats { | ||
| 77 | + pub layer: Option<Layer>, | ||
| 78 | + pub engine: Option<Engine>, | ||
| 79 | + pub kbps: u32, | ||
| 80 | + pub fps: f32, | ||
| 81 | + pub loss: f32, | ||
| 82 | + pub keyframes: u32, | ||
| 83 | + pub delay_ms: i64, | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +#[derive(Default)] | ||
| 87 | +pub struct ShareSample { | ||
| 88 | + pub sending: Vec<LayerStats>, | ||
| 89 | + pub watching: Vec<(String, WatchStats)>, | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +struct Tally { | ||
| 93 | + engine: Engine, | ||
| 94 | + bytes: u64, | ||
| 95 | + frames: u32, | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +struct Sent { | ||
| 99 | + since: Instant, | ||
| 100 | + tallies: HashMap<Layer, Tally>, | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +impl Sent { | ||
| 104 | + fn record(&mut self, encoded: &Encoded) { | ||
| 105 | + let tally = self.tallies.entry(encoded.layer).or_insert(Tally { | ||
| 106 | + engine: encoded.engine, | ||
| 107 | + bytes: 0, | ||
| 108 | + frames: 0, | ||
| 109 | + }); | ||
| 110 | + tally.bytes += encoded.data.len() as u64; | ||
| 111 | + tally.frames += 1; | ||
| 112 | + } | ||
| 113 | + | ||
| 114 | + fn take(&mut self) -> Vec<LayerStats> { | ||
| 115 | + let seconds = std::mem::replace(&mut self.since, Instant::now()) | ||
| 116 | + .elapsed() | ||
| 117 | + .as_secs_f32() | ||
| 118 | + .max(f32::EPSILON); | ||
| 119 | + let mut stats: Vec<LayerStats> = std::mem::take(&mut self.tallies) | ||
| 120 | + .into_iter() | ||
| 121 | + .map(|(layer, tally)| LayerStats { | ||
| 122 | + layer, | ||
| 123 | + engine: tally.engine, | ||
| 124 | + kbps: (tally.bytes as f32 * 8. / 1000. / seconds) as u32, | ||
| 125 | + fps: tally.frames as f32 / seconds, | ||
| 126 | + }) | ||
| 127 | + .collect(); | ||
| 128 | + stats.sort_by_key(|stat| stat.layer.to_byte()); | ||
| 129 | + stats | ||
| 130 | + } | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +fn next<T>(rx: &Receiver<T>, stop: &AtomicBool) -> Option<T> { | ||
| 134 | + while !stop.load(Ordering::Relaxed) { | ||
| 135 | + match rx.recv_timeout(STOP_CHECK) { | ||
| 136 | + Ok(item) => return Some(item), | ||
| 137 | + Err(RecvTimeoutError::Timeout) => {} | ||
| 138 | + Err(RecvTimeoutError::Disconnected) => return None, | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + None | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +#[cfg(not(target_os = "linux"))] | ||
| 145 | +pub struct Sharing {} | ||
| 146 | + | ||
| 147 | +#[cfg(target_os = "linux")] | ||
| 148 | +pub struct Sharing { | ||
| 149 | + encoders: Arc<Mutex<Encoders>>, | ||
| 150 | + _feed: Worker, | ||
| 151 | + _capture: Capture, | ||
| 152 | + _audio: Option<AudioCapture>, | ||
| 153 | + _audio_encode: Option<Worker>, | ||
| 154 | + _sender: Worker, | ||
| 155 | + sent: Arc<Mutex<Sent>>, | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +#[cfg(not(target_os = "linux"))] | ||
| 159 | +impl Sharing { | ||
| 160 | + pub async fn start( | ||
| 161 | + _: Connection, | ||
| 162 | + _: Quality, | ||
| 163 | + _: Vec<Codec>, | ||
| 164 | + _: Option<AudioMode>, | ||
| 165 | + ) -> Result<(Sharing, Source), String> { | ||
| 166 | + Err("screen share needs linux".into()) | ||
| 167 | + } | ||
| 168 | + | ||
| 169 | + pub fn set_layers(&mut self, _: &[Layer]) {} | ||
| 170 | + | ||
| 171 | + pub fn keyframe(&self, _: Layer) {} | ||
| 172 | + | ||
| 173 | + pub fn stats(&self) -> Vec<LayerStats> { | ||
| 174 | + Vec::new() | ||
| 175 | + } | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +#[cfg(target_os = "linux")] | ||
| 179 | +impl Sharing { | ||
| 180 | + pub async fn start( | ||
| 181 | + connection: Connection, | ||
| 182 | + top: Quality, | ||
| 183 | + encode: Vec<Codec>, | ||
| 184 | + audio: Option<AudioMode>, | ||
| 185 | + ) -> Result<(Sharing, Source), String> { | ||
| 186 | + if encode.is_empty() { | ||
| 187 | + return Err("codec unavailable".into()); | ||
| 188 | + } | ||
| 189 | + let mut capture = capture::open().await?; | ||
| 190 | + let (resolutions, frame_rates) = options( | ||
| 191 | + capture.height, | ||
| 192 | + capture.refresh, | ||
| 193 | + encode::capabilities().max_height, | ||
| 194 | + ); | ||
| 195 | + let clamped = Quality { | ||
| 196 | + resolution: resolutions | ||
| 197 | + .into_iter() | ||
| 198 | + .filter(|resolution| *resolution <= top.resolution) | ||
| 199 | + .max() | ||
| 200 | + .ok_or("no share resolution")?, | ||
| 201 | + fps: frame_rates | ||
| 202 | + .into_iter() | ||
| 203 | + .filter(|fps| *fps <= top.fps) | ||
| 204 | + .max() | ||
| 205 | + .ok_or("no share fps")?, | ||
| 206 | + }; | ||
| 207 | + let source = Source { | ||
| 208 | + width: capture.width, | ||
| 209 | + height: capture.height, | ||
| 210 | + top: clamped, | ||
| 211 | + encode, | ||
| 212 | + }; | ||
| 213 | + | ||
| 214 | + let frames = std::mem::replace(&mut capture.frames, mpsc::channel().1); | ||
| 215 | + let (output, encoded) = mpsc::channel(); | ||
| 216 | + let encoders = Arc::new(Mutex::new(Encoders::new( | ||
| 217 | + capture.width, | ||
| 218 | + capture.height, | ||
| 219 | + output, | ||
| 220 | + ))); | ||
| 221 | + let started = Instant::now(); | ||
| 222 | + let feed = { | ||
| 223 | + let encoders = encoders.clone(); | ||
| 224 | + Worker::spawn("share-feed", move |stop| { | ||
| 225 | + feed(frames, encoders, started, stop) | ||
| 226 | + }) | ||
| 227 | + }; | ||
| 228 | + | ||
| 229 | + let (audio_capture, audio_encode) = match audio { | ||
| 230 | + Some(mode) => { | ||
| 231 | + let (producer, consumer) = RingBuffer::new(AUDIO_RING); | ||
| 232 | + let audio_connection = connection.clone(); | ||
| 233 | + let encode = Worker::spawn("share-audio-encode", move |stop| { | ||
| 234 | + encode_audio(consumer, audio_connection, started, stop) | ||
| 235 | + }); | ||
| 236 | + (Some(audio_capture::start(mode, producer)), Some(encode)) | ||
| 237 | + } | ||
| 238 | + None => (None, None), | ||
| 239 | + }; | ||
| 240 | + | ||
| 241 | + let sent = Arc::new(Mutex::new(Sent { | ||
| 242 | + since: Instant::now(), | ||
| 243 | + tallies: HashMap::new(), | ||
| 244 | + })); | ||
| 245 | + let sender = { | ||
| 246 | + let sent = sent.clone(); | ||
| 247 | + Worker::spawn("share-send", move |stop| { | ||
| 248 | + send(encoded, connection, sent, stop) | ||
| 249 | + }) | ||
| 250 | + }; | ||
| 251 | + | ||
| 252 | + Ok(( | ||
| 253 | + Sharing { | ||
| 254 | + encoders, | ||
| 255 | + _feed: feed, | ||
| 256 | + _capture: capture, | ||
| 257 | + _audio: audio_capture, | ||
| 258 | + _audio_encode: audio_encode, | ||
| 259 | + _sender: sender, | ||
| 260 | + sent, | ||
| 261 | + }, | ||
| 262 | + source, | ||
| 263 | + )) | ||
| 264 | + } | ||
| 265 | + | ||
| 266 | + pub fn set_layers(&mut self, layers: &[Layer]) { | ||
| 267 | + lock(&self.encoders).set_layers(layers); | ||
| 268 | + } | ||
| 269 | + | ||
| 270 | + pub fn keyframe(&self, layer: Layer) { | ||
| 271 | + lock(&self.encoders).keyframe(layer); | ||
| 272 | + } | ||
| 273 | + | ||
| 274 | + pub fn stats(&self) -> Vec<LayerStats> { | ||
| 275 | + lock(&self.sent).take() | ||
| 276 | + } | ||
| 277 | +} | ||
| 278 | + | ||
| 279 | +fn feed( | ||
| 280 | + frames: Receiver<Frame>, | ||
| 281 | + encoders: Arc<Mutex<Encoders>>, | ||
| 282 | + started: Instant, | ||
| 283 | + stop: &AtomicBool, | ||
| 284 | +) { | ||
| 285 | + while let Some(mut frame) = next(&frames, stop) { | ||
| 286 | + frame.timestamp_ms = started.elapsed().as_millis() as u32; | ||
| 287 | + lock(&encoders).push(Arc::new(frame)); | ||
| 288 | + } | ||
| 289 | +} | ||
| 290 | + | ||
| 291 | +fn send(rx: Receiver<Encoded>, connection: Connection, sent: Arc<Mutex<Sent>>, stop: &AtomicBool) { | ||
| 292 | + let mut counters: HashMap<Layer, u32> = HashMap::new(); | ||
| 293 | + while let Some(item) = next(&rx, stop) { | ||
| 294 | + lock(&sent).record(&item); | ||
| 295 | + let counter = counters.entry(item.layer).or_default(); | ||
| 296 | + let number = *counter; | ||
| 297 | + *counter = counter.wrapping_add(1); | ||
| 298 | + for packet in fragments( | ||
| 299 | + item.layer, | ||
| 300 | + number, | ||
| 301 | + item.keyframe, | ||
| 302 | + item.timestamp_ms, | ||
| 303 | + &item.data, | ||
| 304 | + ) { | ||
| 305 | + let _ = connection.send_datagram(Bytes::from(packet)); | ||
| 306 | + } | ||
| 307 | + } | ||
| 308 | +} | ||
| 309 | + | ||
| 310 | +fn encode_audio( | ||
| 311 | + mut samples: Consumer<f32>, | ||
| 312 | + connection: Connection, | ||
| 313 | + started: Instant, | ||
| 314 | + stop: &AtomicBool, | ||
| 315 | +) { | ||
| 316 | + let Ok(mut encoder) = Encoder::new(VOICE_SAMPLE_RATE, SHARE_AUDIO_CHANNELS, Application::Audio) | ||
| 317 | + else { | ||
| 318 | + warn!("share audio encoder not started"); | ||
| 319 | + return; | ||
| 320 | + }; | ||
| 321 | + encoder.set_bitrate(SHARE_AUDIO_BITRATE as u32); | ||
| 322 | + let mut pcm = vec![0.0; CHUNK_SAMPLES]; | ||
| 323 | + let mut payload = [0u8; VOICE_MAX_PAYLOAD]; | ||
| 324 | + let mut sequence = 0u32; | ||
| 325 | + while !stop.load(Ordering::Relaxed) { | ||
| 326 | + if samples.slots() < CHUNK_SAMPLES { | ||
| 327 | + wait(stop, AUDIO_STEP); | ||
| 328 | + continue; | ||
| 329 | + } | ||
| 330 | + for sample in pcm.iter_mut() { | ||
| 331 | + *sample = samples.pop().unwrap_or(0.0); | ||
| 332 | + } | ||
| 333 | + let Ok(length) = encoder.encode_float(&pcm, VOICE_FRAME_SAMPLES, &mut payload) else { | ||
| 334 | + continue; | ||
| 335 | + }; | ||
| 336 | + let packet = Datagram::ShareAudio { | ||
| 337 | + sequence, | ||
| 338 | + timestamp_ms: (started.elapsed().as_millis() as u32).saturating_sub(CHUNK_MS), | ||
| 339 | + payload: &payload[..length], | ||
| 340 | + } | ||
| 341 | + .encode(); | ||
| 342 | + let _ = connection.send_datagram(Bytes::from(packet)); | ||
| 343 | + sequence = sequence.wrapping_add(1); | ||
| 344 | + } | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +struct Clock { | ||
| 348 | + started: Instant, | ||
| 349 | + offset: AtomicI64, | ||
| 350 | +} | ||
| 351 | + | ||
| 352 | +impl Clock { | ||
| 353 | + fn now(&self) -> i64 { | ||
| 354 | + self.started.elapsed().as_millis() as i64 | ||
| 355 | + } | ||
| 356 | + | ||
| 357 | + fn delay(&self) -> i64 { | ||
| 358 | + match self.offset.load(Ordering::Relaxed) { | ||
| 359 | + i64::MAX => 0, | ||
| 360 | + offset => offset + DELAY_MS, | ||
| 361 | + } | ||
| 362 | + } | ||
| 363 | + | ||
| 364 | + fn observe(&self, sharer_ms: u32) { | ||
| 365 | + self.offset | ||
| 366 | + .fetch_min(self.now() - i64::from(sharer_ms), Ordering::Relaxed); | ||
| 367 | + } | ||
| 368 | + | ||
| 369 | + fn due(&self, sharer_ms: u32) -> i64 { | ||
| 370 | + i64::from(sharer_ms) + self.offset.load(Ordering::Relaxed) + DELAY_MS | ||
| 371 | + } | ||
| 372 | +} | ||
| 373 | + | ||
| 374 | +#[derive(Default)] | ||
| 375 | +struct Video { | ||
| 376 | + queue: VecDeque<(i64, media::Frame)>, | ||
| 377 | + shown: Option<media::Frame>, | ||
| 378 | + generation: u64, | ||
| 379 | + decoded: u32, | ||
| 380 | + engine: Option<Engine>, | ||
| 381 | +} | ||
| 382 | + | ||
| 383 | +#[derive(Default)] | ||
| 384 | +struct Health { | ||
| 385 | + loss: f32, | ||
| 386 | + lost: bool, | ||
| 387 | + served: Option<Layer>, | ||
| 388 | +} | ||
| 389 | + | ||
| 390 | +pub struct Watching { | ||
| 391 | + clock: Arc<Clock>, | ||
| 392 | + video: Arc<Mutex<Video>>, | ||
| 393 | + health: Arc<Mutex<Health>>, | ||
| 394 | + volume: Arc<AtomicU32>, | ||
| 395 | + video_tx: Sender<Vec<u8>>, | ||
| 396 | + audio_tx: Sender<Vec<u8>>, | ||
| 397 | + received: AtomicU64, | ||
| 398 | + keyframes: u32, | ||
| 399 | + since: Instant, | ||
| 400 | + _video: Worker, | ||
| 401 | + _audio: Worker, | ||
| 402 | + _output: Audio, | ||
| 403 | + quality: WatchQuality, | ||
| 404 | + emitted: Option<Quality>, | ||
| 405 | + rung: usize, | ||
| 406 | + clean: u32, | ||
| 407 | +} | ||
| 408 | + | ||
| 409 | +impl Watching { | ||
| 410 | + pub fn new(quality: WatchQuality, volume: f32, choice: Choice) -> Watching { | ||
| 411 | + let clock = Arc::new(Clock { | ||
| 412 | + started: Instant::now(), | ||
| 413 | + offset: AtomicI64::new(i64::MAX), | ||
| 414 | + }); | ||
| 415 | + let video = Arc::new(Mutex::new(Video::default())); | ||
| 416 | + let health = Arc::new(Mutex::new(Health::default())); | ||
| 417 | + let volume = Arc::new(AtomicU32::new((volume / 100.0).to_bits())); | ||
| 418 | + let (video_tx, video_rx) = mpsc::channel(); | ||
| 419 | + let (audio_tx, audio_rx) = mpsc::channel(); | ||
| 420 | + let (producer, consumer) = RingBuffer::new(AUDIO_RING); | ||
| 421 | + let playback: Playback = Arc::new(Mutex::new(consumer)); | ||
| 422 | + let output = audio::start(None, playback, choice); | ||
| 423 | + | ||
| 424 | + let video_worker = { | ||
| 425 | + let (clock, video, health) = (clock.clone(), video.clone(), health.clone()); | ||
| 426 | + Worker::spawn("share-video", move |stop| { | ||
| 427 | + watch_video(video_rx, &clock, &video, &health, stop) | ||
| 428 | + }) | ||
| 429 | + }; | ||
| 430 | + let audio_worker = { | ||
| 431 | + let (clock, volume) = (clock.clone(), volume.clone()); | ||
| 432 | + Worker::spawn("share-play", move |stop| { | ||
| 433 | + play_audio(audio_rx, &clock, producer, &volume, stop) | ||
| 434 | + }) | ||
| 435 | + }; | ||
| 436 | + | ||
| 437 | + Watching { | ||
| 438 | + clock, | ||
| 439 | + video, | ||
| 440 | + health, | ||
| 441 | + volume, | ||
| 442 | + video_tx, | ||
| 443 | + audio_tx, | ||
| 444 | + received: AtomicU64::new(0), | ||
| 445 | + keyframes: 0, | ||
| 446 | + since: Instant::now(), | ||
| 447 | + _video: video_worker, | ||
| 448 | + _audio: audio_worker, | ||
| 449 | + _output: output, | ||
| 450 | + quality, | ||
| 451 | + emitted: None, | ||
| 452 | + rung: rungs() | ||
| 453 | + .iter() | ||
| 454 | + .position(|quality| *quality == SHARE_QUALITY) | ||
| 455 | + .unwrap_or(0), | ||
| 456 | + clean: 0, | ||
| 457 | + } | ||
| 458 | + } | ||
| 459 | + | ||
| 460 | + pub fn receive(&self, datagram: Datagram<'_>) { | ||
| 461 | + let (timestamp_ms, tx) = match datagram { | ||
| 462 | + Datagram::Video(fragment) => (fragment.timestamp_ms, &self.video_tx), | ||
| 463 | + Datagram::ShareAudio { timestamp_ms, .. } => (timestamp_ms, &self.audio_tx), | ||
| 464 | + Datagram::Voice { .. } => return, | ||
| 465 | + }; | ||
| 466 | + self.clock.observe(timestamp_ms); | ||
| 467 | + let bytes = datagram.encode(); | ||
| 468 | + self.received | ||
| 469 | + .fetch_add(bytes.len() as u64, Ordering::Relaxed); | ||
| 470 | + let _ = tx.send(bytes); | ||
| 471 | + } | ||
| 472 | + | ||
| 473 | + pub fn stats(&mut self) -> WatchStats { | ||
| 474 | + let seconds = std::mem::replace(&mut self.since, Instant::now()) | ||
| 475 | + .elapsed() | ||
| 476 | + .as_secs_f32() | ||
| 477 | + .max(f32::EPSILON); | ||
| 478 | + let bytes = self.received.swap(0, Ordering::Relaxed); | ||
| 479 | + let (decoded, engine) = { | ||
| 480 | + let mut video = lock(&self.video); | ||
| 481 | + (std::mem::take(&mut video.decoded), video.engine) | ||
| 482 | + }; | ||
| 483 | + let health = lock(&self.health); | ||
| 484 | + WatchStats { | ||
| 485 | + layer: health.served, | ||
| 486 | + engine, | ||
| 487 | + kbps: (bytes as f32 * 8. / 1000. / seconds) as u32, | ||
| 488 | + fps: decoded as f32 / seconds, | ||
| 489 | + loss: health.loss, | ||
| 490 | + keyframes: self.keyframes, | ||
| 491 | + delay_ms: self.clock.delay(), | ||
| 492 | + } | ||
| 493 | + } | ||
| 494 | + | ||
| 495 | + pub fn frame(&self) -> Option<media::Frame> { | ||
| 496 | + let now = self.clock.now(); | ||
| 497 | + let mut video = lock(&self.video); | ||
| 498 | + let mut due = None; | ||
| 499 | + while video.queue.front().is_some_and(|(at, _)| *at <= now) { | ||
| 500 | + due = video.queue.pop_front(); | ||
| 501 | + } | ||
| 502 | + if let Some((_, mut frame)) = due { | ||
| 503 | + video.generation += 1; | ||
| 504 | + frame.generation = video.generation; | ||
| 505 | + video.shown = Some(frame); | ||
| 506 | + } | ||
| 507 | + video.shown.clone() | ||
| 508 | + } | ||
| 509 | + | ||
| 510 | + pub fn set_quality(&mut self, quality: WatchQuality) { | ||
| 511 | + self.quality = quality; | ||
| 512 | + self.emitted = None; | ||
| 513 | + } | ||
| 514 | + | ||
| 515 | + pub fn set_volume(&self, volume: f32) { | ||
| 516 | + self.volume | ||
| 517 | + .store((volume / 100.0).to_bits(), Ordering::Relaxed); | ||
| 518 | + } | ||
| 519 | + | ||
| 520 | + pub fn tick(&mut self) -> Vec<Tick> { | ||
| 521 | + let (loss, lost, served) = { | ||
| 522 | + let mut health = lock(&self.health); | ||
| 523 | + (health.loss, std::mem::take(&mut health.lost), health.served) | ||
| 524 | + }; | ||
| 525 | + let mut ticks = Vec::new(); | ||
| 526 | + if lost { | ||
| 527 | + self.keyframes += 1; | ||
| 528 | + ticks.push(Tick::Keyframe); | ||
| 529 | + } | ||
| 530 | + let wanted = match self.quality { | ||
| 531 | + WatchQuality::Fixed(quality) => quality, | ||
| 532 | + WatchQuality::Auto => { | ||
| 533 | + self.adapt(loss, served); | ||
| 534 | + rungs()[self.rung] | ||
| 535 | + } | ||
| 536 | + }; | ||
| 537 | + if self.emitted != Some(wanted) { | ||
| 538 | + self.emitted = Some(wanted); | ||
| 539 | + ticks.push(Tick::Quality(wanted)); | ||
| 540 | + } | ||
| 541 | + ticks | ||
| 542 | + } | ||
| 543 | + | ||
| 544 | + fn adapt(&mut self, loss: f32, served: Option<Layer>) { | ||
| 545 | + if loss > LOSS_LIMIT { | ||
| 546 | + self.rung = (self.rung + 1).min(rungs().len() - 1); | ||
| 547 | + self.clean = 0; | ||
| 548 | + } else if loss == 0.0 { | ||
| 549 | + self.clean += 1; | ||
| 550 | + if self.clean >= CLEAN_SECONDS | ||
| 551 | + && served.is_some_and(|layer| layer.quality == rungs()[self.rung]) | ||
| 552 | + { | ||
| 553 | + self.rung = self.rung.saturating_sub(1); | ||
| 554 | + self.clean = 0; | ||
| 555 | + } | ||
| 556 | + } else { | ||
| 557 | + self.clean = 0; | ||
| 558 | + } | ||
| 559 | + } | ||
| 560 | +} | ||
| 561 | + | ||
| 562 | +fn rungs() -> Vec<Quality> { | ||
| 563 | + let mut rungs: Vec<Quality> = Resolution::ALL | ||
| 564 | + .into_iter() | ||
| 565 | + .flat_map(|resolution| { | ||
| 566 | + Fps::ALL | ||
| 567 | + .into_iter() | ||
| 568 | + .map(move |fps| Quality { resolution, fps }) | ||
| 569 | + }) | ||
| 570 | + .collect(); | ||
| 571 | + rungs.sort_by_key(|quality| { | ||
| 572 | + Reverse((quality.resolution.height() * quality.fps.value(), *quality)) | ||
| 573 | + }); | ||
| 574 | + rungs | ||
| 575 | +} | ||
| 576 | + | ||
| 577 | +fn watch_video( | ||
| 578 | + rx: Receiver<Vec<u8>>, | ||
| 579 | + clock: &Clock, | ||
| 580 | + video: &Mutex<Video>, | ||
| 581 | + health: &Mutex<Health>, | ||
| 582 | + stop: &AtomicBool, | ||
| 583 | +) { | ||
| 584 | + let mut reassembler = Reassembler::new(); | ||
| 585 | + let mut decoder: Option<(Codec, VideoDecoder)> = None; | ||
| 586 | + let mut sampled = Instant::now(); | ||
| 587 | + while !stop.load(Ordering::Relaxed) { | ||
| 588 | + match rx.recv_timeout(STOP_CHECK) { | ||
| 589 | + Ok(bytes) => { | ||
| 590 | + if let Some(Datagram::Video(fragment)) = Datagram::decode(&bytes) | ||
| 591 | + && let Some(assembled) = reassembler.push(fragment) | ||
| 592 | + { | ||
| 593 | + lock(health).served = Some(assembled.layer); | ||
| 594 | + decode_video(&mut decoder, &assembled, clock, video); | ||
| 595 | + } | ||
| 596 | + } | ||
| 597 | + Err(RecvTimeoutError::Timeout) => {} | ||
| 598 | + Err(RecvTimeoutError::Disconnected) => break, | ||
| 599 | + } | ||
| 600 | + if sampled.elapsed() >= SAMPLE { | ||
| 601 | + let mut health = lock(health); | ||
| 602 | + health.loss = reassembler.loss_ratio(); | ||
| 603 | + health.lost |= reassembler.take_lost(); | ||
| 604 | + sampled = Instant::now(); | ||
| 605 | + } | ||
| 606 | + } | ||
| 607 | +} | ||
| 608 | + | ||
| 609 | +fn decode_video( | ||
| 610 | + decoder: &mut Option<(Codec, VideoDecoder)>, | ||
| 611 | + assembled: &Assembled, | ||
| 612 | + clock: &Clock, | ||
| 613 | + video: &Mutex<Video>, | ||
| 614 | +) { | ||
| 615 | + let codec = assembled.layer.codec; | ||
| 616 | + if decoder.as_ref().map(|(current, _)| *current) != Some(codec) { | ||
| 617 | + *decoder = VideoDecoder::for_codec(codec).map(|created| (codec, created)); | ||
| 618 | + } | ||
| 619 | + let Some((_, active)) = decoder.as_mut() else { | ||
| 620 | + return; | ||
| 621 | + }; | ||
| 622 | + let due = clock.due(assembled.timestamp_ms); | ||
| 623 | + let engine = active.engine(); | ||
| 624 | + let pictures = active.decode(&assembled.data, assembled.timestamp_ms); | ||
| 625 | + let mut video = lock(video); | ||
| 626 | + video.engine = Some(engine); | ||
| 627 | + for picture in pictures { | ||
| 628 | + let Some(frame) = to_frame(&picture) else { | ||
| 629 | + continue; | ||
| 630 | + }; | ||
| 631 | + video.queue.push_back((due, frame)); | ||
| 632 | + video.decoded += 1; | ||
| 633 | + while video.queue.len() > QUEUE_LIMIT { | ||
| 634 | + video.queue.pop_front(); | ||
| 635 | + } | ||
| 636 | + } | ||
| 637 | +} | ||
| 638 | + | ||
| 639 | +fn to_frame(picture: &Picture) -> Option<media::Frame> { | ||
| 640 | + let (width, height, bgra) = media::convert::yuv_to_bgra( | ||
| 641 | + &picture.y, | ||
| 642 | + picture.y_stride, | ||
| 643 | + &picture.u, | ||
| 644 | + &picture.v, | ||
| 645 | + picture.uv_stride, | ||
| 646 | + picture.width, | ||
| 647 | + picture.height, | ||
| 648 | + media::convert::SHARE_WIDTH, | ||
| 649 | + )?; | ||
| 650 | + Some(media::Frame { | ||
| 651 | + width, | ||
| 652 | + height, | ||
| 653 | + bgra: Arc::new(bgra), | ||
| 654 | + generation: 0, | ||
| 655 | + }) | ||
| 656 | +} | ||
| 657 | + | ||
| 658 | +fn play_audio( | ||
| 659 | + rx: Receiver<Vec<u8>>, | ||
| 660 | + clock: &Clock, | ||
| 661 | + mut ring: Producer<f32>, | ||
| 662 | + volume: &AtomicU32, | ||
| 663 | + stop: &AtomicBool, | ||
| 664 | +) { | ||
| 665 | + let Ok(mut decoder) = Decoder::new(VOICE_SAMPLE_RATE, SHARE_AUDIO_CHANNELS) else { | ||
| 666 | + warn!("share audio decoder not started"); | ||
| 667 | + return; | ||
| 668 | + }; | ||
| 669 | + let mut scratch = vec![0.0; DECODE_SAMPLES]; | ||
| 670 | + let mut pending: VecDeque<(i64, Vec<f32>)> = VecDeque::new(); | ||
| 671 | + while !stop.load(Ordering::Relaxed) { | ||
| 672 | + match rx.recv_timeout(AUDIO_STEP) { | ||
| 673 | + Ok(bytes) => { | ||
| 674 | + if let Some(Datagram::ShareAudio { | ||
| 675 | + timestamp_ms, | ||
| 676 | + payload, | ||
| 677 | + .. | ||
| 678 | + }) = Datagram::decode(&bytes) | ||
| 679 | + && let Ok(count) = decoder.decode_float(payload, &mut scratch) | ||
| 680 | + { | ||
| 681 | + let samples = scratch[..count * SHARE_AUDIO_CHANNELS].to_vec(); | ||
| 682 | + pending.push_back((clock.due(timestamp_ms), samples)); | ||
| 683 | + } | ||
| 684 | + } | ||
| 685 | + Err(RecvTimeoutError::Timeout) => {} | ||
| 686 | + Err(RecvTimeoutError::Disconnected) => break, | ||
| 687 | + } | ||
| 688 | + let gain = f32::from_bits(volume.load(Ordering::Relaxed)); | ||
| 689 | + flush(&mut pending, clock.now(), &mut ring, gain); | ||
| 690 | + } | ||
| 691 | +} | ||
| 692 | + | ||
| 693 | +fn flush(pending: &mut VecDeque<(i64, Vec<f32>)>, now: i64, ring: &mut Producer<f32>, gain: f32) { | ||
| 694 | + while pending.front().is_some_and(|(due, _)| *due <= now) { | ||
| 695 | + let Some((due, samples)) = pending.pop_front() else { | ||
| 696 | + break; | ||
| 697 | + }; | ||
| 698 | + if now - due > LATE_MS { | ||
| 699 | + continue; | ||
| 700 | + } | ||
| 701 | + for sample in samples { | ||
| 702 | + let _ = ring.push(sample * gain); | ||
| 703 | + } | ||
| 704 | + } | ||
| 705 | +} | ||
| 706 | + | ||
| 707 | +#[cfg(test)] | ||
| 708 | +mod tests { | ||
| 709 | + use super::*; | ||
| 710 | + use common::datagram::fragments; | ||
| 711 | + | ||
| 712 | + #[test] | ||
| 713 | + fn every_codec_round_trips() { | ||
| 714 | + let capabilities = encode::capabilities(); | ||
| 715 | + let (width, height) = (1280, 720); | ||
| 716 | + for codec in capabilities.encode.clone() { | ||
| 717 | + let layer = Layer { | ||
| 718 | + quality: Quality { | ||
| 719 | + resolution: Resolution::P720, | ||
| 720 | + fps: Fps::F30, | ||
| 721 | + }, | ||
| 722 | + codec, | ||
| 723 | + }; | ||
| 724 | + let (tx, rx) = mpsc::channel(); | ||
| 725 | + let mut encoders = Encoders::new(width, height, tx); | ||
| 726 | + encoders.set_layers(&[layer]); | ||
| 727 | + for index in 0..10u32 { | ||
| 728 | + let bgra = (0..width * height * 4) | ||
| 729 | + .map(|byte| (byte / 4 % width + index * 8) as u8) | ||
| 730 | + .collect(); | ||
| 731 | + encoders.push(Arc::new(Frame { | ||
| 732 | + width, | ||
| 733 | + height, | ||
| 734 | + stride: width * 4, | ||
| 735 | + timestamp_ms: index * 34, | ||
| 736 | + bgra, | ||
| 737 | + })); | ||
| 738 | + std::thread::sleep(Duration::from_millis(40)); | ||
| 739 | + } | ||
| 740 | + std::thread::sleep(Duration::from_millis(300)); | ||
| 741 | + drop(encoders); | ||
| 742 | + | ||
| 743 | + let mut reassembler = Reassembler::new(); | ||
| 744 | + let mut decoder = VideoDecoder::for_codec(codec).expect("decoder"); | ||
| 745 | + let mut pictures = 0; | ||
| 746 | + for (number, encoded) in rx.try_iter().enumerate() { | ||
| 747 | + for packet in fragments( | ||
| 748 | + encoded.layer, | ||
| 749 | + number as u32, | ||
| 750 | + encoded.keyframe, | ||
| 751 | + encoded.timestamp_ms, | ||
| 752 | + &encoded.data, | ||
| 753 | + ) { | ||
| 754 | + let Some(Datagram::Video(fragment)) = Datagram::decode(&packet) else { | ||
| 755 | + panic!("fragment"); | ||
| 756 | + }; | ||
| 757 | + if let Some(assembled) = reassembler.push(fragment) { | ||
| 758 | + for picture in decoder.decode(&assembled.data, assembled.timestamp_ms) { | ||
| 759 | + assert_eq!((picture.width, picture.height), (width, height)); | ||
| 760 | + pictures += 1; | ||
| 761 | + } | ||
| 762 | + } | ||
| 763 | + } | ||
| 764 | + } | ||
| 765 | + eprintln!("{codec:?}: {pictures} pictures"); | ||
| 766 | + assert!(pictures > 0, "{codec:?} decoded nothing"); | ||
| 767 | + } | ||
| 768 | + } | ||
| 769 | +} | ||
crates/client/src/voice/audio.rsmodified+15 -13
| @@ -11,7 +11,7 @@ use std::{ | |||
| 11 | use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; | 11 | use common::constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}; |
| 12 | use tracing::{info, warn}; | 12 | use tracing::{info, warn}; |
| 13 | 13 | ||
| 14 | -use super::{Capture, Playback}; | 14 | +use super::{Capture, PLAYBACK_CHANNELS, Playback}; |
| 15 | 15 | ||
| 16 | #[cfg(target_os = "macos")] | 16 | #[cfg(target_os = "macos")] |
| 17 | #[path = "audio/coreaudio.rs"] | 17 | #[path = "audio/coreaudio.rs"] |
| @@ -119,11 +119,10 @@ pub fn stereo_frame(bytes: &[u8; 8]) -> [f32; 2] { | |||
| 119 | [left, right].map(|half| f32::from_le_bytes(half.try_into().unwrap_or_default())) | 119 | [left, right].map(|half| f32::from_le_bytes(half.try_into().unwrap_or_default())) |
| 120 | } | 120 | } |
| 121 | 121 | ||
| 122 | -pub fn stereo_bytes(sample: f32) -> [u8; 8] { | 122 | +pub fn frame_bytes(left: f32, right: f32) -> [u8; 8] { |
| 123 | - let bytes = sample.to_le_bytes(); | ||
| 124 | let mut frame = [0; 8]; | 123 | let mut frame = [0; 8]; |
| 125 | - frame[..4].copy_from_slice(&bytes); | 124 | + frame[..4].copy_from_slice(&left.to_le_bytes()); |
| 126 | - frame[4..].copy_from_slice(&bytes); | 125 | + frame[4..].copy_from_slice(&right.to_le_bytes()); |
| 127 | frame | 126 | frame |
| 128 | } | 127 | } |
| 129 | 128 | ||
| @@ -159,14 +158,17 @@ impl Downmix { | |||
| 159 | } | 158 | } |
| 160 | } | 159 | } |
| 161 | 160 | ||
| 162 | -pub fn play(playback: &Playback, count: usize, mut write: impl FnMut(usize, f32)) { | 161 | +pub fn play(playback: &Playback, count: usize, mut write: impl FnMut(usize, (f32, f32))) { |
| 163 | let mut playback = playback.try_lock().ok(); | 162 | let mut playback = playback.try_lock().ok(); |
| 164 | - for index in 0..count { | 163 | + let mut pop = || { |
| 165 | - let sample = playback | 164 | + playback |
| 166 | .as_mut() | 165 | .as_mut() |
| 167 | .and_then(|playback| playback.pop().ok()) | 166 | .and_then(|playback| playback.pop().ok()) |
| 168 | - .unwrap_or(0.0); | 167 | + .unwrap_or(0.0) |
| 169 | - write(index, sample); | 168 | + }; |
| 169 | + for index in 0..count { | ||
| 170 | + let frame = (pop(), pop()); | ||
| 171 | + write(index, frame); | ||
| 170 | } | 172 | } |
| 171 | } | 173 | } |
| 172 | 174 | ||
| @@ -247,14 +249,14 @@ fn tone(capture: Option<&Capture>, playback: &Playback, stop: &AtomicBool) { | |||
| 247 | }), | 249 | }), |
| 248 | ); | 250 | ); |
| 249 | } | 251 | } |
| 250 | - play(playback, VOICE_FRAME_SAMPLES, |_, sample| { | 252 | + play(playback, VOICE_FRAME_SAMPLES, |_, (left, right)| { |
| 251 | - energy += sample * sample | 253 | + energy += left * left + right * right |
| 252 | }); | 254 | }); |
| 253 | frames += 1; | 255 | frames += 1; |
| 254 | if frames == REPORT_FRAMES { | 256 | if frames == REPORT_FRAMES { |
| 255 | info!( | 257 | info!( |
| 256 | "voice tone rms {:.3}", | 258 | "voice tone rms {:.3}", |
| 257 | - (energy / (REPORT_FRAMES * VOICE_FRAME_SAMPLES) as f32).sqrt() | 259 | + (energy / (REPORT_FRAMES * VOICE_FRAME_SAMPLES * PLAYBACK_CHANNELS) as f32).sqrt() |
| 258 | ); | 260 | ); |
| 259 | energy = 0.0; | 261 | energy = 0.0; |
| 260 | frames = 0; | 262 | frames = 0; |
crates/client/src/voice/audio/coreaudio.rsmodified+7 -4
| @@ -159,10 +159,13 @@ fn playback_unit(playback: Playback, device: Option<u32>) -> Result<AudioUnit, E | |||
| 159 | let Some(left) = channels.next() else { | 159 | let Some(left) = channels.next() else { |
| 160 | return Ok(()); | 160 | return Ok(()); |
| 161 | }; | 161 | }; |
| 162 | - play(&playback, left.len(), |index, sample| left[index] = sample); | 162 | + let Some(right) = channels.next() else { |
| 163 | - if let Some(right) = channels.next() { | 163 | + return Ok(()); |
| 164 | - right.copy_from_slice(left); | 164 | + }; |
| 165 | - } | 165 | + play(&playback, left.len(), |index, (l, r)| { |
| 166 | + left[index] = l; | ||
| 167 | + right[index] = r; | ||
| 168 | + }); | ||
| 166 | Ok(()) | 169 | Ok(()) |
| 167 | })?; | 170 | })?; |
| 168 | unit.initialize()?; | 171 | unit.initialize()?; |
crates/client/src/voice/audio/pipewire.rsmodified+3 -3
| @@ -11,7 +11,7 @@ use pw::{loop_::Timeout, properties::properties, spa, stream::StreamState, types | |||
| 11 | use spa::pod::Pod; | 11 | use spa::pod::Pod; |
| 12 | 12 | ||
| 13 | use super::{ | 13 | use super::{ |
| 14 | - BYTES_PER_FRAME, Choice, Device, Devices, STOP_CHECK, Worker, play, record, stereo_bytes, | 14 | + BYTES_PER_FRAME, Choice, Device, Devices, STOP_CHECK, Worker, frame_bytes, play, record, |
| 15 | supervise, | 15 | supervise, |
| 16 | }; | 16 | }; |
| 17 | use crate::voice::{Capture, Playback}; | 17 | use crate::voice::{Capture, Playback}; |
| @@ -255,8 +255,8 @@ fn run( | |||
| 255 | } else { | 255 | } else { |
| 256 | requested.min(chunks.len()) | 256 | requested.min(chunks.len()) |
| 257 | }; | 257 | }; |
| 258 | - play(&playback, frames, |index, sample| { | 258 | + play(&playback, frames, |index, (left, right)| { |
| 259 | - chunks[index] = stereo_bytes(sample); | 259 | + chunks[index] = frame_bytes(left, right); |
| 260 | }); | 260 | }); |
| 261 | 261 | ||
| 262 | let chunk = data.chunk_mut(); | 262 | let chunk = data.chunk_mut(); |
crates/client/src/voice/audio/wasapi.rsmodified+4 -4
| @@ -13,8 +13,8 @@ use wasapi::{ | |||
| 13 | }; | 13 | }; |
| 14 | 14 | ||
| 15 | use super::{ | 15 | use super::{ |
| 16 | - BYTES_PER_FRAME, Choice, Device, Devices, Downmix, STOP_CHECK, Worker, play, record, | 16 | + BYTES_PER_FRAME, Choice, Device, Devices, Downmix, STOP_CHECK, Worker, frame_bytes, play, |
| 17 | - stereo_bytes, stereo_frame, supervise, | 17 | + record, stereo_frame, supervise, |
| 18 | }; | 18 | }; |
| 19 | use crate::voice::{Capture, Playback}; | 19 | use crate::voice::{Capture, Playback}; |
| 20 | 20 | ||
| @@ -273,8 +273,8 @@ fn render_frames( | |||
| 273 | let frames = client.get_available_space_in_frames()? as usize; | 273 | let frames = client.get_available_space_in_frames()? as usize; |
| 274 | bytes.resize(frames * BYTES_PER_FRAME, 0); | 274 | bytes.resize(frames * BYTES_PER_FRAME, 0); |
| 275 | let chunks = bytes.as_chunks_mut::<BYTES_PER_FRAME>().0; | 275 | let chunks = bytes.as_chunks_mut::<BYTES_PER_FRAME>().0; |
| 276 | - play(playback, frames, |index, sample| { | 276 | + play(playback, frames, |index, (left, right)| { |
| 277 | - chunks[index] = stereo_bytes(sample); | 277 | + chunks[index] = frame_bytes(left, right); |
| 278 | }); | 278 | }); |
| 279 | writer.write_to_device(&bytes, None)?; | 279 | writer.write_to_device(&bytes, None)?; |
| 280 | if default_changed(target, &mut checked)? { | 280 | if default_changed(target, &mut checked)? { |
crates/client/src/voice/engine.rsmodified+8 -4
| @@ -7,7 +7,7 @@ use common::{ | |||
| 7 | constant::{ | 7 | constant::{ |
| 8 | MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, | 8 | MUSIC_BITRATE, VOICE_BITRATE, VOICE_FRAME_SAMPLES, VOICE_MAX_PAYLOAD, VOICE_SAMPLE_RATE, |
| 9 | }, | 9 | }, |
| 10 | - voice::{decode_relay, encode_packet}, | 10 | + datagram::{Datagram, decode_relay}, |
| 11 | }; | 11 | }; |
| 12 | use ec_opus::{Application, Bandwidth, Decoder, Encoder}; | 12 | use ec_opus::{Application, Bandwidth, Decoder, Encoder}; |
| 13 | 13 | ||
| @@ -266,7 +266,11 @@ impl Engine { | |||
| 266 | continue; | 266 | continue; |
| 267 | }; | 267 | }; |
| 268 | 268 | ||
| 269 | - let packet = encode_packet(self.sequence, &payload[..length]); | 269 | + let packet = Datagram::Voice { |
| 270 | + sequence: self.sequence, | ||
| 271 | + payload: &payload[..length], | ||
| 272 | + } | ||
| 273 | + .encode(); | ||
| 270 | self.sent_bytes += packet.len(); | 274 | self.sent_bytes += packet.len(); |
| 271 | packets.push(packet); | 275 | packets.push(packet); |
| 272 | self.sequence = self.sequence.wrapping_add(1); | 276 | self.sequence = self.sequence.wrapping_add(1); |
| @@ -276,7 +280,7 @@ impl Engine { | |||
| 276 | } | 280 | } |
| 277 | 281 | ||
| 278 | pub fn receive(&mut self, datagram: &[u8]) { | 282 | pub fn receive(&mut self, datagram: &[u8]) { |
| 279 | - let Some((user_id, sequence, payload)) = decode_relay(datagram) else { | 283 | + let Some((user_id, Datagram::Voice { sequence, payload })) = decode_relay(datagram) else { |
| 280 | return; | 284 | return; |
| 281 | }; | 285 | }; |
| 282 | let now = Instant::now(); | 286 | let now = Instant::now(); |
| @@ -422,7 +426,7 @@ impl Engine { | |||
| 422 | mod tests { | 426 | mod tests { |
| 423 | use std::f32::consts::TAU; | 427 | use std::f32::consts::TAU; |
| 424 | 428 | ||
| 425 | - use common::voice::encode_relay; | 429 | + use common::datagram::encode_relay; |
| 426 | 430 | ||
| 427 | use super::*; | 431 | use super::*; |
| 428 | 432 | ||
crates/client/src/voice/mod.rsmodified+13 -8
| @@ -10,7 +10,7 @@ use std::{ | |||
| 10 | use bytes::Bytes; | 10 | use bytes::Bytes; |
| 11 | use common::{ | 11 | use common::{ |
| 12 | constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, | 12 | constant::{VOICE_FRAME_SAMPLES, VOICE_SAMPLE_RATE}, |
| 13 | - voice::encode_relay, | 13 | + datagram::encode_relay, |
| 14 | }; | 14 | }; |
| 15 | use quinn::Connection; | 15 | use quinn::Connection; |
| 16 | use rtrb::{Consumer, Producer, RingBuffer}; | 16 | use rtrb::{Consumer, Producer, RingBuffer}; |
| @@ -24,11 +24,14 @@ use audio::{Audio, Choice}; | |||
| 24 | use engine::{Engine, SILENT_DB, Traffic}; | 24 | use engine::{Engine, SILENT_DB, Traffic}; |
| 25 | 25 | ||
| 26 | const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; | 26 | const RING_SAMPLES: usize = VOICE_SAMPLE_RATE as usize / 2; |
| 27 | -const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2; | 27 | +const PLAYBACK_RING: usize = RING_SAMPLES * PLAYBACK_CHANNELS; |
| 28 | +const PLAYBACK_AHEAD: usize = VOICE_FRAME_SAMPLES * 2 * PLAYBACK_CHANNELS; | ||
| 28 | const TICK: Duration = Duration::from_millis(5); | 29 | const TICK: Duration = Duration::from_millis(5); |
| 29 | const LOOPBACK: &str = "00000000-0000-0000-0000-000000000000"; | 30 | const LOOPBACK: &str = "00000000-0000-0000-0000-000000000000"; |
| 30 | const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)]; | 31 | const CHIME: [(f32, f32); 2] = [(660.0, 0.18), (880.0, 0.32)]; |
| 31 | 32 | ||
| 33 | +pub const PLAYBACK_CHANNELS: usize = 2; | ||
| 34 | + | ||
| 32 | pub type Capture = Arc<Mutex<Producer<f32>>>; | 35 | pub type Capture = Arc<Mutex<Producer<f32>>>; |
| 33 | pub type Playback = Arc<Mutex<Consumer<f32>>>; | 36 | pub type Playback = Arc<Mutex<Consumer<f32>>>; |
| 34 | 37 | ||
| @@ -54,7 +57,7 @@ pub fn start(connection: Option<Connection>, settings: &VoiceSettings) -> Voice | |||
| 54 | let engine = Arc::new(Mutex::new(Engine::new())); | 57 | let engine = Arc::new(Mutex::new(Engine::new())); |
| 55 | let stop = Arc::new(AtomicBool::new(false)); | 58 | let stop = Arc::new(AtomicBool::new(false)); |
| 56 | let (capture_producer, from_capture) = RingBuffer::new(RING_SAMPLES); | 59 | let (capture_producer, from_capture) = RingBuffer::new(RING_SAMPLES); |
| 57 | - let (to_playback, playback_consumer) = RingBuffer::new(RING_SAMPLES); | 60 | + let (to_playback, playback_consumer) = RingBuffer::new(PLAYBACK_RING); |
| 58 | let capture: Capture = Arc::new(Mutex::new(capture_producer)); | 61 | let capture: Capture = Arc::new(Mutex::new(capture_producer)); |
| 59 | let playback: Playback = Arc::new(Mutex::new(playback_consumer)); | 62 | let playback: Playback = Arc::new(Mutex::new(playback_consumer)); |
| 60 | 63 | ||
| @@ -208,9 +211,11 @@ fn play(samples: Vec<f32>, gain: f32, settings: &VoiceSettings) { | |||
| 208 | let rate = VOICE_SAMPLE_RATE as f32; | 211 | let rate = VOICE_SAMPLE_RATE as f32; |
| 209 | let gain = gain * settings.output_volume / 100.0; | 212 | let gain = gain * settings.output_volume / 100.0; |
| 210 | let duration = Duration::from_secs_f32(samples.len() as f32 / rate + 0.3); | 213 | let duration = Duration::from_secs_f32(samples.len() as f32 / rate + 0.3); |
| 211 | - let (mut producer, consumer) = RingBuffer::new(samples.len().max(1)); | 214 | + let (mut producer, consumer) = RingBuffer::new(samples.len().max(1) * PLAYBACK_CHANNELS); |
| 212 | for sample in samples { | 215 | for sample in samples { |
| 213 | - let _ = producer.push(sample * gain); | 216 | + for _ in 0..PLAYBACK_CHANNELS { |
| 217 | + let _ = producer.push(sample * gain); | ||
| 218 | + } | ||
| 214 | } | 219 | } |
| 215 | let choice = settings.choice.clone(); | 220 | let choice = settings.choice.clone(); |
| 216 | 221 | ||
| @@ -252,10 +257,10 @@ fn work( | |||
| 252 | } | 257 | } |
| 253 | } | 258 | } |
| 254 | } | 259 | } |
| 255 | - while RING_SAMPLES - to_playback.slots() < PLAYBACK_AHEAD { | 260 | + while PLAYBACK_RING - to_playback.slots() < PLAYBACK_AHEAD { |
| 256 | locked.playback(&mut frame); | 261 | locked.playback(&mut frame); |
| 257 | - for sample in &frame { | 262 | + for sample in frame.iter().flat_map(|sample| [*sample; PLAYBACK_CHANNELS]) { |
| 258 | - let _ = to_playback.push(*sample); | 263 | + let _ = to_playback.push(sample); |
| 259 | } | 264 | } |
| 260 | } | 265 | } |
| 261 | drop(locked); | 266 | drop(locked); |
crates/common/src/constant.rsmodified+4 -0
| @@ -36,3 +36,7 @@ pub const ATTACHMENT_HEAD_BYTES: usize = 64; | |||
| 36 | pub const DEFAULT_MAX_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024; | 36 | pub const DEFAULT_MAX_ATTACHMENT_BYTES: u64 = 25 * 1024 * 1024; |
| 37 | pub const DEFAULT_MESSAGES_PER_MINUTE: u32 = 30; | 37 | pub const DEFAULT_MESSAGES_PER_MINUTE: u32 = 30; |
| 38 | pub const DEFAULT_LOGINS_PER_MINUTE: u32 = 10; | 38 | pub const DEFAULT_LOGINS_PER_MINUTE: u32 = 10; |
| 39 | +pub const VIDEO_FRAGMENT_BYTES: usize = 1100; | ||
| 40 | +pub const MAXIMUM_SHARE_LAYERS: usize = 4; | ||
| 41 | +pub const SHARE_AUDIO_BITRATE: i32 = 128_000; | ||
| 42 | +pub const SHARE_AUDIO_CHANNELS: usize = 2; | ||
crates/common/src/datagram.rsadded+216 -0
| @@ -0,0 +1,216 @@ | |||
| 1 | +use uuid::Uuid; | ||
| 2 | + | ||
| 3 | +use crate::{ | ||
| 4 | + constant::{VIDEO_FRAGMENT_BYTES, VOICE_MAX_PAYLOAD}, | ||
| 5 | + share::Layer, | ||
| 6 | +}; | ||
| 7 | + | ||
| 8 | +const USER_ID_LENGTH: usize = 16; | ||
| 9 | + | ||
| 10 | +#[repr(u8)] | ||
| 11 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 12 | +enum Tag { | ||
| 13 | + Voice = 0, | ||
| 14 | + Video = 1, | ||
| 15 | + ShareAudio = 2, | ||
| 16 | +} | ||
| 17 | + | ||
| 18 | +impl Tag { | ||
| 19 | + fn parse(byte: u8) -> Option<Self> { | ||
| 20 | + match byte { | ||
| 21 | + 0 => Some(Self::Voice), | ||
| 22 | + 1 => Some(Self::Video), | ||
| 23 | + 2 => Some(Self::ShareAudio), | ||
| 24 | + _ => None, | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 30 | +pub struct Fragment<'a> { | ||
| 31 | + pub layer: Layer, | ||
| 32 | + pub frame: u32, | ||
| 33 | + pub index: u16, | ||
| 34 | + pub count: u16, | ||
| 35 | + pub keyframe: bool, | ||
| 36 | + pub timestamp_ms: u32, | ||
| 37 | + pub payload: &'a [u8], | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 41 | +pub enum Datagram<'a> { | ||
| 42 | + Voice { | ||
| 43 | + sequence: u32, | ||
| 44 | + payload: &'a [u8], | ||
| 45 | + }, | ||
| 46 | + Video(Fragment<'a>), | ||
| 47 | + ShareAudio { | ||
| 48 | + sequence: u32, | ||
| 49 | + timestamp_ms: u32, | ||
| 50 | + payload: &'a [u8], | ||
| 51 | + }, | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +impl<'a> Datagram<'a> { | ||
| 55 | + pub fn encode(&self) -> Vec<u8> { | ||
| 56 | + let mut bytes = Vec::new(); | ||
| 57 | + match self { | ||
| 58 | + Self::Voice { sequence, payload } => { | ||
| 59 | + bytes.push(Tag::Voice as u8); | ||
| 60 | + bytes.extend_from_slice(&sequence.to_be_bytes()); | ||
| 61 | + bytes.extend_from_slice(payload); | ||
| 62 | + } | ||
| 63 | + Self::Video(fragment) => { | ||
| 64 | + bytes.push(Tag::Video as u8); | ||
| 65 | + bytes.push(fragment.layer.to_byte()); | ||
| 66 | + bytes.extend_from_slice(&fragment.frame.to_be_bytes()); | ||
| 67 | + bytes.extend_from_slice(&fragment.index.to_be_bytes()); | ||
| 68 | + bytes.extend_from_slice(&fragment.count.to_be_bytes()); | ||
| 69 | + bytes.push(fragment.keyframe as u8); | ||
| 70 | + bytes.extend_from_slice(&fragment.timestamp_ms.to_be_bytes()); | ||
| 71 | + bytes.extend_from_slice(fragment.payload); | ||
| 72 | + } | ||
| 73 | + Self::ShareAudio { | ||
| 74 | + sequence, | ||
| 75 | + timestamp_ms, | ||
| 76 | + payload, | ||
| 77 | + } => { | ||
| 78 | + bytes.push(Tag::ShareAudio as u8); | ||
| 79 | + bytes.extend_from_slice(&sequence.to_be_bytes()); | ||
| 80 | + bytes.extend_from_slice(×tamp_ms.to_be_bytes()); | ||
| 81 | + bytes.extend_from_slice(payload); | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + bytes | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + pub fn decode(bytes: &'a [u8]) -> Option<Self> { | ||
| 88 | + let (tag, rest) = bytes.split_first()?; | ||
| 89 | + let datagram = match Tag::parse(*tag)? { | ||
| 90 | + Tag::Voice => { | ||
| 91 | + let (sequence, payload) = rest.split_first_chunk::<4>()?; | ||
| 92 | + Self::Voice { | ||
| 93 | + sequence: u32::from_be_bytes(*sequence), | ||
| 94 | + payload, | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + Tag::Video => { | ||
| 98 | + let (layer, rest) = rest.split_first()?; | ||
| 99 | + let (frame, rest) = rest.split_first_chunk::<4>()?; | ||
| 100 | + let (index, rest) = rest.split_first_chunk::<2>()?; | ||
| 101 | + let (count, rest) = rest.split_first_chunk::<2>()?; | ||
| 102 | + let (keyframe, rest) = rest.split_first()?; | ||
| 103 | + let (timestamp_ms, payload) = rest.split_first_chunk::<4>()?; | ||
| 104 | + let fragment = Fragment { | ||
| 105 | + layer: Layer::from_byte(*layer)?, | ||
| 106 | + frame: u32::from_be_bytes(*frame), | ||
| 107 | + index: u16::from_be_bytes(*index), | ||
| 108 | + count: u16::from_be_bytes(*count), | ||
| 109 | + keyframe: *keyframe != 0, | ||
| 110 | + timestamp_ms: u32::from_be_bytes(*timestamp_ms), | ||
| 111 | + payload, | ||
| 112 | + }; | ||
| 113 | + if fragment.index >= fragment.count { | ||
| 114 | + return None; | ||
| 115 | + } | ||
| 116 | + Self::Video(fragment) | ||
| 117 | + } | ||
| 118 | + Tag::ShareAudio => { | ||
| 119 | + let (sequence, rest) = rest.split_first_chunk::<4>()?; | ||
| 120 | + let (timestamp_ms, payload) = rest.split_first_chunk::<4>()?; | ||
| 121 | + Self::ShareAudio { | ||
| 122 | + sequence: u32::from_be_bytes(*sequence), | ||
| 123 | + timestamp_ms: u32::from_be_bytes(*timestamp_ms), | ||
| 124 | + payload, | ||
| 125 | + } | ||
| 126 | + } | ||
| 127 | + }; | ||
| 128 | + let limit = match datagram { | ||
| 129 | + Self::Voice { .. } | Self::ShareAudio { .. } => VOICE_MAX_PAYLOAD, | ||
| 130 | + Self::Video(_) => VIDEO_FRAGMENT_BYTES, | ||
| 131 | + }; | ||
| 132 | + (datagram.payload().len() <= limit).then_some(datagram) | ||
| 133 | + } | ||
| 134 | + | ||
| 135 | + pub fn payload(&self) -> &'a [u8] { | ||
| 136 | + match self { | ||
| 137 | + Self::Voice { payload, .. } | Self::ShareAudio { payload, .. } => payload, | ||
| 138 | + Self::Video(fragment) => fragment.payload, | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | +} | ||
| 142 | + | ||
| 143 | +pub fn fragments( | ||
| 144 | + layer: Layer, | ||
| 145 | + frame: u32, | ||
| 146 | + keyframe: bool, | ||
| 147 | + timestamp_ms: u32, | ||
| 148 | + data: &[u8], | ||
| 149 | +) -> Vec<Vec<u8>> { | ||
| 150 | + let chunks: Vec<&[u8]> = data.chunks(VIDEO_FRAGMENT_BYTES).collect(); | ||
| 151 | + let count = chunks.len() as u16; | ||
| 152 | + chunks | ||
| 153 | + .into_iter() | ||
| 154 | + .enumerate() | ||
| 155 | + .map(|(index, payload)| { | ||
| 156 | + Datagram::Video(Fragment { | ||
| 157 | + layer, | ||
| 158 | + frame, | ||
| 159 | + index: index as u16, | ||
| 160 | + count, | ||
| 161 | + keyframe, | ||
| 162 | + timestamp_ms, | ||
| 163 | + payload, | ||
| 164 | + }) | ||
| 165 | + .encode() | ||
| 166 | + }) | ||
| 167 | + .collect() | ||
| 168 | +} | ||
| 169 | + | ||
| 170 | +pub fn encode_relay(user_id: &str, packet: &[u8]) -> Option<Vec<u8>> { | ||
| 171 | + let user_id = Uuid::parse_str(user_id).ok()?; | ||
| 172 | + let mut bytes = user_id.as_bytes().to_vec(); | ||
| 173 | + bytes.extend_from_slice(packet); | ||
| 174 | + | ||
| 175 | + Some(bytes) | ||
| 176 | +} | ||
| 177 | + | ||
| 178 | +pub fn decode_relay(bytes: &[u8]) -> Option<(String, Datagram<'_>)> { | ||
| 179 | + let user_id = Uuid::from_slice(bytes.get(..USER_ID_LENGTH)?).ok()?; | ||
| 180 | + | ||
| 181 | + Some(( | ||
| 182 | + user_id.to_string(), | ||
| 183 | + Datagram::decode(&bytes[USER_ID_LENGTH..])?, | ||
| 184 | + )) | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +#[cfg(test)] | ||
| 188 | +mod tests { | ||
| 189 | + use super::*; | ||
| 190 | + use crate::share::{Codec, Fps, Quality, Resolution}; | ||
| 191 | + | ||
| 192 | + #[test] | ||
| 193 | + fn relay_round_trip() { | ||
| 194 | + let user_id = Uuid::now_v7().to_string(); | ||
| 195 | + let layer = Layer { | ||
| 196 | + quality: Quality { | ||
| 197 | + resolution: Resolution::P1080, | ||
| 198 | + fps: Fps::F60, | ||
| 199 | + }, | ||
| 200 | + codec: Codec::Av1, | ||
| 201 | + }; | ||
| 202 | + let data = vec![7u8; VIDEO_FRAGMENT_BYTES + 5]; | ||
| 203 | + let packets = fragments(layer, 3, true, 99, &data); | ||
| 204 | + assert_eq!(packets.len(), 2); | ||
| 205 | + | ||
| 206 | + let relay = encode_relay(&user_id, &packets[1]).unwrap(); | ||
| 207 | + let (decoded_id, datagram) = decode_relay(&relay).unwrap(); | ||
| 208 | + assert_eq!(decoded_id, user_id); | ||
| 209 | + let Datagram::Video(fragment) = datagram else { | ||
| 210 | + panic!("not video"); | ||
| 211 | + }; | ||
| 212 | + assert_eq!(fragment.layer, layer); | ||
| 213 | + assert_eq!((fragment.index, fragment.count), (1, 2)); | ||
| 214 | + assert_eq!(fragment.payload.len(), 5); | ||
| 215 | + } | ||
| 216 | +} | ||
crates/common/src/event.rsmodified+14 -1
| @@ -3,6 +3,7 @@ use bitcode::{Decode, Encode}; | |||
| 3 | use crate::model::{ | 3 | use crate::model::{ |
| 4 | Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, User, | 4 | Community, Friends, Invitation, Member, Message, Presence, Rank, Sanction, User, |
| 5 | }; | 5 | }; |
| 6 | +use crate::share::{Layer, Share}; | ||
| 6 | 7 | ||
| 7 | #[derive(Debug, Clone, Encode, Decode)] | 8 | #[derive(Debug, Clone, Encode, Decode)] |
| 8 | pub enum Event { | 9 | pub enum Event { |
| @@ -63,6 +64,16 @@ pub enum Event { | |||
| 63 | community_id: String, | 64 | community_id: String, |
| 64 | user_id: String, | 65 | user_id: String, |
| 65 | }, | 66 | }, |
| 67 | + ShareStarted { | ||
| 68 | + community_id: String, | ||
| 69 | + share: Share, | ||
| 70 | + }, | ||
| 71 | + ShareStopped { | ||
| 72 | + community_id: String, | ||
| 73 | + user_id: String, | ||
| 74 | + }, | ||
| 75 | + ShareLayers(Vec<Layer>), | ||
| 76 | + KeyframeWanted(Layer), | ||
| 66 | } | 77 | } |
| 67 | 78 | ||
| 68 | impl Event { | 79 | impl Event { |
| @@ -76,7 +87,9 @@ impl Event { | |||
| 76 | | Self::MemberLeft { community_id, .. } | 87 | | Self::MemberLeft { community_id, .. } |
| 77 | | Self::RankChanged { community_id, .. } | 88 | | Self::RankChanged { community_id, .. } |
| 78 | | Self::VoiceJoined { community_id, .. } | 89 | | Self::VoiceJoined { community_id, .. } |
| 79 | - | Self::VoiceLeft { community_id, .. } => Some(community_id), | 90 | + | Self::VoiceLeft { community_id, .. } |
| 91 | + | Self::ShareStarted { community_id, .. } | ||
| 92 | + | Self::ShareStopped { community_id, .. } => Some(community_id), | ||
| 80 | _ => None, | 93 | _ => None, |
| 81 | } | 94 | } |
| 82 | } | 95 | } |
crates/common/src/lib.rsmodified+2 -1
| @@ -1,5 +1,6 @@ | |||
| 1 | pub mod config; | 1 | pub mod config; |
| 2 | pub mod constant; | 2 | pub mod constant; |
| 3 | +pub mod datagram; | ||
| 3 | pub mod error; | 4 | pub mod error; |
| 4 | pub mod event; | 5 | pub mod event; |
| 5 | pub mod model; | 6 | pub mod model; |
| @@ -7,6 +8,6 @@ pub mod network; | |||
| 7 | pub mod permission; | 8 | pub mod permission; |
| 8 | pub mod request; | 9 | pub mod request; |
| 9 | pub mod response; | 10 | pub mod response; |
| 11 | +pub mod share; | ||
| 10 | pub mod time; | 12 | pub mod time; |
| 11 | pub mod validate; | 13 | pub mod validate; |
| 12 | -pub mod voice; | ||
crates/common/src/permission.rsmodified+4 -0
| @@ -19,6 +19,10 @@ pub fn can_join_voice(actor: Option<Rank>) -> bool { | |||
| 19 | actor.is_some() | 19 | actor.is_some() |
| 20 | } | 20 | } |
| 21 | 21 | ||
| 22 | +pub fn can_share(actor: Option<Rank>) -> bool { | ||
| 23 | + actor.is_some() | ||
| 24 | +} | ||
| 25 | + | ||
| 22 | pub fn can_post(actor: Option<Rank>) -> bool { | 26 | pub fn can_post(actor: Option<Rank>) -> bool { |
| 23 | actor.is_some() | 27 | actor.is_some() |
| 24 | } | 28 | } |
crates/common/src/request.rsmodified+22 -1
| @@ -1,6 +1,9 @@ | |||
| 1 | use bitcode::{Decode, Encode}; | 1 | use bitcode::{Decode, Encode}; |
| 2 | 2 | ||
| 3 | -use crate::model::{BanScope, Presence, Rank, ReportStatus, Role, ServerSettings}; | 3 | +use crate::{ |
| 4 | + model::{BanScope, Presence, Rank, ReportStatus, Role, ServerSettings}, | ||
| 5 | + share::{Codec, Quality, Source}, | ||
| 6 | +}; | ||
| 4 | 7 | ||
| 5 | #[derive(Debug, Clone, Encode, Decode)] | 8 | #[derive(Debug, Clone, Encode, Decode)] |
| 6 | pub struct UploadHeader { | 9 | pub struct UploadHeader { |
| @@ -157,6 +160,24 @@ pub enum Request { | |||
| 157 | community_id: String, | 160 | community_id: String, |
| 158 | }, | 161 | }, |
| 159 | LeaveVoice, | 162 | LeaveVoice, |
| 163 | + StartShare { | ||
| 164 | + source: Source, | ||
| 165 | + }, | ||
| 166 | + StopShare, | ||
| 167 | + Shares { | ||
| 168 | + community_id: String, | ||
| 169 | + }, | ||
| 170 | + WatchShare { | ||
| 171 | + user_id: String, | ||
| 172 | + quality: Quality, | ||
| 173 | + decode: Vec<Codec>, | ||
| 174 | + }, | ||
| 175 | + UnwatchShare { | ||
| 176 | + user_id: String, | ||
| 177 | + }, | ||
| 178 | + RequestKeyframe { | ||
| 179 | + user_id: String, | ||
| 180 | + }, | ||
| 160 | DeclineCall { | 181 | DeclineCall { |
| 161 | community_id: String, | 182 | community_id: String, |
| 162 | }, | 183 | }, |
crates/common/src/response.rsmodified+2 -0
| @@ -8,6 +8,7 @@ use crate::{ | |||
| 8 | Member, Message, MessageHit, Overview, Presence, Report, ServerBan, ServerSettings, | 8 | Member, Message, MessageHit, Overview, Presence, Report, ServerBan, ServerSettings, |
| 9 | SessionInfo, Unread, Usage, User, VoiceRoom, | 9 | SessionInfo, Unread, Usage, User, VoiceRoom, |
| 10 | }, | 10 | }, |
| 11 | + share::Share, | ||
| 11 | }; | 12 | }; |
| 12 | 13 | ||
| 13 | #[derive(Debug, Clone, Encode, Decode)] | 14 | #[derive(Debug, Clone, Encode, Decode)] |
| @@ -27,6 +28,7 @@ pub enum Response { | |||
| 27 | Unreads(Vec<Unread>), | 28 | Unreads(Vec<Unread>), |
| 28 | Attachment(Attachment), | 29 | Attachment(Attachment), |
| 29 | Voice(Vec<String>), | 30 | Voice(Vec<String>), |
| 31 | + Shares(Vec<Share>), | ||
| 30 | Friends(Friends), | 32 | Friends(Friends), |
| 31 | Invitations(Vec<Invitation>), | 33 | Invitations(Vec<Invitation>), |
| 32 | Done, | 34 | Done, |
crates/common/src/share.rsadded+243 -0
| @@ -0,0 +1,243 @@ | |||
| 1 | +use bitcode::{Decode, Encode}; | ||
| 2 | + | ||
| 3 | +use crate::constant::MAXIMUM_SHARE_LAYERS; | ||
| 4 | + | ||
| 5 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] | ||
| 6 | +pub enum Codec { | ||
| 7 | + H264, | ||
| 8 | + H265, | ||
| 9 | + Av1, | ||
| 10 | + Vp8, | ||
| 11 | + Vp9, | ||
| 12 | +} | ||
| 13 | + | ||
| 14 | +impl Codec { | ||
| 15 | + pub const ALL: [Self; 5] = [Self::H264, Self::H265, Self::Av1, Self::Vp8, Self::Vp9]; | ||
| 16 | + pub const PREFERENCE: [Self; 3] = [Self::Av1, Self::H265, Self::H264]; | ||
| 17 | + | ||
| 18 | + pub fn name(self) -> &'static str { | ||
| 19 | + match self { | ||
| 20 | + Self::H264 => "H264", | ||
| 21 | + Self::H265 => "H265", | ||
| 22 | + Self::Av1 => "AV1", | ||
| 23 | + Self::Vp8 => "VP8", | ||
| 24 | + Self::Vp9 => "VP9", | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + pub fn parse(name: &str) -> Option<Self> { | ||
| 29 | + Self::ALL.into_iter().find(|codec| codec.name() == name) | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + pub fn bits_per_pixel(self) -> f32 { | ||
| 33 | + match self { | ||
| 34 | + Self::H264 | Self::Vp8 => 0.1, | ||
| 35 | + Self::H265 | Self::Vp9 => 0.07, | ||
| 36 | + Self::Av1 => 0.06, | ||
| 37 | + } | ||
| 38 | + } | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] | ||
| 42 | +pub enum Resolution { | ||
| 43 | + P360, | ||
| 44 | + P480, | ||
| 45 | + P720, | ||
| 46 | + P1080, | ||
| 47 | + P1440, | ||
| 48 | + P2160, | ||
| 49 | +} | ||
| 50 | + | ||
| 51 | +impl Resolution { | ||
| 52 | + pub const ALL: [Self; 6] = [ | ||
| 53 | + Self::P360, | ||
| 54 | + Self::P480, | ||
| 55 | + Self::P720, | ||
| 56 | + Self::P1080, | ||
| 57 | + Self::P1440, | ||
| 58 | + Self::P2160, | ||
| 59 | + ]; | ||
| 60 | + | ||
| 61 | + pub fn height(self) -> u32 { | ||
| 62 | + match self { | ||
| 63 | + Self::P360 => 360, | ||
| 64 | + Self::P480 => 480, | ||
| 65 | + Self::P720 => 720, | ||
| 66 | + Self::P1080 => 1080, | ||
| 67 | + Self::P1440 => 1440, | ||
| 68 | + Self::P2160 => 2160, | ||
| 69 | + } | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + pub fn size(self, source_width: u32, source_height: u32) -> (u32, u32) { | ||
| 73 | + let height = self.height().min(source_height); | ||
| 74 | + let width = (source_width as u64 * height as u64 / source_height.max(1) as u64) as u32; | ||
| 75 | + (width & !1, height & !1) | ||
| 76 | + } | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] | ||
| 80 | +pub enum Fps { | ||
| 81 | + F15, | ||
| 82 | + F30, | ||
| 83 | + F60, | ||
| 84 | +} | ||
| 85 | + | ||
| 86 | +impl Fps { | ||
| 87 | + pub const ALL: [Self; 3] = [Self::F15, Self::F30, Self::F60]; | ||
| 88 | + | ||
| 89 | + pub fn value(self) -> u32 { | ||
| 90 | + match self { | ||
| 91 | + Self::F15 => 15, | ||
| 92 | + Self::F30 => 30, | ||
| 93 | + Self::F60 => 60, | ||
| 94 | + } | ||
| 95 | + } | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] | ||
| 99 | +pub struct Quality { | ||
| 100 | + pub resolution: Resolution, | ||
| 101 | + pub fps: Fps, | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)] | ||
| 105 | +pub struct Layer { | ||
| 106 | + pub quality: Quality, | ||
| 107 | + pub codec: Codec, | ||
| 108 | +} | ||
| 109 | + | ||
| 110 | +impl Layer { | ||
| 111 | + pub fn to_byte(self) -> u8 { | ||
| 112 | + (self.quality.resolution as u8) << 5 | (self.quality.fps as u8) << 3 | self.codec as u8 | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + pub fn from_byte(byte: u8) -> Option<Self> { | ||
| 116 | + Some(Self { | ||
| 117 | + quality: Quality { | ||
| 118 | + resolution: *Resolution::ALL.get((byte >> 5) as usize)?, | ||
| 119 | + fps: *Fps::ALL.get((byte >> 3 & 0b11) as usize)?, | ||
| 120 | + }, | ||
| 121 | + codec: *Codec::ALL.get((byte & 0b111) as usize)?, | ||
| 122 | + }) | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + pub fn bitrate(self, source_width: u32, source_height: u32) -> u32 { | ||
| 126 | + let (width, height) = self.quality.resolution.size(source_width, source_height); | ||
| 127 | + (width as f32 | ||
| 128 | + * height as f32 | ||
| 129 | + * self.quality.fps.value() as f32 | ||
| 130 | + * self.codec.bits_per_pixel()) as u32 | ||
| 131 | + } | ||
| 132 | +} | ||
| 133 | + | ||
| 134 | +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | ||
| 135 | +pub struct Source { | ||
| 136 | + pub width: u32, | ||
| 137 | + pub height: u32, | ||
| 138 | + pub top: Quality, | ||
| 139 | + pub encode: Vec<Codec>, | ||
| 140 | +} | ||
| 141 | + | ||
| 142 | +#[derive(Debug, Clone, PartialEq, Eq, Encode, Decode)] | ||
| 143 | +pub struct Share { | ||
| 144 | + pub user_id: String, | ||
| 145 | + pub source: Source, | ||
| 146 | +} | ||
| 147 | + | ||
| 148 | +pub fn options(source_height: u32, refresh: u32, max_height: u32) -> (Vec<Resolution>, Vec<Fps>) { | ||
| 149 | + let resolutions = Resolution::ALL | ||
| 150 | + .into_iter() | ||
| 151 | + .filter(|resolution| resolution.height() <= source_height.min(max_height)) | ||
| 152 | + .collect(); | ||
| 153 | + let fps = Fps::ALL | ||
| 154 | + .into_iter() | ||
| 155 | + .filter(|fps| fps.value() <= refresh) | ||
| 156 | + .collect(); | ||
| 157 | + (resolutions, fps) | ||
| 158 | +} | ||
| 159 | + | ||
| 160 | +pub fn ladder(top: Quality) -> Vec<Quality> { | ||
| 161 | + let rungs = [ | ||
| 162 | + top, | ||
| 163 | + Quality { | ||
| 164 | + resolution: Resolution::P720, | ||
| 165 | + fps: Fps::F30, | ||
| 166 | + }, | ||
| 167 | + Quality { | ||
| 168 | + resolution: Resolution::P360, | ||
| 169 | + fps: Fps::F15, | ||
| 170 | + }, | ||
| 171 | + ]; | ||
| 172 | + let mut ladder: Vec<Quality> = rungs | ||
| 173 | + .into_iter() | ||
| 174 | + .filter(|rung| rung.resolution <= top.resolution && rung.fps <= top.fps) | ||
| 175 | + .collect(); | ||
| 176 | + ladder.dedup(); | ||
| 177 | + ladder | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +pub fn best_codec(encode: &[Codec], decode: &[Codec]) -> Option<Codec> { | ||
| 181 | + Codec::PREFERENCE | ||
| 182 | + .into_iter() | ||
| 183 | + .find(|codec| encode.contains(codec) && decode.contains(codec)) | ||
| 184 | +} | ||
| 185 | + | ||
| 186 | +pub fn choose(source: &Source, wanted: Quality, decode: &[Codec], used: &[Layer]) -> Option<Layer> { | ||
| 187 | + let codec = best_codec(&source.encode, decode)?; | ||
| 188 | + let quality = Quality { | ||
| 189 | + resolution: wanted.resolution.min(source.top.resolution), | ||
| 190 | + fps: wanted.fps.min(source.top.fps), | ||
| 191 | + }; | ||
| 192 | + let layer = Layer { quality, codec }; | ||
| 193 | + if used.len() < MAXIMUM_SHARE_LAYERS || used.contains(&layer) { | ||
| 194 | + return Some(layer); | ||
| 195 | + } | ||
| 196 | + used.iter() | ||
| 197 | + .copied() | ||
| 198 | + .filter(|used| used.quality <= quality && decode.contains(&used.codec)) | ||
| 199 | + .max() | ||
| 200 | + .or_else(|| { | ||
| 201 | + used.iter() | ||
| 202 | + .copied() | ||
| 203 | + .filter(|used| decode.contains(&used.codec)) | ||
| 204 | + .min() | ||
| 205 | + }) | ||
| 206 | +} | ||
| 207 | + | ||
| 208 | +#[cfg(test)] | ||
| 209 | +mod tests { | ||
| 210 | + use super::*; | ||
| 211 | + | ||
| 212 | + #[test] | ||
| 213 | + fn layer_byte_round_trip_and_choice() { | ||
| 214 | + for resolution in Resolution::ALL { | ||
| 215 | + for fps in Fps::ALL { | ||
| 216 | + for codec in Codec::ALL { | ||
| 217 | + let layer = Layer { | ||
| 218 | + quality: Quality { resolution, fps }, | ||
| 219 | + codec, | ||
| 220 | + }; | ||
| 221 | + assert_eq!(Layer::from_byte(layer.to_byte()), Some(layer)); | ||
| 222 | + } | ||
| 223 | + } | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + let source = Source { | ||
| 227 | + width: 2560, | ||
| 228 | + height: 1440, | ||
| 229 | + top: Quality { | ||
| 230 | + resolution: Resolution::P1440, | ||
| 231 | + fps: Fps::F60, | ||
| 232 | + }, | ||
| 233 | + encode: vec![Codec::H264, Codec::Av1], | ||
| 234 | + }; | ||
| 235 | + let wanted = Quality { | ||
| 236 | + resolution: Resolution::P1080, | ||
| 237 | + fps: Fps::F60, | ||
| 238 | + }; | ||
| 239 | + let layer = choose(&source, wanted, &[Codec::H264, Codec::H265], &[]).unwrap(); | ||
| 240 | + assert_eq!(layer.quality.resolution, Resolution::P1080); | ||
| 241 | + assert_eq!(layer.codec, Codec::H264); | ||
| 242 | + } | ||
| 243 | +} | ||
crates/common/src/voice.rsdeleted+0 -54
| @@ -1,54 +0,0 @@ | |||
| 1 | -use uuid::Uuid; | ||
| 2 | - | ||
| 3 | -use crate::constant::VOICE_MAX_PAYLOAD; | ||
| 4 | - | ||
| 5 | -pub const SEQUENCE_LENGTH: usize = 4; | ||
| 6 | -const USER_ID_LENGTH: usize = 16; | ||
| 7 | - | ||
| 8 | -pub fn encode_packet(sequence: u32, payload: &[u8]) -> Vec<u8> { | ||
| 9 | - let mut bytes = sequence.to_be_bytes().to_vec(); | ||
| 10 | - bytes.extend_from_slice(payload); | ||
| 11 | - bytes | ||
| 12 | -} | ||
| 13 | - | ||
| 14 | -pub fn decode_packet(bytes: &[u8]) -> Option<(u32, &[u8])> { | ||
| 15 | - if bytes.len() < SEQUENCE_LENGTH || bytes.len() - SEQUENCE_LENGTH > VOICE_MAX_PAYLOAD { | ||
| 16 | - return None; | ||
| 17 | - } | ||
| 18 | - let sequence = u32::from_be_bytes(bytes[..SEQUENCE_LENGTH].try_into().ok()?); | ||
| 19 | - | ||
| 20 | - Some((sequence, &bytes[SEQUENCE_LENGTH..])) | ||
| 21 | -} | ||
| 22 | - | ||
| 23 | -pub fn encode_relay(user_id: &str, packet: &[u8]) -> Option<Vec<u8>> { | ||
| 24 | - let user_id = Uuid::parse_str(user_id).ok()?; | ||
| 25 | - let mut bytes = user_id.as_bytes().to_vec(); | ||
| 26 | - bytes.extend_from_slice(packet); | ||
| 27 | - | ||
| 28 | - Some(bytes) | ||
| 29 | -} | ||
| 30 | - | ||
| 31 | -pub fn decode_relay(bytes: &[u8]) -> Option<(String, u32, &[u8])> { | ||
| 32 | - let user_id = Uuid::from_slice(bytes.get(..USER_ID_LENGTH)?).ok()?; | ||
| 33 | - let (sequence, payload) = decode_packet(&bytes[USER_ID_LENGTH..])?; | ||
| 34 | - | ||
| 35 | - Some((user_id.to_string(), sequence, payload)) | ||
| 36 | -} | ||
| 37 | - | ||
| 38 | -#[cfg(test)] | ||
| 39 | -mod tests { | ||
| 40 | - use super::*; | ||
| 41 | - | ||
| 42 | - #[test] | ||
| 43 | - fn relay_round_trip() { | ||
| 44 | - let user_id = Uuid::now_v7().to_string(); | ||
| 45 | - let packet = encode_packet(7, &[1, 2, 3]); | ||
| 46 | - let relay = encode_relay(&user_id, &packet).unwrap(); | ||
| 47 | - | ||
| 48 | - let (decoded_id, sequence, payload) = decode_relay(&relay).unwrap(); | ||
| 49 | - | ||
| 50 | - assert_eq!(decoded_id, user_id); | ||
| 51 | - assert_eq!(sequence, 7); | ||
| 52 | - assert_eq!(payload, &[1, 2, 3]); | ||
| 53 | - } | ||
| 54 | -} | ||
crates/server/src/lib.rsmodified+1 -0
| @@ -21,6 +21,7 @@ pub mod request; | |||
| 21 | pub mod retention; | 21 | pub mod retention; |
| 22 | pub mod server_ban; | 22 | pub mod server_ban; |
| 23 | pub mod server_settings; | 23 | pub mod server_settings; |
| 24 | +pub mod share; | ||
| 24 | pub mod stats; | 25 | pub mod stats; |
| 25 | pub mod user; | 26 | pub mod user; |
| 26 | pub mod user_community; | 27 | pub mod user_community; |
crates/server/src/network.rsmodified+14 -6
| @@ -24,6 +24,7 @@ use crate::{ | |||
| 24 | rate_limit::RateLimit, | 24 | rate_limit::RateLimit, |
| 25 | request::{self, Broadcast}, | 25 | request::{self, Broadcast}, |
| 26 | server_ban, | 26 | server_ban, |
| 27 | + share::Shares, | ||
| 27 | voice::Voice, | 28 | voice::Voice, |
| 28 | }; | 29 | }; |
| 29 | 30 | ||
| @@ -86,6 +87,7 @@ impl Visits { | |||
| 86 | #[derive(Clone, Default)] | 87 | #[derive(Clone, Default)] |
| 87 | pub struct Services { | 88 | pub struct Services { |
| 88 | pub voice: Voice, | 89 | pub voice: Voice, |
| 90 | + pub share: Shares, | ||
| 89 | pub presence: Presence, | 91 | pub presence: Presence, |
| 90 | pub rate_limit: RateLimit, | 92 | pub rate_limit: RateLimit, |
| 91 | pub visits: Visits, | 93 | pub visits: Visits, |
| @@ -248,7 +250,7 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 248 | tokio::spawn(relay_datagrams( | 250 | tokio::spawn(relay_datagrams( |
| 249 | connection.clone(), | 251 | connection.clone(), |
| 250 | Arc::clone(&state), | 252 | Arc::clone(&state), |
| 251 | - shared.services.voice.clone(), | 253 | + shared.clone(), |
| 252 | )); | 254 | )); |
| 253 | 255 | ||
| 254 | while let Ok(streams) = connection.accept_bi().await { | 256 | while let Ok(streams) = connection.accept_bi().await { |
| @@ -266,9 +268,13 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 266 | if let Some((user_id, token)) = signed_in(&state) { | 268 | if let Some((user_id, token)) = signed_in(&state) { |
| 267 | let conn = database::connect(&shared.db).await?; | 269 | let conn = database::connect(&shared.db).await?; |
| 268 | authentication::seen(&user_id, &token, &conn).await?; | 270 | authentication::seen(&user_id, &token, &conn).await?; |
| 269 | - let mut broadcasts = | 271 | + let mut broadcasts = request::leave_connection_voice( |
| 270 | - request::leave_connection_voice(&shared.services.voice, Some(&connection), &conn) | 272 | + &shared.services.voice, |
| 271 | - .await?; | 273 | + &shared.services.share, |
| 274 | + Some(&connection), | ||
| 275 | + &conn, | ||
| 276 | + ) | ||
| 277 | + .await?; | ||
| 272 | broadcasts | 278 | broadcasts |
| 273 | .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); | 279 | .extend(request::presence_changed(&shared.services.presence, &user_id, &conn).await?); |
| 274 | publish(&shared, broadcasts).await; | 280 | publish(&shared, broadcasts).await; |
| @@ -277,10 +283,12 @@ async fn serve_connection(incoming: Incoming, shared: Shared) -> Result<(), Erro | |||
| 277 | Ok(()) | 283 | Ok(()) |
| 278 | } | 284 | } |
| 279 | 285 | ||
| 280 | -async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, voice: Voice) { | 286 | +async fn relay_datagrams(connection: Connection, state: Arc<Mutex<State>>, shared: Shared) { |
| 281 | while let Ok(bytes) = connection.read_datagram().await { | 287 | while let Ok(bytes) = connection.read_datagram().await { |
| 282 | if signed_user_id(&state).is_some() { | 288 | if signed_user_id(&state).is_some() { |
| 283 | - voice.relay(connection.stable_id(), &bytes); | 289 | + shared.services.voice.relay(connection.stable_id(), &bytes); |
| 290 | + let broadcasts = shared.services.share.relay(connection.stable_id(), &bytes); | ||
| 291 | + publish(&shared, broadcasts).await; | ||
| 284 | } | 292 | } |
| 285 | } | 293 | } |
| 286 | } | 294 | } |
crates/server/src/request.rsmodified+134 -24
| @@ -14,6 +14,7 @@ use common::{ | |||
| 14 | permission, | 14 | permission, |
| 15 | request::Request, | 15 | request::Request, |
| 16 | response::Response, | 16 | response::Response, |
| 17 | + share::Share, | ||
| 17 | time::{self, MINUTE_MILLIS}, | 18 | time::{self, MINUTE_MILLIS}, |
| 18 | validate::{ | 19 | validate::{ |
| 19 | validate_avatar_size, validate_forward, validate_message_body, validate_new_message, | 20 | validate_avatar_size, validate_forward, validate_message_body, validate_new_message, |
| @@ -31,7 +32,9 @@ use crate::{ | |||
| 31 | network::{self, Services, State}, | 32 | network::{self, Services, State}, |
| 32 | notes, overview, | 33 | notes, overview, |
| 33 | rate_limit::RateLimit, | 34 | rate_limit::RateLimit, |
| 34 | - report, server_ban, server_settings, stats, user, user_community, | 35 | + report, server_ban, server_settings, |
| 36 | + share::Shares, | ||
| 37 | + stats, user, user_community, | ||
| 35 | voice::{CallEnd, Left, Voice}, | 38 | voice::{CallEnd, Left, Voice}, |
| 36 | }; | 39 | }; |
| 37 | 40 | ||
| @@ -68,6 +71,7 @@ async fn dispatch( | |||
| 68 | ) -> Result<Outcome, Error> { | 71 | ) -> Result<Outcome, Error> { |
| 69 | let Services { | 72 | let Services { |
| 70 | voice, | 73 | voice, |
| 74 | + share, | ||
| 71 | presence, | 75 | presence, |
| 72 | rate_limit, | 76 | rate_limit, |
| 73 | visits, | 77 | visits, |
| @@ -84,7 +88,7 @@ async fn dispatch( | |||
| 84 | let (user, token) = | 88 | let (user, token) = |
| 85 | authentication::register(&username, &password, invite.as_deref(), &mut conn) | 89 | authentication::register(&username, &password, invite.as_deref(), &mut conn) |
| 86 | .await?; | 90 | .await?; |
| 87 | - let broadcasts = leave_connection_voice(voice, connection, &conn).await?; | 91 | + let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; |
| 88 | sign_in(state, user, token, broadcasts) | 92 | sign_in(state, user, token, broadcasts) |
| 89 | } | 93 | } |
| 90 | Request::Login { username, password } => { | 94 | Request::Login { username, password } => { |
| @@ -92,19 +96,19 @@ async fn dispatch( | |||
| 92 | let (user, token) = authentication::login(&username, &password, &conn).await?; | 96 | let (user, token) = authentication::login(&username, &password, &conn).await?; |
| 93 | stats::mark_active(&user.id, &conn).await?; | 97 | stats::mark_active(&user.id, &conn).await?; |
| 94 | record_address(&user, connection, &conn).await?; | 98 | record_address(&user, connection, &conn).await?; |
| 95 | - let broadcasts = leave_connection_voice(voice, connection, &conn).await?; | 99 | + let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; |
| 96 | sign_in(state, user, token, broadcasts) | 100 | sign_in(state, user, token, broadcasts) |
| 97 | } | 101 | } |
| 98 | Request::Resume { token } => { | 102 | Request::Resume { token } => { |
| 99 | let user = authentication::resume(&token, &conn).await?; | 103 | let user = authentication::resume(&token, &conn).await?; |
| 100 | stats::mark_active(&user.id, &conn).await?; | 104 | stats::mark_active(&user.id, &conn).await?; |
| 101 | record_address(&user, connection, &conn).await?; | 105 | record_address(&user, connection, &conn).await?; |
| 102 | - let broadcasts = leave_connection_voice(voice, connection, &conn).await?; | 106 | + let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; |
| 103 | sign_in(state, user, token, broadcasts) | 107 | sign_in(state, user, token, broadcasts) |
| 104 | } | 108 | } |
| 105 | Request::Detach => { | 109 | Request::Detach => { |
| 106 | authenticated(state, &conn).await?; | 110 | authenticated(state, &conn).await?; |
| 107 | - let broadcasts = leave_connection_voice(voice, connection, &conn).await?; | 111 | + let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; |
| 108 | set_state(state, State::Anonymous); | 112 | set_state(state, State::Anonymous); |
| 109 | (Response::Done, broadcasts) | 113 | (Response::Done, broadcasts) |
| 110 | } | 114 | } |
| @@ -112,7 +116,7 @@ async fn dispatch( | |||
| 112 | authenticated(state, &conn).await?; | 116 | authenticated(state, &conn).await?; |
| 113 | let token = session_token(state)?; | 117 | let token = session_token(state)?; |
| 114 | authentication::logout(&token, &conn).await?; | 118 | authentication::logout(&token, &conn).await?; |
| 115 | - let broadcasts = leave_connection_voice(voice, connection, &conn).await?; | 119 | + let broadcasts = leave_connection_voice(voice, share, connection, &conn).await?; |
| 116 | set_state(state, State::Anonymous); | 120 | set_state(state, State::Anonymous); |
| 117 | (Response::Done, broadcasts) | 121 | (Response::Done, broadcasts) |
| 118 | } | 122 | } |
| @@ -414,7 +418,7 @@ async fn dispatch( | |||
| 414 | } | 418 | } |
| 415 | for community_id in user_community::owned(&user_id, &tx).await? { | 419 | for community_id in user_community::owned(&user_id, &tx).await? { |
| 416 | let members = user_community::members(&community_id, &tx).await?; | 420 | let members = user_community::members(&community_id, &tx).await?; |
| 417 | - broadcasts.extend(voice_closed(voice, &community_id, &tx).await?); | 421 | + broadcasts.extend(voice_closed(voice, share, &community_id, &tx).await?); |
| 418 | community::delete(&community_id, &user_id, &tx).await?; | 422 | community::delete(&community_id, &user_id, &tx).await?; |
| 419 | let event = Event::CommunityDeleted { community_id }; | 423 | let event = Event::CommunityDeleted { community_id }; |
| 420 | broadcasts.push(broadcast(event, &members)); | 424 | broadcasts.push(broadcast(event, &members)); |
| @@ -429,7 +433,7 @@ async fn dispatch( | |||
| 429 | }; | 433 | }; |
| 430 | broadcasts.push(broadcast(event, &members)); | 434 | broadcasts.push(broadcast(event, &members)); |
| 431 | } | 435 | } |
| 432 | - broadcasts.extend(leave_user_voice(voice, &user_id, &tx).await?); | 436 | + broadcasts.extend(leave_user_voice(voice, share, &user_id, &tx).await?); |
| 433 | let deleted = user::delete(&user_id, &tx).await?; | 437 | let deleted = user::delete(&user_id, &tx).await?; |
| 434 | tx.commit().await?; | 438 | tx.commit().await?; |
| 435 | if me.id == user_id { | 439 | if me.id == user_id { |
| @@ -521,7 +525,7 @@ async fn dispatch( | |||
| 521 | .await?; | 525 | .await?; |
| 522 | } | 526 | } |
| 523 | tx.commit().await?; | 527 | tx.commit().await?; |
| 524 | - let mut broadcasts = voice_closed(voice, &community_id, &conn).await?; | 528 | + let mut broadcasts = voice_closed(voice, share, &community_id, &conn).await?; |
| 525 | let event = Event::CommunityDeleted { | 529 | let event = Event::CommunityDeleted { |
| 526 | community_id: deleted.id.clone(), | 530 | community_id: deleted.id.clone(), |
| 527 | }; | 531 | }; |
| @@ -540,7 +544,8 @@ async fn dispatch( | |||
| 540 | community::delete(&community_id, &me.id, &tx).await?; | 544 | community::delete(&community_id, &me.id, &tx).await?; |
| 541 | } | 545 | } |
| 542 | tx.commit().await?; | 546 | tx.commit().await?; |
| 543 | - let mut broadcasts = leave_room_voice(voice, &community_id, &me.id, &conn).await?; | 547 | + let mut broadcasts = |
| 548 | + leave_room_voice(voice, share, &community_id, &me.id, &conn).await?; | ||
| 544 | let event = Event::MemberLeft { | 549 | let event = Event::MemberLeft { |
| 545 | community_id, | 550 | community_id, |
| 546 | user_id: me.id, | 551 | user_id: me.id, |
| @@ -578,6 +583,7 @@ async fn dispatch( | |||
| 578 | sanction: Sanction::Kick, | 583 | sanction: Sanction::Kick, |
| 579 | }, | 584 | }, |
| 580 | voice, | 585 | voice, |
| 586 | + share, | ||
| 581 | &mut conn, | 587 | &mut conn, |
| 582 | ) | 588 | ) |
| 583 | .await? | 589 | .await? |
| @@ -597,6 +603,7 @@ async fn dispatch( | |||
| 597 | sanction: Sanction::Ban, | 603 | sanction: Sanction::Ban, |
| 598 | }, | 604 | }, |
| 599 | voice, | 605 | voice, |
| 606 | + share, | ||
| 600 | &mut conn, | 607 | &mut conn, |
| 601 | ) | 608 | ) |
| 602 | .await? | 609 | .await? |
| @@ -926,7 +933,7 @@ async fn dispatch( | |||
| 926 | && voice.participants(&community_id).is_empty(); | 933 | && voice.participants(&community_id).is_empty(); |
| 927 | let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost); | 934 | let joined = voice.join(&community_id, &me.id, connection.clone(), muted, ghost); |
| 928 | let mut broadcasts = match joined { | 935 | let mut broadcasts = match joined { |
| 929 | - Some(previous) => voice_left(previous, &conn).await?, | 936 | + Some(previous) => voice_left(share, previous, &conn).await?, |
| 930 | None => Vec::new(), | 937 | None => Vec::new(), |
| 931 | }; | 938 | }; |
| 932 | if starts_call { | 939 | if starts_call { |
| @@ -966,9 +973,71 @@ async fn dispatch( | |||
| 966 | authenticated(state, &conn).await?; | 973 | authenticated(state, &conn).await?; |
| 967 | ( | 974 | ( |
| 968 | Response::Done, | 975 | Response::Done, |
| 969 | - leave_connection_voice(voice, connection, &conn).await?, | 976 | + leave_connection_voice(voice, share, connection, &conn).await?, |
| 970 | ) | 977 | ) |
| 971 | } | 978 | } |
| 979 | + Request::StartShare { source } => { | ||
| 980 | + let me = authenticated(state, &conn).await?; | ||
| 981 | + let Some(community_id) = voice.room_of(&me.id) else { | ||
| 982 | + return Err(CommonError::NotFound.into()); | ||
| 983 | + }; | ||
| 984 | + allowed(&me, &community_id, &conn, permission::can_share).await?; | ||
| 985 | + ensure(!source.encode.is_empty())?; | ||
| 986 | + ensure(!user::is_ghost(&me.id, &conn).await?)?; | ||
| 987 | + let Some(connection) = connection else { | ||
| 988 | + return Err(CommonError::Server.into()); | ||
| 989 | + }; | ||
| 990 | + let members = user_community::members(&community_id, &conn).await?; | ||
| 991 | + share.start(&community_id, &me.id, connection.clone(), source.clone()); | ||
| 992 | + let event = Event::ShareStarted { | ||
| 993 | + community_id, | ||
| 994 | + share: Share { | ||
| 995 | + user_id: me.id.clone(), | ||
| 996 | + source, | ||
| 997 | + }, | ||
| 998 | + }; | ||
| 999 | + | ||
| 1000 | + (Response::Done, vec![broadcast(event, &members)]) | ||
| 1001 | + } | ||
| 1002 | + Request::StopShare => { | ||
| 1003 | + let me = authenticated(state, &conn).await?; | ||
| 1004 | + (Response::Done, share_stopped(share, &me.id, &conn).await?) | ||
| 1005 | + } | ||
| 1006 | + Request::Shares { community_id } => { | ||
| 1007 | + let me = authenticated(state, &conn).await?; | ||
| 1008 | + allowed(&me, &community_id, &conn, permission::can_read).await?; | ||
| 1009 | + (Response::Shares(share.list(&community_id)), Vec::new()) | ||
| 1010 | + } | ||
| 1011 | + Request::WatchShare { | ||
| 1012 | + user_id, | ||
| 1013 | + quality, | ||
| 1014 | + decode, | ||
| 1015 | + } => { | ||
| 1016 | + let me = authenticated(state, &conn).await?; | ||
| 1017 | + let Some(connection) = connection else { | ||
| 1018 | + return Err(CommonError::Server.into()); | ||
| 1019 | + }; | ||
| 1020 | + let room = voice.room_of(&me.id); | ||
| 1021 | + ensure(room.is_some() && room == voice.room_of(&user_id))?; | ||
| 1022 | + let broadcasts = share | ||
| 1023 | + .watch(&user_id, &me.id, connection.clone(), quality, &decode) | ||
| 1024 | + .ok_or(CommonError::NotFound)?; | ||
| 1025 | + | ||
| 1026 | + (Response::Done, broadcasts) | ||
| 1027 | + } | ||
| 1028 | + Request::UnwatchShare { user_id } => { | ||
| 1029 | + let me = authenticated(state, &conn).await?; | ||
| 1030 | + | ||
| 1031 | + (Response::Done, share.unwatch(&user_id, &me.id)) | ||
| 1032 | + } | ||
| 1033 | + Request::RequestKeyframe { user_id } => { | ||
| 1034 | + let me = authenticated(state, &conn).await?; | ||
| 1035 | + let keyframe = share | ||
| 1036 | + .keyframe(&user_id, &me.id) | ||
| 1037 | + .ok_or(CommonError::NotFound)?; | ||
| 1038 | + | ||
| 1039 | + (Response::Done, vec![keyframe]) | ||
| 1040 | + } | ||
| 972 | Request::DeclineCall { community_id } => { | 1041 | Request::DeclineCall { community_id } => { |
| 973 | let me = authenticated(state, &conn).await?; | 1042 | let me = authenticated(state, &conn).await?; |
| 974 | ensure(community::is_direct(&community_id, &conn).await?)?; | 1043 | ensure(community::is_direct(&community_id, &conn).await?)?; |
| @@ -1487,7 +1556,7 @@ async fn dispatch( | |||
| 1487 | Request::KickFromVoice { user_id } => { | 1556 | Request::KickFromVoice { user_id } => { |
| 1488 | let me = authenticated(state, &conn).await?; | 1557 | let me = authenticated(state, &conn).await?; |
| 1489 | managed(&me, &user_id, &conn).await?; | 1558 | managed(&me, &user_id, &conn).await?; |
| 1490 | - let broadcasts = leave_user_voice(voice, &user_id, &conn).await?; | 1559 | + let broadcasts = leave_user_voice(voice, share, &user_id, &conn).await?; |
| 1491 | if !broadcasts.is_empty() { | 1560 | if !broadcasts.is_empty() { |
| 1492 | admin_log::record( | 1561 | admin_log::record( |
| 1493 | Some(&me.id), | 1562 | Some(&me.id), |
| @@ -1552,7 +1621,7 @@ async fn dispatch( | |||
| 1552 | tx.commit().await?; | 1621 | tx.commit().await?; |
| 1553 | let mut broadcasts = Vec::new(); | 1622 | let mut broadcasts = Vec::new(); |
| 1554 | if !enabled { | 1623 | if !enabled { |
| 1555 | - broadcasts.extend(voice_silenced(voice, &community_id, &conn).await?); | 1624 | + broadcasts.extend(voice_silenced(voice, share, &community_id, &conn).await?); |
| 1556 | } | 1625 | } |
| 1557 | let event = Event::CommunityUpdated(updated.clone()); | 1626 | let event = Event::CommunityUpdated(updated.clone()); |
| 1558 | broadcasts.push(broadcast(event, &members)); | 1627 | broadcasts.push(broadcast(event, &members)); |
| @@ -1583,6 +1652,7 @@ async fn dispatch( | |||
| 1583 | { | 1652 | { |
| 1584 | let members = user_community::members(&community_id, &conn).await?; | 1653 | let members = user_community::members(&community_id, &conn).await?; |
| 1585 | if enabled { | 1654 | if enabled { |
| 1655 | + broadcasts.extend(share_left(share, &me.id, &conn).await?); | ||
| 1586 | broadcasts | 1656 | broadcasts |
| 1587 | .extend(call_ended(&community_id, &me.id, call, &members, &conn).await?); | 1657 | .extend(call_ended(&community_id, &me.id, call, &members, &conn).await?); |
| 1588 | broadcasts.push(Broadcast { | 1658 | broadcasts.push(Broadcast { |
| @@ -1693,6 +1763,7 @@ async fn remove_member( | |||
| 1693 | me: &User, | 1763 | me: &User, |
| 1694 | removal: Removal, | 1764 | removal: Removal, |
| 1695 | voice: &Voice, | 1765 | voice: &Voice, |
| 1766 | + share: &Shares, | ||
| 1696 | conn: &mut Connection, | 1767 | conn: &mut Connection, |
| 1697 | ) -> Result<Outcome, Error> { | 1768 | ) -> Result<Outcome, Error> { |
| 1698 | let Removal { | 1769 | let Removal { |
| @@ -1725,7 +1796,7 @@ async fn remove_member( | |||
| 1725 | }; | 1796 | }; |
| 1726 | log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; | 1797 | log::record(&community_id, Some(&me.id), Some(&user_id), &action, &tx).await?; |
| 1727 | tx.commit().await?; | 1798 | tx.commit().await?; |
| 1728 | - let mut broadcasts = leave_room_voice(voice, &community_id, &user_id, conn).await?; | 1799 | + let mut broadcasts = leave_room_voice(voice, share, &community_id, &user_id, conn).await?; |
| 1729 | broadcasts.push(Broadcast { | 1800 | broadcasts.push(Broadcast { |
| 1730 | event: Event::Removed { | 1801 | event: Event::Removed { |
| 1731 | community_id: community_id.clone(), | 1802 | community_id: community_id.clone(), |
| @@ -1814,34 +1885,37 @@ async fn invitations_updated(user_id: &str, conn: &Connection) -> Result<Broadca | |||
| 1814 | 1885 | ||
| 1815 | async fn leave_user_voice( | 1886 | async fn leave_user_voice( |
| 1816 | voice: &Voice, | 1887 | voice: &Voice, |
| 1888 | + share: &Shares, | ||
| 1817 | user_id: &str, | 1889 | user_id: &str, |
| 1818 | conn: &Connection, | 1890 | conn: &Connection, |
| 1819 | ) -> Result<Vec<Broadcast>, Error> { | 1891 | ) -> Result<Vec<Broadcast>, Error> { |
| 1820 | match voice.leave(user_id) { | 1892 | match voice.leave(user_id) { |
| 1821 | - Some(left) => voice_left(left, conn).await, | 1893 | + Some(left) => voice_left(share, left, conn).await, |
| 1822 | None => Ok(Vec::new()), | 1894 | None => Ok(Vec::new()), |
| 1823 | } | 1895 | } |
| 1824 | } | 1896 | } |
| 1825 | 1897 | ||
| 1826 | pub async fn leave_connection_voice( | 1898 | pub async fn leave_connection_voice( |
| 1827 | voice: &Voice, | 1899 | voice: &Voice, |
| 1900 | + share: &Shares, | ||
| 1828 | connection: Option<&quinn::Connection>, | 1901 | connection: Option<&quinn::Connection>, |
| 1829 | conn: &Connection, | 1902 | conn: &Connection, |
| 1830 | ) -> Result<Vec<Broadcast>, Error> { | 1903 | ) -> Result<Vec<Broadcast>, Error> { |
| 1831 | match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) { | 1904 | match connection.and_then(|connection| voice.leave_connection(connection.stable_id())) { |
| 1832 | - Some(left) => voice_left(left, conn).await, | 1905 | + Some(left) => voice_left(share, left, conn).await, |
| 1833 | None => Ok(Vec::new()), | 1906 | None => Ok(Vec::new()), |
| 1834 | } | 1907 | } |
| 1835 | } | 1908 | } |
| 1836 | 1909 | ||
| 1837 | async fn leave_room_voice( | 1910 | async fn leave_room_voice( |
| 1838 | voice: &Voice, | 1911 | voice: &Voice, |
| 1912 | + share: &Shares, | ||
| 1839 | community_id: &str, | 1913 | community_id: &str, |
| 1840 | user_id: &str, | 1914 | user_id: &str, |
| 1841 | conn: &Connection, | 1915 | conn: &Connection, |
| 1842 | ) -> Result<Vec<Broadcast>, Error> { | 1916 | ) -> Result<Vec<Broadcast>, Error> { |
| 1843 | match voice.leave_room(community_id, user_id) { | 1917 | match voice.leave_room(community_id, user_id) { |
| 1844 | - Some(left) => voice_left(left, conn).await, | 1918 | + Some(left) => voice_left(share, left, conn).await, |
| 1845 | None => Ok(Vec::new()), | 1919 | None => Ok(Vec::new()), |
| 1846 | } | 1920 | } |
| 1847 | } | 1921 | } |
| @@ -1875,6 +1949,7 @@ async fn voice_unmuted( | |||
| 1875 | 1949 | ||
| 1876 | async fn voice_silenced( | 1950 | async fn voice_silenced( |
| 1877 | voice: &Voice, | 1951 | voice: &Voice, |
| 1952 | + share: &Shares, | ||
| 1878 | community_id: &str, | 1953 | community_id: &str, |
| 1879 | conn: &Connection, | 1954 | conn: &Connection, |
| 1880 | ) -> Result<Vec<Broadcast>, Error> { | 1955 | ) -> Result<Vec<Broadcast>, Error> { |
| @@ -1884,7 +1959,7 @@ async fn voice_silenced( | |||
| 1884 | continue; | 1959 | continue; |
| 1885 | } | 1960 | } |
| 1886 | if let Some(left) = voice.leave_room(community_id, &user_id) { | 1961 | if let Some(left) = voice.leave_room(community_id, &user_id) { |
| 1887 | - broadcasts.extend(voice_left(left, conn).await?); | 1962 | + broadcasts.extend(voice_left(share, left, conn).await?); |
| 1888 | } | 1963 | } |
| 1889 | } | 1964 | } |
| 1890 | 1965 | ||
| @@ -1893,12 +1968,13 @@ async fn voice_silenced( | |||
| 1893 | 1968 | ||
| 1894 | async fn voice_closed( | 1969 | async fn voice_closed( |
| 1895 | voice: &Voice, | 1970 | voice: &Voice, |
| 1971 | + share: &Shares, | ||
| 1896 | community_id: &str, | 1972 | community_id: &str, |
| 1897 | conn: &Connection, | 1973 | conn: &Connection, |
| 1898 | ) -> Result<Vec<Broadcast>, Error> { | 1974 | ) -> Result<Vec<Broadcast>, Error> { |
| 1899 | let mut broadcasts = Vec::new(); | 1975 | let mut broadcasts = Vec::new(); |
| 1900 | for left in voice.remove_room(community_id) { | 1976 | for left in voice.remove_room(community_id) { |
| 1901 | - broadcasts.extend(voice_left(left, conn).await?); | 1977 | + broadcasts.extend(voice_left(share, left, conn).await?); |
| 1902 | } | 1978 | } |
| 1903 | 1979 | ||
| 1904 | Ok(broadcasts) | 1980 | Ok(broadcasts) |
| @@ -1933,11 +2009,17 @@ async fn call_ended( | |||
| 1933 | Ok(vec![broadcast(Event::MessageCreated(created), members)]) | 2009 | Ok(vec![broadcast(Event::MessageCreated(created), members)]) |
| 1934 | } | 2010 | } |
| 1935 | 2011 | ||
| 1936 | -async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Error> { | 2012 | +async fn voice_left( |
| 2013 | + share: &Shares, | ||
| 2014 | + left: Left, | ||
| 2015 | + conn: &Connection, | ||
| 2016 | +) -> Result<Vec<Broadcast>, Error> { | ||
| 2017 | + let mut broadcasts = share_left(share, &left.user_id, conn).await?; | ||
| 1937 | let Some(seconds) = left.ghost_seconds else { | 2018 | let Some(seconds) = left.ghost_seconds else { |
| 1938 | let members = user_community::members(&left.community_id, conn).await?; | 2019 | let members = user_community::members(&left.community_id, conn).await?; |
| 1939 | - let mut broadcasts = | 2020 | + broadcasts.extend( |
| 1940 | - call_ended(&left.community_id, &left.user_id, left.call, &members, conn).await?; | 2021 | + call_ended(&left.community_id, &left.user_id, left.call, &members, conn).await?, |
| 2022 | + ); | ||
| 1941 | let event = Event::VoiceLeft { | 2023 | let event = Event::VoiceLeft { |
| 1942 | community_id: left.community_id, | 2024 | community_id: left.community_id, |
| 1943 | user_id: left.user_id, | 2025 | user_id: left.user_id, |
| @@ -1948,7 +2030,35 @@ async fn voice_left(left: Left, conn: &Connection) -> Result<Vec<Broadcast>, Err | |||
| 1948 | }; | 2030 | }; |
| 1949 | record_ghost_voice(&left.user_id, &left.community_id, seconds, conn).await?; | 2031 | record_ghost_voice(&left.user_id, &left.community_id, seconds, conn).await?; |
| 1950 | 2032 | ||
| 1951 | - Ok(Vec::new()) | 2033 | + Ok(broadcasts) |
| 2034 | +} | ||
| 2035 | + | ||
| 2036 | +async fn share_stopped( | ||
| 2037 | + share: &Shares, | ||
| 2038 | + user_id: &str, | ||
| 2039 | + conn: &Connection, | ||
| 2040 | +) -> Result<Vec<Broadcast>, Error> { | ||
| 2041 | + let Some(community_id) = share.stop(user_id) else { | ||
| 2042 | + return Ok(Vec::new()); | ||
| 2043 | + }; | ||
| 2044 | + let members = user_community::members(&community_id, conn).await?; | ||
| 2045 | + let event = Event::ShareStopped { | ||
| 2046 | + community_id, | ||
| 2047 | + user_id: user_id.to_string(), | ||
| 2048 | + }; | ||
| 2049 | + | ||
| 2050 | + Ok(vec![broadcast(event, &members)]) | ||
| 2051 | +} | ||
| 2052 | + | ||
| 2053 | +async fn share_left( | ||
| 2054 | + share: &Shares, | ||
| 2055 | + user_id: &str, | ||
| 2056 | + conn: &Connection, | ||
| 2057 | +) -> Result<Vec<Broadcast>, Error> { | ||
| 2058 | + let mut broadcasts = share_stopped(share, user_id, conn).await?; | ||
| 2059 | + broadcasts.extend(share.leave_viewer(user_id)); | ||
| 2060 | + | ||
| 2061 | + Ok(broadcasts) | ||
| 1952 | } | 2062 | } |
| 1953 | 2063 | ||
| 1954 | fn sign_in(state: &Mutex<State>, user: User, token: String, broadcasts: Vec<Broadcast>) -> Outcome { | 2064 | fn sign_in(state: &Mutex<State>, user: User, token: String, broadcasts: Vec<Broadcast>) -> Outcome { |
crates/server/src/share.rsadded+249 -0
| @@ -0,0 +1,249 @@ | |||
| 1 | +use std::{ | ||
| 2 | + collections::{BTreeMap, BTreeSet}, | ||
| 3 | + sync::{Arc, Mutex}, | ||
| 4 | +}; | ||
| 5 | + | ||
| 6 | +use bytes::Bytes; | ||
| 7 | +use common::{ | ||
| 8 | + datagram::{Datagram, encode_relay}, | ||
| 9 | + event::Event, | ||
| 10 | + share::{Codec, Layer, Quality, Share, Source, choose}, | ||
| 11 | +}; | ||
| 12 | +use quinn::Connection; | ||
| 13 | + | ||
| 14 | +use crate::request::Broadcast; | ||
| 15 | + | ||
| 16 | +#[derive(Clone, Copy)] | ||
| 17 | +enum Forward { | ||
| 18 | + Waiting(Layer), | ||
| 19 | + Live(Layer), | ||
| 20 | + Switching { live: Layer, next: Layer }, | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +impl Forward { | ||
| 24 | + fn target(self) -> Layer { | ||
| 25 | + match self { | ||
| 26 | + Self::Waiting(layer) | Self::Live(layer) => layer, | ||
| 27 | + Self::Switching { next, .. } => next, | ||
| 28 | + } | ||
| 29 | + } | ||
| 30 | + | ||
| 31 | + fn layers(self) -> Vec<Layer> { | ||
| 32 | + match self { | ||
| 33 | + Self::Waiting(layer) | Self::Live(layer) => vec![layer], | ||
| 34 | + Self::Switching { live, next } => vec![live, next], | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | + | ||
| 38 | + fn live(self) -> Option<Layer> { | ||
| 39 | + match self { | ||
| 40 | + Self::Waiting(_) => None, | ||
| 41 | + Self::Live(layer) | Self::Switching { live: layer, .. } => Some(layer), | ||
| 42 | + } | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + fn retarget(self, next: Layer) -> Self { | ||
| 46 | + match self { | ||
| 47 | + Self::Waiting(_) => Self::Waiting(next), | ||
| 48 | + Self::Live(live) | Self::Switching { live, .. } if live == next => Self::Live(live), | ||
| 49 | + Self::Live(live) | Self::Switching { live, .. } => Self::Switching { live, next }, | ||
| 50 | + } | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + fn on_keyframe(self, layer: Layer) -> Self { | ||
| 54 | + match self { | ||
| 55 | + Self::Waiting(next) | Self::Switching { next, .. } if next == layer => { | ||
| 56 | + Self::Live(layer) | ||
| 57 | + } | ||
| 58 | + _ => self, | ||
| 59 | + } | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +struct Viewer { | ||
| 64 | + user_id: String, | ||
| 65 | + connection: Connection, | ||
| 66 | + forward: Forward, | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +struct Sharing { | ||
| 70 | + community_id: String, | ||
| 71 | + connection: Connection, | ||
| 72 | + source: Source, | ||
| 73 | + viewers: Vec<Viewer>, | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +impl Sharing { | ||
| 77 | + fn layers(&self) -> BTreeSet<Layer> { | ||
| 78 | + self.viewers | ||
| 79 | + .iter() | ||
| 80 | + .flat_map(|viewer| viewer.forward.layers()) | ||
| 81 | + .collect() | ||
| 82 | + } | ||
| 83 | + | ||
| 84 | + fn viewer(&self, user_id: &str) -> Option<&Viewer> { | ||
| 85 | + self.viewers.iter().find(|viewer| viewer.user_id == user_id) | ||
| 86 | + } | ||
| 87 | +} | ||
| 88 | + | ||
| 89 | +fn to(user_id: &str, event: Event) -> Broadcast { | ||
| 90 | + Broadcast { | ||
| 91 | + event, | ||
| 92 | + user_ids: vec![user_id.to_string()], | ||
| 93 | + } | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +fn layers_changed( | ||
| 97 | + sharer_id: &str, | ||
| 98 | + sharing: &Sharing, | ||
| 99 | + before: BTreeSet<Layer>, | ||
| 100 | +) -> Option<Broadcast> { | ||
| 101 | + let after = sharing.layers(); | ||
| 102 | + | ||
| 103 | + (after != before).then(|| to(sharer_id, Event::ShareLayers(after.into_iter().collect()))) | ||
| 104 | +} | ||
| 105 | + | ||
| 106 | +fn remove_viewer(sharer_id: &str, sharing: &mut Sharing, viewer_id: &str) -> Option<Broadcast> { | ||
| 107 | + let before = sharing.layers(); | ||
| 108 | + sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | ||
| 109 | + | ||
| 110 | + layers_changed(sharer_id, sharing, before) | ||
| 111 | +} | ||
| 112 | + | ||
| 113 | +#[derive(Clone, Default)] | ||
| 114 | +pub struct Shares(Arc<Mutex<BTreeMap<String, Sharing>>>); | ||
| 115 | + | ||
| 116 | +impl Shares { | ||
| 117 | + pub fn start(&self, community_id: &str, user_id: &str, connection: Connection, source: Source) { | ||
| 118 | + self.0.lock().unwrap().insert( | ||
| 119 | + user_id.to_string(), | ||
| 120 | + Sharing { | ||
| 121 | + community_id: community_id.to_string(), | ||
| 122 | + connection, | ||
| 123 | + source, | ||
| 124 | + viewers: Vec::new(), | ||
| 125 | + }, | ||
| 126 | + ); | ||
| 127 | + } | ||
| 128 | + | ||
| 129 | + pub fn stop(&self, user_id: &str) -> Option<String> { | ||
| 130 | + self.0 | ||
| 131 | + .lock() | ||
| 132 | + .unwrap() | ||
| 133 | + .remove(user_id) | ||
| 134 | + .map(|sharing| sharing.community_id) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + pub fn list(&self, community_id: &str) -> Vec<Share> { | ||
| 138 | + self.0 | ||
| 139 | + .lock() | ||
| 140 | + .unwrap() | ||
| 141 | + .iter() | ||
| 142 | + .filter(|(_, sharing)| sharing.community_id == community_id) | ||
| 143 | + .map(|(user_id, sharing)| Share { | ||
| 144 | + user_id: user_id.clone(), | ||
| 145 | + source: sharing.source.clone(), | ||
| 146 | + }) | ||
| 147 | + .collect() | ||
| 148 | + } | ||
| 149 | + | ||
| 150 | + pub fn watch( | ||
| 151 | + &self, | ||
| 152 | + sharer_id: &str, | ||
| 153 | + viewer_id: &str, | ||
| 154 | + connection: Connection, | ||
| 155 | + quality: Quality, | ||
| 156 | + decode: &[Codec], | ||
| 157 | + ) -> Option<Vec<Broadcast>> { | ||
| 158 | + let mut sharings = self.0.lock().unwrap(); | ||
| 159 | + let sharing = sharings.get_mut(sharer_id)?; | ||
| 160 | + let before = sharing.layers(); | ||
| 161 | + let used: Vec<Layer> = before.iter().copied().collect(); | ||
| 162 | + let layer = choose(&sharing.source, quality, decode, &used)?; | ||
| 163 | + let forward = sharing | ||
| 164 | + .viewer(viewer_id) | ||
| 165 | + .map_or(Forward::Waiting(layer), |viewer| { | ||
| 166 | + viewer.forward.retarget(layer) | ||
| 167 | + }); | ||
| 168 | + sharing.viewers.retain(|viewer| viewer.user_id != viewer_id); | ||
| 169 | + sharing.viewers.push(Viewer { | ||
| 170 | + user_id: viewer_id.to_string(), | ||
| 171 | + connection, | ||
| 172 | + forward, | ||
| 173 | + }); | ||
| 174 | + let mut broadcasts: Vec<Broadcast> = layers_changed(sharer_id, sharing, before) | ||
| 175 | + .into_iter() | ||
| 176 | + .collect(); | ||
| 177 | + broadcasts.push(to(sharer_id, Event::KeyframeWanted(layer))); | ||
| 178 | + | ||
| 179 | + Some(broadcasts) | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + pub fn unwatch(&self, sharer_id: &str, viewer_id: &str) -> Vec<Broadcast> { | ||
| 183 | + self.0 | ||
| 184 | + .lock() | ||
| 185 | + .unwrap() | ||
| 186 | + .get_mut(sharer_id) | ||
| 187 | + .and_then(|sharing| remove_viewer(sharer_id, sharing, viewer_id)) | ||
| 188 | + .into_iter() | ||
| 189 | + .collect() | ||
| 190 | + } | ||
| 191 | + | ||
| 192 | + pub fn leave_viewer(&self, viewer_id: &str) -> Vec<Broadcast> { | ||
| 193 | + self.0 | ||
| 194 | + .lock() | ||
| 195 | + .unwrap() | ||
| 196 | + .iter_mut() | ||
| 197 | + .filter_map(|(sharer_id, sharing)| remove_viewer(sharer_id, sharing, viewer_id)) | ||
| 198 | + .collect() | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + pub fn keyframe(&self, sharer_id: &str, viewer_id: &str) -> Option<Broadcast> { | ||
| 202 | + let sharings = self.0.lock().unwrap(); | ||
| 203 | + let viewer = sharings.get(sharer_id)?.viewer(viewer_id)?; | ||
| 204 | + | ||
| 205 | + Some(to( | ||
| 206 | + sharer_id, | ||
| 207 | + Event::KeyframeWanted(viewer.forward.target()), | ||
| 208 | + )) | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + pub fn relay(&self, connection_id: usize, packet: &[u8]) -> Vec<Broadcast> { | ||
| 212 | + let mut sharings = self.0.lock().unwrap(); | ||
| 213 | + let Some((sharer_id, sharing)) = sharings | ||
| 214 | + .iter_mut() | ||
| 215 | + .find(|(_, sharing)| sharing.connection.stable_id() == connection_id) | ||
| 216 | + else { | ||
| 217 | + return Vec::new(); | ||
| 218 | + }; | ||
| 219 | + let Some(relay) = encode_relay(sharer_id, packet) else { | ||
| 220 | + return Vec::new(); | ||
| 221 | + }; | ||
| 222 | + let bytes = Bytes::from(relay); | ||
| 223 | + match Datagram::decode(packet) { | ||
| 224 | + Some(Datagram::Video(fragment)) => { | ||
| 225 | + let before = sharing.layers(); | ||
| 226 | + for viewer in &mut sharing.viewers { | ||
| 227 | + if fragment.keyframe && fragment.index == 0 { | ||
| 228 | + viewer.forward = viewer.forward.on_keyframe(fragment.layer); | ||
| 229 | + } | ||
| 230 | + if viewer.forward.live() == Some(fragment.layer) { | ||
| 231 | + let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 232 | + } | ||
| 233 | + } | ||
| 234 | + | ||
| 235 | + layers_changed(sharer_id, sharing, before) | ||
| 236 | + .into_iter() | ||
| 237 | + .collect() | ||
| 238 | + } | ||
| 239 | + Some(Datagram::ShareAudio { .. }) => { | ||
| 240 | + for viewer in &sharing.viewers { | ||
| 241 | + let _ = viewer.connection.send_datagram(bytes.clone()); | ||
| 242 | + } | ||
| 243 | + | ||
| 244 | + Vec::new() | ||
| 245 | + } | ||
| 246 | + _ => Vec::new(), | ||
| 247 | + } | ||
| 248 | + } | ||
| 249 | +} | ||
crates/server/src/voice.rsmodified+10 -3
| @@ -6,8 +6,8 @@ use std::{ | |||
| 6 | 6 | ||
| 7 | use bytes::Bytes; | 7 | use bytes::Bytes; |
| 8 | use common::{ | 8 | use common::{ |
| 9 | + datagram::{Datagram, encode_relay}, | ||
| 9 | time, | 10 | time, |
| 10 | - voice::{decode_packet, encode_relay}, | ||
| 11 | }; | 11 | }; |
| 12 | use quinn::Connection; | 12 | use quinn::Connection; |
| 13 | 13 | ||
| @@ -247,7 +247,7 @@ impl Voice { | |||
| 247 | } | 247 | } |
| 248 | 248 | ||
| 249 | pub fn relay(&self, connection_id: usize, packet: &[u8]) { | 249 | pub fn relay(&self, connection_id: usize, packet: &[u8]) { |
| 250 | - let Some((sequence, _)) = decode_packet(packet) else { | 250 | + let Some(Datagram::Voice { sequence, .. }) = Datagram::decode(packet) else { |
| 251 | return; | 251 | return; |
| 252 | }; | 252 | }; |
| 253 | let rooms = self.0.lock().unwrap(); | 253 | let rooms = self.0.lock().unwrap(); |
| @@ -270,7 +270,14 @@ impl Voice { | |||
| 270 | } | 270 | } |
| 271 | let (Some(relay), Some(echo)) = ( | 271 | let (Some(relay), Some(echo)) = ( |
| 272 | encode_relay(&sender.user_id, packet), | 272 | encode_relay(&sender.user_id, packet), |
| 273 | - encode_relay(&sender.user_id, &sequence.to_be_bytes()), | 273 | + encode_relay( |
| 274 | + &sender.user_id, | ||
| 275 | + &Datagram::Voice { | ||
| 276 | + sequence, | ||
| 277 | + payload: &[], | ||
| 278 | + } | ||
| 279 | + .encode(), | ||
| 280 | + ), | ||
| 274 | ) else { | 281 | ) else { |
| 275 | return; | 282 | return; |
| 276 | }; | 283 | }; |