bevy_iroh 0.4.4

Share Bevy entities between peers over iroh: replication, rooms, presence and typed messages, with optional voice and video
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! Linux: the ScreenCast portal chooses, PipeWire delivers.
//!
//! Two threads. The first owns a small tokio runtime for the D-Bus conversation with
//! `xdg-desktop-portal`: create a session, select sources (this is where the compositor's
//! picker appears and the call waits for the user), start, and open the PipeWire remote. It
//! keeps the session alive until the capture is dropped, then closes it. The second runs
//! PipeWire's main loop on the file descriptor the portal handed over, with one input stream
//! on the node the portal named, and copies each buffer out into a tightly packed frame.
//!
//! Only shared-memory buffers are negotiated: the format offer carries no modifier, so the
//! compositor does not try DMA-BUF, and `MAP_BUFFERS` maps what it sends. The picker itself
//! is the portal's, so which monitor or window, and whether both may be offered, is the
//! backend's policy and not ours.

use std::{
    sync::{Arc, Once},
    time::Duration,
};

use ashpd::desktop::{
    CreateSessionOptions, PersistMode, Session,
    screencast::{
        CursorMode, OpenPipeWireRemoteOptions, Screencast, SelectSourcesOptions, SourceType,
        StartCastOptions,
    },
};
use futures_util::StreamExt;
use pipewire as pw;
use pw::spa::{
    self,
    param::video::{VideoFormat, VideoInfoRaw},
    pod::Pod,
};

use super::{DesktopConfig, Format, Shared, State, unpad_rows};

static INIT: Once = Once::new();

pub(crate) fn spawn(config: DesktopConfig, shared: Arc<Shared>) -> Result<(), String> {
    std::thread::Builder::new()
        .name("desktop-portal".into())
        .spawn(move || portal_thread(config, shared))
        .map_err(|e| format!("could not start the portal thread: {e}"))?;
    Ok(())
}

fn portal_thread(config: DesktopConfig, shared: Arc<Shared>) {
    let runtime = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(r) => r,
        Err(e) => {
            shared.finish(State::Failed(format!("no runtime for the portal: {e}")));
            return;
        }
    };
    runtime.block_on(async {
        let (proxy, session, node, fd) = match handshake(&config, &shared).await {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!("bevy_iroh: screen: {e}");
                shared.finish(State::Failed(e));
                return;
            }
        };
        let pw_shared = shared.clone();
        let capture = std::thread::Builder::new()
            .name("desktop-pipewire".into())
            .spawn(move || {
                if let Err(e) = pipewire_thread(fd, node, pw_shared.clone()) {
                    tracing::warn!("bevy_iroh: screen: pipewire: {e}");
                    pw_shared.finish(State::Failed(e));
                }
            });
        if let Err(e) = capture {
            shared.finish(State::Failed(format!("could not start the capture thread: {e}")));
            return;
        }
        // The session stays open while the capture lives, and closes when it is dropped or
        // the compositor ends the share.
        let mut closed = match session.receive_closed().await {
            Ok(stream) => Some(stream),
            Err(e) => {
                tracing::debug!("bevy_iroh: screen: no Closed signal: {e}");
                None
            }
        };
        loop {
            let tick = tokio::time::sleep(Duration::from_millis(100));
            let ended = async {
                match closed.as_mut() {
                    Some(stream) => stream.next().await,
                    None => std::future::pending().await,
                }
            };
            tokio::select! {
                _ = tick => {
                    if shared.stopped() || matches!(shared.state(), State::Ended | State::Failed(_)) {
                        break;
                    }
                }
                _ = ended => {
                    tracing::info!("bevy_iroh: screen: the share was ended from the desktop side");
                    shared.finish(State::Ended);
                    break;
                }
            }
        }
        drop(proxy);
        if let Err(e) = session.close().await {
            tracing::debug!("bevy_iroh: screen: closing the portal session: {e}");
        }
    });
}

type Handshake = (Screencast, Session<Screencast>, u32, std::os::fd::OwnedFd);

