use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::{Duration, Instant};
use anyhow::{anyhow, Result};
use base64::Engine;
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use tokio::sync::{mpsc, oneshot, Mutex};
use tokio::time::timeout;
use tokio_tungstenite::{
MaybeTlsStream, WebSocketStream, connect_async,
tungstenite::{Message, client::IntoClientRequest},
};
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
const RECONNECT_DELAY: Duration = Duration::from_millis(1000);
type WsStream = WebSocketStream<MaybeTlsStream<tokio::net::TcpStream>>;
enum Command {
Request {
id: u64,
request_type: String,
data: Option<Value>,
tx: oneshot::Sender<Result<Value, String>>,
},
}
enum LoopExit {
Shutdown,
Retry,
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectionStatus {
pub connected: bool,
pub identified: bool,
pub url: String,
pub has_password: bool,
pub auto_start_configured: bool,
pub auto_start_triggered: bool,
pub obs_studio_version: Option<String>,
pub obs_web_socket_version: Option<String>,
pub rpc_version: Option<u64>,
}
#[derive(Default)]
struct SharedInfo {
connected: bool,
identified: bool,
obs_studio_version: Option<String>,
obs_web_socket_version: Option<String>,
rpc_version: Option<u64>,
}
struct ClientState {
task: Option<tokio::task::JoinHandle<()>>,
cmd_tx: Option<mpsc::Sender<Command>>,
}
#[derive(Clone)]
pub struct ObsClient {
url: String,
password: Option<String>,
start_command: Option<String>,
start_triggered: Arc<AtomicBool>,
next_id: Arc<AtomicU64>,
info: Arc<Mutex<SharedInfo>>,
state: Arc<Mutex<ClientState>>,
}
impl ObsClient {
pub fn from_env() -> Self {
let url = std::env::var("OBS_WEBSOCKET_URL")
.unwrap_or_else(|_| "ws://localhost:4455".to_string());
let password = std::env::var("OBS_WEBSOCKET_PASSWORD").ok();
let start_command = std::env::var("OBS_START_COMMAND")
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
Self {
url,
password,
start_command,
start_triggered: Arc::new(AtomicBool::new(false)),
next_id: Arc::new(AtomicU64::new(1)),
info: Arc::new(Mutex::new(SharedInfo::default())),
state: Arc::new(Mutex::new(ClientState {
task: None,
cmd_tx: None,
})),
}
}
fn maybe_start_obs(&self) {
let Some(command) = &self.start_command else {
return;
};
if self.start_triggered.swap(true, Ordering::SeqCst) {
return;
}
tracing::info!("OBS not reachable; launching via OBS_START_COMMAND: {command}");
let mut child = tokio::process::Command::new("sh")
.arg("-c")
.arg(command)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.kill_on_drop(false)
.spawn();
if let Err(e) = &mut child {
tracing::warn!("failed to start OBS via OBS_START_COMMAND: {e}");
} else {
drop(child);
}
}
pub async fn send_request(&self, request_type: &str, data: Option<Value>) -> Result<Value> {
let tx = self.ensure_connected().await?;
let id = self.next_id.fetch_add(1, Ordering::SeqCst);
let (rtx, rrx) = oneshot::channel();
tx.send(Command::Request {
id,
request_type: request_type.to_string(),
data,
tx: rtx,
})
.await
.map_err(|_| anyhow!("OBS WebSocket connection is closed"))?;
match timeout(REQUEST_TIMEOUT, rrx).await {
Ok(Ok(Ok(resp))) => Ok(resp),
Ok(Ok(Err(e))) => Err(anyhow!("{e}")),
Ok(Err(_)) => Err(anyhow!("OBS WebSocket task stopped")),
Err(_) => Err(anyhow!(
"request {request_type} timed out after {} ms",
REQUEST_TIMEOUT.as_millis()
)),
}
}
pub async fn status(&self) -> ConnectionStatus {
let info = self.info.lock().await;
ConnectionStatus {
connected: info.connected,
identified: info.identified,
url: self.url.clone(),
has_password: self.password.is_some(),
auto_start_configured: self.start_command.is_some(),
auto_start_triggered: self.start_triggered.load(Ordering::SeqCst),
obs_studio_version: info.obs_studio_version.clone(),
obs_web_socket_version: info.obs_web_socket_version.clone(),
rpc_version: info.rpc_version,
}
}
pub async fn status_json(&self) -> Value {
let s = self.status().await;
json!({
"server": {
"name": env!("CARGO_PKG_NAME"),
"version": env!("CARGO_PKG_VERSION"),
"status": "running",
},
"obs": {
"connected": s.connected,
"identified": s.identified,
"url": s.url,
"hasPassword": s.has_password,
"autoStartConfigured": s.auto_start_configured,
"autoStartTriggered": s.auto_start_triggered,
"obsStudioVersion": s.obs_studio_version,
"obsWebSocketVersion": s.obs_web_socket_version,
"rpcVersion": s.rpc_version,
},
})
}
async fn ensure_connected(&self) -> Result<mpsc::Sender<Command>> {
let boot_grace = if self.start_command.is_some() {
Duration::from_secs(25)
} else {
HANDSHAKE_TIMEOUT
};
let deadline = Instant::now() + boot_grace;
loop {
{
let mut state = self.state.lock().await;
let alive = state.task.as_ref().is_some_and(|t| !t.is_finished());
let identified = self.info.lock().await.identified;
if alive && identified {
if let Some(tx) = state.cmd_tx.clone() {
return Ok(tx);
}
}
if !alive {
let (cmd_tx, cmd_rx) = mpsc::channel(64);
let client = self.clone();
let task = tokio::spawn(async move {
client.run_connection(cmd_rx).await;
});
state.task = Some(task);
state.cmd_tx = Some(cmd_tx.clone());
}
}
if Instant::now() > deadline {
return Err(anyhow!(
"could not connect to OBS WebSocket at {}: connection not established",
self.url
));
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
async fn run_connection(&self, mut cmd_rx: mpsc::Receiver<Command>) {
loop {
self.info.lock().await.connected = false;
self.info.lock().await.identified = false;
let ws = match timeout(HANDSHAKE_TIMEOUT, self.handshake()).await {
Ok(Ok(ws)) => ws,
Ok(Err(e)) => {
tracing::warn!("OBS WebSocket handshake failed: {e}");
self.maybe_start_obs();
tokio::time::sleep(RECONNECT_DELAY).await;
continue;
}
Err(_) => {
tracing::warn!("OBS WebSocket handshake timed out");
self.maybe_start_obs();
tokio::time::sleep(RECONNECT_DELAY).await;
continue;
}
};
{
let mut info = self.info.lock().await;
info.connected = true;
info.identified = true;
}
tracing::info!("connected to OBS WebSocket at {}", self.url);
match self.main_loop(ws, &mut cmd_rx).await {
LoopExit::Shutdown => return,
LoopExit::Retry => {
tracing::warn!("OBS WebSocket connection lost; reconnecting");
tokio::time::sleep(RECONNECT_DELAY).await;
}
}
}
}
async fn handshake(&self) -> Result<WsStream> {
let request = self
.url
.clone()
.into_client_request()
.map_err(|e| anyhow!("invalid WebSocket URL '{}': {e}", self.url))?;
let (ws, _resp) = connect_async(request)
.await
.map_err(|e| anyhow!("connect to {} failed: {e}", self.url))?;
let mut ws = ws;
let hello: HelloMessage = serde_json::from_value(
read_json(&mut ws)
.await?
.ok_or_else(|| anyhow!("connection closed during handshake"))?,
)
.map_err(|e| anyhow!("invalid Hello from OBS: {e}"))?;
if hello.op != 0 {
return Err(anyhow!(
"expected Hello (op 0) from OBS, got op {}",
hello.op
));
}
let auth = match (&hello.d.authentication, &self.password) {
(Some(a), Some(pw)) => Some(auth_string(pw, &a.salt, &a.challenge)?),
(Some(_), None) => {
return Err(anyhow!(
"OBS WebSocket requires a password; set OBS_WEBSOCKET_PASSWORD"
))
}
(None, _) => None,
};
let rpc_version = hello.d.rpc_version.min(1);
let mut identify = json!({
"op": 1,
"d": {
"rpcVersion": rpc_version,
"eventSubscriptions": 0,
}
});
if let Some(auth) = auth {
identify["d"]["authentication"] = Value::String(auth);
}
ws.send(Message::Text(identify.to_string().into()))
.await
.map_err(|e| anyhow!("failed to send Identify: {e}"))?;
loop {
let msg = read_json(&mut ws)
.await?
.ok_or_else(|| anyhow!("connection closed waiting for Identified"))?;
match msg.get("op").and_then(|v| v.as_u64()) {
Some(2) => {
{
let mut info = self.info.lock().await;
info.obs_studio_version = Some(hello.d.obs_studio_version.clone());
info.obs_web_socket_version = Some(hello.d.obs_web_socket_version.clone());
info.rpc_version = Some(hello.d.rpc_version);
}
return Ok(ws);
}
Some(other) => {
tracing::debug!("ignoring op {other} during handshake");
}
None => {
return Err(anyhow!("message without op code during handshake"));
}
}
}
}
async fn main_loop(
&self,
mut ws: WsStream,
cmd_rx: &mut mpsc::Receiver<Command>,
) -> LoopExit {
let mut pending: HashMap<u64, oneshot::Sender<Result<Value, String>>> = HashMap::new();
loop {
tokio::select! {
incoming = ws.next() => {
match incoming {
Some(Ok(Message::Text(text))) => {
if let Ok(msg) = serde_json::from_str::<Value>(&text) {
if msg.get("op").and_then(|v| v.as_u64()) == Some(7) {
let id: u64 = msg["d"]["requestId"]
.as_str()
.and_then(|s| s.parse().ok())
.unwrap_or(0);
if let Some(tx) = pending.remove(&id) {
let ok = msg["d"]["requestStatus"]["result"]
.as_bool()
.unwrap_or(false);
let resp = if ok {
Ok(msg["d"]["responseData"].clone())
} else {
let code = msg["d"]["requestStatus"]["code"].as_i64().unwrap_or(-1);
let comment = msg["d"]["requestStatus"]["comment"]
.as_str()
.unwrap_or("unknown error");
Err(format!("OBS error {code}: {comment}"))
};
let _ = tx.send(resp);
}
}
}
}
Some(Ok(Message::Close(_))) | None => {
flush_pending(&mut pending, "connection closed");
return LoopExit::Retry;
}
Some(Ok(_)) => {}
Some(Err(e)) => {
flush_pending(&mut pending, &format!("connection error: {e}"));
return LoopExit::Retry;
}
}
}
cmd = cmd_rx.recv() => {
match cmd {
Some(Command::Request { id, request_type, data, tx }) => {
let message = json!({
"op": 6,
"d": {
"requestType": request_type,
"requestId": id.to_string(),
"requestData": data,
}
});
if let Err(e) = ws
.send(Message::Text(message.to_string().into()))
.await
{
let _ = tx.send(Err(format!("send failed: {e}")));
flush_pending(&mut pending, "connection error");
return LoopExit::Retry;
}
pending.insert(id, tx);
}
None => {
flush_pending(&mut pending, "server shutting down");
return LoopExit::Shutdown;
}
}
}
}
}
}
}
fn flush_pending(pending: &mut HashMap<u64, oneshot::Sender<Result<Value, String>>>, why: &str) {
for (_, tx) in pending.drain() {
let _ = tx.send(Err(why.to_string()));
}
}
async fn read_json(ws: &mut WsStream) -> Result<Option<serde_json::Value>> {
loop {
match ws.next().await {
Some(Ok(Message::Text(text))) => {
return serde_json::from_str(&text)
.map(Some)
.map_err(|e| anyhow!("invalid JSON from OBS: {e}"))
}
Some(Ok(_)) => continue,
Some(Err(e)) => return Err(anyhow!("read error: {e}")),
None => return Ok(None),
}
}
}
fn auth_string(password: &str, salt: &str, challenge: &str) -> Result<String> {
let secret = Sha256::digest(format!("{password}{salt}").as_bytes());
let secret_b64 = base64::engine::general_purpose::STANDARD.encode(secret);
let auth = Sha256::digest(format!("{secret_b64}{challenge}").as_bytes());
Ok(base64::engine::general_purpose::STANDARD.encode(auth))
}
#[derive(Debug, Deserialize)]
struct HelloMessage {
op: u8,
d: HelloData,
}
#[derive(Debug, Deserialize)]
struct HelloData {
#[serde(rename = "obsStudioVersion")]
obs_studio_version: String,
#[serde(rename = "obsWebSocketVersion")]
obs_web_socket_version: String,
#[serde(rename = "rpcVersion")]
rpc_version: u64,
authentication: Option<HelloAuth>,
}
#[derive(Debug, Deserialize)]
struct HelloAuth {
challenge: String,
salt: String,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn auth_string_matches_obs_websocket_algorithm() {
let password = "hunter2";
let salt = "4E79jP7Wtd0lUqdyQzLzaWY";
let challenge = "yTfS08Wq3gGRMSbv9FcdVxSJzN21H2Yc";
let auth = auth_string(password, salt, challenge).unwrap();
assert_eq!(auth.len(), 44, "base64 sha256 is 44 chars");
assert_eq!(auth, auth_string(password, salt, challenge).unwrap());
assert_ne!(auth, auth_string("hunter3", salt, challenge).unwrap());
}
}