Skip to main content

rustduck_core/
input_switcher.rs

1//! Typed, single-threaded `InputSwitcher` lifecycle management.
2
3use std::rc::Rc;
4use std::sync::Arc;
5
6use rustduck_sys::bridge::ffi;
7
8use crate::error::native_exception;
9use crate::host::invalid_state;
10use crate::memory::{MemoryInputBinding, MemoryOutputBinding, install_dispatcher};
11use crate::{CallbackError, Error, HostState, MemoryInput, MemoryOutput, Report, Result};
12
13mod config;
14mod native_config;
15
16pub use config::{InputSwitcherConfig, SwitcherInput, SwitcherOutput};
17
18/// A `!Send + !Sync` native input-switcher owner.
19///
20/// Native deletion occurs before destruction of its report, handler, and
21/// endpoint leases because the native field is declared first. Drop stops and
22/// waits for active work before the typed native owner is deleted.
23pub struct InputSwitcher {
24    native: cxx::UniquePtr<ffi::RustDuckInputSwitcher>,
25    report: Rc<Report>,
26    handler: Option<cxx::UniquePtr<ffi::RustDuckMemoryHandler>>,
27    input_bindings: Vec<MemoryInputBinding>,
28    output_binding: Option<MemoryOutputBinding>,
29    inputs: Vec<Arc<MemoryInput>>,
30    output: Option<Arc<MemoryOutput>>,
31    native_shutdown_required: bool,
32    state: HostState,
33}
34
35impl InputSwitcher {
36    /// Creates an input switcher bound to `report`.
37    pub fn new(report: Rc<Report>) -> Result<Self> {
38        let native = ffi::rustduck_input_switcher_new(report.native())
39            .map_err(|error| native_exception("InputSwitcher::new", error))?;
40        if native.is_null() {
41            return Err(Error::NativeFailure {
42                operation: "InputSwitcher::new",
43            });
44        }
45        Ok(Self {
46            native,
47            report,
48            handler: None,
49            input_bindings: Vec::new(),
50            output_binding: None,
51            inputs: Vec::new(),
52            output: None,
53            native_shutdown_required: false,
54            state: HostState::Created,
55        })
56    }
57
58    /// Returns the report retained for the switcher's native lifetime.
59    pub fn report(&self) -> &Rc<Report> {
60        &self.report
61    }
62
63    /// Returns the host lifecycle state.
64    pub const fn state(&self) -> HostState {
65        self.state
66    }
67
68    /// Starts the switcher.
69    pub fn start(&mut self, config: &InputSwitcherConfig) -> Result<()> {
70        if self.state != HostState::Created {
71            return Err(invalid_state("InputSwitcher", "start", self.state));
72        }
73        config::validate(config)?;
74        let inputs = config
75            .inputs
76            .iter()
77            .filter_map(|input| match input {
78                SwitcherInput::Memory(endpoint) => Some(Arc::clone(endpoint)),
79                SwitcherInput::Native(_) => None,
80            })
81            .collect::<Vec<_>>();
82        let output = match &config.output {
83            Some(SwitcherOutput::Memory(endpoint)) => Some(Arc::clone(endpoint)),
84            _ => None,
85        };
86        if !inputs.is_empty() || output.is_some() {
87            install_dispatcher()?;
88        }
89        let handler = if !inputs.is_empty() || output.is_some() {
90            let handler = ffi::rustduck_memory_handler_new()
91                .map_err(|error| native_exception("InputSwitcher::memory_handler", error))?;
92            if handler.is_null() {
93                return Err(Error::NativeFailure {
94                    operation: "InputSwitcher::memory_handler",
95                });
96            }
97            Some(handler)
98        } else {
99            None
100        };
101        let input_bindings = inputs
102            .iter()
103            .map(|input| input.bind())
104            .collect::<Result<Vec<_>>>()?;
105        let output_binding = output
106            .as_ref()
107            .map(|endpoint| endpoint.bind())
108            .transpose()?;
109        self.handler = handler;
110        self.input_bindings = input_bindings;
111        self.output_binding = output_binding;
112        self.inputs = inputs;
113        self.output = output;
114        self.native_shutdown_required = true;
115        if let Err(error) = self.register_memory_handlers() {
116            self.fail_memory_endpoints();
117            self.state = HostState::Failed;
118            return Err(error);
119        }
120        let native_config = self.native_config(config)?;
121        let started = ffi::rustduck_input_switcher_start(self.native.pin_mut(), &native_config)
122            .map_err(|error| self.fail_after_native_exception("InputSwitcher::start", error))?;
123        if !started {
124            self.fail_memory_endpoints();
125            self.state = HostState::Failed;
126            return Err(Error::NativeFailure {
127                operation: "InputSwitcher::start",
128            });
129        }
130        self.state = HostState::Running;
131        Ok(())
132    }
133
134    /// Requests native switcher stop.
135    pub fn stop(&mut self) -> Result<()> {
136        if self.state != HostState::Running {
137            return Err(invalid_state("InputSwitcher", "stop", self.state));
138        }
139        self.fail_memory_endpoints();
140        self.state = HostState::Stopping;
141        ffi::rustduck_input_switcher_stop(self.native.pin_mut())
142            .map_err(|error| self.fail_after_native_exception("InputSwitcher::stop", error))
143    }
144
145    /// Waits until native switching has stopped.
146    pub fn wait_for_termination(&mut self) -> Result<()> {
147        if !self.state.is_active() {
148            return Err(invalid_state(
149                "InputSwitcher",
150                "wait_for_termination",
151                self.state,
152            ));
153        }
154        ffi::rustduck_input_switcher_wait(self.native.pin_mut()).map_err(|error| {
155            self.fail_after_native_exception("InputSwitcher::wait_for_termination", error)
156        })?;
157        self.close_memory_outputs();
158        self.native_shutdown_required = false;
159        self.state = HostState::Stopped;
160        Ok(())
161    }
162
163    /// Takes the latest callback failure from a bound endpoint.
164    pub fn take_memory_error(&self) -> Option<CallbackError> {
165        self.inputs
166            .iter()
167            .find_map(|input| input.take_callback_error())
168            .or_else(|| {
169                self.output
170                    .as_ref()
171                    .and_then(|output| output.take_callback_error())
172            })
173    }
174
175    fn native_config(
176        &self,
177        config: &InputSwitcherConfig,
178    ) -> Result<ffi::RustDuckInputSwitcherConfig> {
179        native_config::build(config, &self.input_bindings, self.output_binding.as_ref())
180    }
181
182    fn register_memory_handlers(&mut self) -> Result<()> {
183        let Some(handler) = self.handler.as_ref() else {
184            return Ok(());
185        };
186        if !self.input_bindings.is_empty() {
187            ffi::rustduck_input_switcher_register_input(self.native.pin_mut(), handler)
188                .map_err(|error| native_exception("InputSwitcher::register_input", error))?;
189        }
190        if self.output_binding.is_some() {
191            ffi::rustduck_input_switcher_register_output(self.native.pin_mut(), handler)
192                .map_err(|error| native_exception("InputSwitcher::register_output", error))?;
193        }
194        Ok(())
195    }
196
197    fn fail_after_native_exception(
198        &mut self,
199        operation: &'static str,
200        error: cxx::Exception,
201    ) -> Error {
202        self.fail_memory_endpoints();
203        self.state = HostState::Failed;
204        native_exception(operation, error)
205    }
206
207    fn fail_memory_endpoints(&self) {
208        for input in &self.inputs {
209            input.abort();
210        }
211        if let Some(output) = &self.output {
212            output.abort();
213        }
214    }
215
216    fn close_memory_outputs(&self) {
217        if let Some(output) = &self.output {
218            output.close();
219        }
220    }
221}
222
223impl Drop for InputSwitcher {
224    fn drop(&mut self) {
225        if self.native_shutdown_required {
226            self.fail_memory_endpoints();
227            let _ = ffi::rustduck_input_switcher_stop(self.native.pin_mut());
228            let _ = ffi::rustduck_input_switcher_wait(self.native.pin_mut());
229        }
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use std::num::NonZeroUsize;
236
237    use super::*;
238    use crate::{MemoryQueuePolicy, PluginOptions, TS_PACKET_SIZE};
239
240    #[test]
241    fn rejects_empty_inputs_without_native_state_change() {
242        let _lock = crate::host::native_test_lock();
243        let report = Report::null().expect("report");
244        let mut switcher = InputSwitcher::new(report).expect("switcher");
245        assert!(matches!(
246            switcher.start(&InputSwitcherConfig::default()),
247            Err(Error::InvalidArgument { .. })
248        ));
249        assert_eq!(switcher.state(), HostState::Created);
250    }
251
252    #[test]
253    fn failed_start_keeps_memory_lease_until_owner_drop() {
254        let _lock = crate::host::native_test_lock();
255        let report = Report::null().expect("report");
256        let input = MemoryInput::new(
257            NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
258            MemoryQueuePolicy::Drop,
259        )
260        .expect("input");
261        let mut switcher = InputSwitcher::new(report).expect("switcher");
262        let config = InputSwitcherConfig {
263            inputs: vec![SwitcherInput::Memory(Arc::clone(&input))],
264            output: Some(SwitcherOutput::Native(PluginOptions::without_arguments(
265                "rustduck-definitely-not-a-plugin",
266            ))),
267            ..InputSwitcherConfig::default()
268        };
269        assert!(matches!(
270            switcher.start(&config),
271            Err(Error::NativeFailure {
272                operation: "InputSwitcher::start"
273            })
274        ));
275        assert_eq!(switcher.state(), HostState::Failed);
276        assert!(matches!(input.bind(), Err(Error::InvalidState { .. })));
277        drop(switcher);
278        input.bind().expect("lease released after owner deletion");
279    }
280}