async fn handshake(config: &DesktopConfig, shared: &Shared) -> Result<Handshake, String> {
    let proxy = Screencast::new()
        .await
        .map_err(|e| format!("no ScreenCast portal: {e}"))?;
    let session = proxy
        .create_session(CreateSessionOptions::default())
        .await
        .map_err(|e| format!("portal session: {e}"))?;
    let cursor = if config.cursor {
        CursorMode::Embedded
    } else {
        CursorMode::Hidden
    };
    let cursor = match proxy.available_cursor_modes().await {
        Ok(modes) if !modes.contains(cursor) => CursorMode::Hidden,
        _ => cursor,
    };
    let sources = match proxy.available_source_types().await {
        Ok(types) => types & (SourceType::Monitor | SourceType::Window),
        Err(_) => SourceType::Monitor.into(),
    };
    let options = SelectSourcesOptions::default()
        .set_cursor_mode(cursor)
        .set_sources(sources)
        .set_multiple(false)
        .set_persist_mode(PersistMode::ExplicitlyRevoked)
        .set_restore_token(config.restore_token.as_deref());
    proxy
        .select_sources(&session, options)
        .await
        .map_err(|e| format!("select sources: {e}"))?
        .response()
        .map_err(|e| format!("select sources: {e}"))?;
    if shared.stopped() {
        return Err("stopped while the picker was up".into());
    }
    let streams = proxy
        .start(&session, None, StartCastOptions::default())
        .await
        .map_err(|e| format!("start: {e}"))?
        .response()
        .map_err(|e| format!("start: {e}"))?;
    shared.set_restore_token(streams.restore_token().map(str::to_owned));
    let stream = streams
        .streams()
        .first()
        .ok_or("the portal started no stream")?;
    let node = stream.pipe_wire_node_id();
    tracing::info!(
        "bevy_iroh: screen: sharing {:?} {:?} on PipeWire node {node}",
        stream.source_type(),
        stream.size()
    );
    let fd = proxy
        .open_pipe_wire_remote(&session, OpenPipeWireRemoteOptions::default())
        .await
        .map_err(|e| format!("PipeWire remote: {e}"))?;
    Ok((proxy, session, node, fd))
}

struct Negotiated {
    info: VideoInfoRaw,
    format: Option<Format>,
    shared: Arc<Shared>,
    /// Buffer reused across frames when nobody has taken the last one yet.
    scratch: Vec<u8>,
}

