use std::rc::Rc;
use std::sync::Arc;
use rustduck_sys::bridge::ffi;
use crate::error::native_exception;
use crate::host::invalid_state;
use crate::memory::{MemoryInputBinding, MemoryOutputBinding, install_dispatcher};
use crate::{CallbackError, Error, HostState, MemoryInput, MemoryOutput, Report, Result};
mod config;
mod native_config;
pub use config::{InputSwitcherConfig, SwitcherInput, SwitcherOutput};
pub struct InputSwitcher {
native: cxx::UniquePtr<ffi::RustDuckInputSwitcher>,
report: Rc<Report>,
handler: Option<cxx::UniquePtr<ffi::RustDuckMemoryHandler>>,
input_bindings: Vec<MemoryInputBinding>,
output_binding: Option<MemoryOutputBinding>,
inputs: Vec<Arc<MemoryInput>>,
output: Option<Arc<MemoryOutput>>,
native_shutdown_required: bool,
state: HostState,
}
impl InputSwitcher {
pub fn new(report: Rc<Report>) -> Result<Self> {
let native = ffi::rustduck_input_switcher_new(report.native())
.map_err(|error| native_exception("InputSwitcher::new", error))?;
if native.is_null() {
return Err(Error::NativeFailure {
operation: "InputSwitcher::new",
});
}
Ok(Self {
native,
report,
handler: None,
input_bindings: Vec::new(),
output_binding: None,
inputs: Vec::new(),
output: None,
native_shutdown_required: false,
state: HostState::Created,
})
}
pub fn report(&self) -> &Rc<Report> {
&self.report
}
pub const fn state(&self) -> HostState {
self.state
}
pub fn start(&mut self, config: &InputSwitcherConfig) -> Result<()> {
if self.state != HostState::Created {
return Err(invalid_state("InputSwitcher", "start", self.state));
}
config::validate(config)?;
let inputs = config
.inputs
.iter()
.filter_map(|input| match input {
SwitcherInput::Memory(endpoint) => Some(Arc::clone(endpoint)),
SwitcherInput::Native(_) => None,
})
.collect::<Vec<_>>();
let output = match &config.output {
Some(SwitcherOutput::Memory(endpoint)) => Some(Arc::clone(endpoint)),
_ => None,
};
if !inputs.is_empty() || output.is_some() {
install_dispatcher()?;
}
let handler = if !inputs.is_empty() || output.is_some() {
let handler = ffi::rustduck_memory_handler_new()
.map_err(|error| native_exception("InputSwitcher::memory_handler", error))?;
if handler.is_null() {
return Err(Error::NativeFailure {
operation: "InputSwitcher::memory_handler",
});
}
Some(handler)
} else {
None
};
let input_bindings = inputs
.iter()
.map(|input| input.bind())
.collect::<Result<Vec<_>>>()?;
let output_binding = output
.as_ref()
.map(|endpoint| endpoint.bind())
.transpose()?;
self.handler = handler;
self.input_bindings = input_bindings;
self.output_binding = output_binding;
self.inputs = inputs;
self.output = output;
self.native_shutdown_required = true;
if let Err(error) = self.register_memory_handlers() {
self.fail_memory_endpoints();
self.state = HostState::Failed;
return Err(error);
}
let native_config = self.native_config(config)?;
let started = ffi::rustduck_input_switcher_start(self.native.pin_mut(), &native_config)
.map_err(|error| self.fail_after_native_exception("InputSwitcher::start", error))?;
if !started {
self.fail_memory_endpoints();
self.state = HostState::Failed;
return Err(Error::NativeFailure {
operation: "InputSwitcher::start",
});
}
self.state = HostState::Running;
Ok(())
}
pub fn stop(&mut self) -> Result<()> {
if self.state != HostState::Running {
return Err(invalid_state("InputSwitcher", "stop", self.state));
}
self.fail_memory_endpoints();
self.state = HostState::Stopping;
ffi::rustduck_input_switcher_stop(self.native.pin_mut())
.map_err(|error| self.fail_after_native_exception("InputSwitcher::stop", error))
}
pub fn wait_for_termination(&mut self) -> Result<()> {
if !self.state.is_active() {
return Err(invalid_state(
"InputSwitcher",
"wait_for_termination",
self.state,
));
}
ffi::rustduck_input_switcher_wait(self.native.pin_mut()).map_err(|error| {
self.fail_after_native_exception("InputSwitcher::wait_for_termination", error)
})?;
self.close_memory_outputs();
self.native_shutdown_required = false;
self.state = HostState::Stopped;
Ok(())
}
pub fn take_memory_error(&self) -> Option<CallbackError> {
self.inputs
.iter()
.find_map(|input| input.take_callback_error())
.or_else(|| {
self.output
.as_ref()
.and_then(|output| output.take_callback_error())
})
}
fn native_config(
&self,
config: &InputSwitcherConfig,
) -> Result<ffi::RustDuckInputSwitcherConfig> {
native_config::build(config, &self.input_bindings, self.output_binding.as_ref())
}
fn register_memory_handlers(&mut self) -> Result<()> {
let Some(handler) = self.handler.as_ref() else {
return Ok(());
};
if !self.input_bindings.is_empty() {
ffi::rustduck_input_switcher_register_input(self.native.pin_mut(), handler)
.map_err(|error| native_exception("InputSwitcher::register_input", error))?;
}
if self.output_binding.is_some() {
ffi::rustduck_input_switcher_register_output(self.native.pin_mut(), handler)
.map_err(|error| native_exception("InputSwitcher::register_output", error))?;
}
Ok(())
}
fn fail_after_native_exception(
&mut self,
operation: &'static str,
error: cxx::Exception,
) -> Error {
self.fail_memory_endpoints();
self.state = HostState::Failed;
native_exception(operation, error)
}
fn fail_memory_endpoints(&self) {
for input in &self.inputs {
input.abort();
}
if let Some(output) = &self.output {
output.abort();
}
}
fn close_memory_outputs(&self) {
if let Some(output) = &self.output {
output.close();
}
}
}
impl Drop for InputSwitcher {
fn drop(&mut self) {
if self.native_shutdown_required {
self.fail_memory_endpoints();
let _ = ffi::rustduck_input_switcher_stop(self.native.pin_mut());
let _ = ffi::rustduck_input_switcher_wait(self.native.pin_mut());
}
}
}
#[cfg(test)]
mod tests {
use std::num::NonZeroUsize;
use super::*;
use crate::{MemoryQueuePolicy, PluginOptions, TS_PACKET_SIZE};
#[test]
fn rejects_empty_inputs_without_native_state_change() {
let _lock = crate::host::native_test_lock();
let report = Report::null().expect("report");
let mut switcher = InputSwitcher::new(report).expect("switcher");
assert!(matches!(
switcher.start(&InputSwitcherConfig::default()),
Err(Error::InvalidArgument { .. })
));
assert_eq!(switcher.state(), HostState::Created);
}
#[test]
fn failed_start_keeps_memory_lease_until_owner_drop() {
let _lock = crate::host::native_test_lock();
let report = Report::null().expect("report");
let input = MemoryInput::new(
NonZeroUsize::new(TS_PACKET_SIZE).expect("capacity"),
MemoryQueuePolicy::Drop,
)
.expect("input");
let mut switcher = InputSwitcher::new(report).expect("switcher");
let config = InputSwitcherConfig {
inputs: vec![SwitcherInput::Memory(Arc::clone(&input))],
output: Some(SwitcherOutput::Native(PluginOptions::without_arguments(
"rustduck-definitely-not-a-plugin",
))),
..InputSwitcherConfig::default()
};
assert!(matches!(
switcher.start(&config),
Err(Error::NativeFailure {
operation: "InputSwitcher::start"
})
));
assert_eq!(switcher.state(), HostState::Failed);
assert!(matches!(input.bind(), Err(Error::InvalidState { .. })));
drop(switcher);
input.bind().expect("lease released after owner deletion");
}
}