diff --git a/docs/features.md b/docs/features.md index e254acf9eb..cd929e1368 100644 --- a/docs/features.md +++ b/docs/features.md @@ -75,6 +75,12 @@ not get a line. ### Headless and automation +- **Virtual device and media control.** MCP can start/stop Virtual Camera, inspect + its paired mic, restart media, inspect pipeline graphs and read/reset measured + stage counters. Unmeasured device/sync values stay null. *All* (device support + depends on the loaded plugin), 2026-11-09. Issue [#4446](https://github.com/obs-rust/obs-studio/issues/4446), + PR [#4452](https://github.com/obs-rust/obs-studio/pull/4452). + - **Typed MCP control.** Existing OBS MCP tools publish input and output schemas, structured results and machine-readable domain errors. Read operations carry annotations, and repeated output start/stop calls succeed with current state. diff --git a/docs/rust-port/control-api.schema.json b/docs/rust-port/control-api.schema.json index 5656f4d596..2e6ab44ae5 100644 --- a/docs/rust-port/control-api.schema.json +++ b/docs/rust-port/control-api.schema.json @@ -1,6 +1,9 @@ { "toolError": {"$defs":{"ErrorCategory":{"description":"Domain failure category, using obs-websocket v5 status ranges.","oneOf":[{"const":"not_ready","description":"A resource is absent or not ready (ResourceNotFound/NotReady).","type":"string"},{"const":"wrong_state","description":"The current state prevents the operation (6xx).","type":"string"},{"const":"processing","description":"OBS failed to process the operation (7xx).","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A domain failure, distinct from a JSON-RPC fault.","properties":{"category":{"$ref":"#/$defs/ErrorCategory","description":"Stable machine-readable category."},"code":{"description":"obs-websocket v5 RequestStatus code.","format":"uint16","maximum":65535,"minimum":0,"type":"integer"},"message":{"description":"Human-readable context.","type":"string"},"retryable":{"description":"Whether a later retry may succeed.","type":"boolean"}},"required":["code","category","message","retryable"],"title":"ToolError","type":"object"}, "tools": [ + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_restart","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"A media source selection.","properties":{"name":{"description":"Name of an existing media source.","type":"string"}},"required":["name"],"title":"MediaInput","type":"object"},"name":"media_status","outputSchema":{"$defs":{"MediaState":{"description":"libobs media state.","oneOf":[{"const":"none","description":"Not a controllable media source.","type":"string"},{"const":"playing","description":"Playing.","type":"string"},{"const":"opening","description":"Opening.","type":"string"},{"const":"buffering","description":"Buffering.","type":"string"},{"const":"paused","description":"Paused.","type":"string"},{"const":"stopped","description":"Stopped.","type":"string"},{"const":"ended","description":"Playback reached the end.","type":"string"},{"const":"error","description":"Playback failed.","type":"string"}]}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Media playback snapshot, in milliseconds.","properties":{"duration_ms":{"description":"Total duration, if known.","format":"int64","type":["integer","null"]},"name":{"description":"Source name.","type":"string"},"position_ms":{"description":"Playback position, if known.","format":"int64","type":["integer","null"]},"state":{"$ref":"#/$defs/MediaState","description":"Current media state."}},"required":["name","state"],"title":"MediaStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"pipeline_dump","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"StatsSnapshot":{"description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"},"VcamStatus":{"description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Graph snapshot useful for diagnosing missing sources and outputs.","properties":{"program":{"description":"Program source name.","type":["string","null"]},"sources":{"description":"Source names in stable order.","items":{"type":"string"},"type":"array"},"stats":{"$ref":"#/$defs/StatsSnapshot","description":"Current pipeline measurements."},"vcam":{"$ref":"#/$defs/VcamStatus","description":"Virtual output state."}},"required":["sources","vcam","stats"],"title":"PipelineDump","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"record_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, @@ -17,8 +20,14 @@ {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$defs":{"Pair":{"additionalProperties":false,"description":"Pixel position or scale factors.","properties":{"x":{"description":"Horizontal component.","format":"double","type":"number"},"y":{"description":"Vertical component.","format":"double","type":"number"}},"required":["x","y"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Source creation, optionally placing it in a scene.","properties":{"kind":{"description":"Source kind id.","type":"string"},"name":{"description":"Unique name.","type":"string"},"position":{"anyOf":[{"$ref":"#/$defs/Pair"},{"type":"null"}],"description":"Initial position (requires scene)."},"scene":{"description":"Scene receiving the source.","type":["string","null"]},"settings":{"additionalProperties":true,"description":"Kind-specific settings.","type":"object"}},"required":["kind","name","settings"],"title":"CreateInput","type":"object"},"name":"source_create","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Created source.","properties":{"item":{"description":"Created item id.","format":"int64","type":["integer","null"]},"kind":{"description":"Source kind.","type":"string"},"name":{"description":"Source name.","type":"string"},"scene":{"description":"Scene receiving the new item.","type":["string","null"]}},"required":["name","kind"],"title":"CreateOutput","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Settings update.","properties":{"name":{"description":"Source name.","type":"string"},"settings":{"additionalProperties":true,"description":"Kind-specific settings to merge.","type":"object"}},"required":["name","settings"],"title":"SettingsInput","type":"object"},"name":"source_set_settings","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Updated source name.","properties":{"name":{"description":"Source name.","type":"string"}},"required":["name"],"title":"NameOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"sources_list","outputSchema":{"$defs":{"SourceInfo":{"description":"A source as listed by [`SourceBackend::sources`].","properties":{"kind":{"description":"The source kind id, such as `color_source`.","type":"string"},"name":{"description":"The source's unique name.","type":"string"}},"required":["name","kind"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Source listing.","properties":{"sources":{"description":"Sources in stable order.","items":{"$ref":"#/$defs/SourceInfo"},"type":"array"}},"required":["sources"],"title":"SourcesOutput","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_get","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stats_reset","outputSchema":{"$defs":{"RenderStats":{"description":"GetStats-style render counters.","properties":{"active_fps":{"description":"Actual render FPS.","format":"double","type":"number"},"average_frame_time_ns":{"description":"Average render duration, not end-to-end latency.","format":"uint64","minimum":0,"type":"integer"},"render_skipped_frames":{"description":"Frames lagged since baseline.","format":"uint64","minimum":0,"type":"integer"},"render_total_frames":{"description":"Frames rendered since baseline.","format":"uint64","minimum":0,"type":"integer"}},"required":["active_fps","average_frame_time_ns","render_total_frames","render_skipped_frames"],"type":"object"},"StageStats":{"description":"One live pipeline stage; null values are unmeasured, never synthetic zeroes.","properties":{"frames_dropped":{"description":"Dropped frames since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"frames_total":{"description":"Frames handled since the counter baseline.","format":"uint64","minimum":0,"type":["integer","null"]},"generation":{"description":"Counter generation, when the provider exposes one.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_max_ns":{"description":"Observed maximum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"latency_min_ns":{"description":"Observed minimum stage residence time, if measured.","format":"uint64","minimum":0,"type":["integer","null"]},"live":{"description":"Currently running.","type":"boolean"},"xruns":{"description":"Underruns/overruns since baseline, if measured.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["live"],"type":"object"},"Stages":{"description":"Render and device stages.","properties":{"render":{"$ref":"#/$defs/StageStats","description":"OBS render stage."},"vcam":{"$ref":"#/$defs/StageStats","description":"Virtual Camera write stage."},"vmic":{"$ref":"#/$defs/StageStats","description":"Virtual microphone stage."}},"required":["render","vcam","vmic"],"type":"object"},"SyncStats":{"description":"End-to-end measurement provenance.","properties":{"av_offset_ms":{"description":"Measured audio minus video offset; null until independently measured.","format":"double","type":["number","null"]},"measured_from":{"description":"Measurement source; queue estimates are not end-to-end measurements.","type":"string"}},"required":["measured_from"],"type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Typed pipeline statistics.","properties":{"end_to_end":{"$ref":"#/$defs/SyncStats","description":"End-to-end sync, with explicit provenance."},"render":{"$ref":"#/$defs/RenderStats","description":"Render counters."},"stages":{"$ref":"#/$defs/Stages","description":"Per-stage measured counters and bounds."}},"required":["stages","end_to_end","render"],"title":"StatsSnapshot","type":"object"}}, {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"The state of an output as reported by [`OutputBackend::status`].","properties":{"active":{"description":"Whether the output is running.","type":"boolean"},"bytes":{"description":"Bytes written or sent so far, where known.","format":"uint64","minimum":0,"type":["integer","null"]},"duration_ms":{"description":"Milliseconds since the output started, where known.","format":"uint64","minimum":0,"type":["integer","null"]}},"required":["active"],"title":"OutputStatus","type":"object"}}, - {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}} + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"stream_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"State returned by a start or stop operation.","properties":{"active":{"description":"Whether the output is running.","type":"boolean"}},"required":["active"],"title":"ActiveOutput","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Bounded start options, extended by the wait domain.","properties":{"audio_enabled":{"default":true,"description":"Enable the paired microphone before a stopped output starts.","type":"boolean"},"audio_track":{"default":1,"description":"One-based OBS audio mix (1 through 6).","format":"uint32","minimum":0,"type":"integer"},"wait":{"default":false,"description":"Wait until the output reports active.","type":"boolean"}},"title":"StartInput","type":"object"},"name":"vcam_start","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":true,"readOnlyHint":false},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vcam_stop","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual Camera and its paired audio source.","properties":{"active":{"description":"Video output is active.","type":"boolean"},"configured":{"description":"Whether the registered output exists.","type":"boolean"},"vmic_active":{"description":"Paired virtual microphone is active, when the plugin supports the query.","type":["boolean","null"]}},"required":["configured","active"],"title":"VcamStatus","type":"object"}}, + {"annotations":{"destructiveHint":false,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":true},"inputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"description":"Empty arguments, with unknown fields rejected.","properties":{},"title":"EmptyInput","type":"object"},"name":"vmic_status","outputSchema":{"$schema":"https://json-schema.org/draft/2020-12/schema","description":"Virtual microphone state.","properties":{"active":{"description":"Active according to virtualcam_audio; null means unsupported.","type":["boolean","null"]},"source_name":{"description":"Runtime source name, when known.","type":["string","null"]}},"title":"VmicStatus","type":"object"}} ] } diff --git a/plugins/linux-v4l2/v4l2-output.c.h b/plugins/linux-v4l2/v4l2-output.c.h index ecab2c2c42..b52e1c4172 100644 --- a/plugins/linux-v4l2/v4l2-output.c.h +++ b/plugins/linux-v4l2/v4l2-output.c.h @@ -49,6 +49,12 @@ struct virtualcam_data { char mic_path[256]; char mic_lock_path[256]; int mic_lock; + /* Lifetime counters; all accesses hold sync.mutex. Never consumed by logging. */ + uint64_t stats_generation; + uint64_t stats_video_frames, stats_video_dropped, stats_video_measured; + uint64_t stats_video_min_ns, stats_video_max_ns; + uint64_t stats_audio_frames, stats_audio_dropped, stats_audio_measured; + uint64_t stats_audio_min_ns, stats_audio_max_ns; }; static void vmic_stop(struct virtualcam_data *vcam); @@ -941,10 +947,47 @@ static void virtualcam_audio_proc(void *data, calldata_t *cd) calldata_set_bool(cd, "active", vcam->mic_fifo >= 0); } +/* Private Control API: bounds measure libobs timestamps to completed writes, + * not device capture or end-to-end A/V latency. Native PipeWire xruns remain + * absent on the FIFO backend (#4124); consumers must represent them as unknown. */ +static void virtualcam_stats_proc(void *data, calldata_t *cd) +{ + struct virtualcam_data *vcam = data; + pthread_mutex_lock(&vcam->sync.mutex); + calldata_set_int(cd, "generation", (long long)vcam->stats_generation); + calldata_set_int(cd, "vcam_frames", (long long)vcam->stats_video_frames); + calldata_set_int(cd, "vcam_dropped", (long long)vcam->stats_video_dropped); + calldata_set_int(cd, "vmic_frames", (long long)vcam->stats_audio_frames); + calldata_set_int(cd, "vmic_dropped", (long long)vcam->stats_audio_dropped); + if (vcam->stats_video_measured) { + calldata_set_int(cd, "vcam_min_ns", (long long)vcam->stats_video_min_ns); + calldata_set_int(cd, "vcam_max_ns", (long long)vcam->stats_video_max_ns); + } + if (vcam->stats_audio_measured) { + calldata_set_int(cd, "vmic_min_ns", (long long)vcam->stats_audio_min_ns); + calldata_set_int(cd, "vmic_max_ns", (long long)vcam->stats_audio_max_ns); + } + pthread_mutex_unlock(&vcam->sync.mutex); +} + +static void virtualcam_stats_reset_proc(void *data, calldata_t *cd) +{ + struct virtualcam_data *vcam = data; + pthread_mutex_lock(&vcam->sync.mutex); + vcam->stats_generation = os_gettime_ns(); + vcam->stats_video_frames = vcam->stats_video_dropped = vcam->stats_video_measured = 0; + vcam->stats_video_min_ns = vcam->stats_video_max_ns = 0; + vcam->stats_audio_frames = vcam->stats_audio_dropped = vcam->stats_audio_measured = 0; + vcam->stats_audio_min_ns = vcam->stats_audio_max_ns = 0; + pthread_mutex_unlock(&vcam->sync.mutex); + UNUSED_PARAMETER(cd); +} + static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) { struct virtualcam_data *vcam = (struct virtualcam_data *)bzalloc(sizeof(*vcam)); vcam->output = output; + vcam->stats_generation = os_gettime_ns(); vcam->device = -1; vcam->mic_fifo = -1; vcam->mic_drain = -1; @@ -957,6 +1000,14 @@ static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) if (output) proc_handler_add(obs_output_get_proc_handler(output), "void virtualcam_audio(out bool active)", virtualcam_audio_proc, vcam); + if (output) + proc_handler_add( + obs_output_get_proc_handler(output), + "void virtualcam_stats(out int generation, out int vcam_frames, out int vcam_dropped, out int vmic_frames, out int vmic_dropped, out int vcam_min_ns, out int vcam_max_ns, out int vmic_min_ns, out int vmic_max_ns)", + virtualcam_stats_proc, vcam); + if (output) + proc_handler_add(obs_output_get_proc_handler(output), "void virtualcam_stats_reset()", + virtualcam_stats_reset_proc, vcam); return vcam; } @@ -1136,7 +1187,7 @@ static void virtualcam_stop(void *data, uint64_t ts) UNUSED_PARAMETER(ts); } -static void vcam_write_frame(struct virtualcam_data *vcam, const uint8_t *frame_data) +static void vcam_write_frame(struct virtualcam_data *vcam, const uint8_t *frame_data, uint64_t timestamp) { uint32_t frame_size = vcam->frame_size; while (frame_size > 0) { @@ -1148,6 +1199,20 @@ static void vcam_write_frame(struct virtualcam_data *vcam, const uint8_t *frame_ frame_data += written; frame_size -= (uint32_t)written; } + if (frame_size) { + vcam->stats_video_dropped++; + } else { + uint64_t now = os_gettime_ns(); + vcam->stats_video_frames++; + if (now < timestamp) + return; + uint64_t latency = now - timestamp; + if (!vcam->stats_video_measured || latency < vcam->stats_video_min_ns) + vcam->stats_video_min_ns = latency; + if (latency > vcam->stats_video_max_ns) + vcam->stats_video_max_ns = latency; + vcam->stats_video_measured++; + } } /* Sends the waiting frames whose audio the microphone has; under sync.mutex. */ @@ -1155,7 +1220,7 @@ static void vcam_sync_flush(struct virtualcam_data *vcam) { struct vcam_sync *sync = &vcam->sync; while (sync->len > 0 && sync->ts[sync->head] + vcam->mic_lead_ns <= sync->audio_end) { - vcam_write_frame(vcam, sync->frame[sync->head]); + vcam_write_frame(vcam, sync->frame[sync->head], sync->ts[sync->head]); sync->head = (sync->head + 1) % VCAM_SYNC_FRAMES; sync->len--; } @@ -1170,13 +1235,13 @@ static void virtual_video(void *param, struct video_data *frame) /* No running microphone (mic_rate is set only by vmic_start): nothing to wait for. */ if (vcam->mic_fifo < 0 || vcam->mic_rate == 0 || (sync->len == 0 && frame->timestamp + vcam->mic_lead_ns <= sync->audio_end)) { - vcam_write_frame(vcam, frame->data[0]); + vcam_write_frame(vcam, frame->data[0], frame->timestamp); pthread_mutex_unlock(&sync->mutex); return; } if (sync->len == VCAM_SYNC_FRAMES) { /* The audio stopped: the picture goes on without it. */ - vcam_write_frame(vcam, sync->frame[sync->head]); + vcam_write_frame(vcam, sync->frame[sync->head], sync->ts[sync->head]); sync->head = (sync->head + 1) % VCAM_SYNC_FRAMES; sync->len--; } @@ -1196,11 +1261,24 @@ static void virtual_audio(void *param, struct audio_data *frames) return; size_t size = (size_t)frames->frames * VMIC_CHANNELS * sizeof(float); /* Keep at most one packet unread, so a reader hears the newest audio. */ - vmic_drop_stale(vcam->mic_drain, vcam->mic_fifo, size); - vmic_write_packet(vcam->mic_fifo, vcam->mic_pipe_size, &vcam->mic_tail, frames->data[0], size); + size_t discarded = vmic_drop_stale(vcam->mic_drain, vcam->mic_fifo, size); + bool accepted = vmic_write_packet(vcam->mic_fifo, vcam->mic_pipe_size, &vcam->mic_tail, frames->data[0], size); uint64_t end = frames->timestamp + util_mul_div64(frames->frames, 1000000000ULL, vcam->mic_rate); pthread_mutex_lock(&vcam->sync.mutex); + vcam->stats_audio_frames += frames->frames; + vcam->stats_audio_dropped += discarded / (VMIC_CHANNELS * sizeof(float)); + if (!accepted) + vcam->stats_audio_dropped += frames->frames; + uint64_t now = os_gettime_ns(); + if (accepted && !vcam->mic_tail.len && now >= frames->timestamp) { + uint64_t latency = now - frames->timestamp; + if (!vcam->stats_audio_measured || latency < vcam->stats_audio_min_ns) + vcam->stats_audio_min_ns = latency; + if (latency > vcam->stats_audio_max_ns) + vcam->stats_audio_max_ns = latency; + vcam->stats_audio_measured++; + } if (end > vcam->sync.audio_end) vcam->sync.audio_end = end; vcam_sync_flush(vcam); diff --git a/rust/obs-mcp/src/backend/control.rs b/rust/obs-mcp/src/backend/control.rs new file mode 100644 index 0000000000..051ea058b1 --- /dev/null +++ b/rust/obs-mcp/src/backend/control.rs @@ -0,0 +1,143 @@ +//! Native implementations of typed control domains. +use super::{ObsBackend, Output, Source}; +use crate::server::ToolError; +use crate::tools::EmptyInput; +use crate::tools::control::{ + ControlBackend, MediaInput, MediaStatus, PipelineDump, StageStats, Stages, StartInput, + StatsSnapshot, SyncStats, VcamStatus, VmicStatus, +}; +use crate::tools::scenes::SceneBackend; +use crate::tools::sources::SourceBackend; + +const CAMERA: &str = "virtualcam_output"; +impl ObsBackend { + fn camera(&self, create: bool) -> Result, ToolError> { + if let Some(output) = Output::by_name(CAMERA) { + return Ok(Some(output)); + } + if !create { + return Ok(None); + } + let output = + Output::create(CAMERA, CAMERA, &serde_json::json!({})).map_err(ToolError::not_ready)?; + self.camera.replace(Some(output)); + Ok(Output::by_name(CAMERA)) + } + fn raw_stats(&self) -> Result { + let render = crate::ffi::render_stats(); + let mut stages = Stages { + render: StageStats { + live: crate::ffi::has_video(), + frames_total: Some(render.render_total_frames), + frames_dropped: Some(render.render_skipped_frames), + ..StageStats::default() + }, + ..Stages::default() + }; + if let Some(output) = self.camera(false)? { + if let Some((video, audio)) = output.device_stats() { + stages.vcam = video; + stages.vmic = audio; + } else { + stages.vcam.live = output.active(); + stages.vmic.live = output.virtual_audio().unwrap_or(false); + } + } + Ok(StatsSnapshot { stages, render, end_to_end: SyncStats { av_offset_ms: None, measured_from: "unavailable: independent capture probe required; stage bounds are libobs timestamp to completed device write".into() } }) + } + fn media_source(request: &MediaInput) -> Result { + if request.name.is_empty() { + return Err(ToolError::wrong_state("media name must not be empty")); + } + Source::by_name(&request.name) + .ok_or_else(|| ToolError::not_found(format!("no source named '{}'", request.name))) + } +} +impl ControlBackend for ObsBackend { + fn vcam_start(&self, request: StartInput) -> Result { + if !crate::ffi::has_video() { + return Err(ToolError::not_ready( + "Virtual Camera requires initialized video", + )); + } + if !(1..=6).contains(&request.audio_track) { + return Err(ToolError::wrong_state( + "audio_track must be between 1 and 6", + )); + } + let output = self + .camera(true)? + .ok_or_else(|| ToolError::not_ready("Virtual Camera output unavailable"))?; + if !output.active() { + output.update(&serde_json::json!({"audio_enabled":request.audio_enabled,"audio_track":request.audio_track})).map_err(ToolError::processing)?; + output.start().map_err(ToolError::processing)?; + } + let status = self.vcam_status(EmptyInput::default())?; + if request.wait && !status.active { + return Err(ToolError::not_ready("Virtual Camera has not become active")); + } + Ok(status) + } + fn vcam_stop(&self, _request: EmptyInput) -> Result { + if let Some(output) = self.camera(false)? + && output.active() + { + output.stop(); + } + self.vcam_status(EmptyInput::default()) + } + fn vcam_status(&self, _request: EmptyInput) -> Result { + Ok(self + .camera(false)? + .map_or_else(VcamStatus::default, |output| VcamStatus { + configured: true, + active: output.active(), + vmic_active: output.virtual_audio(), + })) + } + fn vmic_status(&self, _request: EmptyInput) -> Result { + Ok(VmicStatus { + active: self + .camera(false)? + .and_then(|output| output.virtual_audio()), + source_name: None, + }) + } + fn media_restart(&self, request: MediaInput) -> Result { + let source = Self::media_source(&request)?; + source.restart_media().map_err(ToolError::wrong_state)?; + Ok(source.media()) + } + fn media_status(&self, request: MediaInput) -> Result { + Ok(Self::media_source(&request)?.media()) + } + fn stats_get(&self, _request: EmptyInput) -> Result { + let current = self.raw_stats()?; + if let Some(baseline) = self.baseline.borrow_mut().as_mut() { + return Ok(baseline.apply(current)); + } + Ok(current) + } + fn stats_reset(&self, _request: EmptyInput) -> Result { + if let Some(output) = self.camera(false)? { + output.reset_device_stats(); + } + self.baseline + .replace(Some(crate::tools::control::StatsBaseline::new( + self.raw_stats()?, + ))); + self.stats_get(EmptyInput::default()) + } + fn pipeline_dump(&self, _request: EmptyInput) -> Result { + Ok(PipelineDump { + program: self.current(), + sources: self + .sources() + .into_iter() + .map(|source| source.name) + .collect(), + vcam: self.vcam_status(EmptyInput::default())?, + stats: self.stats_get(EmptyInput::default())?, + }) + } +} diff --git a/rust/obs-mcp/src/backend/mod.rs b/rust/obs-mcp/src/backend/mod.rs index d63c0baff4..90aa838905 100644 --- a/rust/obs-mcp/src/backend/mod.rs +++ b/rust/obs-mcp/src/backend/mod.rs @@ -55,6 +55,8 @@ pub struct ObsBackend { /// Why the host could not create the outputs, quoted in the errors that need them. output_error: Option, cpu: Option, + camera: RefCell>, + baseline: RefCell>, } impl Default for ObsBackend { @@ -78,6 +80,8 @@ impl ObsBackend { video_error: None, output_error: None, cpu: CpuUsage::start(), + camera: RefCell::new(None), + baseline: RefCell::new(None), } } @@ -131,6 +135,8 @@ impl ObsBackend { sources::register(&mut tools, &sources); outputs::register(&mut tools, &outputs); screenshot::register(&mut tools, &capture); + let control: Rc = Rc::clone(backend) as _; + crate::tools::control::register(&mut tools, &control); let mut resources = ResourceRegistry::new(); resources::scenes::register(&mut resources, &scenes, &sources); @@ -472,3 +478,5 @@ impl StatsBackend for ObsBackend { } } } + +mod control; diff --git a/rust/obs-mcp/src/ffi/control.rs b/rust/obs-mcp/src/ffi/control.rs new file mode 100644 index 0000000000..de95e2749d --- /dev/null +++ b/rust/obs-mcp/src/ffi/control.rs @@ -0,0 +1,166 @@ +//! Private libobs media/procedure bindings; public C headers stay unchanged. +use super::{Output, Source, sys}; +use crate::tools::control::{MediaState, MediaStatus, RenderStats, StageStats}; +// The layout is the stable calldata_t ABI in callback/calldata.h. Keeping +// this declaration local avoids linking callback implementations into a plugin. +#[repr(C)] +struct Calldata { + stack: *mut u8, + size: usize, + capacity: usize, + fixed: bool, +} +use std::ffi::{CStr, c_char, c_int, c_void}; + +unsafe extern "C" { + fn obs_source_get_output_flags(source: *const sys::obs_source_t) -> u32; + fn obs_source_media_restart(source: *mut sys::obs_source_t); + fn obs_source_media_get_state(source: *mut sys::obs_source_t) -> c_int; + fn obs_source_media_get_duration(source: *mut sys::obs_source_t) -> i64; + fn obs_source_media_get_time(source: *mut sys::obs_source_t) -> i64; + fn obs_get_total_frames() -> u32; + fn obs_get_average_frame_time_ns() -> u64; + fn obs_output_get_proc_handler(output: *const sys::obs_output_t) -> *mut c_void; + fn proc_handler_call(handler: *mut c_void, name: *const c_char, params: *mut Calldata) -> bool; + fn calldata_get_data( + data: *const Calldata, + name: *const c_char, + out: *mut c_void, + size: usize, + ) -> bool; + fn bfree(data: *mut c_void); +} +struct Params(Calldata); +impl Params { + fn new() -> Self { + Self(Calldata { + stack: std::ptr::null_mut(), + size: 0, + capacity: 0, + fixed: false, + }) + } + fn count(&self, name: &CStr) -> Option { + let mut value = 0_i64; + // SAFETY: live calldata, terminated key and correctly sized writable integer. + let found = unsafe { + calldata_get_data( + &raw const self.0, + name.as_ptr(), + (&raw mut value).cast(), + size_of::(), + ) + }; + found.then(|| u64::try_from(value).ok()).flatten() + } + fn boolean(&self, name: &CStr) -> Option { + let mut value = false; + // SAFETY: live calldata, terminated key and correctly sized writable C bool. + unsafe { + calldata_get_data( + &raw const self.0, + name.as_ptr(), + (&raw mut value).cast(), + size_of::(), + ) + } + .then_some(value) + } +} +impl Drop for Params { + fn drop(&mut self) { + // SAFETY: dynamic calldata storage is owned here and allocated by libobs. + unsafe { bfree(self.0.stack.cast()) }; + } +} +impl Source { + pub fn restart_media(&self) -> Result<(), String> { + // SAFETY: owns a live source reference; the flag is OBS_SOURCE_CONTROLLABLE_MEDIA. + if unsafe { obs_source_get_output_flags(self.0.as_ptr()) } & (1 << 13) == 0 { + return Err(format!( + "source '{}' is not controllable media", + self.name() + )); + } + // SAFETY: live controllable media source. + unsafe { obs_source_media_restart(self.0.as_ptr()) }; + Ok(()) + } + pub fn media(&self) -> MediaStatus { + // SAFETY: all queries retain the live source reference throughout. + let (state, duration, position) = unsafe { + ( + obs_source_media_get_state(self.0.as_ptr()), + obs_source_media_get_duration(self.0.as_ptr()), + obs_source_media_get_time(self.0.as_ptr()), + ) + }; + let state = match state { + 1 => MediaState::Playing, + 2 => MediaState::Opening, + 3 => MediaState::Buffering, + 4 => MediaState::Paused, + 5 => MediaState::Stopped, + 6 => MediaState::Ended, + 7 => MediaState::Error, + _ => MediaState::None, + }; + MediaStatus { + name: self.name(), + state, + duration_ms: (duration > 0).then_some(duration), + position_ms: (state != MediaState::None && position >= 0).then_some(position), + } + } +} +impl Output { + fn procedure(&self, name: &CStr) -> Option { + let mut params = Params::new(); + // SAFETY: the output reference pins its procedure handler and callback data; + // params owns the returned calldata until all values have been copied. + let found = unsafe { + let handler = obs_output_get_proc_handler(self.0.as_ptr()); + !handler.is_null() && proc_handler_call(handler, name.as_ptr(), &raw mut params.0) + }; + found.then_some(params) + } + pub fn virtual_audio(&self) -> Option { + self.procedure(c"virtualcam_audio")?.boolean(c"active") + } + pub fn reset_device_stats(&self) { + let _ = self.procedure(c"virtualcam_stats_reset"); + } + pub fn device_stats(&self) -> Option<(StageStats, StageStats)> { + let data = self.procedure(c"virtualcam_stats")?; + let video = StageStats { + live: self.active(), + generation: data.count(c"generation"), + latency_min_ns: data.count(c"vcam_min_ns"), + latency_max_ns: data.count(c"vcam_max_ns"), + frames_total: data.count(c"vcam_frames"), + frames_dropped: data.count(c"vcam_dropped"), + xruns: None, + }; + let audio = StageStats { + live: self.virtual_audio().unwrap_or(false), + generation: data.count(c"generation"), + latency_min_ns: data.count(c"vmic_min_ns"), + latency_max_ns: data.count(c"vmic_max_ns"), + frames_total: data.count(c"vmic_frames"), + frames_dropped: data.count(c"vmic_dropped"), + xruns: data.count(c"vmic_xruns"), + }; + Some((video, audio)) + } +} +pub fn render_stats() -> RenderStats { + // SAFETY: plain libobs statistics queries, valid even without configured video. + unsafe { + RenderStats { + active_fps: sys::obs_get_active_fps(), + average_frame_time_ns: obs_get_average_frame_time_ns(), + render_total_frames: u64::from(obs_get_total_frames()), + render_skipped_frames: u64::from(sys::obs_get_lagged_frames()), + } + } +} diff --git a/rust/obs-mcp/src/ffi/mod.rs b/rust/obs-mcp/src/ffi/mod.rs index ab43faeb28..69b5253b1e 100644 --- a/rust/obs-mcp/src/ffi/mod.rs +++ b/rust/obs-mcp/src/ffi/mod.rs @@ -677,3 +677,6 @@ pub fn log_warning(text: &str) { // consumes exactly the one argument passed. unsafe { blog(LOG_WARNING, c"obs-mcp: %s".as_ptr(), text.as_ptr()) }; } + +mod control; +pub use control::render_stats; diff --git a/rust/obs-mcp/src/tools/control.rs b/rust/obs-mcp/src/tools/control.rs new file mode 100644 index 0000000000..8429f7acb7 --- /dev/null +++ b/rust/obs-mcp/src/tools/control.rs @@ -0,0 +1,449 @@ +//! Device, media and measured pipeline control (#4446). +use super::EmptyInput; +use crate::server::{ToolError, ToolRegistry}; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::rc::Rc; + +/// Bounded start options, extended by the wait domain. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct StartInput { + /// Wait until the output reports active. + #[serde(default)] + pub wait: bool, + /// Enable the paired microphone before a stopped output starts. + #[serde(default = "enabled")] + pub audio_enabled: bool, + /// One-based OBS audio mix (1 through 6). + #[serde(default = "first_mix")] + pub audio_track: u32, +} +fn enabled() -> bool { + true +} +fn first_mix() -> u32 { + 1 +} +impl Default for StartInput { + fn default() -> Self { + Self { + wait: false, + audio_enabled: true, + audio_track: 1, + } + } +} +/// Virtual Camera and its paired audio source. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct VcamStatus { + /// Whether the registered output exists. + pub configured: bool, + /// Video output is active. + pub active: bool, + /// Paired virtual microphone is active, when the plugin supports the query. + pub vmic_active: Option, +} +/// Virtual microphone state. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct VmicStatus { + /// Active according to virtualcam_audio; null means unsupported. + pub active: Option, + /// Runtime source name, when known. + pub source_name: Option, +} +/// A media source selection. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +#[serde(deny_unknown_fields)] +pub struct MediaInput { + /// Name of an existing media source. + pub name: String, +} +/// libobs media state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum MediaState { + /// Not a controllable media source. + #[default] + None, + /// Playing. + Playing, + /// Opening. + Opening, + /// Buffering. + Buffering, + /// Paused. + Paused, + /// Stopped. + Stopped, + /// Playback reached the end. + Ended, + /// Playback failed. + Error, +} +/// Media playback snapshot, in milliseconds. +#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)] +pub struct MediaStatus { + /// Source name. + pub name: String, + /// Current media state. + pub state: MediaState, + /// Total duration, if known. + pub duration_ms: Option, + /// Playback position, if known. + pub position_ms: Option, +} +/// One live pipeline stage; null values are unmeasured, never synthetic zeroes. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct StageStats { + /// Currently running. + pub live: bool, + /// Counter generation, when the provider exposes one. + pub generation: Option, + /// Observed minimum stage residence time, if measured. + pub latency_min_ns: Option, + /// Observed maximum stage residence time, if measured. + pub latency_max_ns: Option, + /// Frames handled since the counter baseline. + pub frames_total: Option, + /// Dropped frames since baseline, if measured. + pub frames_dropped: Option, + /// Underruns/overruns since baseline, if measured. + pub xruns: Option, +} +/// Render and device stages. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct Stages { + /// OBS render stage. + pub render: StageStats, + /// Virtual Camera write stage. + pub vcam: StageStats, + /// Virtual microphone stage. + pub vmic: StageStats, +} +/// End-to-end measurement provenance. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct SyncStats { + /// Measured audio minus video offset; null until independently measured. + pub av_offset_ms: Option, + /// Measurement source; queue estimates are not end-to-end measurements. + pub measured_from: String, +} +/// GetStats-style render counters. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct RenderStats { + /// Actual render FPS. + pub active_fps: f64, + /// Average render duration, not end-to-end latency. + pub average_frame_time_ns: u64, + /// Frames rendered since baseline. + pub render_total_frames: u64, + /// Frames lagged since baseline. + pub render_skipped_frames: u64, +} +/// Typed pipeline statistics. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct StatsSnapshot { + /// Per-stage measured counters and bounds. + pub stages: Stages, + /// End-to-end sync, with explicit provenance. + pub end_to_end: SyncStats, + /// Render counters. + pub render: RenderStats, +} +/// Graph snapshot useful for diagnosing missing sources and outputs. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct PipelineDump { + /// Program source name. + pub program: Option, + /// Source names in stable order. + pub sources: Vec, + /// Virtual output state. + pub vcam: VcamStatus, + /// Current pipeline measurements. + pub stats: StatsSnapshot, +} +/// Backend operations take typed requests and return typed responses. +pub trait ControlBackend { + /// Starts or observes an already-running camera. + /// # Errors + /// Reports missing plugins, unavailable devices or processing failures. + fn vcam_start(&self, request: StartInput) -> Result; + /// Stops or observes an already-stopped camera. + /// # Errors + /// Reports unavailable output configuration. + fn vcam_stop(&self, request: EmptyInput) -> Result; + /// Camera status. + /// # Errors + /// Reports query failures. + fn vcam_status(&self, request: EmptyInput) -> Result; + /// Microphone status. + /// # Errors + /// Reports query failures. + fn vmic_status(&self, request: EmptyInput) -> Result; + /// Restarts a media source. + /// # Errors + /// Reports missing or non-media sources. + fn media_restart(&self, request: MediaInput) -> Result; + /// Media status. + /// # Errors + /// Reports missing sources. + fn media_status(&self, request: MediaInput) -> Result; + /// Statistics since the current baseline. + /// # Errors + /// Reports query failures. + fn stats_get(&self, request: EmptyInput) -> Result; + /// Sets a new baseline and returns the resulting snapshot. + /// # Errors + /// Reports query failures. + fn stats_reset(&self, request: EmptyInput) -> Result; + /// Graph and measurements. + /// # Errors + /// Reports query failures. + fn pipeline_dump(&self, request: EmptyInput) -> Result; +} +/// Difference from a baseline; a recreated counter begins a new generation. +#[must_use] +pub fn counter_delta(current: u64, baseline: u64) -> u64 { + if current >= baseline { + current - baseline + } else { + current + } +} + +typed_tool!( + VcamStart, + "vcam_start", + ControlBackend, + StartInput, + VcamStatus, + IDEMPOTENT, + "vcam start: control and inspect OBS directly.", + |backend, input| { backend.vcam_start(input) } +); + +typed_tool!( + VcamStop, + "vcam_stop", + ControlBackend, + EmptyInput, + VcamStatus, + IDEMPOTENT, + "vcam stop: control and inspect OBS directly.", + |backend, input| { backend.vcam_stop(input) } +); + +typed_tool!( + VcamGet, + "vcam_status", + ControlBackend, + EmptyInput, + VcamStatus, + READ_ONLY, + "vcam status: control and inspect OBS directly.", + |backend, input| { backend.vcam_status(input) } +); + +typed_tool!( + VmicGet, + "vmic_status", + ControlBackend, + EmptyInput, + VmicStatus, + READ_ONLY, + "vmic status: control and inspect OBS directly.", + |backend, input| { backend.vmic_status(input) } +); + +typed_tool!( + MediaRestart, + "media_restart", + ControlBackend, + MediaInput, + MediaStatus, + MUTATING, + "media restart: control and inspect OBS directly.", + |backend, input| { backend.media_restart(input) } +); + +typed_tool!( + MediaGet, + "media_status", + ControlBackend, + MediaInput, + MediaStatus, + READ_ONLY, + "media status: control and inspect OBS directly.", + |backend, input| { backend.media_status(input) } +); + +typed_tool!( + StatsGet, + "stats_get", + ControlBackend, + EmptyInput, + StatsSnapshot, + READ_ONLY, + "stats get: control and inspect OBS directly.", + |backend, input| { backend.stats_get(input) } +); + +typed_tool!( + StatsReset, + "stats_reset", + ControlBackend, + EmptyInput, + StatsSnapshot, + MUTATING, + "stats reset: control and inspect OBS directly.", + |backend, input| { backend.stats_reset(input) } +); + +typed_tool!( + PipelineGet, + "pipeline_dump", + ControlBackend, + EmptyInput, + PipelineDump, + READ_ONLY, + "pipeline dump: control and inspect OBS directly.", + |backend, input| { backend.pipeline_dump(input) } +); + +/// Registers device, media and measurement tools. +pub fn register(registry: &mut ToolRegistry, backend: &Rc) { + registry.register(Box::new(VcamStart { + backend: Rc::clone(backend), + })); + registry.register(Box::new(VcamStop { + backend: Rc::clone(backend), + })); + registry.register(Box::new(VcamGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(VmicGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(MediaRestart { + backend: Rc::clone(backend), + })); + registry.register(Box::new(MediaGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StatsGet { + backend: Rc::clone(backend), + })); + registry.register(Box::new(StatsReset { + backend: Rc::clone(backend), + })); + registry.register(Box::new(PipelineGet { + backend: Rc::clone(backend), + })); +} + +/// Generated tool contracts. +#[must_use] +pub fn schemas() -> Vec { + vec![ + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + crate::server::tool_schema::(), + ] +} + +impl StatsSnapshot { + /// Subtract counter baselines while leaving latency gauges unchanged. + #[must_use] + pub fn relative_to(mut self, baseline: &Self) -> Self { + fn stage(now: &mut StageStats, old: &StageStats) { + let delta = + |n: Option, b: Option| n.map(|v| counter_delta(v, b.unwrap_or(0))); + now.frames_total = delta(now.frames_total, old.frames_total); + now.frames_dropped = delta(now.frames_dropped, old.frames_dropped); + now.xruns = delta(now.xruns, old.xruns); + } + stage(&mut self.stages.render, &baseline.stages.render); + stage(&mut self.stages.vcam, &baseline.stages.vcam); + stage(&mut self.stages.vmic, &baseline.stages.vmic); + self.render.render_total_frames = counter_delta( + self.render.render_total_frames, + baseline.render.render_total_frames, + ); + self.render.render_skipped_frames = counter_delta( + self.render.render_skipped_frames, + baseline.render.render_skipped_frames, + ); + self + } +} + +/// Stateful baselines detect provider recreation even after raw counters exceed +/// the previous baseline. Latency bounds are gauges, reset by the provider. +#[derive(Clone, Debug)] +pub struct StatsBaseline { + baseline: StatsSnapshot, + previous: StatsSnapshot, +} +impl StatsBaseline { + /// Establishes a baseline from the current raw snapshot. + #[must_use] + pub fn new(snapshot: StatsSnapshot) -> Self { + Self { + previous: snapshot.clone(), + baseline: snapshot, + } + } + /// Observe a raw snapshot, resetting rolled-back/recreated counter baselines. + pub fn apply(&mut self, snapshot: StatsSnapshot) -> StatsSnapshot { + fn stage(now: &StageStats, previous: &StageStats, baseline: &mut StageStats) { + let recreated = now.generation.is_some() && now.generation != previous.generation; + let fix = |current: Option, prior: Option, base: &mut Option| { + if recreated || current.zip(prior).is_some_and(|(n, p)| n < p) { + *base = current.map(|_| 0); + } + }; + fix( + now.frames_total, + previous.frames_total, + &mut baseline.frames_total, + ); + fix( + now.frames_dropped, + previous.frames_dropped, + &mut baseline.frames_dropped, + ); + fix(now.xruns, previous.xruns, &mut baseline.xruns); + baseline.generation = now.generation; + } + stage( + &snapshot.stages.render, + &self.previous.stages.render, + &mut self.baseline.stages.render, + ); + stage( + &snapshot.stages.vcam, + &self.previous.stages.vcam, + &mut self.baseline.stages.vcam, + ); + stage( + &snapshot.stages.vmic, + &self.previous.stages.vmic, + &mut self.baseline.stages.vmic, + ); + if snapshot.render.render_total_frames < self.previous.render.render_total_frames { + self.baseline.render.render_total_frames = 0; + } + if snapshot.render.render_skipped_frames < self.previous.render.render_skipped_frames { + self.baseline.render.render_skipped_frames = 0; + } + self.previous = snapshot.clone(); + snapshot.relative_to(&self.baseline) + } +} diff --git a/rust/obs-mcp/src/tools/mod.rs b/rust/obs-mcp/src/tools/mod.rs index 981e9fd27d..1051b39105 100644 --- a/rust/obs-mcp/src/tools/mod.rs +++ b/rust/obs-mcp/src/tools/mod.rs @@ -40,6 +40,9 @@ pub fn schema_snapshot() -> serde_json::Value { tools.extend(sources::schemas()); tools.extend(outputs::schemas()); tools.extend(screenshot::schemas()); + tools.extend(control::schemas()); tools.sort_by(|a, b| a["name"].as_str().cmp(&b["name"].as_str())); serde_json::json!({"tools": tools, "toolError": schemars::schema_for!(crate::server::ToolError)}) } + +pub mod control; diff --git a/rust/obs-mcp/tests/libobs_backend.rs b/rust/obs-mcp/tests/libobs_backend.rs index ad56b907eb..3304eee439 100644 --- a/rust/obs-mcp/tests/libobs_backend.rs +++ b/rust/obs-mcp/tests/libobs_backend.rs @@ -234,6 +234,12 @@ fn sources_and_items(backend: &ObsBackend) { } fn stats_capture_and_outputs(backend: &ObsBackend) { + let error = obs_mcp::tools::control::ControlBackend::vcam_start(backend, Default::default()) + .unwrap_err(); + assert_eq!( + error.code, 207, + "no video must be rejected before entering the native camera plugin" + ); let stats = backend.stats(); assert_eq!(stats.fps, 0.0, "no video subsystem, no frames"); assert_eq!(stats.dropped_frames, 0); diff --git a/rust/obs-mcp/tests/mcp/control.rs b/rust/obs-mcp/tests/mcp/control.rs new file mode 100644 index 0000000000..e0dffa1696 --- /dev/null +++ b/rust/obs-mcp/tests/mcp/control.rs @@ -0,0 +1,142 @@ +//! Control API domains (#4446); no additional test executable. +use obs_mcp::tools::control::counter_delta; +#[test] +fn counters_are_relative_to_baseline_and_survive_recreation() { + assert_eq!(counter_delta(20, 5), 15); + assert_eq!(counter_delta(5, 5), 0); + assert_eq!(counter_delta(3, 20), 3); +} +use obs_mcp::server::{Server, ToolError, ToolRegistry}; +use obs_mcp::tools::{ + EmptyInput, + control::{ + ControlBackend, MediaInput, MediaState, MediaStatus, PipelineDump, StartInput, + StatsSnapshot, VcamStatus, VmicStatus, register, + }, +}; +use serde_json::{Value, json}; +use std::cell::Cell; +use std::rc::Rc; +#[derive(Default)] +struct Fake { + active: Cell, +} +impl ControlBackend for Fake { + fn vcam_start(&self, _: StartInput) -> Result { + self.active.set(true); + self.vcam_status(EmptyInput {}) + } + fn vcam_stop(&self, _: EmptyInput) -> Result { + self.active.set(false); + self.vcam_status(EmptyInput {}) + } + fn vcam_status(&self, _: EmptyInput) -> Result { + Ok(VcamStatus { + configured: true, + active: self.active.get(), + vmic_active: Some(self.active.get()), + }) + } + fn vmic_status(&self, _: EmptyInput) -> Result { + Ok(VmicStatus { + active: Some(self.active.get()), + source_name: None, + }) + } + fn media_restart(&self, request: MediaInput) -> Result { + self.media_status(request) + } + fn media_status(&self, request: MediaInput) -> Result { + if request.name != "clip" { + return Err(ToolError::not_found("missing media")); + } + Ok(MediaStatus { + name: request.name, + state: MediaState::Playing, + duration_ms: Some(1000), + position_ms: Some(0), + }) + } + fn stats_get(&self, _: EmptyInput) -> Result { + Ok(StatsSnapshot::default()) + } + fn stats_reset(&self, _: EmptyInput) -> Result { + self.stats_get(EmptyInput {}) + } + fn pipeline_dump(&self, _: EmptyInput) -> Result { + Ok(PipelineDump::default()) + } +} +fn rpc(server: &mut Server, name: &str, arguments: Value) -> Value { + let request = json!({"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":name,"arguments":arguments}}).to_string()+"\n"; + let mut output = Vec::new(); + server.serve(request.as_bytes(), &mut output).unwrap(); + serde_json::from_slice(&output).unwrap() +} +#[test] +fn device_media_tools_have_typed_results_and_strict_arguments() { + let mut tools = ToolRegistry::new(); + let backend: Rc = Rc::new(Fake::default()); + register(&mut tools, &backend); + assert_eq!(tools.list()["tools"].as_array().unwrap().len(), 9); + let mut server = Server::with_tools(tools); + for name in ["vcam_start", "vcam_start", "vcam_stop", "vcam_stop"] { + let response = rpc(&mut server, name, json!({})); + assert_eq!(response["result"]["isError"], false); + assert_eq!( + response["result"]["structuredContent"]["active"], + name.ends_with("start") + ); + } + assert_eq!( + rpc(&mut server, "media_restart", json!({"name":"clip"}))["result"]["structuredContent"]["state"], + "playing" + ); + assert_eq!( + rpc(&mut server, "media_status", json!({"name":"missing"}))["result"]["structuredContent"] + ["code"], + 600 + ); + assert_eq!( + rpc(&mut server, "vcam_start", json!({"typo":true}))["error"]["code"], + -32602 + ); + let stats = rpc(&mut server, "stats_get", json!({})); + assert!(stats["result"]["structuredContent"]["end_to_end"]["av_offset_ms"].is_null()); + assert!(stats["result"]["structuredContent"]["stages"]["vmic"]["xruns"].is_null()); +} +#[test] +fn reset_changes_counters_but_preserves_gauges_and_unknown_values() { + let mut now = StatsSnapshot::default(); + now.stages.vcam.frames_total = Some(30); + now.stages.vcam.latency_max_ns = Some(800); + let mut baseline = StatsSnapshot::default(); + baseline.stages.vcam.frames_total = Some(10); + let result = now.relative_to(&baseline); + assert_eq!(result.stages.vcam.frames_total, Some(20)); + assert_eq!(result.stages.vcam.latency_max_ns, Some(800)); + assert_eq!(result.stages.vmic.xruns, None); +} + +#[test] +fn recreated_counter_stays_in_new_generation_across_old_baseline() { + use obs_mcp::tools::control::StatsBaseline; + let mut old = StatsSnapshot::default(); + old.stages.vcam.frames_total = Some(20); + old.stages.vcam.generation = Some(1); + let mut tracker = StatsBaseline::new(old); + let mut new = StatsSnapshot::default(); + new.stages.vcam.frames_total = Some(3); + new.stages.vcam.generation = Some(2); + assert_eq!(tracker.apply(new.clone()).stages.vcam.frames_total, Some(3)); + new.stages.vcam.frames_total = Some(25); + assert_eq!( + tracker.apply(new.clone()).stages.vcam.frames_total, + Some(25) + ); + new.stages.vcam.frames_total = Some(30); + new.stages.vcam.generation = Some(3); + assert_eq!(tracker.apply(new).stages.vcam.frames_total, Some(30)); + assert!(StartInput::default().audio_enabled); + assert_eq!(StartInput::default().audio_track, 1); +} diff --git a/rust/obs-mcp/tests/mcp/main.rs b/rust/obs-mcp/tests/mcp/main.rs index dd42459744..eeb8ab3bec 100644 --- a/rust/obs-mcp/tests/mcp/main.rs +++ b/rust/obs-mcp/tests/mcp/main.rs @@ -25,3 +25,5 @@ pub(crate) fn roundtrip(input: &str) -> Vec { } mod typed; + +mod control;