-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObsWebSocketClient.cs
More file actions
346 lines (297 loc) · 14.2 KB
/
Copy pathObsWebSocketClient.cs
File metadata and controls
346 lines (297 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace ObsHelper
{
public enum ObsConnectionState { Disconnected, Connecting, Connected }
/// <summary>
/// Cliente ligero para OBS WebSocket v5 (OBS 28+).
/// Soporta iniciar/detener grabación y notificaciones de estado en tiempo real.
/// </summary>
public class ObsWebSocketClient : IDisposable
{
private ClientWebSocket _ws;
private CancellationTokenSource _cts;
private Task _receiveTask;
private readonly Dictionary<string, TaskCompletionSource<JObject>> _pending
= new Dictionary<string, TaskCompletionSource<JObject>>();
private readonly SynchronizationContext _syncCtx;
private bool _disposed;
public ObsConnectionState State { get; private set; } = ObsConnectionState.Disconnected;
public bool IsRecording { get; private set; }
/// <summary>Disparado en el hilo UI cuando cambia el estado de conexión.</summary>
public event EventHandler<ObsConnectionState> ConnectionStateChanged;
/// <summary>Disparado en el hilo UI cuando OBS inicia o detiene la grabación.</summary>
public event EventHandler<bool> RecordingStateChanged;
/// <summary>Disparado en el hilo UI cuando ocurre un error inesperado.</summary>
public event EventHandler<string> ErrorOccurred;
public ObsWebSocketClient()
{
// Capturar el SynchronizationContext de WinForms para despachar eventos en el hilo UI
_syncCtx = SynchronizationContext.Current;
}
// ─────────────────────────────────────────────────────────────────────
// API pública
// ─────────────────────────────────────────────────────────────────────
public async Task ConnectAsync(string host, int port, string password)
{
if (_disposed) throw new ObjectDisposedException(nameof(ObsWebSocketClient));
if (State != ObsConnectionState.Disconnected)
throw new InvalidOperationException("Ya está conectado o conectando.");
Logger.Info($"Conectando a OBS WebSocket en ws://{host}:{port}");
SetState(ObsConnectionState.Connecting);
_cts = new CancellationTokenSource();
_ws = new ClientWebSocket();
await _ws.ConnectAsync(new Uri("ws://" + host + ":" + port), _cts.Token);
Logger.Info("TCP conectado. Esperando Hello...");
// Paso 1: Recibir Hello (op=0)
var hello = await ReceiveMessageAsync(_cts.Token);
var helloData = hello?["d"] as JObject;
Logger.Debug($"Hello recibido: {hello}");
// Paso 2: Calcular autenticación si es necesaria
string authString = null;
if (helloData?["authentication"] != null)
{
Logger.Info("OBS requiere autenticación. Calculando hash...");
if (string.IsNullOrEmpty(password))
throw new Exception("OBS requiere contraseña pero no se proporcionó ninguna.");
string salt = helloData["authentication"]["salt"].Value<string>();
string challenge = helloData["authentication"]["challenge"].Value<string>();
authString = ComputeAuth(password, salt, challenge);
Logger.Info("Hash de autenticación calculado correctamente.");
}
else
{
Logger.Info("OBS no requiere autenticación.");
}
// Paso 3: Enviar Identify (op=1)
var identifyPayload = new JObject
{
["rpcVersion"] = 1,
["eventSubscriptions"] = 65 // General(1) | Outputs(64) — para RecordStateChanged
};
if (authString != null) identifyPayload["authentication"] = authString;
Logger.Debug("Enviando Identify (op=1)...");
await SendRawAsync(
new JObject { ["op"] = 1, ["d"] = identifyPayload }.ToString(),
_cts.Token);
// Paso 4: Esperar Identified (op=2)
var identified = await ReceiveMessageAsync(_cts.Token);
Logger.Debug($"Identified recibido: {identified}");
if (identified?["op"]?.Value<int>() != 2)
throw new Exception("Handshake fallido. Verifica la contraseña de OBS WebSocket.");
Logger.Info("Handshake completado. Conexión establecida.");
SetState(ObsConnectionState.Connected);
// Iniciar bucle de recepción en background
_receiveTask = Task.Run(() => ReceiveLoopAsync(_cts.Token));
// Consultar estado actual de grabación
await RefreshRecordingStateAsync();
}
public async Task DisconnectAsync()
{
if (State == ObsConnectionState.Disconnected) return;
Logger.Info("Desconectando de OBS WebSocket...");
_cts?.Cancel();
if (_ws?.State == WebSocketState.Open)
{
try
{
using (var t = new CancellationTokenSource(2000))
await _ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, t.Token);
}
catch (Exception ex)
{
Logger.Warn("Excepción al cerrar WebSocket limpiamente: " + ex.Message);
}
}
if (_receiveTask != null)
{
try { await _receiveTask; } catch { }
_receiveTask = null;
}
_ws?.Dispose();
_ws = null;
Logger.Info("Desconectado.");
if (State != ObsConnectionState.Disconnected)
SetState(ObsConnectionState.Disconnected);
}
public Task StartRecordingAsync() => SendRequestAsync("StartRecord");
public Task StopRecordingAsync() => SendRequestAsync("StopRecord");
public async Task RefreshRecordingStateAsync()
{
var resp = await SendRequestAsync("GetRecordStatus");
bool active = resp?["outputActive"]?.Value<bool>() ?? false;
IsRecording = active;
RaiseEvent(RecordingStateChanged, IsRecording);
}
public async Task<string> GetRecordDirectoryAsync()
{
var resp = await SendRequestAsync("GetRecordDirectory");
return resp?["recordDirectory"]?.Value<string>();
}
public Task SetRecordDirectoryAsync(string path)
{
return SendRequestAsync("SetRecordDirectory",
new JObject { ["recordDirectory"] = path });
}
// ─────────────────────────────────────────────────────────────────────
// Internos
// ─────────────────────────────────────────────────────────────────────
private async Task<JObject> SendRequestAsync(string requestType, JObject requestData = null)
{
if (_ws?.State != WebSocketState.Open)
throw new InvalidOperationException("No hay conexión activa con OBS.");
string id = Guid.NewGuid().ToString("N");
var tcs = new TaskCompletionSource<JObject>();
lock (_pending) _pending[id] = tcs;
Logger.Debug($"Enviando request: {requestType} (id={id})");
var d = new JObject { ["requestType"] = requestType, ["requestId"] = id };
if (requestData != null) d["requestData"] = requestData;
await SendRawAsync(new JObject { ["op"] = 6, ["d"] = d }.ToString(), _cts.Token);
// Esperar respuesta con timeout de 5 segundos
var timeout = Task.Delay(5000);
if (await Task.WhenAny(tcs.Task, timeout) == timeout)
{
lock (_pending) _pending.Remove(id);
Logger.Error($"Timeout esperando respuesta de OBS para: {requestType}");
throw new TimeoutException("OBS no respondió a tiempo.");
}
var result = await tcs.Task;
Logger.Debug($"Respuesta recibida para {requestType}: {result}");
return result;
}
private async Task ReceiveLoopAsync(CancellationToken ct)
{
Logger.Info("Bucle de recepción iniciado.");
try
{
while (!ct.IsCancellationRequested && _ws?.State == WebSocketState.Open)
{
var msg = await ReceiveMessageAsync(ct);
if (msg == null)
{
Logger.Warn("WebSocket cerrado por el servidor (mensaje nulo).");
break;
}
HandleMessage(msg);
}
}
catch (OperationCanceledException)
{
Logger.Info("Bucle de recepción cancelado (desconexión solicitada).");
}
catch (Exception ex)
{
Logger.Error("Error inesperado en el bucle de recepción.", ex);
RaiseEvent(ErrorOccurred, "Conexión perdida: " + ex.Message);
}
finally
{
Logger.Info("Bucle de recepción terminado.");
lock (_pending)
{
foreach (var kv in _pending) kv.Value.TrySetCanceled();
_pending.Clear();
}
if (State == ObsConnectionState.Connected)
SetState(ObsConnectionState.Disconnected);
}
}
private void HandleMessage(JObject msg)
{
int op = msg["op"]?.Value<int>() ?? -1;
switch (op)
{
case 7: // RequestResponse
{
string reqId = msg["d"]?["requestId"]?.Value<string>();
if (reqId == null) break;
TaskCompletionSource<JObject> tcs;
lock (_pending)
{
if (!_pending.TryGetValue(reqId, out tcs)) break;
_pending.Remove(reqId);
}
bool success = msg["d"]?["requestStatus"]?["result"]?.Value<bool>() ?? false;
string code = msg["d"]?["requestStatus"]?["code"]?.ToString() ?? "?";
if (!success)
Logger.Warn($"OBS respondió con error al request {reqId}: code={code}, msg={msg["d"]?["requestStatus"]?["comment"]}");
tcs.TrySetResult(msg["d"]?["responseData"] as JObject ?? new JObject());
break;
}
case 5: // Event
{
string eventType = msg["d"]?["eventType"]?.Value<string>();
Logger.Debug($"Evento recibido: {eventType}");
if (eventType == "RecordStateChanged")
{
bool active = msg["d"]?["eventData"]?["outputActive"]?.Value<bool>() ?? false;
string outState = msg["d"]?["eventData"]?["outputState"]?.Value<string>() ?? "?";
Logger.Info($"RecordStateChanged → outputActive={active}, outputState={outState}");
IsRecording = active;
RaiseEvent(RecordingStateChanged, IsRecording);
}
break;
}
default:
Logger.Debug($"Mensaje recibido con op={op} (ignorado)");
break;
}
}
private async Task<JObject> ReceiveMessageAsync(CancellationToken ct)
{
var buffer = new byte[65536];
var sb = new StringBuilder();
WebSocketReceiveResult result;
do
{
result = await _ws.ReceiveAsync(new ArraySegment<byte>(buffer), ct);
if (result.MessageType == WebSocketMessageType.Close) return null;
sb.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
} while (!result.EndOfMessage);
return JObject.Parse(sb.ToString());
}
private Task SendRawAsync(string text, CancellationToken ct)
{
var bytes = Encoding.UTF8.GetBytes(text);
return _ws.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, ct);
}
private void SetState(ObsConnectionState state)
{
State = state;
RaiseEvent(ConnectionStateChanged, state);
}
private void RaiseEvent<T>(EventHandler<T> handler, T arg)
{
if (handler == null) return;
if (_syncCtx != null)
_syncCtx.Post(_ => handler(this, arg), null);
else
handler(this, arg);
}
private static string ComputeAuth(string password, string salt, string challenge)
{
using (var sha = SHA256.Create())
{
// secret = base64( SHA256(password + salt) )
byte[] s1 = sha.ComputeHash(Encoding.UTF8.GetBytes(password + salt));
string secret = Convert.ToBase64String(s1);
// auth = base64( SHA256(secret + challenge) )
byte[] s2 = sha.ComputeHash(Encoding.UTF8.GetBytes(secret + challenge));
return Convert.ToBase64String(s2);
}
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_cts?.Cancel();
_ws?.Dispose();
}
}
}