forge
Explore
Log in

Don't you dare go Hollow

Add initial monitor screencast portal impl

Browse files at this commit

d52ca23caa4345ddf768da5af24f47eae6fd4738Ivan MolodetskikhParent: bd0ecf9
DmaBuf monitor screencasting through xdg-dekstop-portal-gnome!

Somewhat limited currently, e.g. the cursor is always embedded. But gets
most of the job done.
.github/workflows/ci.ymlmodified+6 -2
@@ -29,8 +29,10 @@ jobs:
2929
3030 - name: Install dependencies
3131 run: |
32+ sudo apt-get install -y software-properties-common
33+ sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
3234 sudo apt-get update -y
33- sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev
35+ sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev
3436
3537 - name: Install Rust
3638 run: |
@@ -67,8 +69,10 @@ jobs:
6769
6870 - name: Install dependencies
6971 run: |
72+ sudo apt-get install -y software-properties-common
73+ sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
7074 sudo apt-get update -y
71- sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev
75+ sudo apt-get install -y libudev-dev libgbm-dev libxkbcommon-dev libegl1-mesa-dev libwayland-dev libinput-dev libdbus-1-dev libsystemd-dev libseat-dev libpipewire-0.3-dev
7276
7377 - name: Install Rust
7478 run: |
Cargo.lockmodified+216 -2
@@ -294,6 +294,26 @@ version = "0.21.3"
294294 source = "registry+https://github.com/rust-lang/crates.io-index"
295295 checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53"
296296
297+[[package]]
298+name = "bindgen"
299+version = "0.66.1"
300+source = "registry+https://github.com/rust-lang/crates.io-index"
301+checksum = "f2b84e06fc203107bfbad243f4aba2af864eb7db3b1cf46ea0a023b0b433d2a7"
302+dependencies = [
303+ "bitflags 2.4.0",
304+ "cexpr",
305+ "clang-sys",
306+ "lazy_static",
307+ "lazycell",
308+ "peeking_take_while",
309+ "proc-macro2",
310+ "quote",
311+ "regex",
312+ "rustc-hash",
313+ "shlex",
314+ "syn 2.0.31",
315+]
316+
297317 [[package]]
298318 name = "bitflags"
299319 version = "1.3.2"
@@ -405,6 +425,25 @@ dependencies = [
405425 "libc",
406426 ]
407427
428+[[package]]
429+name = "cexpr"
430+version = "0.6.0"
431+source = "registry+https://github.com/rust-lang/crates.io-index"
432+checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
433+dependencies = [
434+ "nom",
435+]
436+
437+[[package]]
438+name = "cfg-expr"
439+version = "0.15.5"
440+source = "registry+https://github.com/rust-lang/crates.io-index"
441+checksum = "03915af431787e6ffdcc74c645077518c6b6e01f80b761e0fbbfa288536311b3"
442+dependencies = [
443+ "smallvec",
444+ "target-lexicon",
445+]
446+
408447 [[package]]
409448 name = "cfg-if"
410449 version = "1.0.0"
@@ -436,6 +475,17 @@ dependencies = [
436475 "hashbrown 0.12.3",
437476 ]
438477
478+[[package]]
479+name = "clang-sys"
480+version = "1.6.1"
481+source = "registry+https://github.com/rust-lang/crates.io-index"
482+checksum = "c688fc74432808e3eb684cae8830a86be1d66a2bd58e1f248ed0960a590baf6f"
483+dependencies = [
484+ "glob",
485+ "libc",
486+ "libloading 0.7.4",
487+]
488+
439489 [[package]]
440490 name = "clap"
441491 version = "4.4.2"
@@ -497,6 +547,21 @@ dependencies = [
497547 "crossbeam-utils",
498548 ]
499549
550+[[package]]
551+name = "convert_case"
552+version = "0.6.0"
553+source = "registry+https://github.com/rust-lang/crates.io-index"
554+checksum = "ec182b0ca2f35d8fc196cf3404988fd8b8c739a4d270ff118a398feb0cbec1ca"
555+dependencies = [
556+ "unicode-segmentation",
557+]
558+
559+[[package]]
560+name = "cookie-factory"
561+version = "0.3.2"
562+source = "registry+https://github.com/rust-lang/crates.io-index"
563+checksum = "396de984970346b0d9e93d1415082923c679e5ae5c3ee3dcbd104f5610af126b"
564+
500565 [[package]]
501566 name = "core-foundation"
502567 version = "0.9.3"
@@ -634,7 +699,7 @@ version = "0.5.2"
634699 source = "registry+https://github.com/rust-lang/crates.io-index"
635700 checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
636701 dependencies = [
637- "libloading",
702+ "libloading 0.8.0",
638703 ]
639704
640705 [[package]]
@@ -920,6 +985,12 @@ dependencies = [
920985 "xml-rs",
921986 ]
922987
988+[[package]]
989+name = "glob"
990+version = "0.3.1"
991+source = "registry+https://github.com/rust-lang/crates.io-index"
992+checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
993+
923994 [[package]]
924995 name = "hashbrown"
925996 version = "0.12.3"
@@ -1130,12 +1201,28 @@ version = "1.4.0"
11301201 source = "registry+https://github.com/rust-lang/crates.io-index"
11311202 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
11321203
1204+[[package]]
1205+name = "lazycell"
1206+version = "1.3.0"
1207+source = "registry+https://github.com/rust-lang/crates.io-index"
1208+checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55"
1209+
11331210 [[package]]
11341211 name = "libc"
11351212 version = "0.2.147"
11361213 source = "registry+https://github.com/rust-lang/crates.io-index"
11371214 checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
11381215
1216+[[package]]
1217+name = "libloading"
1218+version = "0.7.4"
1219+source = "registry+https://github.com/rust-lang/crates.io-index"
1220+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"
1221+dependencies = [
1222+ "cfg-if",
1223+ "winapi",
1224+]
1225+
11391226 [[package]]
11401227 name = "libloading"
11411228 version = "0.8.0"
@@ -1172,6 +1259,34 @@ dependencies = [
11721259 "pkg-config",
11731260 ]
11741261
1262+[[package]]
1263+name = "libspa"
1264+version = "0.7.2"
1265+source = "registry+https://github.com/rust-lang/crates.io-index"
1266+checksum = "0434617020ddca18b86067912970c55410ca654cdafd775480322f50b857a8c4"
1267+dependencies = [
1268+ "bitflags 2.4.0",
1269+ "cc",
1270+ "convert_case",
1271+ "cookie-factory",
1272+ "libc",
1273+ "libspa-sys",
1274+ "nix 0.26.4",
1275+ "nom",
1276+ "system-deps",
1277+]
1278+
1279+[[package]]
1280+name = "libspa-sys"
1281+version = "0.7.2"
1282+source = "registry+https://github.com/rust-lang/crates.io-index"
1283+checksum = "b3e70ca3f3e70f858ef363046d06178c427b4e0b63d210c95fd87d752679d345"
1284+dependencies = [
1285+ "bindgen",
1286+ "cc",
1287+ "system-deps",
1288+]
1289+
11751290 [[package]]
11761291 name = "libudev-sys"
11771292 version = "0.1.4"
@@ -1368,6 +1483,7 @@ name = "niri"
13681483 version = "0.1.0"
13691484 dependencies = [
13701485 "anyhow",
1486+ "async-io",
13711487 "bitflags 2.4.0",
13721488 "clap",
13731489 "directories",
@@ -1376,6 +1492,7 @@ dependencies = [
13761492 "knuffel",
13771493 "logind-zbus",
13781494 "miette",
1495+ "pipewire",
13791496 "portable-atomic",
13801497 "profiling",
13811498 "sd-notify",
@@ -1614,6 +1731,12 @@ version = "2.1.0"
16141731 source = "registry+https://github.com/rust-lang/crates.io-index"
16151732 checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e"
16161733
1734+[[package]]
1735+name = "peeking_take_while"
1736+version = "0.1.2"
1737+source = "registry+https://github.com/rust-lang/crates.io-index"
1738+checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
1739+
16171740 [[package]]
16181741 name = "percent-encoding"
16191742 version = "2.3.0"
@@ -1632,6 +1755,34 @@ version = "0.1.0"
16321755 source = "registry+https://github.com/rust-lang/crates.io-index"
16331756 checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
16341757
1758+[[package]]
1759+name = "pipewire"
1760+version = "0.7.2"
1761+source = "registry+https://github.com/rust-lang/crates.io-index"
1762+checksum = "a2d009c8dd65e890b515a71950f7e4c801523b8894ff33863a40830bf762e9e9"
1763+dependencies = [
1764+ "anyhow",
1765+ "bitflags 2.4.0",
1766+ "libc",
1767+ "libspa",
1768+ "libspa-sys",
1769+ "nix 0.26.4",
1770+ "once_cell",
1771+ "pipewire-sys",
1772+ "thiserror",
1773+]
1774+
1775+[[package]]
1776+name = "pipewire-sys"
1777+version = "0.7.2"
1778+source = "registry+https://github.com/rust-lang/crates.io-index"
1779+checksum = "890c084e7b737246cb4799c86b71a0e4da536031ff7473dd639eba9f95039f64"
1780+dependencies = [
1781+ "bindgen",
1782+ "libspa-sys",
1783+ "system-deps",
1784+]
1785+
16351786 [[package]]
16361787 name = "pkg-config"
16371788 version = "0.3.27"
@@ -1875,6 +2026,12 @@ version = "0.1.23"
18752026 source = "registry+https://github.com/rust-lang/crates.io-index"
18762027 checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
18772028
2029+[[package]]
2030+name = "rustc-hash"
2031+version = "1.1.0"
2032+source = "registry+https://github.com/rust-lang/crates.io-index"
2033+checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2"
2034+
18782035 [[package]]
18792036 name = "rustix"
18802037 version = "0.37.23"
@@ -1957,6 +2114,15 @@ dependencies = [
19572114 "syn 2.0.31",
19582115 ]
19592116
2117+[[package]]
2118+name = "serde_spanned"
2119+version = "0.6.3"
2120+source = "registry+https://github.com/rust-lang/crates.io-index"
2121+checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186"
2122+dependencies = [
2123+ "serde",
2124+]
2125+
19602126 [[package]]
19612127 name = "sha1"
19622128 version = "0.10.5"
@@ -1977,6 +2143,12 @@ dependencies = [
19772143 "lazy_static",
19782144 ]
19792145
2146+[[package]]
2147+name = "shlex"
2148+version = "1.2.0"
2149+source = "registry+https://github.com/rust-lang/crates.io-index"
2150+checksum = "a7cee0529a6d40f580e7a5e6c495c8fbfe21b7b52795ed4bb5e62cdf92bc6380"
2151+
19802152 [[package]]
19812153 name = "signal-hook"
19822154 version = "0.3.17"
@@ -2052,7 +2224,7 @@ dependencies = [
20522224 "input",
20532225 "lazy_static",
20542226 "libc",
2055- "libloading",
2227+ "libloading 0.8.0",
20562228 "libseat",
20572229 "nix 0.26.4",
20582230 "once_cell",
@@ -2175,6 +2347,25 @@ dependencies = [
21752347 "unicode-ident",
21762348 ]
21772349
2350+[[package]]
2351+name = "system-deps"
2352+version = "6.1.1"
2353+source = "registry+https://github.com/rust-lang/crates.io-index"
2354+checksum = "30c2de8a4d8f4b823d634affc9cd2a74ec98c53a756f317e529a48046cbf71f3"
2355+dependencies = [
2356+ "cfg-expr",
2357+ "heck",
2358+ "pkg-config",
2359+ "toml",
2360+ "version-compare",
2361+]
2362+
2363+[[package]]
2364+name = "target-lexicon"
2365+version = "0.12.11"
2366+source = "registry+https://github.com/rust-lang/crates.io-index"
2367+checksum = "9d0e916b1148c8e263850e1ebcbd046f333e0683c724876bb0da63ea4373dc8a"
2368+
21782369 [[package]]
21792370 name = "tempfile"
21802371 version = "3.8.0"
@@ -2269,11 +2460,26 @@ dependencies = [
22692460 "time-core",
22702461 ]
22712462
2463+[[package]]
2464+name = "toml"
2465+version = "0.7.7"
2466+source = "registry+https://github.com/rust-lang/crates.io-index"
2467+checksum = "de0a3ab2091e52d7299a39d098e200114a972df0a7724add02a273aa9aada592"
2468+dependencies = [
2469+ "serde",
2470+ "serde_spanned",
2471+ "toml_datetime",
2472+ "toml_edit",
2473+]
2474+
22722475 [[package]]
22732476 name = "toml_datetime"
22742477 version = "0.6.3"
22752478 source = "registry+https://github.com/rust-lang/crates.io-index"
22762479 checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
2480+dependencies = [
2481+ "serde",
2482+]
22772483
22782484 [[package]]
22792485 name = "toml_edit"
@@ -2282,6 +2488,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
22822488 checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
22832489 dependencies = [
22842490 "indexmap 2.0.0",
2491+ "serde",
2492+ "serde_spanned",
22852493 "toml_datetime",
22862494 "winnow",
22872495 ]
@@ -2437,6 +2645,12 @@ version = "0.8.2"
24372645 source = "registry+https://github.com/rust-lang/crates.io-index"
24382646 checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
24392647
2648+[[package]]
2649+name = "version-compare"
2650+version = "0.1.1"
2651+source = "registry+https://github.com/rust-lang/crates.io-index"
2652+checksum = "579a42fc0b8e0c63b76519a339be31bed574929511fa53c1a3acae26eb258f29"
2653+
24402654 [[package]]
24412655 name = "version_check"
24422656 version = "0.9.4"
Cargo.tomlmodified+4 -0
@@ -16,6 +16,7 @@ keyframe = { version = "1.1.1", default-features = false }
1616 knuffel = "3.2.0"
1717 logind-zbus = "3.1.2"
1818 miette = { version = "5.10.0", features = ["fancy"] }
19+pipewire = "0.7.2"
1920 portable-atomic = { version = "1.4.3", default-features = false, features = ["float"] }
2021 profiling = "1.0.10"
2122 sd-notify = "0.4.1"
@@ -26,9 +27,11 @@ tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
2627 tracy-client = { version = "0.15", default-features = false }
2728 xcursor = "0.3.4"
2829 zbus = { version = "3.14.1" }
30+async-io = "1.13.0"
2931
3032 [dependencies.smithay]
3133 git = "https://github.com/Smithay/smithay.git"
34+# path = "../smithay"
3235 default-features = false
3336 features = [
3437 "backend_drm",
@@ -48,6 +51,7 @@ features = [
4851
4952 [dependencies.smithay-drm-extras]
5053 git = "https://github.com/Smithay/smithay.git"
54+# path = "../smithay/smithay-drm-extras"
5155
5256 [features]
5357 profile-with-tracy = ["profiling/profile-with-tracy", "tracy-client/default"]
src/backend/mod.rsmodified+19 -0
@@ -1,3 +1,8 @@
1+use std::collections::HashMap;
2+use std::sync::{Arc, Mutex};
3+
4+use smithay::backend::allocator::gbm::GbmDevice;
5+use smithay::backend::drm::DrmDeviceFd;
16 use smithay::backend::renderer::gles::GlesRenderer;
27 use smithay::output::Output;
38 use smithay::wayland::dmabuf::DmabufFeedback;
@@ -79,6 +84,20 @@ impl Backend {
7984 }
8085 }
8186
87+ pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
88+ match self {
89+ Backend::Tty(tty) => tty.connectors(),
90+ Backend::Winit(winit) => winit.connectors(),
91+ }
92+ }
93+
94+ pub fn gbm_device(&self) -> Option<GbmDevice<DrmDeviceFd>> {
95+ match self {
96+ Backend::Tty(tty) => tty.gbm_device(),
97+ Backend::Winit(_) => None,
98+ }
99+ }
100+
82101 pub fn tty(&mut self) -> &mut Tty {
83102 if let Self::Tty(v) = self {
84103 v
src/backend/tty.rsmodified+21 -3
@@ -1,6 +1,7 @@
11 use std::collections::{HashMap, HashSet};
22 use std::os::fd::FromRawFd;
33 use std::path::{Path, PathBuf};
4+use std::sync::{Mutex, Arc};
45 use std::time::Duration;
56
67 use anyhow::{anyhow, Context};
@@ -44,6 +45,7 @@ pub struct Tty {
4445 udev_dispatcher: Dispatcher<'static, UdevBackend, LoopData>,
4546 primary_gpu_path: PathBuf,
4647 output_device: Option<OutputDevice>,
48+ connectors: Arc<Mutex<HashMap<String, Output>>>,
4749 }
4850
4951 type GbmDrmCompositor = DrmCompositor<
@@ -236,6 +238,7 @@ impl Tty {
236238 udev_dispatcher,
237239 primary_gpu_path,
238240 output_device: None,
241+ connectors: Arc::new(Mutex::new(HashMap::new())),
239242 }
240243 }
241244
@@ -549,6 +552,11 @@ impl Tty {
549552 tracy_client::internal::create_frame_name(format!("vblank on {output_name}\0").leak())
550553 };
551554
555+ self.connectors
556+ .lock()
557+ .unwrap()
558+ .insert(output_name.clone(), output.clone());
559+
552560 let surface = Surface {
553561 name: output_name,
554562 compositor,
@@ -574,10 +582,10 @@ impl Tty {
574582 debug!("disconnecting connector: {connector:?}");
575583 let device = self.output_device.as_mut().unwrap();
576584
577- if device.surfaces.remove(&crtc).is_none() {
578- debug!("crts wasn't enabled");
585+ let Some(surface) = device.surfaces.remove(&crtc) else {
586+ debug!("crtc wasn't enabled");
579587 return;
580- }
588+ };
581589
582590 let output = niri
583591 .global_space
@@ -590,6 +598,8 @@ impl Tty {
590598 .clone();
591599
592600 niri.remove_output(&output);
601+
602+ self.connectors.lock().unwrap().remove(&surface.name);
593603 }
594604
595605 pub fn seat_name(&self) -> String {
@@ -680,6 +690,14 @@ impl Tty {
680690 pub fn dmabuf_state(&mut self) -> &mut DmabufState {
681691 &mut self.output_device.as_mut().unwrap().dmabuf_state
682692 }
693+
694+ pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
695+ self.connectors.clone()
696+ }
697+
698+ pub fn gbm_device(&self) -> Option<GbmDevice<DrmDeviceFd>> {
699+ self.output_device.as_ref().map(|d| d.gbm.clone())
700+ }
683701 }
684702
685703 fn refresh_interval(mode: DrmMode) -> Duration {
src/backend/winit.rsmodified+13 -0
@@ -1,3 +1,5 @@
1+use std::collections::HashMap;
2+use std::sync::{Arc, Mutex};
13 use std::time::Duration;
24
35 use smithay::backend::renderer::damage::OutputDamageTracker;
@@ -21,6 +23,7 @@ pub struct Winit {
2123 output: Output,
2224 backend: WinitGraphicsBackend<GlesRenderer>,
2325 damage_tracker: OutputDamageTracker,
26+ connectors: Arc<Mutex<HashMap<String, Output>>>,
2427 }
2528
2629 impl Winit {
@@ -53,6 +56,11 @@ impl Winit {
5356 );
5457 output.set_preferred(mode);
5558
59+ let connectors = Arc::new(Mutex::new(HashMap::from([(
60+ "winit".to_owned(),
61+ output.clone(),
62+ )])));
63+
5664 let damage_tracker = OutputDamageTracker::from_output(&output);
5765
5866 let timer = Timer::immediate();
@@ -99,6 +107,7 @@ impl Winit {
99107 output,
100108 backend,
101109 damage_tracker,
110+ connectors,
102111 }
103112 }
104113
@@ -162,4 +171,8 @@ impl Winit {
162171 let renderer = self.backend.renderer();
163172 renderer.set_debug_flags(renderer.debug_flags() ^ DebugFlags::TINT);
164173 }
174+
175+ pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
176+ self.connectors.clone()
177+ }
165178 }
src/config.rsmodified+4 -0
@@ -128,12 +128,15 @@ pub enum Action {
128128 pub struct DebugConfig {
129129 #[knuffel(child, unwrap(argument), default = 1.)]
130130 pub animation_slowdown: f64,
131+ #[knuffel(child)]
132+ pub screen_cast_in_non_session_instances: bool,
131133 }
132134
133135 impl Default for DebugConfig {
134136 fn default() -> Self {
135137 Self {
136138 animation_slowdown: 1.,
139+ screen_cast_in_non_session_instances: false,
137140 }
138141 }
139142 }
@@ -308,6 +311,7 @@ mod tests {
308311 ]),
309312 debug: DebugConfig {
310313 animation_slowdown: 2.,
314+ ..Default::default()
311315 },
312316 },
313317 );
src/dbus/mod.rsmodified+2 -0
@@ -1 +1,3 @@
1+pub mod mutter_display_config;
2+pub mod mutter_screen_cast;
13 pub mod mutter_service_channel;
src/dbus/mutter_display_config.rsadded+88 -0
@@ -0,0 +1,88 @@
1+use std::collections::HashMap;
2+use std::sync::{Arc, Mutex};
3+
4+use serde::Serialize;
5+use smithay::output::Output;
6+use zbus::zvariant::{OwnedValue, Type};
7+use zbus::{dbus_interface, fdo};
8+
9+pub struct DisplayConfig {
10+ connectors: Arc<Mutex<HashMap<String, Output>>>,
11+}
12+
13+#[derive(Serialize, Type)]
14+pub struct Monitor {
15+ names: (String, String, String, String),
16+ modes: Vec<Mode>,
17+ properties: HashMap<String, OwnedValue>,
18+}
19+
20+#[derive(Serialize, Type)]
21+pub struct Mode {
22+ id: String,
23+ width: i32,
24+ height: i32,
25+ refresh_rate: f64,
26+ preferred_scale: f64,
27+ supported_scales: Vec<f64>,
28+ properties: HashMap<String, OwnedValue>,
29+}
30+
31+#[derive(Serialize, Type)]
32+pub struct LogicalMonitor {
33+ x: i32,
34+ y: i32,
35+ scale: f64,
36+ transform: u32,
37+ is_primary: bool,
38+ monitors: Vec<(String, String, String, String)>,
39+ properties: HashMap<String, OwnedValue>,
40+}
41+
42+#[dbus_interface(name = "org.gnome.Mutter.DisplayConfig")]
43+impl DisplayConfig {
44+ async fn get_current_state(
45+ &self,
46+ ) -> fdo::Result<(
47+ u32,
48+ Vec<Monitor>,
49+ Vec<LogicalMonitor>,
50+ HashMap<String, OwnedValue>,
51+ )> {
52+ // Construct the DBus response.
53+ let monitors: Vec<Monitor> = self
54+ .connectors
55+ .lock()
56+ .unwrap()
57+ .keys()
58+ .map(|c| Monitor {
59+ names: (c.clone(), String::new(), String::new(), String::new()),
60+ modes: vec![],
61+ properties: HashMap::new(),
62+ })
63+ .collect();
64+
65+ let logical_monitors = monitors
66+ .iter()
67+ .map(|m| LogicalMonitor {
68+ x: 0,
69+ y: 0,
70+ scale: 1.,
71+ transform: 0,
72+ is_primary: false,
73+ monitors: vec![m.names.clone()],
74+ properties: HashMap::new(),
75+ })
76+ .collect();
77+
78+ Ok((0, monitors, logical_monitors, HashMap::new()))
79+ }
80+
81+ // FIXME: monitors-changed signal.
82+}
83+
84+impl DisplayConfig {
85+ pub fn new(connectors: Arc<Mutex<HashMap<String, Output>>>) -> Self {
86+ Self { connectors }
87+ }
88+}
src/dbus/mutter_screen_cast.rsadded+256 -0
@@ -0,0 +1,256 @@
1+use std::collections::HashMap;
2+use std::mem;
3+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
4+use std::sync::{Arc, Mutex};
5+
6+use serde::Deserialize;
7+use smithay::output::Output;
8+use smithay::reexports::calloop;
9+use zbus::zvariant::{DeserializeDict, OwnedObjectPath, Type, Value};
10+use zbus::{dbus_interface, fdo, InterfaceRef, ObjectServer, SignalContext};
11+
12+#[derive(Clone)]
13+pub struct ScreenCast {
14+ connectors: Arc<Mutex<HashMap<String, Output>>>,
15+ to_niri: calloop::channel::Sender<ToNiriMsg>,
16+ sessions: Arc<Mutex<Vec<(Session, InterfaceRef<Session>)>>>,
17+}
18+
19+#[derive(Clone)]
20+pub struct Session {
21+ id: usize,
22+ connectors: Arc<Mutex<HashMap<String, Output>>>,
23+ to_niri: calloop::channel::Sender<ToNiriMsg>,
24+ streams: Arc<Mutex<Vec<(Stream, InterfaceRef<Stream>)>>>,
25+}
26+
27+#[derive(Debug, Default, Deserialize, Type, Clone, Copy)]
28+pub enum CursorMode {
29+ #[default]
30+ Hidden = 0,
31+ Embedded = 1,
32+ Metadata = 2,
33+}
34+
35+#[derive(Debug, DeserializeDict, Type)]
36+#[zvariant(signature = "dict")]
37+struct RecordMonitorProperties {
38+ #[zvariant(rename = "cursor-mode")]
39+ cursor_mode: Option<CursorMode>,
40+ #[zvariant(rename = "is-recording")]
41+ _is_recording: Option<bool>,
42+}
43+
44+#[derive(Clone)]
45+pub struct Stream {
46+ output: Output,
47+ cursor_mode: CursorMode,
48+ was_started: Arc<AtomicBool>,
49+ to_niri: calloop::channel::Sender<ToNiriMsg>,
50+}
51+
52+pub enum ToNiriMsg {
53+ StartCast {
54+ session_id: usize,
55+ output: Output,
56+ cursor_mode: CursorMode,
57+ signal_ctx: SignalContext<'static>,
58+ },
59+ StopCast {
60+ session_id: usize,
61+ },
62+}
63+
64+#[dbus_interface(name = "org.gnome.Mutter.ScreenCast")]
65+impl ScreenCast {
66+ async fn create_session(
67+ &self,
68+ #[zbus(object_server)] server: &ObjectServer,
69+ properties: HashMap<&str, Value<'_>>,
70+ ) -> fdo::Result<OwnedObjectPath> {
71+ if properties.contains_key("remote-desktop-session-id") {
72+ return Err(fdo::Error::Failed(
73+ "there are no remote desktop sessions".to_owned(),
74+ ));
75+ }
76+
77+ static NUMBER: AtomicUsize = AtomicUsize::new(0);
78+ let session_id = NUMBER.fetch_add(1, Ordering::SeqCst);
79+ let path = format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id);
80+ let path = OwnedObjectPath::try_from(path).unwrap();
81+
82+ let session = Session::new(session_id, self.connectors.clone(), self.to_niri.clone());
83+ match server.at(&path, session.clone()).await {
84+ Ok(true) => {
85+ let iface = server.interface(&path).await.unwrap();
86+ self.sessions.lock().unwrap().push((session, iface));
87+ }
88+ Ok(false) => return Err(fdo::Error::Failed("session path already exists".to_owned())),
89+ Err(err) => {
90+ return Err(fdo::Error::Failed(format!(
91+ "error creating session object: {err:?}"
92+ )))
93+ }
94+ }
95+
96+ Ok(path)
97+ }
98+
99+ #[dbus_interface(property)]
100+ async fn version(&self) -> i32 {
101+ 4
102+ }
103+}
104+
105+#[dbus_interface(name = "org.gnome.Mutter.ScreenCast.Session")]
106+impl Session {
107+ async fn start(&self) {
108+ debug!("start");
109+
110+ for (stream, iface) in &*self.streams.lock().unwrap() {
111+ stream.start(self.id, iface.signal_context().clone());
112+ }
113+ }
114+
115+ pub async fn stop(
116+ &self,
117+ #[zbus(object_server)] server: &ObjectServer,
118+ #[zbus(signal_context)] ctxt: SignalContext<'_>,
119+ ) {
120+ debug!("stop");
121+
122+ Session::closed(&ctxt).await.unwrap();
123+
124+ if let Err(err) = self.to_niri.send(ToNiriMsg::StopCast {
125+ session_id: self.id,
126+ }) {
127+ warn!("error sending StopCast to niri: {err:?}");
128+ }
129+
130+ let streams = mem::take(&mut *self.streams.lock().unwrap());
131+ for (_, iface) in streams.iter() {
132+ server
133+ .remove::<Stream, _>(iface.signal_context().path())
134+ .await
135+ .unwrap();
136+ }
137+
138+ server.remove::<Session, _>(ctxt.path()).await.unwrap();
139+ }
140+
141+ async fn record_monitor(
142+ &mut self,
143+ #[zbus(object_server)] server: &ObjectServer,
144+ connector: &str,
145+ properties: RecordMonitorProperties,
146+ ) -> fdo::Result<OwnedObjectPath> {
147+ debug!(connector, ?properties, "record_monitor");
148+
149+ let Some(output) = self.connectors.lock().unwrap().get(connector).cloned() else {
150+ return Err(fdo::Error::Failed("no such monitor".to_owned()));
151+ };
152+
153+ static NUMBER: AtomicUsize = AtomicUsize::new(0);
154+ let path = format!(
155+ "/org/gnome/Mutter/ScreenCast/Stream/u{}",
156+ NUMBER.fetch_add(1, Ordering::SeqCst)
157+ );
158+ let path = OwnedObjectPath::try_from(path).unwrap();
159+
160+ let cursor_mode = properties.cursor_mode.unwrap_or_default();
161+
162+ let stream = Stream::new(output, cursor_mode, self.to_niri.clone());
163+ match server.at(&path, stream.clone()).await {
164+ Ok(true) => {
165+ let iface = server.interface(&path).await.unwrap();
166+ self.streams.lock().unwrap().push((stream, iface));
167+ }
168+ Ok(false) => return Err(fdo::Error::Failed("stream path already exists".to_owned())),
169+ Err(err) => {
170+ return Err(fdo::Error::Failed(format!(
171+ "error creating stream object: {err:?}"
172+ )))
173+ }
174+ }
175+
176+ Ok(path)
177+ }
178+
179+ #[dbus_interface(signal)]
180+ async fn closed(ctxt: &SignalContext<'_>) -> zbus::Result<()>;
181+}
182+
183+#[dbus_interface(name = "org.gnome.Mutter.ScreenCast.Stream")]
184+impl Stream {
185+ #[dbus_interface(signal)]
186+ pub async fn pipe_wire_stream_added(ctxt: &SignalContext<'_>, node_id: u32)
187+ -> zbus::Result<()>;
188+}
189+
190+impl ScreenCast {
191+ pub fn new(
192+ connectors: Arc<Mutex<HashMap<String, Output>>>,
193+ to_niri: calloop::channel::Sender<ToNiriMsg>,
194+ ) -> Self {
195+ Self {
196+ connectors,
197+ to_niri,
198+ sessions: Arc::new(Mutex::new(vec![])),
199+ }
200+ }
201+}
202+
203+impl Session {
204+ pub fn new(
205+ id: usize,
206+ connectors: Arc<Mutex<HashMap<String, Output>>>,
207+ to_niri: calloop::channel::Sender<ToNiriMsg>,
208+ ) -> Self {
209+ Self {
210+ id,
211+ connectors,
212+ streams: Arc::new(Mutex::new(vec![])),
213+ to_niri,
214+ }
215+ }
216+}
217+
218+impl Drop for Session {
219+ fn drop(&mut self) {
220+ let _ = self.to_niri.send(ToNiriMsg::StopCast {
221+ session_id: self.id,
222+ });
223+ }
224+}
225+
226+impl Stream {
227+ pub fn new(
228+ output: Output,
229+ cursor_mode: CursorMode,
230+ to_niri: calloop::channel::Sender<ToNiriMsg>,
231+ ) -> Self {
232+ Self {
233+ output,
234+ cursor_mode,
235+ was_started: Arc::new(AtomicBool::new(false)),
236+ to_niri,
237+ }
238+ }
239+
240+ fn start(&self, session_id: usize, ctxt: SignalContext<'static>) {
241+ if self.was_started.load(Ordering::SeqCst) {
242+ return;
243+ }
244+
245+ let msg = ToNiriMsg::StartCast {
246+ session_id,
247+ output: self.output.clone(),
248+ cursor_mode: self.cursor_mode,
249+ signal_ctx: ctxt,
250+ };
251+
252+ if let Err(err) = self.to_niri.send(msg) {
253+ warn!("error sending StartCast to niri: {err:?}");
254+ }
255+ }
256+}
src/main.rsmodified+1 -0
@@ -10,6 +10,7 @@ mod handlers;
1010 mod input;
1111 mod layout;
1212 mod niri;
13+mod pw_utils;
1314 mod utils;
1415
1516 use std::env;
src/niri.rsmodified+283 -46
@@ -8,6 +8,7 @@ use std::{env, thread};
88 use anyhow::Context;
99 use directories::UserDirs;
1010 use sd_notify::NotifyState;
11+use smithay::backend::allocator::dmabuf::Dmabuf;
1112 use smithay::backend::allocator::Fourcc;
1213 use smithay::backend::renderer::element::surface::{
1314 render_elements_from_surface_tree, WaylandSurfaceRenderElement,
@@ -16,7 +17,7 @@ use smithay::backend::renderer::element::texture::{TextureBuffer, TextureRenderE
1617 use smithay::backend::renderer::element::{
1718 render_elements, AsRenderElements, Element, RenderElement, RenderElementStates,
1819 };
19-use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};
20+use smithay::backend::renderer::gles::{GlesMapping, GlesRenderer, GlesTexture};
2021 use smithay::backend::renderer::{Bind, ExportMem, Frame, ImportAll, Offscreen, Renderer};
2122 use smithay::desktop::utils::{
2223 send_dmabuf_feedback_surface_tree, send_frames_surface_tree,
@@ -31,7 +32,7 @@ use smithay::input::pointer::{CursorImageAttributes, CursorImageStatus, MotionEv
3132 use smithay::input::{Seat, SeatState};
3233 use smithay::output::Output;
3334 use smithay::reexports::calloop::generic::Generic;
34-use smithay::reexports::calloop::{Idle, Interest, LoopHandle, LoopSignal, Mode, PostAction};
35+use smithay::reexports::calloop::{self, Idle, Interest, LoopHandle, LoopSignal, Mode, PostAction};
3536 use smithay::reexports::nix::libc::CLOCK_MONOTONIC;
3637 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
3738 use smithay::reexports::wayland_server::backend::{
@@ -40,7 +41,7 @@ use smithay::reexports::wayland_server::backend::{
4041 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
4142 use smithay::reexports::wayland_server::{Display, DisplayHandle};
4243 use smithay::utils::{
43- IsAlive, Logical, Physical, Point, Rectangle, Scale, Transform, SERIAL_COUNTER,
44+ IsAlive, Logical, Physical, Point, Rectangle, Scale, Size, Transform, SERIAL_COUNTER,
4445 };
4546 use smithay::wayland::compositor::{with_states, CompositorClientState, CompositorState};
4647 use smithay::wayland::data_device::DataDeviceState;
@@ -57,9 +58,12 @@ use time::OffsetDateTime;
5758
5859 use crate::backend::{Backend, Tty, Winit};
5960 use crate::config::Config;
61+use crate::dbus::mutter_display_config::DisplayConfig;
62+use crate::dbus::mutter_screen_cast::{self, ScreenCast, ToNiriMsg};
6063 use crate::dbus::mutter_service_channel::ServiceChannel;
6164 use crate::frame_clock::FrameClock;
6265 use crate::layout::{MonitorRenderElement, MonitorSet};
66+use crate::pw_utils::{Cast, PipeWire};
6367 use crate::utils::{center, get_monotonic_time, load_default_cursor};
6468 use crate::LoopData;
6569
@@ -102,6 +106,11 @@ pub struct Niri {
102106
103107 pub zbus_conn: Option<zbus::blocking::Connection>,
104108 pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,
109+ pub screen_cast: ScreenCast,
110+
111+ // Casts are dropped before PipeWire to prevent a double-free (yay).
112+ pub casts: Vec<Cast>,
113+ pub pipewire: Option<PipeWire>,
105114 }
106115
107116 pub struct OutputState {
@@ -137,13 +146,7 @@ impl State {
137146 Backend::Tty(Tty::new(event_loop.clone()))
138147 };
139148
140- let mut niri = Niri::new(
141- &config,
142- event_loop,
143- stop_signal,
144- display,
145- backend.seat_name(),
146- );
149+ let mut niri = Niri::new(&config, event_loop, stop_signal, display, &backend);
147150 backend.init(&mut niri);
148151
149152 Self {
@@ -195,7 +198,7 @@ impl Niri {
195198 event_loop: LoopHandle<'static, LoopData>,
196199 stop_signal: LoopSignal,
197200 display: &mut Display<State>,
198- seat_name: String,
201+ backend: &Backend,
199202 ) -> Self {
200203 let display_handle = display.handle();
201204
@@ -215,7 +218,7 @@ impl Niri {
215218 let presentation_state =
216219 PresentationState::new::<State>(&display_handle, CLOCK_MONOTONIC as u32);
217220
218- let mut seat: Seat<State> = seat_state.new_wl_seat(&display_handle, seat_name);
221+ let mut seat: Seat<State> = seat_state.new_wl_seat(&display_handle, backend.seat_name());
219222 let xkb = XkbConfig {
220223 rules: &config.input.keyboard.xkb.rules,
221224 model: &config.input.keyboard.xkb.model,
@@ -246,6 +249,102 @@ impl Niri {
246249 socket_name.to_string_lossy()
247250 );
248251
252+ let pipewire = match PipeWire::new(&event_loop) {
253+ Ok(pipewire) => Some(pipewire),
254+ Err(err) => {
255+ warn!("error starting PipeWire: {err:?}");
256+ None
257+ }
258+ };
259+
260+ let (to_niri, from_screen_cast) = calloop::channel::channel();
261+ event_loop
262+ .insert_source(from_screen_cast, {
263+ let to_niri = to_niri.clone();
264+ move |event, _, data| match event {
265+ calloop::channel::Event::Msg(msg) => match msg {
266+ ToNiriMsg::StartCast {
267+ session_id,
268+ output,
269+ cursor_mode,
270+ signal_ctx,
271+ } => {
272+ let _span = tracy_client::span!("StartCast");
273+
274+ debug!(session_id, "StartCast");
275+
276+ let gbm = match data.state.backend.gbm_device() {
277+ Some(gbm) => gbm,
278+ None => {
279+ debug!("no GBM device available");
280+ return;
281+ }
282+ };
283+
284+ let pw = data.state.niri.pipewire.as_ref().unwrap();
285+ match pw.start_cast(
286+ to_niri.clone(),
287+ gbm,
288+ session_id,
289+ output,
290+ cursor_mode,
291+ signal_ctx,
292+ ) {
293+ Ok(cast) => {
294+ data.state.niri.casts.push(cast);
295+ }
296+ Err(err) => {
297+ warn!("error starting screencast: {err:?}");
298+
299+ if let Err(err) =
300+ to_niri.send(ToNiriMsg::StopCast { session_id })
301+ {
302+ warn!("error sending StopCast to niri: {err:?}");
303+ }
304+ }
305+ }
306+ }
307+ ToNiriMsg::StopCast { session_id } => {
308+ let _span = tracy_client::span!("StopCast");
309+
310+ debug!(session_id, "StopCast");
311+
312+ for i in (0..data.state.niri.casts.len()).rev() {
313+ let cast = &data.state.niri.casts[i];
314+ if cast.session_id != session_id {
315+ continue;
316+ }
317+
318+ let cast = data.state.niri.casts.swap_remove(i);
319+ if let Err(err) = cast.stream.disconnect() {
320+ warn!("error disconnecting stream: {err:?}");
321+ }
322+ }
323+
324+ let server =
325+ data.state.niri.zbus_conn.as_ref().unwrap().object_server();
326+ let path =
327+ format!("/org/gnome/Mutter/ScreenCast/Session/u{}", session_id);
328+ if let Ok(iface) =
329+ server.interface::<_, mutter_screen_cast::Session>(path)
330+ {
331+ let _span = tracy_client::span!("invoking Session::stop");
332+
333+ async_io::block_on(async move {
334+ iface
335+ .get()
336+ .stop(&server, iface.signal_context().clone())
337+ .await
338+ });
339+ }
340+ }
341+ },
342+ calloop::channel::Event::Closed => (),
343+ }
344+ })
345+ .unwrap();
346+ let screen_cast = ScreenCast::new(backend.connectors(), to_niri);
347+
249348 let mut zbus_conn = None;
250349 let mut inhibit_power_key_fd = None;
251350 if std::env::var_os("NOTIFY_SOCKET").is_some() {
@@ -278,7 +377,7 @@ impl Niri {
278377 }
279378
280379 // Set up zbus, make sure it happens before anything might want it.
281- let conn = zbus::blocking::ConnectionBuilder::session()
380+ let mut conn = zbus::blocking::ConnectionBuilder::session()
282381 .unwrap()
283382 .name("org.gnome.Mutter.ServiceChannel")
284383 .unwrap()
@@ -286,9 +385,24 @@ impl Niri {
286385 "/org/gnome/Mutter/ServiceChannel",
287386 ServiceChannel::new(display_handle.clone()),
288387 )
289- .unwrap()
290- .build()
291388 .unwrap();
389+
390+ if pipewire.is_some() && !config.debug.screen_cast_in_non_session_instances {
391+ conn = conn
392+ .name("org.gnome.Mutter.ScreenCast")
393+ .unwrap()
394+ .serve_at("/org/gnome/Mutter/ScreenCast", screen_cast.clone())
395+ .unwrap()
396+ .name("org.gnome.Mutter.DisplayConfig")
397+ .unwrap()
398+ .serve_at(
399+ "/org/gnome/Mutter/DisplayConfig",
400+ DisplayConfig::new(backend.connectors()),
401+ )
402+ .unwrap();
403+ }
404+
405+ let conn = conn.build().unwrap();
292406 zbus_conn = Some(conn);
293407
294408 // Notify systemd we're ready.
@@ -321,6 +435,23 @@ impl Niri {
321435 warn!("error inhibiting power key: {err:?}");
322436 }
323437 }
438+ } else if pipewire.is_some() && config.debug.screen_cast_in_non_session_instances {
439+ let conn = zbus::blocking::ConnectionBuilder::session()
440+ .unwrap()
441+ .name("org.gnome.Mutter.ScreenCast")
442+ .unwrap()
443+ .serve_at("/org/gnome/Mutter/ScreenCast", screen_cast.clone())
444+ .unwrap()
445+ .name("org.gnome.Mutter.DisplayConfig")
446+ .unwrap()
447+ .serve_at(
448+ "/org/gnome/Mutter/DisplayConfig",
449+ DisplayConfig::new(backend.connectors()),
450+ )
451+ .unwrap()
452+ .build()
453+ .unwrap();
454+ zbus_conn = Some(conn);
324455 }
325456
326457 let display_source = Generic::new(
@@ -364,6 +495,9 @@ impl Niri {
364495
365496 zbus_conn,
366497 inhibit_power_key_fd,
498+ screen_cast,
499+ pipewire,
500+ casts: vec![],
367501 }
368502 }
369503
@@ -720,6 +854,9 @@ impl Niri {
720854
721855 // Send the frame callbacks.
722856 self.send_frame_callbacks(output);
857+
858+ // Render and send to PipeWire screencast streams.
859+ self.send_for_screen_cast(backend, output, &elements, presentation_time);
723860 }
724861
725862 fn send_dmabuf_feedbacks(&self, output: &Output, feedback: &DmabufFeedback) {
@@ -827,47 +964,74 @@ impl Niri {
827964 feedback
828965 }
829966
830- pub fn screenshot(
967+ fn send_for_screen_cast(
831968 &mut self,
832- renderer: &mut GlesRenderer,
969+ backend: &mut Backend,
833970 output: &Output,
834- ) -> anyhow::Result<()> {
835- let _span = tracy_client::span!("Niri::screenshot");
971+ elements: &[OutputRenderElements<GlesRenderer>],
972+ presentation_time: Duration,
973+ ) {
974+ let _span = tracy_client::span!("Niri::send_for_screen_cast");
836975
837976 let size = output.current_mode().unwrap().size;
838- let output_rect = Rectangle::from_loc_and_size((0, 0), size);
839- let buffer_size = size.to_logical(1).to_buffer(1, Transform::Normal);
840- let fourcc = Fourcc::Abgr8888;
841977
842- let texture: GlesTexture = renderer
843- .create_buffer(fourcc, buffer_size)
844- .context("error creating texture")?;
978+ for cast in &mut self.casts {
979+ if !cast.is_active.get() {
980+ continue;
981+ }
845982
846- let elements = self.render(renderer, output);
983+ if &cast.output != output {
984+ continue;
985+ }
986+
987+ let last = cast.last_frame_time;
988+ let min = cast.min_time_between_frames.get();
989+ if !last.is_zero() && presentation_time - last < min {
990+ trace!(
991+ "skipping frame because it is too soon \
992+ last={last:?} now={presentation_time:?} diff={:?} < min={min:?}",
993+ presentation_time - last,
994+ );
995+ continue;
996+ }
997+
998+ {
999+ let mut buffer = match cast.stream.dequeue_buffer() {
1000+ Some(buffer) => buffer,
1001+ None => {
1002+ warn!("no available buffer in pw stream, skipping frame");
1003+ continue;
1004+ }
1005+ };
8471006
848- renderer.bind(texture).context("error binding texture")?;
849- let mut frame = renderer
850- .render(size, Transform::Normal)
851- .context("error starting frame")?;
852-
853- frame
854- .clear([0.1, 0.1, 0.1, 1.], &[output_rect])
855- .context("error clearing")?;
856-
857- for element in elements.into_iter().rev() {
858- let src = element.src();
859- let dst = element.geometry(Scale::from(1.));
860- element
861- .draw(&mut frame, src, dst, &[output_rect])
862- .context("error drawing element")?;
1007+ let data = &mut buffer.datas_mut()[0];
1008+ let fd = data.as_raw().fd as i32;
1009+ let dmabuf = cast.dmabufs.borrow()[&fd].clone();
1010+
1011+ // FIXME: Hidden / embedded / metadata cursor
1012+ render_to_dmabuf(backend.renderer(), dmabuf, size, elements).unwrap();
1013+
1014+ let maxsize = data.as_raw().maxsize;
1015+ let chunk = data.chunk_mut();
1016+ *chunk.size_mut() = maxsize;
1017+ *chunk.stride_mut() = maxsize as i32 / size.h;
1018+ }
1019+
1020+ cast.last_frame_time = presentation_time;
8631021 }
1022+ }
8641023
865- let sync_point = frame.finish().context("error finishing frame")?;
866- sync_point.wait();
1024+ pub fn screenshot(
1025+ &mut self,
1026+ renderer: &mut GlesRenderer,
1027+ output: &Output,
1028+ ) -> anyhow::Result<()> {
1029+ let _span = tracy_client::span!("Niri::screenshot");
1030+
1031+ let size = output.current_mode().unwrap().size;
1032+ let elements = self.render(renderer, output);
8671033
868- let mapping = renderer
869- .copy_framebuffer(Rectangle::from_loc_and_size((0, 0), buffer_size), fourcc)
870- .context("error copying framebuffer")?;
1034+ let mapping = render_and_download(renderer, size, &elements).context("error rendering")?;
8711035 let copy = renderer
8721036 .map_texture(&mapping)
8731037 .context("error mapping texture")?;
@@ -928,3 +1092,76 @@ impl ClientData for ClientState {
9281092 fn initialized(&self, _client_id: ClientId) {}
9291093 fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
9301094 }
1095+
1096+fn render_and_download(
1097+ renderer: &mut GlesRenderer,
1098+ size: Size<i32, Physical>,
1099+ elements: &[OutputRenderElements<GlesRenderer>],
1100+) -> anyhow::Result<GlesMapping> {
1101+ let _span = tracy_client::span!("render_and_download");
1102+
1103+ let output_rect = Rectangle::from_loc_and_size((0, 0), size);
1104+ let buffer_size = size.to_logical(1).to_buffer(1, Transform::Normal);
1105+ let fourcc = Fourcc::Abgr8888;
1106+
1107+ let texture: GlesTexture = renderer
1108+ .create_buffer(fourcc, buffer_size)
1109+ .context("error creating texture")?;
1110+
1111+ renderer.bind(texture).context("error binding texture")?;
1112+ let mut frame = renderer
1113+ .render(size, Transform::Normal)
1114+ .context("error starting frame")?;
1115+
1116+ frame
1117+ .clear([0.1, 0.1, 0.1, 1.], &[output_rect])
1118+ .context("error clearing")?;
1119+
1120+ for element in elements.iter().rev() {
1121+ let src = element.src();
1122+ let dst = element.geometry(Scale::from(1.));
1123+ element
1124+ .draw(&mut frame, src, dst, &[output_rect])
1125+ .context("error drawing element")?;
1126+ }
1127+
1128+ let sync_point = frame.finish().context("error finishing frame")?;
1129+ sync_point.wait();
1130+
1131+ let mapping = renderer
1132+ .copy_framebuffer(Rectangle::from_loc_and_size((0, 0), buffer_size), fourcc)
1133+ .context("error copying framebuffer")?;
1134+ Ok(mapping)
1135+}
1136+
1137+fn render_to_dmabuf(
1138+ renderer: &mut GlesRenderer,
1139+ dmabuf: Dmabuf,
1140+ size: Size<i32, Physical>,
1141+ elements: &[OutputRenderElements<GlesRenderer>],
1142+) -> anyhow::Result<()> {
1143+ let _span = tracy_client::span!("render_to_dmabuf");
1144+
1145+ let output_rect = Rectangle::from_loc_and_size((0, 0), size);
1146+
1147+ renderer.bind(dmabuf).context("error binding texture")?;
1148+ let mut frame = renderer
1149+ .render(size, Transform::Normal)
1150+ .context("error starting frame")?;
1151+
1152+ frame
1153+ .clear([0.1, 0.1, 0.1, 1.], &[output_rect])
1154+ .context("error clearing")?;
1155+
1156+ for element in elements.iter().rev() {
1157+ let src = element.src();
1158+ let dst = element.geometry(Scale::from(1.));
1159+ element
1160+ .draw(&mut frame, src, dst, &[output_rect])
1161+ .context("error drawing element")?;
1162+ }
1163+
1164+ let _sync_point = frame.finish().context("error finishing frame")?;
1165+
1166+ Ok(())
1167+}
src/pw_utils.rsadded+382 -0
@@ -0,0 +1,382 @@
1+use std::cell::{Cell, RefCell};
2+use std::collections::HashMap;
3+use std::io::Cursor;
4+use std::mem;
5+use std::os::fd::AsRawFd;
6+use std::rc::Rc;
7+use std::time::Duration;
8+
9+use anyhow::Context as _;
10+use pipewire::spa::data::DataType;
11+use pipewire::spa::format::{FormatProperties, MediaSubtype, MediaType};
12+use pipewire::spa::param::format_utils::parse_format;
13+use pipewire::spa::param::video::{VideoFormat, VideoInfoRaw};
14+use pipewire::spa::param::ParamType;
15+use pipewire::spa::pod::serialize::PodSerializer;
16+use pipewire::spa::pod::{self, ChoiceValue, Pod, Property, PropertyFlags};
17+use pipewire::spa::sys::*;
18+use pipewire::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Rectangle, SpaTypes};
19+use pipewire::spa::Direction;
20+use pipewire::stream::{Stream, StreamFlags, StreamListener, StreamState};
21+use pipewire::{Context, Core, MainLoop, Properties};
22+use smithay::backend::allocator::dmabuf::{AsDmabuf, Dmabuf};
23+use smithay::backend::allocator::gbm::{GbmBufferFlags, GbmDevice};
24+use smithay::backend::allocator::Fourcc;
25+use smithay::backend::drm::DrmDeviceFd;
26+use smithay::output::Output;
27+use smithay::reexports::calloop::generic::Generic;
28+use smithay::reexports::calloop::{self, Interest, LoopHandle, Mode, PostAction};
29+use smithay::reexports::gbm::Modifier;
30+use zbus::SignalContext;
31+
32+use crate::dbus::mutter_screen_cast::{self, CursorMode, ToNiriMsg};
33+use crate::LoopData;
34+
35+pub struct PipeWire {
36+ _context: Context<MainLoop>,
37+ pub core: Core,
38+}
39+
40+pub struct Cast {
41+ pub session_id: usize,
42+ pub stream: Rc<Stream>,
43+ _listener: StreamListener<()>,
44+ pub is_active: Rc<Cell<bool>>,
45+ pub output: Output,
46+ pub cursor_mode: CursorMode,
47+ pub last_frame_time: Duration,
48+ pub min_time_between_frames: Rc<Cell<Duration>>,
49+ pub dmabufs: Rc<RefCell<HashMap<i32, Dmabuf>>>,
50+}
51+
52+impl PipeWire {
53+ pub fn new(event_loop: &LoopHandle<'static, LoopData>) -> anyhow::Result<Self> {
54+ let main_loop = MainLoop::new().context("error creating MainLoop")?;
55+ let context = Context::new(&main_loop).context("error creating Context")?;
56+ let core = context.connect(None).context("error creating Core")?;
57+
58+ let listener = core
59+ .add_listener_local()
60+ .error(|id, seq, res, message| {
61+ warn!(id, seq, res, message, "pw error");
62+ })
63+ .register();
64+ mem::forget(listener);
65+
66+ let generic = Generic::new(main_loop.fd().as_raw_fd(), Interest::READ, Mode::Level);
67+ event_loop
68+ .insert_source(generic, move |_, _, _| {
69+ let _span = tracy_client::span!("pipewire iteration");
70+ main_loop.iterate(Duration::ZERO);
71+ Ok(PostAction::Continue)
72+ })
73+ .unwrap();
74+
75+ Ok(Self {
76+ _context: context,
77+ core,
78+ })
79+ }
80+
81+ pub fn start_cast(
82+ &self,
83+ to_niri: calloop::channel::Sender<ToNiriMsg>,
84+ gbm: GbmDevice<DrmDeviceFd>,
85+ session_id: usize,
86+ output: Output,
87+ cursor_mode: CursorMode,
88+ signal_ctx: SignalContext<'static>,
89+ ) -> anyhow::Result<Cast> {
90+ let _span = tracy_client::span!("PipeWire::start_cast");
91+
92+ let stop_cast = move || {
93+ if let Err(err) = to_niri.send(ToNiriMsg::StopCast { session_id }) {
94+ warn!("error sending StopCast to niri: {err:?}");
95+ }
96+ };
97+
98+ let mode = output.current_mode().unwrap();
99+ let size = mode.size;
100+ let refresh = mode.refresh;
101+
102+ let stream = Stream::new(&self.core, "niri-screen-cast-src", Properties::new())
103+ .context("error creating Stream")?;
104+
105+ // Like in good old wayland-rs times...
106+ let stream = Rc::new(stream);
107+ let node_id = Rc::new(Cell::new(None));
108+ let is_active = Rc::new(Cell::new(false));
109+ let min_time_between_frames = Rc::new(Cell::new(Duration::ZERO));
110+ let dmabufs = Rc::new(RefCell::new(HashMap::new()));
111+
112+ let listener = stream
113+ .add_local_listener_with_user_data(())
114+ .state_changed({
115+ let stream = stream.clone();
116+ let is_active = is_active.clone();
117+ let stop_cast = stop_cast.clone();
118+ move |old, new| {
119+ debug!("pw stream: state changed: {old:?} -> {new:?}");
120+
121+ match new {
122+ StreamState::Paused => {
123+ if node_id.get().is_none() {
124+ let id = stream.node_id();
125+ node_id.set(Some(id));
126+ debug!("pw stream: sending signal with {id}");
127+
128+ let _span = tracy_client::span!("sending PipeWireStreamAdded");
129+ async_io::block_on(async {
130+ let res = mutter_screen_cast::Stream::pipe_wire_stream_added(
131+ &signal_ctx,
132+ id,
133+ )
134+ .await;
135+
136+ if let Err(err) = res {
137+ warn!("error sending PipeWireStreamAdded: {err:?}");
138+ stop_cast();
139+ }
140+ });
141+ }
142+
143+ is_active.set(false);
144+ }
145+ StreamState::Error(_) => {
146+ if is_active.get() {
147+ is_active.set(false);
148+ stop_cast();
149+ }
150+ }
151+ StreamState::Unconnected => (),
152+ StreamState::Connecting => (),
153+ StreamState::Streaming => {
154+ is_active.set(true);
155+ }
156+ }
157+ }
158+ })
159+ .param_changed({
160+ let min_time_between_frames = min_time_between_frames.clone();
161+ move |stream, id, _data, pod| {
162+ let id = ParamType::from_raw(id);
163+ trace!(?id, "pw stream: param_changed");
164+
165+ if id != ParamType::Format {
166+ return;
167+ }
168+
169+ let Some(pod) = pod else { return };
170+
171+ let (m_type, m_subtype) = match parse_format(pod) {
172+ Ok(x) => x,
173+ Err(err) => {
174+ warn!("pw stream: error parsing format: {err:?}");
175+ return;
176+ }
177+ };
178+
179+ if m_type != MediaType::Video || m_subtype != MediaSubtype::Raw {
180+ return;
181+ }
182+
183+ let mut format = VideoInfoRaw::new();
184+ format.parse(pod).unwrap();
185+ trace!("pw stream: got format = {format:?}");
186+
187+ let max_frame_rate = format.max_framerate();
188+ // Subtract 0.5 ms to improve edge cases when equal to refresh rate.
189+ let min_frame_time = Duration::from_secs_f64(
190+ max_frame_rate.denom as f64 / max_frame_rate.num as f64,
191+ ) - Duration::from_micros(500);
192+ min_time_between_frames.set(min_frame_time);
193+
194+ const BPP: u32 = 4;
195+ let stride = format.size().width * BPP;
196+ let size = stride * format.size().height;
197+
198+ let o1 = pod::object!(
199+ SpaTypes::ObjectParamBuffers,
200+ ParamType::Buffers,
201+ Property::new(
202+ SPA_PARAM_BUFFERS_buffers,
203+ pod::Value::Choice(ChoiceValue::Int(Choice(
204+ ChoiceFlags::empty(),
205+ ChoiceEnum::Range {
206+ default: 16,
207+ min: 2,
208+ max: 16
209+ }
210+ ))),
211+ ),
212+ Property::new(SPA_PARAM_BUFFERS_blocks, pod::Value::Int(1)),
213+ Property::new(SPA_PARAM_BUFFERS_size, pod::Value::Int(size as i32)),
214+ Property::new(SPA_PARAM_BUFFERS_stride, pod::Value::Int(stride as i32)),
215+ Property::new(SPA_PARAM_BUFFERS_align, pod::Value::Int(16)),
216+ Property::new(
217+ SPA_PARAM_BUFFERS_dataType,
218+ pod::Value::Choice(ChoiceValue::Int(Choice(
219+ ChoiceFlags::empty(),
220+ ChoiceEnum::Flags {
221+ default: 1 << DataType::DmaBuf.as_raw(),
222+ flags: vec![1 << DataType::DmaBuf.as_raw()],
223+ },
224+ ))),
225+ ),
226+ );
227+
228+ // FIXME: Hidden / embedded / metadata cursor
229+
230+ // let o2 = pod::object!(
231+ // SpaTypes::ObjectParamMeta,
232+ // ParamType::Meta,
233+ // Property::new(SPA_PARAM_META_type,
234+ // pod::Value::Id(Id(SPA_META_Header))),
235+ // Property::new(
236+ // SPA_PARAM_META_size,
237+ // pod::Value::Int(size_of::<spa_meta_header>() as i32)
238+ // ),
239+ // );
240+ let mut b1 = vec![];
241+ // let mut b2 = vec![];
242+ let mut params = [
243+ make_pod(&mut b1, o1).as_raw_ptr().cast_const(),
244+ // make_pod(&mut b2, o2).as_raw_ptr().cast_const(),
245+ ];
246+ stream.update_params(&mut params).unwrap();
247+ }
248+ })
249+ .add_buffer({
250+ let dmabufs = dmabufs.clone();
251+ let stop_cast = stop_cast.clone();
252+ move |buffer| {
253+ trace!("pw stream: add_buffer");
254+
255+ unsafe {
256+ let spa_buffer = (*buffer).buffer;
257+ let spa_data = (*spa_buffer).datas;
258+ assert!((*spa_buffer).n_datas > 0);
259+ assert!((*spa_data).type_ & (1 << DataType::DmaBuf.as_raw()) > 0);
260+
261+ let bo = match gbm.create_buffer_object::<()>(
262+ size.w as u32,
263+ size.h as u32,
264+ Fourcc::Xrgb8888,
265+ GbmBufferFlags::RENDERING | GbmBufferFlags::LINEAR,
266+ ) {
267+ Ok(bo) => bo,
268+ Err(err) => {
269+ warn!("error creating GBM buffer object: {err:?}");
270+ stop_cast();
271+ return;
272+ }
273+ };
274+ let dmabuf = match bo.export() {
275+ Ok(dmabuf) => dmabuf,
276+ Err(err) => {
277+ warn!("error exporting GBM buffer object as dmabuf: {err:?}");
278+ stop_cast();
279+ return;
280+ }
281+ };
282+
283+ let fd = dmabuf.handles().next().unwrap().as_raw_fd();
284+
285+ (*spa_data).type_ = DataType::DmaBuf.as_raw();
286+ (*spa_data).maxsize = dmabuf.strides().next().unwrap() * size.h as u32;
287+ (*spa_data).fd = fd as i64;
288+ (*spa_data).flags = SPA_DATA_FLAG_READWRITE;
289+
290+ assert!(dmabufs.borrow_mut().insert(fd, dmabuf).is_none());
291+ }
292+ }
293+ })
294+ .remove_buffer({
295+ let dmabufs = dmabufs.clone();
296+ move |buffer| {
297+ trace!("pw stream: remove_buffer");
298+
299+ unsafe {
300+ let spa_buffer = (*buffer).buffer;
301+ let spa_data = (*spa_buffer).datas;
302+ assert!((*spa_buffer).n_datas > 0);
303+
304+ let fd = (*spa_data).fd as i32;
305+ dmabufs.borrow_mut().remove(&fd);
306+ }
307+ }
308+ })
309+ .register()
310+ .unwrap();
311+
312+ let object = pod::object!(
313+ SpaTypes::ObjectParamFormat,
314+ ParamType::EnumFormat,
315+ pod::property!(FormatProperties::MediaType, Id, MediaType::Video),
316+ pod::property!(FormatProperties::MediaSubtype, Id, MediaSubtype::Raw),
317+ pod::property!(FormatProperties::VideoFormat, Id, VideoFormat::BGRx),
318+ Property {
319+ key: FormatProperties::VideoModifier.as_raw(),
320+ value: pod::Value::Long(u64::from(Modifier::Invalid) as i64),
321+ flags: PropertyFlags::MANDATORY,
322+ },
323+ pod::property!(
324+ FormatProperties::VideoSize,
325+ Rectangle,
326+ Rectangle {
327+ width: size.w as u32,
328+ height: size.h as u32,
329+ }
330+ ),
331+ pod::property!(
332+ FormatProperties::VideoFramerate,
333+ Fraction,
334+ Fraction { num: 0, denom: 1 }
335+ ),
336+ pod::property!(
337+ FormatProperties::VideoMaxFramerate,
338+ Choice,
339+ Range,
340+ Fraction,
341+ Fraction {
342+ num: refresh as u32,
343+ denom: 1000
344+ },
345+ Fraction { num: 1, denom: 1 },
346+ Fraction {
347+ num: refresh as u32,
348+ denom: 1000
349+ }
350+ ),
351+ );
352+
353+ let mut buffer = vec![];
354+ let mut params = [make_pod(&mut buffer, object)];
355+ stream
356+ .connect(
357+ Direction::Output,
358+ None,
359+ StreamFlags::DRIVER | StreamFlags::ALLOC_BUFFERS,
360+ &mut params,
361+ )
362+ .context("error connecting stream")?;
363+
364+ let cast = Cast {
365+ session_id,
366+ stream,
367+ _listener: listener,
368+ is_active,
369+ output,
370+ cursor_mode,
371+ last_frame_time: Duration::ZERO,
372+ min_time_between_frames,
373+ dmabufs,
374+ };
375+ Ok(cast)
376+ }
377+}
378+
379+fn make_pod(buffer: &mut Vec<u8>, object: pod::Object) -> &Pod {
380+ PodSerializer::serialize(Cursor::new(&mut *buffer), &pod::Value::Object(object)).unwrap();
381+ Pod::from_bytes(buffer).unwrap()
382+}