Skip to main content

grafton_ndi/advanced/
kvm.rs

1//! Remote keyboard, mouse, touch and clipboard control of a source.
2
3use std::collections::BTreeSet;
4#[cfg(ndi_has_advanced_kvm)]
5use std::ffi::CString;
6
7use super::{invalid_input, KvmReceiver};
8#[cfg(any(test, ndi_has_advanced_kvm, ndi_test_receiver_proofs))]
9use crate::receiver::control::MutatingControl;
10#[cfg(any(doc, test))]
11use crate::Error;
12use crate::{
13    sys::advanced::{native, Kvm},
14    Receiver, ReceiverMode, Result,
15};
16
17/// A mouse button.
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
19pub enum MouseButton {
20    /// The left button.
21    Left,
22    /// The middle button.
23    Middle,
24    /// The right button.
25    Right,
26}
27
28/// A wheel axis.
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
30pub enum WheelAxis {
31    /// The usual scroll direction.
32    Vertical,
33    /// Sideways scrolling.
34    Horizontal,
35}
36
37/// Input bookkeeping has no receiver borrow. Its table is statically dispatched
38/// so the same rule can be tested when Advanced declarations are unavailable.
39#[derive(Default)]
40struct HeldInputs {
41    keys: BTreeSet<i32>,
42    buttons: BTreeSet<MouseButton>,
43    touching: bool,
44}
45
46/// Nonempty validated coordinates with the exact count the SDK may read.
47#[cfg(any(test, ndi_has_advanced_kvm, ndi_test_receiver_proofs))]
48pub(crate) struct TouchPoints<'a> {
49    points: &'a [[f32; 2]],
50    count: i32,
51}
52
53#[cfg(any(test, ndi_has_advanced_kvm, ndi_test_receiver_proofs))]
54impl<'a> TouchPoints<'a> {
55    fn new(points: &'a [[f32; 2]]) -> Result<Option<Self>> {
56        if points.is_empty() {
57            return Ok(None);
58        }
59        let count = i32::try_from(points.len()).map_err(|_| {
60            invalid_input(crate::InputDefect::KvmTouchCount {
61                count: points.len(),
62            })
63        })?;
64        for [x, y] in points {
65            validate_position(*x, *y)?;
66        }
67        Ok(Some(Self { points, count }))
68    }
69
70    pub(crate) fn count(&self) -> i32 {
71        self.count
72    }
73
74    pub(crate) fn as_ptr(&self) -> *const f32 {
75        self.points.as_ptr().cast()
76    }
77}
78
79#[cfg(any(test, ndi_has_advanced_kvm, ndi_test_receiver_proofs))]
80trait InputSender {
81    fn key(&self, connection: &MutatingControl<'_>, key: i32, down: bool) -> Result<()>;
82    fn mouse(
83        &self,
84        connection: &MutatingControl<'_>,
85        button: MouseButton,
86        down: bool,
87    ) -> Result<()>;
88    fn touch(&self, connection: &MutatingControl<'_>, points: TouchPoints<'_>) -> Result<()>;
89    fn finish_touch(&self, connection: &MutatingControl<'_>) -> Result<()>;
90}
91
92#[cfg(any(test, ndi_has_advanced_kvm, ndi_test_receiver_proofs))]
93impl HeldInputs {
94    fn key(
95        &mut self,
96        connection: &MutatingControl<'_>,
97        sender: &impl InputSender,
98        key: i32,
99        down: bool,
100    ) -> Result<()> {
101        sender.key(connection, key, down)?;
102        if down {
103            self.keys.insert(key);
104        } else {
105            self.keys.remove(&key);
106        }
107        Ok(())
108    }
109
110    fn mouse(
111        &mut self,
112        connection: &MutatingControl<'_>,
113        sender: &impl InputSender,
114        button: MouseButton,
115        down: bool,
116    ) -> Result<()> {
117        sender.mouse(connection, button, down)?;
118        if down {
119            self.buttons.insert(button);
120        } else {
121            self.buttons.remove(&button);
122        }
123        Ok(())
124    }
125
126    fn touch(
127        &mut self,
128        connection: &MutatingControl<'_>,
129        sender: &impl InputSender,
130        points: &[[f32; 2]],
131    ) -> Result<()> {
132        let Some(points) = TouchPoints::new(points)? else {
133            return self.finish_touch(connection, sender);
134        };
135        sender.touch(connection, points)?;
136        self.touching = true;
137        Ok(())
138    }
139
140    fn finish_touch(
141        &mut self,
142        connection: &MutatingControl<'_>,
143        sender: &impl InputSender,
144    ) -> Result<()> {
145        sender.finish_touch(connection)?;
146        self.touching = false;
147        Ok(())
148    }
149
150    fn release_all(
151        &mut self,
152        connection: &MutatingControl<'_>,
153        sender: &impl InputSender,
154    ) -> Result<()> {
155        let mut released = Ok(());
156        for key in std::mem::take(&mut self.keys) {
157            if let Err(error) = self.key(connection, sender, key, false) {
158                self.keys.insert(key);
159                released = released.and(Err(error));
160            }
161        }
162        for button in std::mem::take(&mut self.buttons) {
163            if let Err(error) = self.mouse(connection, sender, button, false) {
164                self.buttons.insert(button);
165                released = released.and(Err(error));
166            }
167        }
168        if self.touching {
169            released = released.and(self.finish_touch(connection, sender));
170        }
171        released
172    }
173
174    fn release_on_drop(&mut self, connection: &MutatingControl<'_>, sender: &impl InputSender) {
175        // Best effort: a source that has disconnected cannot be told.
176        let _ = self.release_all(connection, sender);
177    }
178}
179
180/// Exclusive remote control of the source a receiver is connected to.
181///
182/// Created by [`Receiver::kvm`], which borrows the receiver mutably, so a
183/// receiver has at most one session at a time. The session lends the receiver
184/// back as a restricted [`KvmReceiver`] through [`receiver`](Self::receiver),
185/// so frames can be captured, and held, while keys, buttons and touches stay pressed
186/// across them. The view offers mode-permitted capture, tally, PTZ, statistics
187/// and metadata, without allowing application connection changes. For a
188/// packet session, `session.receiver()` delivers owned or borrowed packets,
189/// decoded media and events through its mode-specific capture methods.
190///
191/// To change source, successfully [`release_all`](Self::release_all), end the
192/// session, change the connection through its owner, then start a new session.
193/// Native disconnection, Discovery Server remote control and failed release
194/// delivery can still leave input pressed on the previous source: release is
195/// best effort and the session cannot address a source it has lost.
196///
197/// The session never reads the local clipboard: it sends only the text it is
198/// given. It is `Send` and `Sync`, as the receiver is; its input methods take
199/// `&mut self`, so one thread at a time sends input.
200///
201/// Every method that sends a message returns
202/// [`Error::NativeOperationFailed`], naming the SDK function, when the SDK did
203/// not send it. Success is not a confirmation that the source acted on the
204/// message. The session remembers which keys, buttons and touches it has
205/// pressed, and dropping it releases them on a best-effort basis; call
206/// [`release_all`](Self::release_all) to learn whether that succeeded.
207pub struct KvmSession<'a, M: ReceiverMode> {
208    receiver: &'a Receiver<M>,
209    kvm: &'a Kvm,
210    held: HeldInputs,
211}
212
213impl<M: ReceiverMode> std::fmt::Debug for KvmSession<'_, M> {
214    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215        f.debug_struct("KvmSession")
216            .field("receiver", self.receiver)
217            .field("pressed_keys", &self.held.keys.len())
218            .field("pressed_buttons", &self.held.buttons.len())
219            .field("touching", &self.held.touching)
220            .finish_non_exhaustive()
221    }
222}
223
224impl<M: ReceiverMode> Receiver<M> {
225    /// Start a remote-control session with the connected source.
226    ///
227    /// # Errors
228    ///
229    /// [`Error::UnsupportedCapability`]
230    /// without an Advanced runtime (or in a build without the Advanced SDK).
231    ///
232    /// The receiver stays borrowed for the session, so only one exists at a
233    /// time; use [`KvmSession::receiver`] to keep using it meanwhile.
234    pub fn kvm(&mut self) -> Result<KvmSession<'_, M>> {
235        Ok(KvmSession {
236            kvm: self.core.ndi().table()?,
237            receiver: &*self,
238            held: HeldInputs::default(),
239        })
240    }
241}
242
243#[cfg(ndi_has_advanced_kvm)]
244impl InputSender for Kvm {
245    fn key(&self, connection: &MutatingControl<'_>, key: i32, down: bool) -> Result<()> {
246        if down {
247            connection.kvm_key_press(self, key)
248        } else {
249            connection.kvm_key_release(self, key)
250        }
251    }
252
253    fn mouse(
254        &self,
255        connection: &MutatingControl<'_>,
256        button: MouseButton,
257        down: bool,
258    ) -> Result<()> {
259        match (button, down) {
260            (MouseButton::Left, true) => connection.kvm_left_click(self),
261            (MouseButton::Middle, true) => connection.kvm_middle_click(self),
262            (MouseButton::Right, true) => connection.kvm_right_click(self),
263            (MouseButton::Left, false) => connection.kvm_left_release(self),
264            (MouseButton::Middle, false) => connection.kvm_middle_release(self),
265            (MouseButton::Right, false) => connection.kvm_right_release(self),
266        }
267    }
268
269    fn touch(&self, connection: &MutatingControl<'_>, points: TouchPoints<'_>) -> Result<()> {
270        // TouchPoints carries validated coordinates and their exact SDK count;
271        // its borrowed slice remains valid through the synchronous call.
272        connection.kvm_touch_positions(self, points)
273    }
274
275    fn finish_touch(&self, connection: &MutatingControl<'_>) -> Result<()> {
276        connection.kvm_touch_finish(self)
277    }
278}
279
280fn key_symbol(keysym: u32) -> Result<i32> {
281    i32::try_from(keysym).map_err(|_| invalid_input(crate::InputDefect::KvmKeySymbol { keysym }))
282}
283
284/// Positions are fractions of the source's screen: `0.0..=1.0` on each axis.
285#[cfg(any(test, ndi_has_advanced_kvm, ndi_test_receiver_proofs))]
286fn validate_position(x: f32, y: f32) -> Result<()> {
287    let in_range = |value: f32| (0.0..=1.0).contains(&value);
288    if in_range(x) && in_range(y) {
289        Ok(())
290    } else {
291        Err(invalid_input(crate::InputDefect::KvmPosition { x, y }))
292    }
293}
294
295impl<'a, M: ReceiverMode> KvmSession<'a, M> {
296    /// Restricted receiver access for the session's original receiver lifetime.
297    ///
298    /// A frame captured through it can be held while the session's input
299    /// methods run, which is how a key, button or touch stays down across
300    /// captured frames. The view cannot change the connection or recover an
301    /// unrestricted receiver, even when moved to a scoped thread. Creating it
302    /// allocates nothing and makes no SDK call or lock acquisition.
303    pub fn receiver(&self) -> KvmReceiver<'a, M> {
304        KvmReceiver::new(self.receiver)
305    }
306
307    /// Whether the connected source accepts remote control. This can change
308    /// during the session when that source enables or disables remote control.
309    #[doc(alias = "NDIlib_recv_kvm_is_supported")]
310    pub fn is_supported(&self) -> bool {
311        native!(Kvm, self.kvm => {
312            self.receiver
313                .core
314                .lock_mutating_control()
315                .is_ok_and(|connection| connection.kvm_is_supported(self.kvm))
316        })
317    }
318
319    /// Press a mouse button.
320    ///
321    /// # Errors
322    ///
323    /// [`Error::NativeOperationFailed`] when the SDK did not send the press.
324    #[doc(alias = "NDIlib_recv_kvm_send_left_mouse_click")]
325    #[doc(alias = "NDIlib_recv_kvm_send_middle_mouse_click")]
326    #[doc(alias = "NDIlib_recv_kvm_send_right_mouse_click")]
327    pub fn mouse_down(&mut self, button: MouseButton) -> Result<()> {
328        native!(Kvm, self.kvm, uses(button) => {
329            let connection = self.receiver.core.lock_mutating_control()?;
330            self.held.mouse(&connection, self.kvm, button, true)
331        })
332    }
333
334    /// Release a mouse button.
335    ///
336    /// # Errors
337    ///
338    /// [`Error::NativeOperationFailed`] when the SDK did not send the release;
339    /// the button stays recorded as pressed.
340    #[doc(alias = "NDIlib_recv_kvm_send_left_mouse_release")]
341    #[doc(alias = "NDIlib_recv_kvm_send_middle_mouse_release")]
342    #[doc(alias = "NDIlib_recv_kvm_send_right_mouse_release")]
343    pub fn mouse_up(&mut self, button: MouseButton) -> Result<()> {
344        native!(Kvm, self.kvm, uses(button) => {
345            let connection = self.receiver.core.lock_mutating_control()?;
346            self.held.mouse(&connection, self.kvm, button, false)
347        })
348    }
349
350    /// Press a key, identified by its X11 key symbol.
351    ///
352    /// # Errors
353    ///
354    /// [`Error::InvalidInput`] when the symbol is outside the range the SDK
355    /// accepts, and [`Error::NativeOperationFailed`] when the SDK did not
356    /// send the press.
357    #[doc(alias = "NDIlib_recv_kvm_send_keyboard_press")]
358    pub fn key_down(&mut self, keysym: u32) -> Result<()> {
359        let key = key_symbol(keysym)?;
360        self.press(key)
361    }
362
363    /// Release a key, identified by its X11 key symbol.
364    ///
365    /// # Errors
366    ///
367    /// As for [`key_down`](Self::key_down); a key whose release the SDK did
368    /// not send stays recorded as pressed.
369    #[doc(alias = "NDIlib_recv_kvm_send_keyboard_release")]
370    pub fn key_up(&mut self, keysym: u32) -> Result<()> {
371        let key = key_symbol(keysym)?;
372        self.release(key)
373    }
374
375    fn press(&mut self, _key: i32) -> Result<()> {
376        native!(Kvm, self.kvm => {
377            let connection = self.receiver.core.lock_mutating_control()?;
378            self.held.key(&connection, self.kvm, _key, true)
379        })
380    }
381
382    fn release(&mut self, _key: i32) -> Result<()> {
383        native!(Kvm, self.kvm => {
384            let connection = self.receiver.core.lock_mutating_control()?;
385            self.held.key(&connection, self.kvm, _key, false)
386        })
387    }
388
389    /// Turn a mouse wheel by `units` notches; the sign gives the direction.
390    ///
391    /// # Errors
392    ///
393    /// [`Error::InvalidInput`] when `units` is not finite, and
394    /// [`Error::NativeOperationFailed`] when the SDK did not send the turn.
395    #[doc(alias = "NDIlib_recv_kvm_send_vertical_mouse_wheel")]
396    #[doc(alias = "NDIlib_recv_kvm_send_horizontal_mouse_wheel")]
397    pub fn wheel(&mut self, axis: WheelAxis, units: f32) -> Result<()> {
398        native!(Kvm, self.kvm, uses(axis, units) => {
399            if !units.is_finite() {
400                return Err(invalid_input(crate::InputDefect::KvmWheel { units }));
401            }
402            let connection = self.receiver.core.lock_mutating_control()?;
403            match axis {
404                WheelAxis::Vertical => connection.kvm_wheel_vertical(self.kvm, units),
405                WheelAxis::Horizontal => connection.kvm_wheel_horizontal(self.kvm, units),
406            }
407        })
408    }
409
410    /// Move the pointer to `(x, y)`, each a fraction of the source's screen
411    /// from `0.0` (left, top) to `1.0` (right, bottom).
412    ///
413    /// # Errors
414    ///
415    /// [`Error::InvalidInput`] when a coordinate is outside `0.0..=1.0`, and
416    /// [`Error::NativeOperationFailed`] when the SDK did not send the move.
417    #[doc(alias = "NDIlib_recv_kvm_send_mouse_position")]
418    pub fn move_pointer(&mut self, x: f32, y: f32) -> Result<()> {
419        native!(Kvm, self.kvm, uses(x, y) => {
420            validate_position(x, y)?;
421            self.receiver
422                .core
423                .lock_mutating_control()?
424                .kvm_mouse_position(self.kvm, &[x, y])
425        })
426    }
427
428    /// Replace the source's clipboard text.
429    ///
430    /// # Errors
431    ///
432    /// [`Error::InvalidCString`] when `text` contains a NUL, and
433    /// [`Error::NativeOperationFailed`] when the SDK did not send the text.
434    #[doc(alias = "NDIlib_recv_kvm_send_clipboard_contents")]
435    pub fn set_clipboard_text(&mut self, text: &str) -> Result<()> {
436        native!(Kvm, self.kvm, uses(text) => {
437            let text = CString::new(text)?;
438            self.receiver
439                .core
440                .lock_mutating_control()?
441                .kvm_clipboard_contents(self.kvm, &text)
442        })
443    }
444
445    /// Report the current touch points, each an `[x, y]` fraction of the
446    /// source's screen. An empty slice sends the same lift as
447    /// [`finish_touch`](Self::finish_touch).
448    ///
449    /// # Errors
450    ///
451    /// [`Error::InvalidInput`] when a coordinate is outside `0.0..=1.0` or
452    /// there are more points than the SDK can count, and
453    /// [`Error::NativeOperationFailed`] when the SDK did not send them.
454    #[doc(alias = "NDIlib_recv_kvm_send_touch_positions")]
455    pub fn touch(&mut self, points: &[[f32; 2]]) -> Result<()> {
456        native!(Kvm, self.kvm, uses(points) => {
457            let connection = self.receiver.core.lock_mutating_control()?;
458            self.held.touch(&connection, self.kvm, points)
459        })
460    }
461
462    /// Lift every touch.
463    ///
464    /// # Errors
465    ///
466    /// [`Error::NativeOperationFailed`] when the SDK did not send the lift;
467    /// the touches stay recorded.
468    #[doc(alias = "NDIlib_recv_kvm_send_touch_finish")]
469    pub fn finish_touch(&mut self) -> Result<()> {
470        native!(Kvm, self.kvm => {
471            let connection = self.receiver.core.lock_mutating_control()?;
472            self.held.finish_touch(&connection, self.kvm)
473        })
474    }
475
476    /// Release every key, button and touch this session has pressed.
477    ///
478    /// # Errors
479    ///
480    /// [`Error::NativeOperationFailed`] for the first release the SDK did not
481    /// send. Every release is still attempted; those the SDK did not send
482    /// stay recorded as pressed, and a later call tries them again.
483    pub fn release_all(&mut self) -> Result<()> {
484        native!(Kvm, self.kvm => {
485            let connection = self.receiver.core.lock_mutating_control()?;
486            self.held.release_all(&connection, self.kvm)
487        })
488    }
489}
490
491impl<M: ReceiverMode> Drop for KvmSession<'_, M> {
492    fn drop(&mut self) {
493        native!(Kvm, self.kvm => {
494            if let Ok(connection) = self.receiver.core.lock_mutating_control() {
495                self.held.release_on_drop(&connection, self.kvm);
496            }
497        })
498    }
499}
500
501#[cfg(test)]
502mod tests {
503    use super::*;
504
505    #[test]
506    fn positions_reject_nan_and_outside_range() {
507        assert!(validate_position(0.0, 1.0).is_ok());
508        for (x, y) in [
509            (f32::NAN, 0.0),
510            (0.0, -0.1),
511            (1.1, 0.5),
512            (f32::INFINITY, 0.5),
513        ] {
514            assert!(matches!(
515                validate_position(x, y),
516                Err(Error::InvalidInput(_))
517            ));
518        }
519    }
520
521    #[test]
522    fn key_symbols_beyond_the_native_range_are_rejected() {
523        assert_eq!(key_symbol(0xff0d).unwrap(), 0xff0d);
524        assert!(matches!(key_symbol(u32::MAX), Err(Error::InvalidInput(_))));
525    }
526}
527
528#[cfg(test)]
529#[path = "kvm_tests.rs"]
530mod ownership_tests;
531
532#[cfg(all(test, ndi_has_advanced_kvm))]
533#[path = "kvm_view_tests.rs"]
534mod view_tests;
535
536#[cfg(ndi_test_receiver_proofs)]
537fn a_raw_handle_cannot_send_input(
538    sender: &impl InputSender,
539    instance: crate::sys::bindings::NDIlib_recv_instance_t,
540) {
541    let _ = sender.key(instance, 1, true);
542}