forge
Explore
Log in

Don't you dare go Hollow

Windows zero-copy screen share: the WGC frame is copied into edith's D3d11Pool in the capture callback and the encoder reads the shared texture (encode_d3d11), 3 frames in flight against the ring of 4

Browse files at this commit

cf604c446622acd4df9b8f21ab1988b2e09337fcAhmet Kaan GümüşParent: 3e62c4a
  • feat
    • Windows zero-copy screen share: the WGC frame is copied into edith's D3d11Pool in the capture callback and the encoder reads the shared texture (encode_d3d11), 3 frames in flight against the ring of 4
    • falls back to cpu copies when d3d11 import is unsupported or fails
    • edith 9b677004
    • Dmabuf renamed Gpu (one GPU frame type per OS)
Show full message
✨ feat: Windows zero-copy screen share: the WGC frame is copied into edith's D3d11Pool in the capture callback and the encoder reads the shared texture (encode_d3d11), 3 frames in flight against the ring of 4; falls back to cpu copies when d3d11 import is unsupported or fails; edith 9b677004; Dmabuf renamed Gpu (one GPU frame type per OS)
crates/client/Cargo.tomlmodified+11 -11
@@ -13,17 +13,17 @@ tokio.workspace = true
13 quinn = { workspace = true, features = ["rustls-ring"] }13 quinn = { workspace = true, features = ["rustls-ring"] }
14 14
15 gpui-kit = { version = "0.11.0", features = ["syntect"] }15 gpui-kit = { version = "0.11.0", features = ["syntect"] }
16-ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }16+ec-opus = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
17-ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }17+ec-core = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
18-ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }18+ec-probe = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
19-ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }19+ec-ogg = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
20-ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }20+ec-h264 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
21-ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }21+ec-vp8 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
22-ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }22+ec-flac = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
23-ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }23+ec-h265 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
24-ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }24+ec-hw = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
25-ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }25+ec-vp9 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
26-ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "1b795c60" }26+ec-av1 = { git = "https://git.tahinli.com/Tahinli/edith_codecs.git", rev = "9b677004" }
27 ureq = "3.5.2"27 ureq = "3.5.2"
28 bytes = "1.12.2"28 bytes = "1.12.2"
29 tracing = "0.1.44"29 tracing = "0.1.44"
crates/client/src/share/camera.rsmodified+1 -1
@@ -256,7 +256,7 @@ fn run(
256 stride: width * BYTES_PER_PIXEL as u32,256 stride: width * BYTES_PER_PIXEL as u32,
257 timestamp_ms,257 timestamp_ms,
258 bgra,258 bgra,
259- dmabuf: None,259+ gpu: None,
260 };260 };
261 let _ = frames.try_send(frame);261 let _ = frames.try_send(frame);
262 }262 }
crates/client/src/share/capture.rsmodified+5 -7
@@ -36,9 +36,7 @@ use spa::{
36 36
37 use super::{37 use super::{
38 fake,38 fake,
39- frame::{39+ frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Frame, Gpu, Release, take_gpu_failed},
40- BYTES_PER_PIXEL, DEFAULT_REFRESH, Dmabuf, FRAME_QUEUE, Frame, Release, take_dmabuf_failed,
41- },
42 };40 };
43 41
44 const NEGOTIATE_TIMEOUT: Duration = Duration::from_secs(10);42 const NEGOTIATE_TIMEOUT: Duration = Duration::from_secs(10);
@@ -211,7 +209,7 @@ fn run(
211 stop: &Arc<AtomicBool>,209 stop: &Arc<AtomicBool>,
212 ) -> Result<(), Box<dyn Error>> {210 ) -> Result<(), Box<dyn Error>> {
213 pw::init();211 pw::init();
214- take_dmabuf_failed();212+ take_gpu_failed();
215 let modifiers = modifiers();213 let modifiers = modifiers();
216 let mainloop = pw::main_loop::MainLoopRc::new(None)?;214 let mainloop = pw::main_loop::MainLoopRc::new(None)?;
217 let context = pw::context::ContextRc::new(&mainloop, None)?;215 let context = pw::context::ContextRc::new(&mainloop, None)?;
@@ -281,7 +279,7 @@ fn run(
281 if failed.get() {279 if failed.get() {
282 return Err("pipewire connection lost".into());280 return Err("pipewire connection lost".into());
283 }281 }
284- if take_dmabuf_failed() {282+ if take_gpu_failed() {
285 tracing::warn!("share capture falls back to shared memory");283 tracing::warn!("share capture falls back to shared memory");
286 let _ = stream.update_params(&mut [shm]);284 let _ = stream.update_params(&mut [shm]);
287 }285 }
@@ -504,7 +502,7 @@ fn on_process(stream: &pw::stream::Stream, state: &mut State) {
504 stride: width * BYTES_PER_PIXEL as u32,502 stride: width * BYTES_PER_PIXEL as u32,
505 timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX),503 timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX),
506 bgra: Vec::new(),504 bgra: Vec::new(),
507- dmabuf: Some(Dmabuf {505+ gpu: Some(Gpu {
508 fd: plane.fd(),506 fd: plane.fd(),
509 offset: chunk.offset(),507 offset: chunk.offset(),
510 stride: u32::try_from(chunk.stride()).unwrap_or(0),508 stride: u32::try_from(chunk.stride()).unwrap_or(0),
@@ -551,7 +549,7 @@ fn on_process(stream: &pw::stream::Stream, state: &mut State) {
551 stride: row as u32,549 stride: row as u32,
552 timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX),550 timestamp_ms: u32::try_from(state.started.elapsed().as_millis()).unwrap_or(u32::MAX),
553 bgra,551 bgra,
554- dmabuf: None,552+ gpu: None,
555 };553 };
556 let _ = state.frames.try_send(frame);554 let _ = state.frames.try_send(frame);
557 }555 }
crates/client/src/share/capture_windows.rsmodified+98 -4
@@ -3,6 +3,8 @@ use std::{
3 time::Instant,3 time::Instant,
4 };4 };
5 5
6+use ec_hw::{D3d11Pool, RgbOrder};
7+
6 use windows_capture::{8 use windows_capture::{
7 capture::{CaptureControl, Context, GraphicsCaptureApiHandler},9 capture::{CaptureControl, Context, GraphicsCaptureApiHandler},
8 frame::Frame as CaptureFrame,10 frame::Frame as CaptureFrame,
@@ -16,9 +18,11 @@ use windows_capture::{
16 18
17 use super::{19 use super::{
18 fake,20 fake,
19- frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Frame},21+ frame::{BYTES_PER_PIXEL, DEFAULT_REFRESH, FRAME_QUEUE, Frame, Gpu, Release, take_gpu_failed},
20 };22 };
21 23
24+const IN_FLIGHT: usize = 3;
25+
22 pub struct Capture {26 pub struct Capture {
23 pub width: u32,27 pub width: u32,
24 pub height: u32,28 pub height: u32,
@@ -88,9 +92,85 @@ fn text(error: impl std::fmt::Display) -> String {
88 error.to_string()92 error.to_string()
89 }93 }
90 94
95+enum Path {
96+ Untried,
97+ Gpu(D3d11Pool),
98+ Cpu,
99+}
100+
91 struct Handler {101 struct Handler {
92 frames: SyncSender<Frame>,102 frames: SyncSender<Frame>,
93 started: Instant,103 started: Instant,
104+ path: Path,
105+ release: SyncSender<()>,
106+ released: Receiver<()>,
107+}
108+
109+impl Handler {
110+ fn timestamp(&self) -> u32 {
111+ u32::try_from(self.started.elapsed().as_millis()).unwrap_or(u32::MAX)
112+ }
113+
114+ fn pick_path(&mut self, frame: &CaptureFrame) {
115+ if take_gpu_failed() && matches!(self.path, Path::Gpu(_)) {
116+ tracing::warn!("share capture falls back to cpu copies");
117+ self.path = Path::Cpu;
118+ }
119+ if !matches!(self.path, Path::Untried) {
120+ return;
121+ }
122+ let wanted = std::env::var_os("YUMUSH_NO_DMABUF").is_none()
123+ && ec_hw::d3d11_supported(RgbOrder::Bgra);
124+ self.path = match wanted.then(|| D3d11Pool::new(frame.device())) {
125+ Some(Ok(pool)) => Path::Gpu(pool),
126+ Some(Err(error)) => {
127+ tracing::warn!(?error, "d3d11 pool");
128+ Path::Cpu
129+ }
130+ None => Path::Cpu,
131+ };
132+ }
133+
134+ fn send_gpu(&mut self, frame: &CaptureFrame) -> bool {
135+ let timestamp_ms = self.timestamp();
136+ let Path::Gpu(pool) = &mut self.path else {
137+ return false;
138+ };
139+ if self.released.try_recv().is_err() {
140+ return true;
141+ }
142+ let release = Release(self.release.clone());
143+ let shared = match pool.submit(frame.as_raw_texture()) {
144+ Ok(shared) => shared
145+ .handle
146+ .try_clone_to_owned()
147+ .map(|handle| (handle, shared.id, shared.width, shared.height, shared.order))
148+ .map_err(|error| error.to_string()),
149+ Err(error) => Err(error.to_string()),
150+ };
151+ let (handle, id, width, height, order) = match shared {
152+ Ok(shared) => shared,
153+ Err(error) => {
154+ tracing::warn!(error, "d3d11 submit");
155+ self.path = Path::Cpu;
156+ return false;
157+ }
158+ };
159+ let _ = self.frames.try_send(Frame {
160+ width,
161+ height,
162+ stride: width * BYTES_PER_PIXEL as u32,
163+ timestamp_ms,
164+ bgra: Vec::new(),
165+ gpu: Some(Gpu {
166+ handle,
167+ id,
168+ bgra: order == RgbOrder::Bgra,
169+ release,
170+ }),
171+ });
172+ true
173+ }
94 }174 }
95 175
96 impl GraphicsCaptureApiHandler for Handler {176 impl GraphicsCaptureApiHandler for Handler {
@@ -99,7 +179,17 @@ impl GraphicsCaptureApiHandler for Handler {
99 179
100 fn new(context: Context<Self::Flags>) -> Result<Self, Self::Error> {180 fn new(context: Context<Self::Flags>) -> Result<Self, Self::Error> {
101 let (frames, started) = context.flags;181 let (frames, started) = context.flags;
102- Ok(Self { frames, started })182+ let (release, released) = sync_channel(IN_FLIGHT);
183+ for _ in 0..IN_FLIGHT {
184+ let _ = release.try_send(());
185+ }
186+ Ok(Self {
187+ frames,
188+ started,
189+ path: Path::Untried,
190+ release,
191+ released,
192+ })
103 }193 }
104 194
105 fn on_frame_arrived(195 fn on_frame_arrived(
@@ -108,6 +198,10 @@ impl GraphicsCaptureApiHandler for Handler {
108 _: InternalCaptureControl,198 _: InternalCaptureControl,
109 ) -> Result<(), Self::Error> {199 ) -> Result<(), Self::Error> {
110 crate::usage::tick(crate::usage::Group::Camera);200 crate::usage::tick(crate::usage::Group::Camera);
201+ self.pick_path(frame);
202+ if self.send_gpu(frame) {
203+ return Ok(());
204+ }
111 let (width, height) = (frame.width(), frame.height());205 let (width, height) = (frame.width(), frame.height());
112 let mut buffer = frame.buffer().map_err(text)?;206 let mut buffer = frame.buffer().map_err(text)?;
113 let pitch = buffer.row_pitch() as usize;207 let pitch = buffer.row_pitch() as usize;
@@ -126,9 +220,9 @@ impl GraphicsCaptureApiHandler for Handler {
126 width,220 width,
127 height,221 height,
128 stride: row as u32,222 stride: row as u32,
129- timestamp_ms: u32::try_from(self.started.elapsed().as_millis()).unwrap_or(u32::MAX),223+ timestamp_ms: self.timestamp(),
130 bgra,224 bgra,
131- dmabuf: None,225+ gpu: None,
132 });226 });
133 Ok(())227 Ok(())
134 }228 }
crates/client/src/share/encode.rsmodified+25 -5
@@ -174,8 +174,8 @@ impl Backend {
174 ) -> Option<(Vec<u8>, bool, bool)> {174 ) -> Option<(Vec<u8>, bool, bool)> {
175 match self {175 match self {
176 Self::Hardware(encoder) => encoder.encode(frame, settings, request),176 Self::Hardware(encoder) => encoder.encode(frame, settings, request),
177- Self::H264(_) if frame.dmabuf.is_some() => {177+ Self::H264(_) if frame.gpu.is_some() => {
178- super::frame::dmabuf_failed();178+ super::frame::gpu_failed();
179 None179 None
180 }180 }
181 Self::H264(encoder) => {181 Self::H264(encoder) => {
@@ -244,10 +244,10 @@ mod hardware {
244 force_keyframe: request == Request::Keyframe,244 force_keyframe: request == Request::Keyframe,
245 };245 };
246 #[cfg(target_os = "linux")]246 #[cfg(target_os = "linux")]
247- if let Some(dmabuf) = &frame.dmabuf {247+ if let Some(dmabuf) = &frame.gpu {
248 use std::os::fd::AsFd;248 use std::os::fd::AsFd;
249 let Some(fd) = report(ec_hw::dup_fd(dmabuf.fd)) else {249 let Some(fd) = report(ec_hw::dup_fd(dmabuf.fd)) else {
250- crate::share::frame::dmabuf_failed();250+ crate::share::frame::gpu_failed();
251 return None;251 return None;
252 };252 };
253 let source = ec_hw::DmaBufFrame {253 let source = ec_hw::DmaBufFrame {
@@ -265,7 +265,27 @@ mod hardware {
265 };265 };
266 let coded = self.0.encode_dmabuf(&source, meta);266 let coded = self.0.encode_dmabuf(&source, meta);
267 if coded.is_err() {267 if coded.is_err() {
268- crate::share::frame::dmabuf_failed();268+ crate::share::frame::gpu_failed();
269+ }
270+ return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery));
271+ }
272+ #[cfg(target_os = "windows")]
273+ if let Some(gpu) = &frame.gpu {
274+ use std::os::windows::io::AsHandle;
275+ let source = ec_hw::D3d11Frame {
276+ handle: gpu.handle.as_handle(),
277+ id: gpu.id,
278+ width: frame.width,
279+ height: frame.height,
280+ order: if gpu.bgra {
281+ ec_hw::RgbOrder::Bgra
282+ } else {
283+ ec_hw::RgbOrder::Rgba
284+ },
285+ };
286+ let coded = self.0.encode_d3d11(&source, meta);
287+ if coded.is_err() {
288+ crate::share::frame::gpu_failed();
269 }289 }
270 return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery));290 return report(coded).map(|coded| (coded.data, coded.is_keyframe, coded.recovery));
271 }291 }
crates/client/src/share/fake.rsmodified+1 -1
@@ -79,7 +79,7 @@ pub fn start(spec: &str) -> (u32, u32, u32, Receiver<Frame>, Generator) {
79 timestamp_ms: u32::try_from(started.elapsed().as_millis())79 timestamp_ms: u32::try_from(started.elapsed().as_millis())
80 .unwrap_or(u32::MAX),80 .unwrap_or(u32::MAX),
81 bgra,81 bgra,
82- dmabuf: None,82+ gpu: None,
83 };83 };
84 let _ = frames_tx.try_send(frame);84 let _ = frames_tx.try_send(frame);
85 number += 1;85 number += 1;
crates/client/src/share/frame.rsmodified+17 -9
@@ -17,14 +17,22 @@ pub struct Frame {
17 pub stride: u32,17 pub stride: u32,
18 pub timestamp_ms: u32,18 pub timestamp_ms: u32,
19 pub bgra: Vec<u8>,19 pub bgra: Vec<u8>,
20- pub dmabuf: Option<Dmabuf>,20+ pub gpu: Option<Gpu>,
21 }21 }
22 22
23-#[cfg(not(target_os = "linux"))]23+#[cfg(not(any(target_os = "linux", target_os = "windows")))]
24-pub enum Dmabuf {}24+pub enum Gpu {}
25+
26+#[cfg(target_os = "windows")]
27+pub struct Gpu {
28+ pub handle: std::os::windows::io::OwnedHandle,
29+ pub id: u64,
30+ pub bgra: bool,
31+ pub release: Release,
32+}
25 33
26 #[cfg(target_os = "linux")]34 #[cfg(target_os = "linux")]
27-pub struct Dmabuf {35+pub struct Gpu {
28 pub fd: std::os::fd::RawFd,36 pub fd: std::os::fd::RawFd,
29 pub offset: u32,37 pub offset: u32,
30 pub stride: u32,38 pub stride: u32,
@@ -41,14 +49,14 @@ impl Drop for Release {
41 }49 }
42 }50 }
43 51
44-static DMABUF_FAILED: AtomicBool = AtomicBool::new(false);52+static GPU_FAILED: AtomicBool = AtomicBool::new(false);
45 53
46-pub fn dmabuf_failed() {54+pub fn gpu_failed() {
47- DMABUF_FAILED.store(true, Ordering::Relaxed);55+ GPU_FAILED.store(true, Ordering::Relaxed);
48 }56 }
49 57
50-pub fn take_dmabuf_failed() -> bool {58+pub fn take_gpu_failed() -> bool {
51- DMABUF_FAILED.swap(false, Ordering::Relaxed)59+ GPU_FAILED.swap(false, Ordering::Relaxed)
52 }60 }
53 61
54 impl Frame {62 impl Frame {
crates/client/src/share/session.rsmodified+3 -3
@@ -393,7 +393,7 @@ fn feed(
393 let mut logged = Instant::now();393 let mut logged = Instant::now();
394 while let Some(mut frame) = next(&frames, stop) {394 while let Some(mut frame) = next(&frames, stop) {
395 frame.timestamp_ms = started.elapsed().as_millis() as u32;395 frame.timestamp_ms = started.elapsed().as_millis() as u32;
396- let unchanged = frame.dmabuf.is_none()396+ let unchanged = frame.gpu.is_none()
397 && previous.as_ref().is_some_and(|last| {397 && previous.as_ref().is_some_and(|last| {
398 last.width == frame.width398 last.width == frame.width
399 && last.height == frame.height399 && last.height == frame.height
@@ -404,7 +404,7 @@ fn feed(
404 if unchanged && !encoders.keyframe_pending() {404 if unchanged && !encoders.keyframe_pending() {
405 skipped += 1;405 skipped += 1;
406 } else {406 } else {
407- let gpu = frame.dmabuf.is_some();407+ let gpu = frame.gpu.is_some();
408 let frame = Arc::new(frame);408 let frame = Arc::new(frame);
409 encoders.push(frame.clone());409 encoders.push(frame.clone());
410 drop(encoders);410 drop(encoders);
@@ -1267,7 +1267,7 @@ mod tests {
1267 stride: width * 4,1267 stride: width * 4,
1268 timestamp_ms: index * 34,1268 timestamp_ms: index * 34,
1269 bgra,1269 bgra,
1270- dmabuf: None,1270+ gpu: None,
1271 }));1271 }));
1272 std::thread::sleep(Duration::from_millis(40));1272 std::thread::sleep(Duration::from_millis(40));
1273 }1273 }