fn pipewire_thread(fd: std::os::fd::OwnedFd, node: u32, shared: Arc<Shared>) -> Result<(), String> {
    INIT.call_once(pw::init);
    let mainloop = pw::main_loop::MainLoopRc::new(None).map_err(|e| format!("main loop: {e}"))?;
    let context =
        pw::context::ContextRc::new(&mainloop, None).map_err(|e| format!("context: {e}"))?;
    let core = context
        .connect_fd_rc(fd, None)
        .map_err(|e| format!("connect: {e}"))?;
    let stream = pw::stream::StreamBox::new(
        &core,
        "bevy_iroh",
        pw::properties::properties! {
            *pw::keys::MEDIA_TYPE => "Video",
            *pw::keys::MEDIA_CATEGORY => "Capture",
            *pw::keys::MEDIA_ROLE => "Screen",
        },
    )
    .map_err(|e| format!("stream: {e}"))?;

    let data = Negotiated {
        info: VideoInfoRaw::default(),
        format: None,
        shared: shared.clone(),
        scratch: Vec::new(),
    };
    let state_shared = shared.clone();
    let _listener = stream
        .add_local_listener_with_user_data(data)
        .state_changed(move |_, _, old, new| {
            tracing::debug!("bevy_iroh: screen: stream {old:?} -> {new:?}");
            match new {
                pw::stream::StreamState::Error(e) => {
                    state_shared.finish(State::Failed(format!("stream: {e}")));
                }
                pw::stream::StreamState::Unconnected
                    if matches!(
                        old,
                        pw::stream::StreamState::Streaming | pw::stream::StreamState::Paused
                    ) =>
                {
                    state_shared.finish(State::Ended);
                }
                _ => {}
            }
        })
        .param_changed(|_, data, id, param| {
            let Some(param) = param else { return };
            if id != spa::param::ParamType::Format.as_raw() {
                return;
            }
            let Ok((media_type, media_subtype)) = spa::param::format_utils::parse_format(param)
            else {
                return;
            };
            if media_type != spa::param::format::MediaType::Video
                || media_subtype != spa::param::format::MediaSubtype::Raw
            {
                return;
            }
            if data.info.parse(param).is_err() {
                return;
            }
            let format = data.info.format();
            data.format = if format == VideoFormat::BGRx || format == VideoFormat::BGRA {
                Some(Format::Bgra)
            } else if format == VideoFormat::RGBx || format == VideoFormat::RGBA {
                Some(Format::Rgba)
            } else {
                None
            };
            let size = data.info.size();
            tracing::info!(
                "bevy_iroh: screen: {}x{} {:?} at {}/{} fps",
                size.width,
                size.height,
                format,
                data.info.framerate().num,
                data.info.framerate().denom
            );
        })
        .process(|stream, data| {
            // Take everything queued and keep the newest: a frame that waited in the queue
            // while we were busy is latency, not information.
            let Some(mut buffer) = stream.dequeue_buffer() else {
                return;
            };
            while let Some(newer) = stream.dequeue_buffer() {
                buffer = newer;
            }
            let Some(format) = data.format else { return };
            let size = data.info.size();
            let datas = buffer.datas_mut();
            let Some(first) = datas.first_mut() else {
                return;
            };
            let (len, stride, offset, corrupted) = {
                let chunk = first.chunk();
                (
                    chunk.size() as usize,
                    chunk.stride().max(0) as usize,
                    chunk.offset() as usize,
                    chunk.flags().contains(spa::buffer::ChunkFlags::CORRUPTED),
                )
            };
            if len == 0 || corrupted {
                return;
            }
            let Some(bytes) = first.data() else { return };
            let bytes = &bytes[offset.min(bytes.len())..];
            let stride = if stride == 0 {
                size.width as usize * 4
            } else {
                stride
            };
            let mut out = std::mem::take(&mut data.scratch);
            let out_len = size.width as usize * size.height as usize * 4;
            if out.capacity() < out_len {
                out = data.shared.buffer(out_len);
            }
            unpad_rows(
                &bytes[..len.min(bytes.len())],
                size.width,
                size.height,
                stride,
                &mut out,
            );
            data.shared.publish(size.width, size.height, format, out);
            data.scratch = data.shared.buffer(out_len);
        })
        .register()
        .map_err(|e| format!("listener: {e}"))?;

    let obj = spa::pod::object!(
        spa::utils::SpaTypes::ObjectParamFormat,
        spa::param::ParamType::EnumFormat,
        spa::pod::property!(
            spa::param::format::FormatProperties::MediaType,
            Id,
            spa::param::format::MediaType::Video
        ),
        spa::pod::property!(
            spa::param::format::FormatProperties::MediaSubtype,
            Id,
            spa::param::format::MediaSubtype::Raw
        ),
        spa::pod::property!(
            spa::param::format::FormatProperties::VideoFormat,
            Choice,
            Enum,
            Id,
            VideoFormat::BGRx,
            VideoFormat::BGRx,
            VideoFormat::BGRA,
            VideoFormat::RGBx,
            VideoFormat::RGBA,
        ),
        spa::pod::property!(
            spa::param::format::FormatProperties::VideoSize,
            Choice,
            Range,
            Rectangle,
            spa::utils::Rectangle {
                width: 1280,
                height: 720
            },
            spa::utils::Rectangle {
                width: 1,
                height: 1
            },
            spa::utils::Rectangle {
                width: 16384,
                height: 16384
            }
        ),
        spa::pod::property!(
            spa::param::format::FormatProperties::VideoFramerate,
            Choice,
            Range,
            Fraction,
            spa::utils::Fraction { num: 30, denom: 1 },
            spa::utils::Fraction { num: 0, denom: 1 },
            spa::utils::Fraction {
                num: 1000,
                denom: 1
            }
        ),
    );
    let values: Vec<u8> = spa::pod::serialize::PodSerializer::serialize(
        std::io::Cursor::new(Vec::new()),
        &spa::pod::Value::Object(obj),
    )
    .map_err(|e| format!("format pod: {e:?}"))?
    .0
    .into_inner();
    let mut params = [Pod::from_bytes(&values).ok_or("format pod")?];
    stream
        .connect(
            spa::utils::Direction::Input,
            Some(node),
            pw::stream::StreamFlags::AUTOCONNECT | pw::stream::StreamFlags::MAP_BUFFERS,
            &mut params,
        )
        .map_err(|e| format!("connect stream: {e}"))?;

    // The loop runs until the capture is dropped or the share ends.
    let quit_loop = mainloop.downgrade();
    let quit_shared = shared.clone();
    let timer = mainloop.loop_().add_timer(move |_| {
        let done =
            quit_shared.stopped() || matches!(quit_shared.state(), State::Ended | State::Failed(_));
        if done && let Some(l) = quit_loop.upgrade() {
            l.quit();
        }
    });
    timer
        .update_timer(
            Some(Duration::from_millis(100)),
            Some(Duration::from_millis(100)),
        )
        .into_result()
        .map_err(|e| format!("timer: {e}"))?;
    mainloop.run();
    let _ = stream.disconnect();
    Ok(())
}