diff --git a/Cargo.lock b/Cargo.lock index 2fe6331eb9..2a14f76eb9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -599,6 +599,7 @@ dependencies = [ "schemars", "serde", "serde_json", + "tempfile", ] [[package]] @@ -665,6 +666,14 @@ dependencies = [ "serde_path_to_error", ] +[[package]] +name = "obs-mcp-module" +version = "0.1.0" +dependencies = [ + "libloading", + "obs-mcp", +] + [[package]] name = "obs-media-io" version = "0.1.0" diff --git a/ci/shared-build-files.txt b/ci/shared-build-files.txt index a9ea465a80..9333f8c4e3 100644 --- a/ci/shared-build-files.txt +++ b/ci/shared-build-files.txt @@ -86,6 +86,9 @@ rust/obs-exit-watchdog/src/platform/mod.rs # new crate's platform boundary (#406 rust/obs-gpu-status/src/platform/mod.rs rust/obs-graphics/src/platform/mod.rs rust/obs-hotkey/build.rs +rust/obs-mcp-module/build.rs # Control transport/platform selector; native module ABI requires cross-platform checks (#4448). +rust/obs-mcp-module/src/platform/mod.rs # Control transport/platform selector; native module ABI requires cross-platform checks (#4448). +rust/obs-mcp/src/platform/mod.rs # Control transport/platform selector; native module ABI requires cross-platform checks (#4448). rust/obs-media-io/src/platform/mod.rs rust/obs-nvenc/src/platform/mod.rs rust/obs-preflight/src/platform/mod.rs diff --git a/ci/test_sanitize_harness.py b/ci/test_sanitize_harness.py index 63777352cb..6d54160fe6 100644 --- a/ci/test_sanitize_harness.py +++ b/ci/test_sanitize_harness.py @@ -134,7 +134,7 @@ def write_stub(directory: Path, name: str, body: str) -> Path: TIMING_TESTS_D = ( "test_slideshow_mem_cap", ) -TIMING_TESTS_GRAPH = ("test_media_cover_art_monitor", "test_media_sync_offset_restart", "test_async_delay_audio", "test_dock_proportions", "test_dock_state_restart", "test_deinterlace_mode_load", "test_hotkey_capture_mnemonic", "test_volume_meter_ticker") +TIMING_TESTS_GRAPH = ("test_media_cover_art_monitor", "test_media_sync_offset_restart", "test_async_delay_audio", "test_dock_proportions", "test_dock_state_restart", "test_deinterlace_mode_load", "test_hotkey_capture_mnemonic", "test_volume_meter_ticker", "test_source_transition_video") TEST_GRAPH = ROOT / "test" / "cmocka" / "build" / "test-graph.json" @@ -147,6 +147,12 @@ def test_timing_tests_hold_the_timing_lock(self): for name in TIMING_TESTS_GRAPH: self.assertIn("timing", tests[name].get("resource_locks", []), name) + def test_transition_video_has_exclusive_ctest_scheduling(self): + # Its frame-bound callback assertions race a background texture trylock + # under competing native-graphics load (#4468). + test = json.loads(TEST_GRAPH.read_text(encoding="utf-8"))["tests"]["test_source_transition_video"] + self.assertTrue(test.get("run_serial"), "transition video must not compete with other CTest processes") + def test_a_resource_lock_runs_alone_in_the_pool(self): payload = json.dumps( {"tests": [{"name": "t", "command": ["/b/t"], "properties": [{"name": "RESOURCE_LOCK", "value": ["timing"]}]}]} diff --git a/ci/test_tier2_concurrency.py b/ci/test_tier2_concurrency.py index 59c3d5bf33..b22f091e48 100644 --- a/ci/test_tier2_concurrency.py +++ b/ci/test_tier2_concurrency.py @@ -22,6 +22,7 @@ "test_pipewire_screencast_shm": 90, "test_screencast_portal_teardown": 60, "test_vlc_audio_pacing": 120, + "test_source_transition_video": 120, "test_xshm_resolution_change": 60, } @@ -107,7 +108,9 @@ def test_isolated_tests_can_overlap_without_losing_timeouts_or_cases(self): name = test["name"] properties = {p["name"]: p["value"] for p in test["properties"]} with self.subTest(test=name): - exclusive = name.startswith("test_deinterlace_2x_field_order_") or (name == "test_xshm_resolution_change" and not wrapper) + exclusive = (name.startswith("test_deinterlace_2x_field_order_") + or name == "test_source_transition_video" + or (name == "test_xshm_resolution_change" and not wrapper)) self.assertEqual(bool(properties.get("RUN_SERIAL")), exclusive, "Retain timing isolation and unisolated display mutation") self.assertEqual(properties["TIMEOUT"], TIMEOUTS[name]) diff --git a/docs/features.md b/docs/features.md index bf17fea8a2..5c77ece973 100644 --- a/docs/features.md +++ b/docs/features.md @@ -3066,3 +3066,6 @@ area. *All platforms*, 2026-11-02. Follows [#3491](https://github.com/obs-rust/obs-studio/pull/3491), epic [#3283](https://github.com/obs-rust/obs-studio/issues/3283). + +- **Control socket** (#4456): private Unix MCP endpoint, `--mcp-attach` stdio proxy, + and an in-app frontend module that controls the existing OBS instance. diff --git a/docs/rust-port/control-api.md b/docs/rust-port/control-api.md index 07f07efaec..ec5d238380 100644 --- a/docs/rust-port/control-api.md +++ b/docs/rust-port/control-api.md @@ -51,3 +51,24 @@ Rust client and ci/vcam_av_sync.py MCP transport. Each slice targets master from a fresh infra/control-api-* branch with RED then GREEN shared MCP tests. The client reuses server types; Python retains websocket and adds --transport mcp plus fallback. Real GUI/device validation runs only in bosn containers. + +## Attach to the application + +Build `soldr cargo build -p obs-mcp-module` and install the resulting +`libobs_mcp_module.so` in OBS's normal module search path. The module binds +`$XDG_RUNTIME_DIR/obs-studio-rust/control.sock` with mode 0600 in a private +directory. It shares the app's libobs and stops its worker on frontend scripting +shutdown, before scene cleanup (EXIT is a fallback). It never starts a second +OBS instance or changes the application's global coordinate mode. + +`obs-studio-rust --mcp-attach [socket]` relays stdio to that instance. The same +newline JSON-RPC Server handles both transports. At most 32 clients share the +control thread; requests are serial, bounded to 16 MiB per buffered frame. +`wait_for` blocks the control thread, while OBS render/audio threads continue. +Windows named pipes are unsupported pending #4455. + +For headless CI use `obs-studio-rust --mcp-listen [socket]` (native build). +Keep its stdin open for the test's lifetime; EOF stops the socket and libobs. +The attached backend resolves frontend scenes and output names on each call, +preserves coordinate settings, and queues scene changes through the graphics +thread so the frontend's UI mutation path cannot block shutdown. diff --git a/local-gate.toml b/local-gate.toml index 88e3d73760..0304c8e9ba 100644 --- a/local-gate.toml +++ b/local-gate.toml @@ -94,7 +94,7 @@ exclude = [ "docs/**", "**/*.md", "build-aux/**", "libobs-d3d11/**", "libobs-metal/**", "libobs-winrt/**", "additional_install_files/**", "tools/**", "ci/**", ".github/**", ".claude/**", "rust/*/tests/**", "rust/*/benches/**", "rust/*/examples/**", "rust/obs-c-oracle/**", "rust/obs-camera-busy/**", "rust/obs-exit-watchdog/**", - "rust/obs-fallback-warning/**", "rust/obs-gpu-status/**", "rust/obs-frontend/**", + "rust/obs-mcp-module/**", "rust/obs-fallback-warning/**", "rust/obs-gpu-status/**", "rust/obs-frontend/**", ] keep = ["rust/*/Cargo.toml", "rust/obs-mcp/tests/**", "rust/obs-studio-rust/tests/**", "rust/obs-sys/tests/**"] diff --git a/rust/obs-data/Cargo.toml b/rust/obs-data/Cargo.toml index 9a6ea0ae8b..28e9662d3b 100644 --- a/rust/obs-data/Cargo.toml +++ b/rust/obs-data/Cargo.toml @@ -21,6 +21,7 @@ libc = { workspace = true, default-features = true } cc = { workspace = true, default-features = true, features = ["parallel"] } [dev-dependencies] +tempfile = { workspace = true, default-features = true } schemars = { workspace = true, features = ["derive", "std"] } serde = { workspace = true, features = ["derive"] } obs-audio-monitoring = { path = "../obs-audio-monitoring" } diff --git a/rust/obs-mcp-module/Cargo.toml b/rust/obs-mcp-module/Cargo.toml new file mode 100644 index 0000000000..702055e1e9 --- /dev/null +++ b/rust/obs-mcp-module/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "obs-mcp-module" +version = "0.1.0" +description = "In-app local control module for OBS" +autotests = false +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true +[lib] +crate-type = ["cdylib"] +test = false +doctest = false +[lints] +workspace = true +[target.'cfg(unix)'.dependencies] +obs-mcp = { path = "../obs-mcp", features = ["libobs"] } +libloading = { workspace = true, default-features = true } diff --git a/rust/obs-mcp-module/build.rs b/rust/obs-mcp-module/build.rs new file mode 100644 index 0000000000..0bcc36074d --- /dev/null +++ b/rust/obs-mcp-module/build.rs @@ -0,0 +1,5 @@ +#[path = "src/platform/link.rs"] +mod link; +fn main() { + link::configure(); +} diff --git a/rust/obs-mcp-module/src/ffi/mod.rs b/rust/obs-mcp-module/src/ffi/mod.rs new file mode 100644 index 0000000000..5494bfa082 --- /dev/null +++ b/rust/obs-mcp-module/src/ffi/mod.rs @@ -0,0 +1,27 @@ +use std::ffi::{c_char, c_void}; +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_ver() -> u32 { + crate::platform::version() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_set_pointer(_: *mut c_void) {} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_load() -> bool { + crate::platform::load() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_unload() { + crate::platform::unload(); +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_name() -> *const c_char { + c"OBS Control API".as_ptr() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_description() -> *const c_char { + c"Owner-only MCP socket for the running OBS instance".as_ptr() +} +#[unsafe(no_mangle)] +pub extern "C" fn obs_module_author() -> *const c_char { + c"obs-rust".as_ptr() +} diff --git a/rust/obs-mcp-module/src/lib.rs b/rust/obs-mcp-module/src/lib.rs new file mode 100644 index 0000000000..55d7fe2b98 --- /dev/null +++ b/rust/obs-mcp-module/src/lib.rs @@ -0,0 +1,5 @@ +//! Loadable OBS frontend control module. It never starts or shuts down libobs. +#![deny(unsafe_code)] +#[allow(unsafe_code, reason = "OBS module C ABI exports")] +mod ffi; +mod platform; diff --git a/rust/obs-mcp-module/src/platform/link.rs b/rust/obs-mcp-module/src/platform/link.rs new file mode 100644 index 0000000000..9000e24d17 --- /dev/null +++ b/rust/obs-mcp-module/src/platform/link.rs @@ -0,0 +1,6 @@ +pub fn configure() { + if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") { + println!("cargo:rustc-link-arg=-undefined"); + println!("cargo:rustc-link-arg=dynamic_lookup"); + } +} diff --git a/rust/obs-mcp-module/src/platform/mod.rs b/rust/obs-mcp-module/src/platform/mod.rs new file mode 100644 index 0000000000..d783680437 --- /dev/null +++ b/rust/obs-mcp-module/src/platform/mod.rs @@ -0,0 +1,4 @@ +std::cfg_select! { + unix => {mod unix; pub use unix::*;} + _ => {pub fn version()->u32{0} pub fn load()->bool{false} pub fn unload(){} } +} diff --git a/rust/obs-mcp-module/src/platform/unix.rs b/rust/obs-mcp-module/src/platform/unix.rs new file mode 100644 index 0000000000..715ceee5f4 --- /dev/null +++ b/rust/obs-mcp-module/src/platform/unix.rs @@ -0,0 +1,299 @@ +//! Frontend callbacks stop the control thread before libobs shutdown. +#![allow(unsafe_code, reason = "resolve the already-loaded OBS frontend ABI")] +use obs_mcp::{ + backend::ObsBackend, + platform::{EndpointOptions, SocketServer}, +}; +use std::{ + ffi::c_void, + rc::Rc, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, Ordering}, + }, + thread::JoinHandle, + time::Duration, +}; +type Callback = unsafe extern "C" fn(i32, *mut c_void); +type Registration = unsafe extern "C" fn(Callback, *mut c_void); +struct Worker { + stop: Arc, + thread: JoinHandle<()>, +} +struct State { + worker: Option, + remove: Registration, + _library: libloading::os::unix::Library, +} +static STATE: Mutex> = Mutex::new(None); +fn stop(state: &mut State) { + if let Some(worker) = state.worker.take() { + worker.stop.store(true, Ordering::Release); + let _ = worker.thread.join(); + } +} +unsafe extern "C" fn event(event: i32, _: *mut c_void) { + // obs-frontend-api.h: stop before ClearSceneData(), with EXIT as fallback. + if matches!(event, 36 | 17) + && let Ok(mut state) = STATE.lock() + && let Some(state) = state.as_mut() + { + stop(state); + } +} +pub fn version() -> u32 { + let lib = libloading::os::unix::Library::this(); + // SAFETY: the host defines the documented no-argument OBS version function. + unsafe { + lib.get:: u32>(b"obs_get_version\0") + .map_or(0, |f| f()) + } +} +pub fn load() -> bool { + match start() { + Ok(()) => true, + Err(e) => { + eprintln!("OBS control module: {e}"); + false + } + } +} +fn start() -> Result<(), String> { + let mut slot = STATE.lock().map_err(|e| e.to_string())?; + if slot.is_some() { + return Ok(()); + } + let library = libloading::os::unix::Library::this(); + // SAFETY: symbols have the signatures in obs-frontend-api.h; library stays owned by State. + let (add, remove) = unsafe { + ( + *library + .get::(b"obs_frontend_add_event_callback\0") + .map_err(|e| e.to_string())?, + *library + .get::(b"obs_frontend_remove_event_callback\0") + .map_err(|e| e.to_string())?, + ) + }; + let frontend = Frontend::resolve(&library)?; + let stop_flag = Arc::new(AtomicBool::new(false)); + let thread_stop = stop_flag.clone(); + let (tx, rx) = std::sync::mpsc::sync_channel(1); + let thread = std::thread::spawn(move || { + let server = match SocketServer::bind(&EndpointOptions::default()) { + Ok(s) => s, + Err(e) => { + let _ = tx.send(Err(e.to_string())); + return; + } + }; + let backend = + Rc::new(ObsBackend::attached(Rc::new(frontend)).with_cancellation(thread_stop.clone())); + if tx.send(Ok(())).is_ok() + && let Err(e) = server.run(&thread_stop, || ObsBackend::server(&backend)) + { + eprintln!("OBS control socket: {e}"); + } + }); + match rx.recv_timeout(Duration::from_secs(5)) { + Ok(Ok(())) => (), + other => { + stop_flag.store(true, Ordering::Release); + let _ = thread.join(); + return Err(format!("control socket startup: {other:?}")); + } + } + // SAFETY: callback is static, userdata null and callback lifetime ends on unload. + unsafe { + add(event, std::ptr::null_mut()); + } + *slot = Some(State { + worker: Some(Worker { + stop: stop_flag, + thread, + }), + remove, + _library: library, + }); + Ok(()) +} +pub fn unload() { + if let Ok(mut slot) = STATE.lock() + && let Some(mut state) = slot.take() + { + // SAFETY: unregister the exact static callback before dropping the library. + unsafe { + (state.remove)(event, std::ptr::null_mut()); + } + stop(&mut state); + } +} + +type GetSource = unsafe extern "C" fn() -> *mut c_void; +type GetName = unsafe extern "C" fn(*mut c_void) -> *const std::ffi::c_char; +type Release = unsafe extern "C" fn(*mut c_void); +#[derive(Clone, Copy)] +struct Frontend { + current: GetSource, + set: unsafe extern "C" fn(*mut c_void), + source: unsafe extern "C" fn(*const std::ffi::c_char) -> *mut c_void, + name: GetName, + release: Release, + record: GetSource, + stream: GetSource, + record_start: unsafe extern "C" fn(), + record_stop: unsafe extern "C" fn(), + record_active: unsafe extern "C" fn() -> bool, + stream_start: unsafe extern "C" fn(), + stream_stop: unsafe extern "C" fn(), + stream_active: unsafe extern "C" fn() -> bool, + output_name: GetName, + output_release: Release, + queue: unsafe extern "C" fn(i32, unsafe extern "C" fn(*mut c_void), *mut c_void, bool), +} +impl Frontend { + fn resolve(lib: &libloading::os::unix::Library) -> Result { + // SAFETY: documented frontend/libobs symbols, held by State for all worker calls. + unsafe { + Ok(Self { + current: *lib + .get(b"obs_frontend_get_current_scene\0") + .map_err(|e| e.to_string())?, + set: *lib + .get(b"obs_frontend_set_current_scene\0") + .map_err(|e| e.to_string())?, + source: *lib + .get(b"obs_get_source_by_name\0") + .map_err(|e| e.to_string())?, + name: *lib + .get(b"obs_source_get_name\0") + .map_err(|e| e.to_string())?, + release: *lib + .get(b"obs_source_release\0") + .map_err(|e| e.to_string())?, + record: *lib + .get(b"obs_frontend_get_recording_output\0") + .map_err(|e| e.to_string())?, + stream: *lib + .get(b"obs_frontend_get_streaming_output\0") + .map_err(|e| e.to_string())?, + output_name: *lib + .get(b"obs_output_get_name\0") + .map_err(|e| e.to_string())?, + record_start: *lib + .get(b"obs_frontend_recording_start\0") + .map_err(|e| e.to_string())?, + record_stop: *lib + .get(b"obs_frontend_recording_stop\0") + .map_err(|e| e.to_string())?, + record_active: *lib + .get(b"obs_frontend_recording_active\0") + .map_err(|e| e.to_string())?, + stream_start: *lib + .get(b"obs_frontend_streaming_start\0") + .map_err(|e| e.to_string())?, + stream_stop: *lib + .get(b"obs_frontend_streaming_stop\0") + .map_err(|e| e.to_string())?, + stream_active: *lib + .get(b"obs_frontend_streaming_active\0") + .map_err(|e| e.to_string())?, + output_release: *lib + .get(b"obs_output_release\0") + .map_err(|e| e.to_string())?, + queue: *lib.get(b"obs_queue_task\0").map_err(|e| e.to_string())?, + }) + } + } + fn name_of(&self, get: GetSource, name: GetName, release: Release) -> Option { + // SAFETY: getter returns an owned OBS reference; copied name is used before release. + unsafe { + let source = get(); + if source.is_null() { + return None; + } + let text = name(source); + let result = (!text.is_null()).then(|| { + std::ffi::CStr::from_ptr(text) + .to_string_lossy() + .into_owned() + }); + release(source); + result + } + } +} +struct SceneChange { + frontend: Frontend, + name: std::ffi::CString, +} +unsafe extern "C" fn change_scene(data: *mut c_void) { + // SAFETY: synchronous graphics queue borrows the stack request until this returns. + let request = unsafe { &*data.cast::() }; + // SAFETY: source is retained across the frontend call, which itself retains queued UI data. + unsafe { + let source = (request.frontend.source)(request.name.as_ptr()); + if !source.is_null() { + (request.frontend.set)(source); + (request.frontend.release)(source); + } + } +} +impl obs_mcp::backend::AttachedFrontend for Frontend { + fn set_output( + &self, + request: obs_mcp::backend::FrontendOutputRequest, + ) -> Result { + use obs_mcp::tools::outputs::OutputKind; + let (active, command) = match (request.kind, request.active) { + (OutputKind::Record, true) => (self.record_active, self.record_start), + (OutputKind::Record, false) => (self.record_active, self.record_stop), + (OutputKind::Stream, true) => (self.stream_active, self.stream_start), + (OutputKind::Stream, false) => (self.stream_active, self.stream_stop), + }; + // SAFETY: frontend start/stop use queued Qt invocations from this worker; + // active getters read atomics. State/library outlive all worker calls. + unsafe { + // The frontend checks idempotency on the UI thread. Do not skip a + // stop based on a stale inactive sample while a start is queued. + command(); + Ok(obs_mcp::tools::outputs::ActiveOutput { active: active() }) + } + } + fn current_scene(&self, _: obs_mcp::tools::EmptyInput) -> obs_mcp::tools::scenes::SceneOutput { + obs_mcp::tools::scenes::SceneOutput { + name: self.name_of(self.current, self.name, self.release), + } + } + fn set_scene( + &self, + request: obs_mcp::tools::scenes::NameInput, + ) -> Result { + let mut change = SceneChange { + frontend: *self, + name: std::ffi::CString::new(request.name.as_str()) + .map_err(|e| obs_mcp::server::ToolError::wrong_state(e.to_string()))?, + }; + // SAFETY: OBS_TASK_GRAPHICS (1) forces the frontend setter's nonblocking UI path. + // The synchronous graphics task completes before this stack request drops. Thus + // frontend EXIT can join the worker without waiting on a blocked UI callback. + unsafe { + (self.queue)(1, change_scene, (&raw mut change).cast(), true); + } + Ok(obs_mcp::tools::scenes::SceneOutput { + name: Some(request.name), + }) + } + fn output_name( + &self, + request: obs_mcp::tools::outputs::OutputRequest, + ) -> obs_mcp::backend::FrontendOutputName { + let get = match request.kind { + obs_mcp::tools::outputs::OutputKind::Record => self.record, + obs_mcp::tools::outputs::OutputKind::Stream => self.stream, + }; + obs_mcp::backend::FrontendOutputName { + name: self.name_of(get, self.output_name, self.output_release), + } + } +} diff --git a/rust/obs-mcp/Cargo.toml b/rust/obs-mcp/Cargo.toml index c43b005d0a..ffcee04b5a 100644 --- a/rust/obs-mcp/Cargo.toml +++ b/rust/obs-mcp/Cargo.toml @@ -19,7 +19,7 @@ test = false # Binds the backend traits to libobs through obs-sys (#3283). Off by default: # it needs the libobs symbols at link time, which only the application and the # `bundled-native` contract tests provide. -libobs = ["dep:obs-sys", "dep:libc"] +libobs = ["dep:obs-sys"] # Test-only fault injection (with `libobs`): `host::fail_audio_mixer` makes the next start # behave as if libobs could not open its audio mixer (#3491). Enabled only by # obs-studio-rust's dev-dependency, so no shipped build can reach it; the @@ -38,4 +38,4 @@ flate2 = { workspace = true, features = ["rust_backend"] } # Redirects descriptor 1 to stderr so libobs logs stay off the protocol stream. [target.'cfg(unix)'.dependencies] -libc = { workspace = true, default-features = true, optional = true } +libc = { workspace = true, default-features = true } diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index d4d0ec7eb1..47c8260e0b 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -43,7 +43,38 @@ use crate::tools::sources::{self, ItemInfo, ItemRef, SourceBackend, SourceInfo, const MAX_SIDE: u32 = 16_384; /// The libobs-backed implementation of every backend trait. +/// Frontend capabilities supplied by an attached application. +pub trait AttachedFrontend { + fn current_scene(&self, request: crate::tools::EmptyInput) + -> crate::tools::scenes::SceneOutput; + fn set_scene( + &self, + request: crate::tools::scenes::NameInput, + ) -> Result; + fn output_name(&self, request: crate::tools::outputs::OutputRequest) -> FrontendOutputName; + fn set_output( + &self, + _request: FrontendOutputRequest, + ) -> Result { + Err(crate::server::ToolError::not_ready( + "frontend output control is unavailable", + )) + } +} +/// Start or stop a frontend-managed output, preserving profile/encoder setup. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct FrontendOutputRequest { + pub kind: crate::tools::outputs::OutputKind, + pub active: bool, +} +/// Current frontend output identity; absent while the frontend has no output. +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)] +pub struct FrontendOutputName { + pub name: Option, +} pub struct ObsBackend { + frontend: Option>, /// References to the scenes and sources created here, by name. owned: RefCell>, record: Option, @@ -73,7 +104,18 @@ impl ObsBackend { #[must_use] pub fn new() -> Self { crate::ffi::use_absolute_coordinates(); + Self::unconfigured() + } + /// Attach without changing global coordinate settings or owning libobs. + #[must_use] + pub fn attached(frontend: Rc) -> Self { + let mut backend = Self::unconfigured(); + backend.frontend = Some(frontend); + backend + } + fn unconfigured() -> Self { Self { + frontend: None, owned: RefCell::new(HashMap::new()), record: None, stream: None, @@ -174,8 +216,14 @@ impl ObsBackend { OutputKind::Record => ("record", &self.record), OutputKind::Stream => ("stream", &self.stream), }; - let name = name + let frontend_name = self.frontend.as_ref().and_then(|frontend| { + frontend + .output_name(crate::tools::outputs::OutputRequest { kind }) + .name + }); + let name = frontend_name .as_deref() + .or(name.as_deref()) .ok_or_else(|| format!("the {label} output is not configured"))?; Output::by_name(name).ok_or_else(|| { Self::because( @@ -219,11 +267,22 @@ impl SceneBackend for ObsBackend { } fn current(&self) -> Option { - ffi::program().filter(Source::is_scene).map(|s| s.name()) + self.frontend.as_ref().map_or_else( + || ffi::program().filter(Source::is_scene).map(|s| s.name()), + |frontend| frontend.current_scene(crate::tools::EmptyInput {}).name, + ) } fn set_current(&self, name: &str) -> Result<(), String> { let scene = Self::scene(name)?; + if let Some(frontend) = &self.frontend { + return frontend + .set_scene(crate::tools::scenes::NameInput { + name: name.to_owned(), + }) + .map(|_| ()) + .map_err(|error| error.message); + } ffi::set_program(Some(&scene)); Ok(()) } @@ -234,7 +293,7 @@ impl SceneBackend for ObsBackend { // A client that makes the first scene wants to see it: with no // program scene the new one becomes the program scene (#3339). if self.current().is_none() { - ffi::set_program(Some(&scene)); + self.set_current(name)?; } self.owned.borrow_mut().insert(name.to_owned(), scene); Ok(()) @@ -243,6 +302,11 @@ impl SceneBackend for ObsBackend { fn remove(&self, name: &str) -> Result<(), String> { let scene = Self::scene(name)?; if self.current().as_deref() == Some(name) { + if self.frontend.is_some() { + return Err( + "switch away from the current frontend scene before removing it".to_owned(), + ); + } ffi::set_program(None); } scene.remove(); @@ -350,6 +414,12 @@ impl OutputBackend for ObsBackend { crate::tools::waiting::WaitBackend::cancelled(self) } fn start_output(&self, request: OutputRequest) -> Result { + if let Some(frontend) = &self.frontend { + return frontend.set_output(FrontendOutputRequest { + kind: request.kind, + active: true, + }); + } let output = self.output(request.kind).map_err(ToolError::not_ready)?; if !output.active() { if request.kind == OutputKind::Record { @@ -364,6 +434,12 @@ impl OutputBackend for ObsBackend { } fn stop_output(&self, request: OutputRequest) -> Result { + if let Some(frontend) = &self.frontend { + return frontend.set_output(FrontendOutputRequest { + kind: request.kind, + active: false, + }); + } let output = self.output(request.kind).map_err(ToolError::not_ready)?; if output.active() { output.stop(); @@ -374,6 +450,12 @@ impl OutputBackend for ObsBackend { } fn start(&self, kind: OutputKind) -> Result<(), String> { + if let Some(frontend) = &self.frontend { + return frontend + .set_output(FrontendOutputRequest { kind, active: true }) + .map(|_| ()) + .map_err(|error| error.message); + } let output = self.output(kind)?; if output.active() { return Err("the output is already running".to_owned()); @@ -385,6 +467,15 @@ impl OutputBackend for ObsBackend { } fn stop(&self, kind: OutputKind) -> Result<(), String> { + if let Some(frontend) = &self.frontend { + return frontend + .set_output(FrontendOutputRequest { + kind, + active: false, + }) + .map(|_| ()) + .map_err(|error| error.message); + } let output = self.output(kind)?; if !output.active() { return Err("the output is not running".to_owned()); diff --git a/rust/obs-mcp/src/host.rs b/rust/obs-mcp/src/host.rs index d9caac76c1..25fab2847a 100644 --- a/rust/obs-mcp/src/host.rs +++ b/rust/obs-mcp/src/host.rs @@ -75,14 +75,7 @@ impl StartOptions { } } -fn default_graphics_module() -> String { - if cfg!(windows) { - "libobs-d3d11" - } else { - "libobs-opengl" - } - .to_owned() -} +use crate::platform::default_graphics_module; /// A started libobs with video, audio, modules and the record and stream /// outputs set up. Every step after `obs_startup` that fails is recorded, not @@ -154,3 +147,27 @@ pub fn serve_stdio(options: &StartOptions) -> io::Result<()> { drop(backend); result } + +/// Start a headless instance on a socket until stdin closes. +/// # Errors +/// Returns startup or transport errors. +pub fn serve_socket( + options: &StartOptions, + endpoint: &crate::platform::EndpointOptions, +) -> io::Result<()> { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + let runtime = Runtime::start(options)?; + let socket = crate::platform::SocketServer::bind(endpoint)?; + let stop = Arc::new(AtomicBool::new(false)); + let stdin_stop = stop.clone(); + std::thread::spawn(move || { + let _ = io::copy(&mut io::stdin().lock(), &mut io::sink()); + stdin_stop.store(true, Ordering::Release); + }); + let backend = Rc::new(runtime.backend().with_cancellation(stop.clone())); + eprintln!("OBS control socket ready"); + socket.run(&stop, || ObsBackend::server(&backend)) +} diff --git a/rust/obs-mcp/src/lib.rs b/rust/obs-mcp/src/lib.rs index 41e611852a..5279e4f382 100644 --- a/rust/obs-mcp/src/lib.rs +++ b/rust/obs-mcp/src/lib.rs @@ -40,3 +40,5 @@ use std::io::{self, BufRead, Write}; pub fn serve(reader: R, writer: W) -> io::Result<()> { server::Server::new().serve(reader, writer) } + +pub mod platform; diff --git a/rust/obs-mcp/src/platform/mod.rs b/rust/obs-mcp/src/platform/mod.rs new file mode 100644 index 0000000000..7862d60a67 --- /dev/null +++ b/rust/obs-mcp/src/platform/mod.rs @@ -0,0 +1,28 @@ +//! Host boundary for local control sockets. +use std::{io, path::PathBuf}; +#[derive(Clone, Debug, Default)] +pub struct EndpointOptions { + pub socket: Option, +} +/// Resolve an explicit endpoint or the per-user runtime endpoint. +/// # Errors +/// Fails if no runtime directory is configured. +pub fn endpoint(options: &EndpointOptions) -> io::Result { + options.socket.clone().map_or_else( + || { + std::env::var_os("XDG_RUNTIME_DIR") + .map(|p| PathBuf::from(p).join("obs-studio-rust/control.sock")) + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::NotFound, + "XDG_RUNTIME_DIR is unset; provide a socket path", + ) + }) + }, + Ok, + ) +} +std::cfg_select! { + unix => { mod unix; pub use unix::*; } + _ => { mod unsupported; pub use unsupported::*; } +} diff --git a/rust/obs-mcp/src/platform/unix.rs b/rust/obs-mcp/src/platform/unix.rs new file mode 100644 index 0000000000..82bf4da9b1 --- /dev/null +++ b/rust/obs-mcp/src/platform/unix.rs @@ -0,0 +1,260 @@ +//! Unix sockets and descriptor relay; no host code escapes this module. +#![allow( + unsafe_code, + reason = "Unix owner checks and stdin polling require libc" +)] +use super::{EndpointOptions, endpoint}; +use crate::server::Server; +use std::{ + fs, + io::{self, BufRead, BufReader, Read, Write}, + os::unix::{ + fs::{DirBuilderExt, FileTypeExt, MetadataExt, PermissionsExt}, + io::AsRawFd, + net::{UnixListener, UnixStream}, + }, + path::PathBuf, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + time::Duration, +}; +const MAX_FRAME: usize = 16 * 1024 * 1024; +pub struct Connection { + pub reader: Box, + pub writer: Box, +} +fn owned(meta: &fs::Metadata) -> io::Result<()> { + // SAFETY: geteuid has no preconditions. + if meta.uid() != unsafe { libc::geteuid() } || meta.mode() & 0o077 != 0 { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "endpoint must be owned by this user and private", + )); + } + Ok(()) +} +fn validate(path: &std::path::Path) -> io::Result { + let meta = fs::symlink_metadata(path)?; + owned(&meta)?; + if !meta.file_type().is_socket() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "endpoint is not a socket", + )); + } + Ok(meta) +} +/// Connect without starting another OBS instance. +/// # Errors +/// Rejects unsafe endpoints and connection failures. +pub fn connect(options: &EndpointOptions) -> io::Result { + let path = endpoint(options)?; + validate(&path)?; + let stream = UnixStream::connect(path)?; + stream.set_read_timeout(Some(Duration::from_secs(310)))?; + stream.set_write_timeout(Some(Duration::from_secs(5)))?; + Ok(Connection { + reader: Box::new(BufReader::new(stream.try_clone()?)), + writer: Box::new(stream), + }) +} +pub struct SocketServer { + listener: UnixListener, + path: PathBuf, + identity: (u64, u64), +} +impl SocketServer { + /// Bind a private socket, refusing active endpoints and non-sockets. + /// # Errors + /// Fails for unsafe permissions, active endpoints or filesystem errors. + pub fn bind(options: &EndpointOptions) -> io::Result { + let path = endpoint(options)?; + let parent = path + .parent() + .ok_or_else(|| io::Error::other("socket needs a parent"))?; + match fs::DirBuilder::new().mode(0o700).create(parent) { + Ok(()) => (), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => (), + Err(e) => return Err(e), + } + let meta = fs::symlink_metadata(parent)?; + owned(&meta)?; + if !meta.is_dir() || meta.file_type().is_symlink() { + return Err(io::Error::other("socket parent is not a directory")); + } + if fs::symlink_metadata(&path).is_ok() { + validate(&path)?; + match UnixStream::connect(&path) { + Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => fs::remove_file(&path)?, + _ => { + return Err(io::Error::new( + io::ErrorKind::AddrInUse, + "control socket already active", + )); + } + } + } + let listener = UnixListener::bind(&path)?; + fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?; + listener.set_nonblocking(true)?; + let meta = fs::symlink_metadata(&path)?; + Ok(Self { + listener, + path, + identity: (meta.dev(), meta.ino()), + }) + } + #[must_use] + pub fn path(&self) -> &std::path::Path { + &self.path + } + /// Multiplex clients on the owning backend thread. Rendering stays on OBS threads. + /// # Errors + /// Returns listener failures; disconnected clients are isolated. + pub fn run( + self, + stop: &Arc, + mut factory: impl FnMut() -> Server, + ) -> io::Result<()> { + struct Peer { + stream: UnixStream, + buffer: Vec, + server: Server, + } + let mut peers: Vec = Vec::new(); + while !stop.load(Ordering::Acquire) { + match self.listener.accept() { + Ok((stream, _)) => { + if peers.len() < 32 { + stream.set_nonblocking(true)?; + peers.push(Peer { + stream, + buffer: Vec::new(), + server: factory(), + }); + } + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => (), + Err(e) => return Err(e), + } + peers.retain_mut(|peer| { + let mut bytes = [0u8; 8192]; + let mut eof = false; + loop { + match peer.stream.read(&mut bytes) { + Ok(0) => { + eof = true; + break; + } + Ok(n) => { + peer.buffer.extend_from_slice(&bytes[..n]); + if peer.buffer.len() > MAX_FRAME { + return false; + } + } + Err(e) if e.kind() == io::ErrorKind::WouldBlock => break, + Err(_) => return false, + } + } + while let Some(n) = peer + .buffer + .iter() + .position(|b| *b == b'\n') + .map(|n| n + 1) + .or_else(|| (eof && !peer.buffer.is_empty()).then_some(peer.buffer.len())) + { + if stop.load(Ordering::Acquire) { + return false; + } + let line: Vec<_> = peer.buffer.drain(..n).collect(); + let mut response = Vec::new(); + if peer.server.serve(line.as_slice(), &mut response).is_err() { + return false; + } + if peer.stream.set_nonblocking(false).is_err() { + return false; + } + let result = peer + .stream + .set_write_timeout(Some(Duration::from_secs(1))) + .and_then(|()| peer.stream.write_all(&response)); + if result.is_err() || peer.stream.set_nonblocking(true).is_err() { + return false; + } + } + !eof + }); + std::thread::park_timeout(Duration::from_millis(2)); + } + Ok(()) + } +} +impl Drop for SocketServer { + fn drop(&mut self) { + if let Ok(meta) = fs::symlink_metadata(&self.path) + && (meta.dev(), meta.ino()) == self.identity + { + let _ = fs::remove_file(&self.path); + } + } +} +/// Relay stdio bytes to an existing instance, preserving newline framing. +/// # Errors +/// Returns connect or relay failures. +pub fn proxy(options: &EndpointOptions) -> io::Result<()> { + let path = endpoint(options)?; + validate(&path)?; + let mut stream = UnixStream::connect(path)?; + let mut stdin_open = true; + let mut stdout = io::stdout().lock(); + loop { + let mut fds = [ + libc::pollfd { + fd: if stdin_open { 0 } else { -1 }, + events: libc::POLLIN, + revents: 0, + }, + libc::pollfd { + fd: stream.as_raw_fd(), + events: libc::POLLIN, + revents: 0, + }, + ]; + // SAFETY: fds is initialized and lives across poll. + if unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) } < 0 { + let e = io::Error::last_os_error(); + if e.kind() == io::ErrorKind::Interrupted { + continue; + } + return Err(e); + } + let mut bytes = [0u8; 8192]; + if fds[0].revents & (libc::POLLIN | libc::POLLHUP) != 0 { + // SAFETY: bytes has the supplied writable capacity; fd 0 is stdin. + let n = unsafe { libc::read(0, bytes.as_mut_ptr().cast(), bytes.len()) }; + if n < 0 { + return Err(io::Error::last_os_error()); + } + if n == 0 { + stdin_open = false; + stream.shutdown(std::net::Shutdown::Write)?; + } else { + stream.write_all(&bytes[..usize::try_from(n).map_err(io::Error::other)?])?; + } + } + if fds[1].revents & (libc::POLLIN | libc::POLLHUP | libc::POLLERR) != 0 { + let n = stream.read(&mut bytes)?; + if n == 0 { + return Ok(()); + } + stdout.write_all(&bytes[..n])?; + stdout.flush()?; + } + } +} +#[must_use] +pub fn default_graphics_module() -> String { + "libobs-opengl".to_owned() +} diff --git a/rust/obs-mcp/src/platform/unsupported.rs b/rust/obs-mcp/src/platform/unsupported.rs new file mode 100644 index 0000000000..f4ea84bd04 --- /dev/null +++ b/rust/obs-mcp/src/platform/unsupported.rs @@ -0,0 +1,37 @@ +//! Windows named-pipe transport is tracked in obs-rust/obs-studio#4455. +use super::EndpointOptions; +use std::io; +pub struct Connection { + pub reader: Box, + pub writer: Box, +} +fn unavailable() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "local control transport unavailable; Windows named pipe: https://github.com/obs-rust/obs-studio/issues/4455", + ) +} +pub fn connect(_: &EndpointOptions) -> io::Result { + Err(unavailable()) +} +pub fn proxy(_: &EndpointOptions) -> io::Result<()> { + Err(unavailable()) +} +#[must_use] +pub fn default_graphics_module() -> String { + "libobs-d3d11".to_owned() +} + +pub struct SocketServer; +impl SocketServer { + pub fn bind(_: &EndpointOptions) -> io::Result { + Err(unavailable()) + } + pub fn run( + self, + _: &std::sync::Arc, + _: impl FnMut() -> crate::server::Server, + ) -> io::Result<()> { + Err(unavailable()) + } +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index 5e6bdfe826..91c270fa13 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -29,3 +29,5 @@ mod typed; mod control; mod waiting; + +mod transport; diff --git a/rust/obs-mcp/tests/mcp/transport.rs b/rust/obs-mcp/tests/mcp/transport.rs new file mode 100644 index 0000000000..58fc2a12a7 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/transport.rs @@ -0,0 +1,178 @@ +use obs_mcp::platform::{EndpointOptions, endpoint}; +#[test] +fn explicit_endpoint_is_preserved() { + let path = std::path::PathBuf::from("/test/control.sock"); + assert_eq!( + endpoint(&EndpointOptions { + socket: Some(path.clone()) + }) + .unwrap(), + path + ); +} +#[cfg(unix)] +#[test] +fn private_socket_serves_fragmented_and_multiple_clients_and_cleans_up() { + use obs_mcp::{ + platform::{SocketServer, connect}, + server::Server, + }; + use std::{ + io::Write, + os::unix::fs::PermissionsExt, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, + }; + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let options = EndpointOptions { + socket: Some(directory.path().join("control.sock")), + }; + let socket = SocketServer::bind(&options).unwrap(); + assert_eq!( + std::fs::metadata(socket.path()) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + assert!(SocketServer::bind(&options).is_err()); + let stop = Arc::new(AtomicBool::new(false)); + struct Guard(Arc, Option>); + impl Drop for Guard { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + self.1.take().unwrap().join().unwrap(); + } + } + let flag = stop.clone(); + let _guard = Guard( + stop, + Some(std::thread::spawn(move || { + socket.run(&flag, Server::new).unwrap() + })), + ); + let mut a = connect(&options).unwrap(); + let mut b = connect(&options).unwrap(); + a.writer + .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":1,") + .unwrap(); + b.writer + .write_all(b"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n") + .unwrap(); + let mut line = String::new(); + b.reader.read_line(&mut line).unwrap(); + assert_eq!( + serde_json::from_str::(&line).unwrap()["id"], + 2 + ); + a.writer.write_all(b"\"method\":\"ping\"}\n").unwrap(); + line.clear(); + a.reader.read_line(&mut line).unwrap(); + assert_eq!( + serde_json::from_str::(&line).unwrap()["id"], + 1 + ); + drop(a); + drop(b); + drop(_guard); + assert!(!options.socket.unwrap().exists()); +} +#[cfg(unix)] +#[test] +fn refuses_non_socket_and_symlink() { + use obs_mcp::platform::SocketServer; + use std::os::unix::fs::{PermissionsExt, symlink}; + let dir = tempfile::tempdir().unwrap(); + std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let file = dir.path().join("file"); + std::fs::write(&file, b"keep").unwrap(); + assert!( + SocketServer::bind(&EndpointOptions { + socket: Some(file.clone()) + }) + .is_err() + ); + let link = dir.path().join("link"); + symlink(&file, &link).unwrap(); + assert!(SocketServer::bind(&EndpointOptions { socket: Some(link) }).is_err()); + assert_eq!(std::fs::read(file).unwrap(), b"keep"); +} + +#[cfg(unix)] +#[test] +fn shutdown_discards_requests_already_buffered_after_cancellation() { + use obs_mcp::{ + platform::{SocketServer, connect}, + server::{Server, ToolAnnotations, ToolError, ToolRegistry, TypedTool}, + tools::EmptyInput, + }; + use std::{ + io::Write, + os::unix::fs::PermissionsExt, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + }; + struct Cancel { + stop: Arc, + calls: Arc, + } + impl TypedTool for Cancel { + type Input = EmptyInput; + type Output = EmptyInput; + const NAME: &'static str = "cancel_test"; + const ANNOTATIONS: ToolAnnotations = ToolAnnotations::MUTATING; + fn description(&self) -> &'static str { + "Cancel the test server" + } + fn call(&self, _: EmptyInput) -> Result { + self.calls.fetch_add(1, Ordering::AcqRel); + self.stop.store(true, Ordering::Release); + Ok(EmptyInput {}) + } + } + let directory = tempfile::tempdir().unwrap(); + std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let options = EndpointOptions { + socket: Some(directory.path().join("control.sock")), + }; + let socket = SocketServer::bind(&options).unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let calls = Arc::new(AtomicUsize::new(0)); + let flag = stop.clone(); + let count = calls.clone(); + struct Guard(Arc, Option>); + impl Drop for Guard { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + self.1.take().unwrap().join().unwrap(); + } + } + let thread = std::thread::spawn(move || { + socket + .run(&flag, || { + let mut tools = ToolRegistry::default(); + tools.register(Box::new(Cancel { + stop: flag.clone(), + calls: count.clone(), + })); + Server::with_tools(tools) + }) + .unwrap() + }); + let guard = Guard(stop, Some(thread)); + let mut connection = connect(&options).unwrap(); + connection.writer.write_all(concat!( + "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_test\",\"arguments\":{}}}\n", + "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{\"name\":\"cancel_test\",\"arguments\":{}}}\n" + ).as_bytes()).unwrap(); + let mut reply = String::new(); + connection.reader.read_line(&mut reply).unwrap(); + drop(guard); + assert_eq!(calls.load(Ordering::Acquire), 1); +} diff --git a/rust/obs-studio-rust/Cargo.toml b/rust/obs-studio-rust/Cargo.toml index e89df2e500..41feea1c5e 100644 --- a/rust/obs-studio-rust/Cargo.toml +++ b/rust/obs-studio-rust/Cargo.toml @@ -18,11 +18,11 @@ path = "src/main.rs" [features] libobs-integration = ["obs-build/libobs-integration"] -bundled-native = ["dep:obs-sys", "obs-sys/bundled", "dep:obs-mcp", "obs-mcp/libobs"] +bundled-native = ["dep:obs-sys", "obs-sys/bundled", "obs-mcp/libobs"] [dependencies] obs-sys = { path = "../obs-sys", optional = true } -obs-mcp = { path = "../obs-mcp", optional = true } +obs-mcp = { path = "../obs-mcp" } base64 = { workspace = true, features = ["std", "simd-unsafe"] } serde_json = { workspace = true, features = ["std"] } sha2 = { workspace = true, features = ["alloc", "oid"] } diff --git a/rust/obs-studio-rust/src/main.rs b/rust/obs-studio-rust/src/main.rs index ab7873b704..26a81c43b3 100644 --- a/rust/obs-studio-rust/src/main.rs +++ b/rust/obs-studio-rust/src/main.rs @@ -39,6 +39,8 @@ struct Args { password: Option, json: bool, mcp: bool, + mcp_attach: bool, + mcp_listen: bool, record_dir: Option, command: String, } @@ -52,6 +54,8 @@ fn parse_args() -> Result, String> { let mut command = None; let mut json = false; let mut mcp = false; + let mut mcp_attach = false; + let mut mcp_listen = false; let mut record_dir = None; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { @@ -73,6 +77,8 @@ fn parse_args() -> Result, String> { "--password" => password = Some(value("--password")?), "--json" => json = true, "--mcp" => mcp = true, + "--mcp-attach" => mcp_attach = true, + "--mcp-listen" => mcp_listen = true, "--record-dir" => record_dir = Some(value("--record-dir")?), _ if arg.starts_with('-') => return Err(format!("unknown option: {arg}")), _ if command.is_none() => command = Some(arg), @@ -81,9 +87,12 @@ fn parse_args() -> Result, String> { } let command = match command { Some(command) => command, - None if mcp => String::new(), + None if mcp || mcp_attach || mcp_listen => String::new(), None => return Err("missing command".to_owned()), }; + if u8::from(mcp) + u8::from(mcp_attach) + u8::from(mcp_listen) > 1 { + return Err("choose --mcp or --mcp-attach".to_owned()); + } if mcp && !command.is_empty() { return Err("--mcp takes no command".to_owned()); } @@ -93,6 +102,8 @@ fn parse_args() -> Result, String> { password, json, mcp, + mcp_attach, + mcp_listen, record_dir, command, })) @@ -141,7 +152,18 @@ fn main() -> ExitCode { return ExitCode::from(2); } }; - let result = if args.mcp { + let result = if args.mcp_listen { + mcp::listen( + args.record_dir.as_deref(), + (!args.command.is_empty()).then_some(args.command.as_str()), + ) + .map_err(Box::from) + } else if args.mcp_attach { + obs_mcp::platform::proxy(&obs_mcp::platform::EndpointOptions { + socket: (!args.command.is_empty()).then(|| args.command.clone().into()), + }) + .map_err(Box::from) + } else if args.mcp { mcp::run(args.record_dir.as_deref()).map_err(Box::from) } else { run(&args) diff --git a/rust/obs-studio-rust/src/mcp.rs b/rust/obs-studio-rust/src/mcp.rs index 750a189894..386d2999a5 100644 --- a/rust/obs-studio-rust/src/mcp.rs +++ b/rust/obs-studio-rust/src/mcp.rs @@ -28,3 +28,20 @@ pub fn run(_record_dir: Option<&str>) -> io::Result<()> { "this build has no libobs; rebuild with --features bundled-native", )) } + +/// Serve a headless socket until stdin closes. +/// # Errors +/// Fails if libobs or the socket cannot start. +#[cfg(feature = "bundled-native")] +pub fn listen(record_dir: Option<&str>, socket: Option<&str>) -> io::Result<()> { + obs_mcp::host::serve_socket( + &obs_mcp::host::StartOptions::from_env(record_dir.map(Into::into)), + &obs_mcp::platform::EndpointOptions { + socket: socket.map(Into::into), + }, + ) +} +#[cfg(not(feature = "bundled-native"))] +pub fn listen(record_dir: Option<&str>, _: Option<&str>) -> io::Result<()> { + run(record_dir) +} diff --git a/test/cmocka/build/test-graph.json b/test/cmocka/build/test-graph.json index 60dcf97315..7d49299c07 100644 --- a/test/cmocka/build/test-graph.json +++ b/test/cmocka/build/test-graph.json @@ -23874,7 +23874,11 @@ ], "suite": "graphics", "working_directory": "${runtime}", - "timeout_seconds": 120 + "timeout_seconds": 120, + "resource_locks": [ + "timing" + ], + "run_serial": true }, "test_source_video_tick_steps": { "target": "test_source_video_tick_steps",