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:
29 29
30 - name: Install dependencies30 - name: Install dependencies
31 run: |31 run: |
32+ sudo apt-get install -y software-properties-common
33+ sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
32 sudo apt-get update -y34 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-dev35+ 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
34 36
35 - name: Install Rust37 - name: Install Rust
36 run: |38 run: |
@@ -67,8 +69,10 @@ jobs:
67 69
68 - name: Install dependencies70 - name: Install dependencies
69 run: |71 run: |
72+ sudo apt-get install -y software-properties-common
73+ sudo add-apt-repository -y ppa:pipewire-debian/pipewire-upstream
70 sudo apt-get update -y74 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-dev75+ 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
72 76
73 - name: Install Rust77 - name: Install Rust
74 run: |78 run: |
Cargo.lockmodified+216 -2
@@ -294,6 +294,26 @@ version = "0.21.3"
294 source = "registry+https://github.com/rust-lang/crates.io-index"294 source = "registry+https://github.com/rust-lang/crates.io-index"
295 checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53"295 checksum = "414dcefbc63d77c526a76b3afcf6fbb9b5e2791c19c3aa2297733208750c6e53"
296 296
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+
297 [[package]]317 [[package]]
298 name = "bitflags"318 name = "bitflags"
299 version = "1.3.2"319 version = "1.3.2"
@@ -405,6 +425,25 @@ dependencies = [
405 "libc",425 "libc",
406 ]426 ]
407 427
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+
408 [[package]]447 [[package]]
409 name = "cfg-if"448 name = "cfg-if"
410 version = "1.0.0"449 version = "1.0.0"
@@ -436,6 +475,17 @@ dependencies = [
436 "hashbrown 0.12.3",475 "hashbrown 0.12.3",
437 ]476 ]
438 477
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+
439 [[package]]489 [[package]]
440 name = "clap"490 name = "clap"
441 version = "4.4.2"491 version = "4.4.2"
@@ -497,6 +547,21 @@ dependencies = [
497 "crossbeam-utils",547 "crossbeam-utils",
498 ]548 ]
499 549
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+
500 [[package]]565 [[package]]
501 name = "core-foundation"566 name = "core-foundation"
502 version = "0.9.3"567 version = "0.9.3"
@@ -634,7 +699,7 @@ version = "0.5.2"
634 source = "registry+https://github.com/rust-lang/crates.io-index"699 source = "registry+https://github.com/rust-lang/crates.io-index"
635 checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"700 checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
636 dependencies = [701 dependencies = [
637- "libloading",702+ "libloading 0.8.0",
638 ]703 ]
639 704
640 [[package]]705 [[package]]
@@ -920,6 +985,12 @@ dependencies = [
920 "xml-rs",985 "xml-rs",
921 ]986 ]
922 987
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+
923 [[package]]994 [[package]]
924 name = "hashbrown"995 name = "hashbrown"
925 version = "0.12.3"996 version = "0.12.3"
@@ -1130,12 +1201,28 @@ version = "1.4.0"
1130 source = "registry+https://github.com/rust-lang/crates.io-index"1201 source = "registry+https://github.com/rust-lang/crates.io-index"
1131 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"1202 checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
1132 1203
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+
1133 [[package]]1210 [[package]]
1134 name = "libc"1211 name = "libc"
1135 version = "0.2.147"1212 version = "0.2.147"
1136 source = "registry+https://github.com/rust-lang/crates.io-index"1213 source = "registry+https://github.com/rust-lang/crates.io-index"
1137 checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"1214 checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
1138 1215
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+
1139 [[package]]1226 [[package]]
1140 name = "libloading"1227 name = "libloading"
1141 version = "0.8.0"1228 version = "0.8.0"
@@ -1172,6 +1259,34 @@ dependencies = [
1172 "pkg-config",1259 "pkg-config",
1173 ]1260 ]
1174 1261
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+
1175 [[package]]1290 [[package]]
1176 name = "libudev-sys"1291 name = "libudev-sys"
1177 version = "0.1.4"1292 version = "0.1.4"
@@ -1368,6 +1483,7 @@ name = "niri"
1368 version = "0.1.0"1483 version = "0.1.0"
1369 dependencies = [1484 dependencies = [
1370 "anyhow",1485 "anyhow",
1486+ "async-io",
1371 "bitflags 2.4.0",1487 "bitflags 2.4.0",
1372 "clap",1488 "clap",
1373 "directories",1489 "directories",
@@ -1376,6 +1492,7 @@ dependencies = [
1376 "knuffel",1492 "knuffel",
1377 "logind-zbus",1493 "logind-zbus",
1378 "miette",1494 "miette",
1495+ "pipewire",
1379 "portable-atomic",1496 "portable-atomic",
1380 "profiling",1497 "profiling",
1381 "sd-notify",1498 "sd-notify",
@@ -1614,6 +1731,12 @@ version = "2.1.0"
1614 source = "registry+https://github.com/rust-lang/crates.io-index"1731 source = "registry+https://github.com/rust-lang/crates.io-index"
1615 checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e"1732 checksum = "14f2252c834a40ed9bb5422029649578e63aa341ac401f74e719dd1afda8394e"
1616 1733
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+
1617 [[package]]1740 [[package]]
1618 name = "percent-encoding"1741 name = "percent-encoding"
1619 version = "2.3.0"1742 version = "2.3.0"
@@ -1632,6 +1755,34 @@ version = "0.1.0"
1632 source = "registry+https://github.com/rust-lang/crates.io-index"1755 source = "registry+https://github.com/rust-lang/crates.io-index"
1633 checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"1756 checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
1634 1757
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+
1635 [[package]]1786 [[package]]
1636 name = "pkg-config"1787 name = "pkg-config"
1637 version = "0.3.27"1788 version = "0.3.27"
@@ -1875,6 +2026,12 @@ version = "0.1.23"
1875 source = "registry+https://github.com/rust-lang/crates.io-index"2026 source = "registry+https://github.com/rust-lang/crates.io-index"
1876 checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"2027 checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76"
1877 2028
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+
1878 [[package]]2035 [[package]]
1879 name = "rustix"2036 name = "rustix"
1880 version = "0.37.23"2037 version = "0.37.23"
@@ -1957,6 +2114,15 @@ dependencies = [
1957 "syn 2.0.31",2114 "syn 2.0.31",
1958 ]2115 ]
1959 2116
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+
1960 [[package]]2126 [[package]]
1961 name = "sha1"2127 name = "sha1"
1962 version = "0.10.5"2128 version = "0.10.5"
@@ -1977,6 +2143,12 @@ dependencies = [
1977 "lazy_static",2143 "lazy_static",
1978 ]2144 ]
1979 2145
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+
1980 [[package]]2152 [[package]]
1981 name = "signal-hook"2153 name = "signal-hook"
1982 version = "0.3.17"2154 version = "0.3.17"
@@ -2052,7 +2224,7 @@ dependencies = [
2052 "input",2224 "input",
2053 "lazy_static",2225 "lazy_static",
2054 "libc",2226 "libc",
2055- "libloading",2227+ "libloading 0.8.0",
2056 "libseat",2228 "libseat",
2057 "nix 0.26.4",2229 "nix 0.26.4",
2058 "once_cell",2230 "once_cell",
@@ -2175,6 +2347,25 @@ dependencies = [
2175 "unicode-ident",2347 "unicode-ident",
2176 ]2348 ]
2177 2349
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+
2178 [[package]]2369 [[package]]
2179 name = "tempfile"2370 name = "tempfile"
2180 version = "3.8.0"2371 version = "3.8.0"
@@ -2269,11 +2460,26 @@ dependencies = [
2269 "time-core",2460 "time-core",
2270 ]2461 ]
2271 2462
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+
2272 [[package]]2475 [[package]]
2273 name = "toml_datetime"2476 name = "toml_datetime"
2274 version = "0.6.3"2477 version = "0.6.3"
2275 source = "registry+https://github.com/rust-lang/crates.io-index"2478 source = "registry+https://github.com/rust-lang/crates.io-index"
2276 checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"2479 checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
2480+dependencies = [
2481+ "serde",
2482+]
2277 2483
2278 [[package]]2484 [[package]]
2279 name = "toml_edit"2485 name = "toml_edit"
@@ -2282,6 +2488,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
2282 checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"2488 checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
2283 dependencies = [2489 dependencies = [
2284 "indexmap 2.0.0",2490 "indexmap 2.0.0",
2491+ "serde",
2492+ "serde_spanned",
2285 "toml_datetime",2493 "toml_datetime",
2286 "winnow",2494 "winnow",
2287 ]2495 ]
@@ -2437,6 +2645,12 @@ version = "0.8.2"
2437 source = "registry+https://github.com/rust-lang/crates.io-index"2645 source = "registry+https://github.com/rust-lang/crates.io-index"
2438 checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"2646 checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
2439 2647
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+
2440 [[package]]2654 [[package]]
2441 name = "version_check"2655 name = "version_check"
2442 version = "0.9.4"2656 version = "0.9.4"
Cargo.tomlmodified+4 -0
@@ -16,6 +16,7 @@ keyframe = { version = "1.1.1", default-features = false }
16 knuffel = "3.2.0"16 knuffel = "3.2.0"
17 logind-zbus = "3.1.2"17 logind-zbus = "3.1.2"
18 miette = { version = "5.10.0", features = ["fancy"] }18 miette = { version = "5.10.0", features = ["fancy"] }
19+pipewire = "0.7.2"
19 portable-atomic = { version = "1.4.3", default-features = false, features = ["float"] }20 portable-atomic = { version = "1.4.3", default-features = false, features = ["float"] }
20 profiling = "1.0.10"21 profiling = "1.0.10"
21 sd-notify = "0.4.1"22 sd-notify = "0.4.1"
@@ -26,9 +27,11 @@ tracing-subscriber = { version = "0.3.17", features = ["env-filter"] }
26 tracy-client = { version = "0.15", default-features = false }27 tracy-client = { version = "0.15", default-features = false }
27 xcursor = "0.3.4"28 xcursor = "0.3.4"
28 zbus = { version = "3.14.1" }29 zbus = { version = "3.14.1" }
30+async-io = "1.13.0"
29 31
30 [dependencies.smithay]32 [dependencies.smithay]
31 git = "https://github.com/Smithay/smithay.git"33 git = "https://github.com/Smithay/smithay.git"
34+# path = "../smithay"
32 default-features = false35 default-features = false
33 features = [36 features = [
34 "backend_drm",37 "backend_drm",
@@ -48,6 +51,7 @@ features = [
48 51
49 [dependencies.smithay-drm-extras]52 [dependencies.smithay-drm-extras]
50 git = "https://github.com/Smithay/smithay.git"53 git = "https://github.com/Smithay/smithay.git"
54+# path = "../smithay/smithay-drm-extras"
51 55
52 [features]56 [features]
53 profile-with-tracy = ["profiling/profile-with-tracy", "tracy-client/default"]57 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;
1 use smithay::backend::renderer::gles::GlesRenderer;6 use smithay::backend::renderer::gles::GlesRenderer;
2 use smithay::output::Output;7 use smithay::output::Output;
3 use smithay::wayland::dmabuf::DmabufFeedback;8 use smithay::wayland::dmabuf::DmabufFeedback;
@@ -79,6 +84,20 @@ impl Backend {
79 }84 }
80 }85 }
81 86
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+
82 pub fn tty(&mut self) -> &mut Tty {101 pub fn tty(&mut self) -> &mut Tty {
83 if let Self::Tty(v) = self {102 if let Self::Tty(v) = self {
84 v103 v
src/backend/tty.rsmodified+21 -3
@@ -1,6 +1,7 @@
1 use std::collections::{HashMap, HashSet};1 use std::collections::{HashMap, HashSet};
2 use std::os::fd::FromRawFd;2 use std::os::fd::FromRawFd;
3 use std::path::{Path, PathBuf};3 use std::path::{Path, PathBuf};
4+use std::sync::{Mutex, Arc};
4 use std::time::Duration;5 use std::time::Duration;
5 6
6 use anyhow::{anyhow, Context};7 use anyhow::{anyhow, Context};
@@ -44,6 +45,7 @@ pub struct Tty {
44 udev_dispatcher: Dispatcher<'static, UdevBackend, LoopData>,45 udev_dispatcher: Dispatcher<'static, UdevBackend, LoopData>,
45 primary_gpu_path: PathBuf,46 primary_gpu_path: PathBuf,
46 output_device: Option<OutputDevice>,47 output_device: Option<OutputDevice>,
48+ connectors: Arc<Mutex<HashMap<String, Output>>>,
47 }49 }
48 50
49 type GbmDrmCompositor = DrmCompositor<51 type GbmDrmCompositor = DrmCompositor<
@@ -236,6 +238,7 @@ impl Tty {
236 udev_dispatcher,238 udev_dispatcher,
237 primary_gpu_path,239 primary_gpu_path,
238 output_device: None,240 output_device: None,
241+ connectors: Arc::new(Mutex::new(HashMap::new())),
239 }242 }
240 }243 }
241 244
@@ -549,6 +552,11 @@ impl Tty {
549 tracy_client::internal::create_frame_name(format!("vblank on {output_name}\0").leak())552 tracy_client::internal::create_frame_name(format!("vblank on {output_name}\0").leak())
550 };553 };
551 554
555+ self.connectors
556+ .lock()
557+ .unwrap()
558+ .insert(output_name.clone(), output.clone());
559+
552 let surface = Surface {560 let surface = Surface {
553 name: output_name,561 name: output_name,
554 compositor,562 compositor,
@@ -574,10 +582,10 @@ impl Tty {
574 debug!("disconnecting connector: {connector:?}");582 debug!("disconnecting connector: {connector:?}");
575 let device = self.output_device.as_mut().unwrap();583 let device = self.output_device.as_mut().unwrap();
576 584
577- if device.surfaces.remove(&crtc).is_none() {585+ let Some(surface) = device.surfaces.remove(&crtc) else {
578- debug!("crts wasn't enabled");586+ debug!("crtc wasn't enabled");
579 return;587 return;
580- }588+ };
581 589
582 let output = niri590 let output = niri
583 .global_space591 .global_space
@@ -590,6 +598,8 @@ impl Tty {
590 .clone();598 .clone();
591 599
592 niri.remove_output(&output);600 niri.remove_output(&output);
601+
602+ self.connectors.lock().unwrap().remove(&surface.name);
593 }603 }
594 604
595 pub fn seat_name(&self) -> String {605 pub fn seat_name(&self) -> String {
@@ -680,6 +690,14 @@ impl Tty {
680 pub fn dmabuf_state(&mut self) -> &mut DmabufState {690 pub fn dmabuf_state(&mut self) -> &mut DmabufState {
681 &mut self.output_device.as_mut().unwrap().dmabuf_state691 &mut self.output_device.as_mut().unwrap().dmabuf_state
682 }692 }
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+ }
683 }701 }
684 702
685 fn refresh_interval(mode: DrmMode) -> Duration {703 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};
1 use std::time::Duration;3 use std::time::Duration;
2 4
3 use smithay::backend::renderer::damage::OutputDamageTracker;5 use smithay::backend::renderer::damage::OutputDamageTracker;
@@ -21,6 +23,7 @@ pub struct Winit {
21 output: Output,23 output: Output,
22 backend: WinitGraphicsBackend<GlesRenderer>,24 backend: WinitGraphicsBackend<GlesRenderer>,
23 damage_tracker: OutputDamageTracker,25 damage_tracker: OutputDamageTracker,
26+ connectors: Arc<Mutex<HashMap<String, Output>>>,
24 }27 }
25 28
26 impl Winit {29 impl Winit {
@@ -53,6 +56,11 @@ impl Winit {
53 );56 );
54 output.set_preferred(mode);57 output.set_preferred(mode);
55 58
59+ let connectors = Arc::new(Mutex::new(HashMap::from([(
60+ "winit".to_owned(),
61+ output.clone(),
62+ )])));
63+
56 let damage_tracker = OutputDamageTracker::from_output(&output);64 let damage_tracker = OutputDamageTracker::from_output(&output);
57 65
58 let timer = Timer::immediate();66 let timer = Timer::immediate();
@@ -99,6 +107,7 @@ impl Winit {
99 output,107 output,
100 backend,108 backend,
101 damage_tracker,109 damage_tracker,
110+ connectors,
102 }111 }
103 }112 }
104 113
@@ -162,4 +171,8 @@ impl Winit {
162 let renderer = self.backend.renderer();171 let renderer = self.backend.renderer();
163 renderer.set_debug_flags(renderer.debug_flags() ^ DebugFlags::TINT);172 renderer.set_debug_flags(renderer.debug_flags() ^ DebugFlags::TINT);
164 }173 }
174+
175+ pub fn connectors(&self) -> Arc<Mutex<HashMap<String, Output>>> {
176+ self.connectors.clone()
177+ }
165 }178 }
src/config.rsmodified+4 -0
@@ -128,12 +128,15 @@ pub enum Action {
128 pub struct DebugConfig {128 pub struct DebugConfig {
129 #[knuffel(child, unwrap(argument), default = 1.)]129 #[knuffel(child, unwrap(argument), default = 1.)]
130 pub animation_slowdown: f64,130 pub animation_slowdown: f64,
131+ #[knuffel(child)]
132+ pub screen_cast_in_non_session_instances: bool,
131 }133 }
132 134
133 impl Default for DebugConfig {135 impl Default for DebugConfig {
134 fn default() -> Self {136 fn default() -> Self {
135 Self {137 Self {
136 animation_slowdown: 1.,138 animation_slowdown: 1.,
139+ screen_cast_in_non_session_instances: false,
137 }140 }
138 }141 }
139 }142 }
@@ -308,6 +311,7 @@ mod tests {
308 ]),311 ]),
309 debug: DebugConfig {312 debug: DebugConfig {
310 animation_slowdown: 2.,313 animation_slowdown: 2.,
314+ ..Default::default()
311 },315 },
312 },316 },
313 );317 );
src/dbus/mod.rsmodified+2 -0
@@ -1 +1,3 @@
1+pub mod mutter_display_config;
2+pub mod mutter_screen_cast;
1 pub mod mutter_service_channel;3 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;
10 mod input;10 mod input;
11 mod layout;11 mod layout;
12 mod niri;12 mod niri;
13+mod pw_utils;
13 mod utils;14 mod utils;
14 15
15 use std::env;16 use std::env;
src/niri.rsmodified+283 -46
@@ -8,6 +8,7 @@ use std::{env, thread};
8 use anyhow::Context;8 use anyhow::Context;
9 use directories::UserDirs;9 use directories::UserDirs;
10 use sd_notify::NotifyState;10 use sd_notify::NotifyState;
11+use smithay::backend::allocator::dmabuf::Dmabuf;
11 use smithay::backend::allocator::Fourcc;12 use smithay::backend::allocator::Fourcc;
12 use smithay::backend::renderer::element::surface::{13 use smithay::backend::renderer::element::surface::{
13 render_elements_from_surface_tree, WaylandSurfaceRenderElement,14 render_elements_from_surface_tree, WaylandSurfaceRenderElement,
@@ -16,7 +17,7 @@ use smithay::backend::renderer::element::texture::{TextureBuffer, TextureRenderE
16 use smithay::backend::renderer::element::{17 use smithay::backend::renderer::element::{
17 render_elements, AsRenderElements, Element, RenderElement, RenderElementStates,18 render_elements, AsRenderElements, Element, RenderElement, RenderElementStates,
18 };19 };
19-use smithay::backend::renderer::gles::{GlesRenderer, GlesTexture};20+use smithay::backend::renderer::gles::{GlesMapping, GlesRenderer, GlesTexture};
20 use smithay::backend::renderer::{Bind, ExportMem, Frame, ImportAll, Offscreen, Renderer};21 use smithay::backend::renderer::{Bind, ExportMem, Frame, ImportAll, Offscreen, Renderer};
21 use smithay::desktop::utils::{22 use smithay::desktop::utils::{
22 send_dmabuf_feedback_surface_tree, send_frames_surface_tree,23 send_dmabuf_feedback_surface_tree, send_frames_surface_tree,
@@ -31,7 +32,7 @@ use smithay::input::pointer::{CursorImageAttributes, CursorImageStatus, MotionEv
31 use smithay::input::{Seat, SeatState};32 use smithay::input::{Seat, SeatState};
32 use smithay::output::Output;33 use smithay::output::Output;
33 use smithay::reexports::calloop::generic::Generic;34 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};
35 use smithay::reexports::nix::libc::CLOCK_MONOTONIC;36 use smithay::reexports::nix::libc::CLOCK_MONOTONIC;
36 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;37 use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel::WmCapabilities;
37 use smithay::reexports::wayland_server::backend::{38 use smithay::reexports::wayland_server::backend::{
@@ -40,7 +41,7 @@ use smithay::reexports::wayland_server::backend::{
40 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;41 use smithay::reexports::wayland_server::protocol::wl_surface::WlSurface;
41 use smithay::reexports::wayland_server::{Display, DisplayHandle};42 use smithay::reexports::wayland_server::{Display, DisplayHandle};
42 use smithay::utils::{43 use smithay::utils::{
43- IsAlive, Logical, Physical, Point, Rectangle, Scale, Transform, SERIAL_COUNTER,44+ IsAlive, Logical, Physical, Point, Rectangle, Scale, Size, Transform, SERIAL_COUNTER,
44 };45 };
45 use smithay::wayland::compositor::{with_states, CompositorClientState, CompositorState};46 use smithay::wayland::compositor::{with_states, CompositorClientState, CompositorState};
46 use smithay::wayland::data_device::DataDeviceState;47 use smithay::wayland::data_device::DataDeviceState;
@@ -57,9 +58,12 @@ use time::OffsetDateTime;
57 58
58 use crate::backend::{Backend, Tty, Winit};59 use crate::backend::{Backend, Tty, Winit};
59 use crate::config::Config;60 use crate::config::Config;
61+use crate::dbus::mutter_display_config::DisplayConfig;
62+use crate::dbus::mutter_screen_cast::{self, ScreenCast, ToNiriMsg};
60 use crate::dbus::mutter_service_channel::ServiceChannel;63 use crate::dbus::mutter_service_channel::ServiceChannel;
61 use crate::frame_clock::FrameClock;64 use crate::frame_clock::FrameClock;
62 use crate::layout::{MonitorRenderElement, MonitorSet};65 use crate::layout::{MonitorRenderElement, MonitorSet};
66+use crate::pw_utils::{Cast, PipeWire};
63 use crate::utils::{center, get_monotonic_time, load_default_cursor};67 use crate::utils::{center, get_monotonic_time, load_default_cursor};
64 use crate::LoopData;68 use crate::LoopData;
65 69
@@ -102,6 +106,11 @@ pub struct Niri {
102 106
103 pub zbus_conn: Option<zbus::blocking::Connection>,107 pub zbus_conn: Option<zbus::blocking::Connection>,
104 pub inhibit_power_key_fd: Option<zbus::zvariant::OwnedFd>,108 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>,
105 }114 }
106 115
107 pub struct OutputState {116 pub struct OutputState {
@@ -137,13 +146,7 @@ impl State {
137 Backend::Tty(Tty::new(event_loop.clone()))146 Backend::Tty(Tty::new(event_loop.clone()))
138 };147 };
139 148
140- let mut niri = Niri::new(149+ let mut niri = Niri::new(&config, event_loop, stop_signal, display, &backend);
141- &config,
142- event_loop,
143- stop_signal,
144- display,
145- backend.seat_name(),
146- );
147 backend.init(&mut niri);150 backend.init(&mut niri);
148 151
149 Self {152 Self {
@@ -195,7 +198,7 @@ impl Niri {
195 event_loop: LoopHandle<'static, LoopData>,198 event_loop: LoopHandle<'static, LoopData>,
196 stop_signal: LoopSignal,199 stop_signal: LoopSignal,
197 display: &mut Display<State>,200 display: &mut Display<State>,
198- seat_name: String,201+ backend: &Backend,
199 ) -> Self {202 ) -> Self {
200 let display_handle = display.handle();203 let display_handle = display.handle();
201 204
@@ -215,7 +218,7 @@ impl Niri {
215 let presentation_state =218 let presentation_state =
216 PresentationState::new::<State>(&display_handle, CLOCK_MONOTONIC as u32);219 PresentationState::new::<State>(&display_handle, CLOCK_MONOTONIC as u32);
217 220
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());
219 let xkb = XkbConfig {222 let xkb = XkbConfig {
220 rules: &config.input.keyboard.xkb.rules,223 rules: &config.input.keyboard.xkb.rules,
221 model: &config.input.keyboard.xkb.model,224 model: &config.input.keyboard.xkb.model,
@@ -246,6 +249,102 @@ impl Niri {
246 socket_name.to_string_lossy()249 socket_name.to_string_lossy()
247 );250 );
248 251
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+
249 let mut zbus_conn = None;348 let mut zbus_conn = None;
250 let mut inhibit_power_key_fd = None;349 let mut inhibit_power_key_fd = None;
251 if std::env::var_os("NOTIFY_SOCKET").is_some() {350 if std::env::var_os("NOTIFY_SOCKET").is_some() {
@@ -278,7 +377,7 @@ impl Niri {
278 }377 }
279 378
280 // Set up zbus, make sure it happens before anything might want it.379 // 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()
282 .unwrap()381 .unwrap()
283 .name("org.gnome.Mutter.ServiceChannel")382 .name("org.gnome.Mutter.ServiceChannel")
284 .unwrap()383 .unwrap()
@@ -286,9 +385,24 @@ impl Niri {
286 "/org/gnome/Mutter/ServiceChannel",385 "/org/gnome/Mutter/ServiceChannel",
287 ServiceChannel::new(display_handle.clone()),386 ServiceChannel::new(display_handle.clone()),
288 )387 )
289- .unwrap()
290- .build()
291 .unwrap();388 .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();
292 zbus_conn = Some(conn);406 zbus_conn = Some(conn);
293 407
294 // Notify systemd we're ready.408 // Notify systemd we're ready.
@@ -321,6 +435,23 @@ impl Niri {
321 warn!("error inhibiting power key: {err:?}");435 warn!("error inhibiting power key: {err:?}");
322 }436 }
323 }437 }
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);
324 }455 }
325 456
326 let display_source = Generic::new(457 let display_source = Generic::new(
@@ -364,6 +495,9 @@ impl Niri {
364 495
365 zbus_conn,496 zbus_conn,
366 inhibit_power_key_fd,497 inhibit_power_key_fd,
498+ screen_cast,
499+ pipewire,
500+ casts: vec![],
367 }501 }
368 }502 }
369 503
@@ -720,6 +854,9 @@ impl Niri {
720 854
721 // Send the frame callbacks.855 // Send the frame callbacks.
722 self.send_frame_callbacks(output);856 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);
723 }860 }
724 861
725 fn send_dmabuf_feedbacks(&self, output: &Output, feedback: &DmabufFeedback) {862 fn send_dmabuf_feedbacks(&self, output: &Output, feedback: &DmabufFeedback) {
@@ -827,47 +964,74 @@ impl Niri {
827 feedback964 feedback
828 }965 }
829 966
830- pub fn screenshot(967+ fn send_for_screen_cast(
831 &mut self,968 &mut self,
832- renderer: &mut GlesRenderer,969+ backend: &mut Backend,
833 output: &Output,970 output: &Output,
834- ) -> anyhow::Result<()> {971+ elements: &[OutputRenderElements<GlesRenderer>],
835- let _span = tracy_client::span!("Niri::screenshot");972+ presentation_time: Duration,
973+ ) {
974+ let _span = tracy_client::span!("Niri::send_for_screen_cast");
836 975
837 let size = output.current_mode().unwrap().size;976 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;
841 977
842- let texture: GlesTexture = renderer978+ for cast in &mut self.casts {
843- .create_buffer(fourcc, buffer_size)979+ if !cast.is_active.get() {
844- .context("error creating texture")?;980+ continue;
981+ }
845 982
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+ };
847 1006
848- renderer.bind(texture).context("error binding texture")?;1007+ let data = &mut buffer.datas_mut()[0];
849- let mut frame = renderer1008+ let fd = data.as_raw().fd as i32;
850- .render(size, Transform::Normal)1009+ let dmabuf = cast.dmabufs.borrow()[&fd].clone();
851- .context("error starting frame")?;1010+
852-1011+ // FIXME: Hidden / embedded / metadata cursor
853- frame1012+ render_to_dmabuf(backend.renderer(), dmabuf, size, elements).unwrap();
854- .clear([0.1, 0.1, 0.1, 1.], &[output_rect])1013+
855- .context("error clearing")?;1014+ let maxsize = data.as_raw().maxsize;
856-1015+ let chunk = data.chunk_mut();
857- for element in elements.into_iter().rev() {1016+ *chunk.size_mut() = maxsize;
858- let src = element.src();1017+ *chunk.stride_mut() = maxsize as i32 / size.h;
859- let dst = element.geometry(Scale::from(1.));1018+ }
860- element1019+
861- .draw(&mut frame, src, dst, &[output_rect])1020+ cast.last_frame_time = presentation_time;
862- .context("error drawing element")?;
863 }1021 }
1022+ }
864 1023
865- let sync_point = frame.finish().context("error finishing frame")?;1024+ pub fn screenshot(
866- sync_point.wait();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);
867 1033
868- let mapping = renderer1034+ let mapping = render_and_download(renderer, size, &elements).context("error rendering")?;
869- .copy_framebuffer(Rectangle::from_loc_and_size((0, 0), buffer_size), fourcc)
870- .context("error copying framebuffer")?;
871 let copy = renderer1035 let copy = renderer
872 .map_texture(&mapping)1036 .map_texture(&mapping)
873 .context("error mapping texture")?;1037 .context("error mapping texture")?;
@@ -928,3 +1092,76 @@ impl ClientData for ClientState {
928 fn initialized(&self, _client_id: ClientId) {}1092 fn initialized(&self, _client_id: ClientId) {}
929 fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}1093 fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
930 }1094 }
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+}