Skip to main content

grafton_ndi/advanced/
controls.rs

1//! Advanced SDK controls on senders and receivers of every mode.
2
3use std::{marker::PhantomData, time::Duration};
4
5#[cfg(any(ndi_has_advanced_encoder_guidance, ndi_has_advanced_quality_planning))]
6use super::{invalid_input, VideoCodec};
7use super::{KvmSession, VideoPacketFormat};
8#[cfg(ndi_has_advanced_keyframe_demand)]
9use crate::sys::bindings::NDIlib_video_frame_v2_t;
10#[cfg(ndi_has_advanced_receiver_bandwidth_control)]
11use crate::sys::bindings::{
12    NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_highest,
13    NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_lowest,
14};
15#[cfg(doc)]
16use crate::Error;
17use crate::{
18    sys::advanced::{
19        native, EncoderGuidance, KeyframeDemand, KeyframeRequest, QualityPlanning,
20        ReceiverBandwidthControl, ReceiverStreamControl, SenderTally,
21    },
22    MediaTypes, Receiver, ReceiverMode, Result, Sender, SenderMode, SettingChange, StreamTier,
23    Tally,
24};
25
26/// Exclusive controls for a receiver held by another resource.
27///
28/// FrameSync and AVSync depend on one particular native receiver. Their
29/// `controls()` methods lend this view instead of a mutable receiver, so it
30/// cannot be replaced while those resources exist. Allocator owners lend this
31/// view too; their registrations independently retain the original receiver core.
32/// Ordinary shared controls remain available through the owner's
33/// `receiver()` method, or [`Self::receiver`].
34///
35/// The view allocates nothing and stays on its borrowing thread (`!Send` and
36/// `!Sync`). This keeps exclusive stream changes sequenced with split capture;
37/// the SDK does not document their overlap across application threads. Its
38/// exclusive borrow prevents changing streams or starting a second KVM session
39/// while a session is live. Use the synchronizer's `split()` method to keep
40/// capturing synchronized output during a KVM session.
41pub struct ReceiverControls<'a, M: ReceiverMode> {
42    receiver: &'a mut Receiver<M>,
43    _thread: PhantomData<*mut ()>,
44}
45
46impl<'a, M: ReceiverMode> ReceiverControls<'a, M> {
47    pub(crate) fn new(receiver: &'a mut Receiver<M>) -> Self {
48        Self {
49            receiver,
50            _thread: PhantomData,
51        }
52    }
53
54    /// The receiver for shared controls and the capture allowed by its mode.
55    /// This borrow never permits replacement or recovery of the receiver.
56    pub fn receiver(&self) -> &Receiver<M> {
57        self.receiver
58    }
59
60    /// Switch between program and preview; see [`Receiver::set_stream_tier`].
61    /// This makes the same synchronous native call without allocating.
62    ///
63    /// # Errors
64    ///
65    /// As for [`Receiver::set_stream_tier`]. A refused or redundant change
66    /// remains [`SettingChange::Unchanged`].
67    #[doc(alias = "NDIlib_recv_set_bandwidth")]
68    pub fn set_stream_tier(&mut self, tier: StreamTier) -> Result<SettingChange> {
69        self.receiver.set_stream_tier(tier)
70    }
71
72    /// Choose the enabled media; see [`Receiver::set_streams`].
73    /// This makes the same synchronous native call without allocating. It
74    /// does not promise to flush a synchronizer's cached output or format.
75    ///
76    /// # Errors
77    ///
78    /// As for [`Receiver::set_streams`]. A refused or redundant change
79    /// remains [`SettingChange::Unchanged`].
80    #[doc(alias = "NDIlib_recv_set_enabled_streams")]
81    pub fn set_streams(&mut self, streams: MediaTypes) -> Result<SettingChange> {
82        self.receiver.set_streams(streams)
83    }
84
85    /// Start KVM, retaining this view's exclusive receiver borrow.
86    ///
87    /// This consumes the view, so a temporary `owner.controls()` can create
88    /// a session lasting until it is dropped. Session creation allocates
89    /// nothing; holding inputs can allocate for tracking. To change source,
90    /// successfully release all inputs and end the session first. Its
91    /// restricted receiver view cannot change the connection.
92    ///
93    /// # Errors
94    ///
95    /// As for [`Receiver::kvm`].
96    pub fn kvm(self) -> Result<KvmSession<'a, M>> {
97        self.receiver.kvm()
98    }
99}
100
101/// Encoder guidance that `operation` returned, which `Processing.NDI.Advanced.h`
102/// describes as a size, a bit rate or a quality: a negative value breaks that
103/// contract.
104#[cfg(any(ndi_has_advanced_encoder_guidance, ndi_has_advanced_quality_planning))]
105fn guidance(called: crate::sys::table::Called<i32>) -> Result<u32> {
106    let (value, operation) = called.into_parts();
107    u32::try_from(value).map_err(|_| {
108        crate::Error::UnexpectedSdkResult(crate::SdkResultDefect::InvalidGuidance {
109            operation,
110            value,
111        })
112    })
113}
114
115/// Refuse a format the quality factor does not apply to.
116///
117/// `Processing.NDI.Advanced.h`: "If the frame passed in is not SpeedHQ then
118/// this will return a value of -1."
119#[cfg(any(ndi_has_advanced_encoder_guidance, ndi_has_advanced_quality_planning))]
120fn require_speedhq(format: VideoPacketFormat) -> Result<()> {
121    match format.codec() {
122        VideoCodec::SpeedHq420 | VideoCodec::SpeedHq422 | VideoCodec::SpeedHq422Alpha => Ok(()),
123        codec => Err(invalid_input(crate::InputDefect::SpeedHqCodec { codec })),
124    }
125}
126
127/// A null descriptor asks about any stream; otherwise the one `format` names.
128#[cfg(ndi_has_advanced_keyframe_demand)]
129fn stream(format: Option<&NDIlib_video_frame_v2_t>) -> *const NDIlib_video_frame_v2_t {
130    format.map_or(std::ptr::null(), |format| format)
131}
132
133impl<M: SenderMode> Sender<M> {
134    /// Set this sender's own contribution to its tally state, which is
135    /// otherwise the combination of what its receivers report: for instance,
136    /// that it is known to be on air. The SDK reflects the state to the
137    /// sender's receivers.
138    ///
139    /// # Errors
140    ///
141    /// [`Error::UnsupportedCapability`]
142    /// without an Advanced runtime.
143    #[doc(alias = "NDIlib_send_set_tally")]
144    pub fn set_external_tally(&self, tally: Tally) -> Result<()> {
145        let table = self.runtime().table::<SenderTally>()?;
146        native!(SenderTally, table, uses(tally) => {
147            let tally = tally.to_sdk();
148            // The SDK gives this control flag no failure meaning.
149            // SAFETY: the sender instance is live for this borrow.
150            unsafe { table.NDIlib_send_set_tally(self.handle().instance(), &tally) };
151            Ok(())
152        })
153    }
154
155    /// The compressed frame size, in bytes, an encoder should aim for when
156    /// producing `format` for this sender's connections.
157    ///
158    /// # Errors
159    ///
160    /// [`Error::UnsupportedCapability`] without an Advanced runtime, and
161    /// [`Error::UnexpectedSdkResult`] when the SDK returns a negative size.
162    #[doc(alias = "NDIlib_send_get_target_frame_size")]
163    pub fn target_frame_bytes(&self, format: VideoPacketFormat) -> Result<u32> {
164        let table = self.runtime().table::<EncoderGuidance>()?;
165        native!(EncoderGuidance, table, uses(format) => {
166            let format = format.raw();
167            // SAFETY: the sender instance is live for this borrow.
168            let value = unsafe {
169                table.named().NDIlib_send_get_target_frame_size(self.handle().instance(), &format)
170            };
171            guidance(value)
172        })
173    }
174
175    /// The bit rate, in bits per second, an encoder should aim for when
176    /// producing `format` for this sender's connections.
177    ///
178    /// # Errors
179    ///
180    /// As for [`target_frame_bytes`](Self::target_frame_bytes), with a
181    /// negative bit rate.
182    #[doc(alias = "NDIlib_send_get_target_bit_rate")]
183    pub fn target_bit_rate(&self, format: VideoPacketFormat) -> Result<u32> {
184        let table = self.runtime().table::<EncoderGuidance>()?;
185        native!(EncoderGuidance, table, uses(format) => {
186            let format = format.raw();
187            // SAFETY: the sender instance is live for this borrow.
188            let value = unsafe {
189                table.named().NDIlib_send_get_target_bit_rate(self.handle().instance(), &format)
190            };
191            guidance(value)
192        })
193    }
194
195    /// The SpeedHQ quality factor for `format`, as the original quality query
196    /// reports it. It says nothing about whether receivers accept the newer
197    /// SpeedHQ format; [`quality_plan`](Self::quality_plan) does.
198    ///
199    /// # Errors
200    ///
201    /// [`Error::UnsupportedCapability`] without an Advanced runtime,
202    /// [`Error::InvalidInput`] when `format` is not SpeedHQ, and
203    /// [`Error::UnexpectedSdkResult`] when the SDK returns a negative quality
204    /// for one that is.
205    #[doc(alias = "NDIlib_send_get_q_factor")]
206    pub fn legacy_quality(&self, format: VideoPacketFormat) -> Result<u32> {
207        let table = self.runtime().table::<EncoderGuidance>()?;
208        native!(EncoderGuidance, table, uses(format) => {
209            require_speedhq(format)?;
210            let format = format.raw();
211            // SAFETY: the sender instance is live for this borrow.
212            let value = unsafe { table.named().NDIlib_send_get_q_factor(self.handle().instance(), &format) };
213            guidance(value)
214        })
215    }
216
217    /// The SpeedHQ quality for `format` and whether the connected receivers
218    /// accept the newer SpeedHQ format. Pass `supports_new_format` as `true`
219    /// when the encoder can produce it.
220    ///
221    /// # Errors
222    ///
223    /// As for [`legacy_quality`](Self::legacy_quality).
224    #[doc(alias = "NDIlib_send_get_q_factor_v2")]
225    pub fn quality_plan(
226        &self,
227        format: VideoPacketFormat,
228        supports_new_format: bool,
229    ) -> Result<QualityPlan> {
230        let table = self.runtime().table::<QualityPlanning>()?;
231        native!(QualityPlanning, table, uses(format, supports_new_format) => {
232            require_speedhq(format)?;
233            let format = format.raw();
234            let mut short_dc = false;
235            // SAFETY: the sender instance is live for this borrow and `short_dc`
236            // is writable storage for the flag.
237            let value = unsafe {
238                table.named().NDIlib_send_get_q_factor_v2(
239                    self.handle().instance(),
240                    &format,
241                    supports_new_format,
242                    &mut short_dc,
243                )
244            };
245            let value = guidance(value)?;
246            // A value of 100 or more permits the newer format; the quality is
247            // then the value less 100.
248            let (quality, new_format) = match value.checked_sub(100) {
249                Some(quality) => (quality, true),
250                None => (value, false),
251            };
252            Ok(QualityPlan { quality, new_format, short_dc })
253        })
254    }
255
256    /// Whether a connected receiver needs a keyframe: on the stream `format`
257    /// names, or on any stream when `format` is `None`.
258    ///
259    /// # Errors
260    ///
261    /// [`Error::UnsupportedCapability`]
262    /// without an Advanced runtime.
263    #[doc(alias = "NDIlib_send_is_keyframe_required")]
264    pub fn keyframe_required(&self, format: Option<VideoPacketFormat>) -> Result<bool> {
265        let table = self.runtime().table::<KeyframeDemand>()?;
266        native!(KeyframeDemand, table, uses(format) => {
267            let format = format.map(VideoPacketFormat::raw);
268            // SAFETY: the sender instance is live for this borrow.
269            Ok(unsafe {
270                table.NDIlib_send_is_keyframe_required(self.handle().instance(), stream(format.as_ref()))
271            })
272        })
273    }
274
275    /// Wait up to `timeout` for keyframe demand to change, on the stream
276    /// `format` names or on any stream when it is `None`.
277    ///
278    /// Returns whether a change was signalled; call
279    /// [`keyframe_required`](Self::keyframe_required) for the new state.
280    /// Concurrent waiters share one native update report. A format-specific
281    /// waiter reports the update when the shared sample observes demand for
282    /// that stream; otherwise it keeps waiting within the same timeout. Demand is sampled
283    /// once per active stream selector before any observer is woken, so a send
284    /// made by the first observer cannot erase another observer's report.
285    /// These are coalesced invalidations, not a per-stream event history:
286    /// pending demand can be reported again, or a concurrent send can clear it
287    /// before the shared sample. A zero timeout beside another native waiter
288    /// only reads reports that waiter has already published.
289    ///
290    /// # Errors
291    ///
292    /// [`Error::UnsupportedCapability`]
293    /// without an Advanced runtime, and
294    /// [`Error::InvalidInput`]
295    /// when `timeout` exceeds [`crate::MAX_TIMEOUT`].
296    #[doc(alias = "NDIlib_send_wait_for_keyframe_request")]
297    pub fn wait_for_keyframe_change(
298        &self,
299        format: Option<VideoPacketFormat>,
300        timeout: Duration,
301    ) -> Result<bool> {
302        let table = self.runtime().table::<KeyframeDemand>()?;
303        native!(KeyframeDemand, table, uses(timeout, format) => {
304            let deadline = crate::timeout::Deadline::after(timeout)?;
305            Ok(self.keyframe_changes().wait(
306                format,
307                deadline,
308                |timeout| {
309                    // SAFETY: the sender lives for the wait. A null selector
310                    // observes all updates without competing native selectors.
311                    unsafe { table.NDIlib_send_wait_for_keyframe_request(
312                        self.handle().instance(), timeout, std::ptr::null(),
313                    ) }
314                },
315                |format| {
316                    let format = format.raw();
317                    // SAFETY: this non-consuming query reads only the live
318                    // sender and the descriptor, which lasts through the call.
319                    unsafe { table.NDIlib_send_is_keyframe_required(
320                        self.handle().instance(), &format,
321                    ) }
322                },
323            ))
324        })
325    }
326}
327
328/// SpeedHQ encoder quality for one stream, from [`Sender::quality_plan`].
329#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
330pub struct QualityPlan {
331    quality: u32,
332    new_format: bool,
333    short_dc: bool,
334}
335
336impl QualityPlan {
337    /// The quality factor to encode with.
338    pub fn quality(self) -> u32 {
339        self.quality
340    }
341
342    /// Whether every connected receiver accepts the newer SpeedHQ format.
343    pub fn permits_new_format(self) -> bool {
344        self.new_format
345    }
346
347    /// Whether the encoder should use the shorter DC coefficient coding.
348    pub fn enable_short_dc(self) -> bool {
349        self.short_dc
350    }
351}
352
353impl<M: ReceiverMode> Receiver<M> {
354    /// Ask the source for a keyframe. The request is advisory: the source
355    /// decides whether and when to send one.
356    ///
357    /// # Errors
358    ///
359    /// [`Error::UnsupportedCapability`]
360    /// without an Advanced runtime.
361    #[doc(alias = "NDIlib_recv_request_keyframe")]
362    pub fn request_keyframe(&self) -> Result<()> {
363        let table = self.core.ndi().table::<KeyframeRequest>()?;
364        native!(KeyframeRequest, table => {
365            self.core.lock_mutating_control()?.request_keyframe(table);
366            Ok(())
367        })
368    }
369
370    /// Switch between the source's program and preview streams.
371    ///
372    /// [`SettingChange::Unchanged`] when the SDK did not switch: the tier was
373    /// already in effect, the receiver was created without video, or the
374    /// runtime is not licensed to switch. The SDK switches only under a vendor
375    /// ID that licenses this function.
376    ///
377    /// # Errors
378    ///
379    /// [`Error::UnsupportedCapability`]
380    /// without an Advanced runtime.
381    #[doc(alias = "NDIlib_recv_set_bandwidth")]
382    pub fn set_stream_tier(&mut self, tier: StreamTier) -> Result<SettingChange> {
383        let exclusive = self.exclusive();
384        let table = exclusive.ndi().table::<ReceiverBandwidthControl>()?;
385        native!(ReceiverBandwidthControl, table, uses(tier) => {
386            let bandwidth = match tier {
387                StreamTier::Program => NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_highest,
388                StreamTier::Preview => NDIlib_recv_bandwidth_e_NDIlib_recv_bandwidth_lowest,
389            };
390            // SAFETY: the exclusive receiver borrow rules out other Rust
391            // stream writers. Advertiser membership uses a separate native
392            // registry lock over retained creation state. For the measured
393            // runtimes, the RecvInstance inventory records the native lock
394            // covering this setter's access to the connection. That locking
395            // evidence is specific to Linux and Advanced Windows.
396            let switched = unsafe { table.NDIlib_recv_set_bandwidth(exclusive.instance(), bandwidth) };
397            Ok(SettingChange::from_sdk(switched))
398        })
399    }
400
401    /// Choose which streams the source sends to this receiver.
402    ///
403    /// [`SettingChange::Unchanged`] when the enabled streams did not change:
404    /// they were already the ones requested, the request asked for a stream
405    /// the receiver was created without, or the runtime is not licensed to
406    /// change them. The SDK applies the change only under a vendor ID that
407    /// licenses this function.
408    ///
409    /// # Errors
410    ///
411    /// [`Error::UnsupportedCapability`]
412    /// without an Advanced runtime.
413    #[doc(alias = "NDIlib_recv_set_enabled_streams")]
414    pub fn set_streams(&mut self, streams: MediaTypes) -> Result<SettingChange> {
415        let exclusive = self.exclusive();
416        let table = exclusive.ndi().table::<ReceiverStreamControl>()?;
417        native!(ReceiverStreamControl, table, uses(streams) => {
418            // SAFETY: the exclusive receiver borrow rules out other Rust
419            // stream writers. Advertiser membership uses a separate native
420            // registry lock over retained creation state. For the measured
421            // runtimes, the RecvInstance inventory records the native lock
422            // covering this setter's access to the connection. That locking
423            // evidence is specific to Linux and Advanced Windows.
424            let changed = unsafe {
425                table.NDIlib_recv_set_enabled_streams(
426                    exclusive.instance(),
427                    streams.contains(MediaTypes::VIDEO),
428                    streams.contains(MediaTypes::AUDIO),
429                    streams.contains(MediaTypes::METADATA),
430                )
431            };
432            Ok(SettingChange::from_sdk(changed))
433        })
434    }
435}
436
437impl<M: ReceiverMode> std::fmt::Debug for ReceiverControls<'_, M> {
438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
439        f.debug_struct("ReceiverControls")
440            .field("receiver", self.receiver())
441            .finish_non_exhaustive()
442    }
443}