-
Notifications
You must be signed in to change notification settings - Fork 12
/
Main.cs
501 lines (430 loc) · 20.1 KB
/
Main.cs
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
using Newtonsoft.Json.Linq;
using OBSWebSocket5;
using SuchByte.MacroDeck.GUI;
using SuchByte.MacroDeck.GUI.CustomControls;
using SuchByte.MacroDeck.Plugins;
using SuchByte.OBSWebSocketPlugin.Actions;
using SuchByte.OBSWebSocketPlugin.GUI;
using SuchByte.OBSWebSocketPlugin.Language;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using SuchByte.OBSWebSocketPlugin.Controllers;
using ToolTip = System.Windows.Forms.ToolTip;
using SuchByte.OBSWebSocketPlugin.Models;
using System.Reflection.Metadata.Ecma335;
using System.Drawing;
using SuchByte.MacroDeck.GUI.CustomControls.Notifications;
using SuchByte.OBSWebSocketPlugin.GUI.Controls;
using SuchByte.MacroDeck.Profiles;
using SuchByte.OBSWebSocketPlugin.Models.Action;
using SuchByte.MacroDeck.Models;
using SuchByte.MacroDeck.Variables;
using SuchByte.MacroDeck.CottleIntegration;
namespace SuchByte.OBSWebSocketPlugin
{
public static class PluginInstance
{
public static Main Main { get; set; }
}
public partial class Main : MacroDeckPlugin
{
public string Author = "Macro Deck";
public string Name = "OBS-WebSocket Plugin";
public const string VariablePrefix = "obs_";
private string[] sceneSuggestions = new string[] { "" };
public override bool CanConfigure => true;
public int NumConnected {
get {
return Connections.Where(c => c.Value.IsConnected).Select(p => p.Value).Count();
}
}
public Dictionary<string, Connection> Connections = new();
private ObsSelectorButton statusButton = new();
private ConnectionTogglerList togglerList = new();
private readonly ToolTip statusToolTip = new();
private MainWindow mainWindow;
public Main()
{
PluginInstance.Main = this;
MacroDeck.MacroDeck.OnMainWindowLoad += MacroDeck_OnMainWindowLoad;
}
private void MacroDeck_OnMainWindowLoad(object sender, EventArgs e)
{
mainWindow = sender as MainWindow;
var numConnected = GetNumConnected();
var buttonWidth = mainWindow.contentButtonPanel.ClientRectangle.Width;
this.statusButton = new ObsSelectorButton
{
AlertText = numConnected.ToString(),
BackgroundImage = numConnected > 0 ? Properties.Resources.OBS_Online : Properties.Resources.OBS_Offline,
BackgroundImageLayout = ImageLayout.Zoom,
Width = buttonWidth,
};
statusToolTip.SetToolTip(statusButton, $"{numConnected} Connection(s) Active");
statusButton.Click += StatusButton_Click;
mainWindow.contentButtonPanel.Controls.Add(statusButton);
// Defined in Main.Migrator.cs
MigrateVersion();
_ = SetupAndStartAsync();
}
private void StatusButton_Click(object sender, EventArgs e)
{
if (togglerList?.Visible ?? false)
{
RemoveTogglerList();
}
else
{
ShowTogglerList();
}
}
private void ShowTogglerList()
{
togglerList?.Close();
togglerList = new ConnectionTogglerList(this.Connections.Values.ToList())
{
StartPosition = FormStartPosition.Manual,
Location = new Point(
mainWindow.Location.X + mainWindow.contentButtonPanel.Location.X + mainWindow.contentButtonPanel.Width + 4,
mainWindow.Location.Y + statusButton.Location.Y + statusButton.Height
)
};
togglerList.Deactivate += (object sender, EventArgs args) =>
{
RemoveTogglerList();
};
togglerList.Show(mainWindow);
}
private void RemoveTogglerList()
{
togglerList.Close();
togglerList = null;
}
public override void Enable()
{
PluginLanguageManager.Initialize();
this.Actions = new List<PluginAction>()
{
new SetReplayBufferState(),
new SaveReplayBufferAction(),
new SourceVisibilityAction(),
new SetFilterStateAction(),
new SetTextValueAction(),
new SetSourceVolumeAction(),
new SetAudioMutedAction(),
new SetProfileAction(),
new SetRecordingStateAction(),
new SetSceneAction(),
new SetStreamingStateAction(),
new SetVirtualCamAction(),
new InteractAction(),
new ToggleConnectionAction(),
};
}
public async Task SetupAndStartAsync()
{
if (Connections != null)
{
foreach (var pair in Connections)
{
pair.Value.Dispose();
}
}
Connections = new();
var credSet = PluginCredentials.GetPluginCredentials(this);
var tasks = new List<Task>();
foreach (var creds in credSet)
{
var config = ConnectionConfig.FromCredentials(creds);
var connection = new Connection(config);
Connections.Add(config.name, connection);
tasks.Add(StoreConnectConnectionAsync(connection));
}
await Task.WhenAll(tasks);
}
public Task StoreConnectConnectionAsync(Connection connection)
{
if (Connections.ContainsKey(connection.Name))
{
Connections[connection.Name] = connection;
}
else
{
Connections.Add(connection.Name, connection);
}
ResetVariables(connection);
WireObs(connection);
togglerList?.AddConnection(connection);
return Task.WhenAny(connection.ConnectAsync(), Task.Delay(10000));
}
public int GetNumConnected()
{
return Connections?.Where(c => c.Value.IsConnected).Select(c => c.Value).Count() ?? 0;
}
public void WireObs(Connection conn)
{
var obs = conn.OBS;
obs.Connected += (sender, args) => OnConnect(conn);
obs.Disposed += (sender, args) => OnDisconnect(conn);
obs.ScenesEvents.CurrentProgramSceneChanged += (sender, args) => OnSceneChange(args, conn);
obs.ConfigEvents.CurrentProfileChanged += (sender, args) => OnProfileChange(args, conn);
obs.TransitionsEvents.CurrentSceneTransitionChanged += (sender, args) => OnTransitionChange(args, conn);
obs.OutputsEvents.StreamStateChanged += (sender, args) => OnStreamingStateChange(args, conn);
obs.OutputsEvents.RecordStateChanged += (sender, args) => OnRecordingStateChange(args, conn);
obs.OutputsEvents.VirtualcamStateChanged += (sender, args) => OnVirtualCameraStateChange(args, conn);
obs.ScenesEvents.SceneListChanged += (sender, args) => OnSceneListChanged(args);
obs.InputsEvents.InputVolumeChanged += (sender, args) => OnSourceVolumeChanged(args, conn);
obs.Connected += (sender, args) => {
_ = Task.Run(async () =>
{
while (obs.IsConnected && !obs.IsDisposed)
{
var stream = await obs.StreamRequests.GetStreamStatusAsync();
OnStreamData(stream, conn);
var stats = await obs.GeneralRequests.GetStatsAsync();
OnStatsData(stats, conn);
await Task.Delay(1000);
}
});
};
obs.InputsEvents.InputMuteStateChanged += (sender, args) => OnSourceMuteStateChanged(args, conn);
obs.SceneItemsEvents.SceneItemEnableStateChanged += (sender, args) => OnSceneItemVisibilityChanged(sender, args, conn);
obs.OutputsEvents.ReplayBufferStateChanged += (sender, args) => OnReplayBufferStateChanged(args, conn);
}
private void OnSceneItemVisibilityChanged(object sender, OBSWebSocket5.Events.SceneItemsEvents.SceneItemEnableStateChangedEventArgs args, Connection connection)
{
var self = this;
_ = Task.Run(async () =>
{
if (sender is OBSWebSocket obs)
{
var sceneItemName = args.SceneItemId.ToString();
var sceneItemsResponse = await obs.SceneItemsRequests.GetSceneItemListAsync(args.SceneName);
var sceneItems = sceneItemsResponse?.SceneItems;
if (sceneItemsResponse == null)
{
var groupSceneItemsResponse = await obs.SceneItemsRequests.GetGroupSceneItemListAsync(args.SceneName);
sceneItems = groupSceneItemsResponse?.SceneItems;
}
if ((sceneItems?.Length ?? 0) > 0) {
foreach (var item in sceneItems)
{
if (item["sceneItemId"]!.ToString().Equals(args.SceneItemId.ToString()) && item["sourceName"] != null)
{
sceneItemName = item["sourceName"].ToString();
break;
}
}
}
connection.SetVariable(args.SceneName + "_" + sceneItemName, args.SceneItemEnabled ? "True" : "False");
}
});
}
private static void OnSourceVolumeChanged(OBSWebSocket5.Events.InputsEvents.InputVolumeChangedEventArgs args, Connection connection)
{
connection.SetVariable(args.InputName + " volume_db", args.InputVolumeDb);
}
private static void OnSourceMuteStateChanged(OBSWebSocket5.Events.InputsEvents.InputMuteStateChangedEventArgs args, Connection connection)
{
connection.SetVariable(args.InputName, args.InputMuted ? "False" : "True");
}
private void OnSceneListChanged(OBSWebSocket5.Events.ScenesEvents.SceneListChangedEventArgs args)
{
List<string> scenesList = new();
foreach (JObject scene in args.Scenes)
{
try
{
var name = scene.GetType().GetProperty("Name");
if (name == null) continue;
scenesList.Add(name.ToString());
}
catch (Exception) { continue; }
}
sceneSuggestions = scenesList.ToArray();
}
private static void ResetVariables(Connection connection)
{
connection.SetVariable("connected", "False");
connection.SetVariable("recording", "False");
ResetStreamVariables(connection);
}
private static void ResetStreamVariables(Connection connection)
{
connection.SetVariable("replay_buffer", "False");
connection.SetVariable("virtual_camera", "False");
connection.SetVariable("streaming", "False");
connection.SetVariable("stream_time", "0h:0m:0s");
connection.SetVariable("kbits", 0);
connection.SetVariable("framerate", 0);
connection.SetVariable("dropped_frames", 0);
connection.SetVariable("total_frames", 0);
}
private void UpdateAllSourceItems()
{
_ = Task.Run(async () =>
{
foreach (var pair in Connections)
{
var connection = pair.Value;
var currentSceneResponse = await connection.OBS.ScenesRequests.GetCurrentProgramSceneAsync();
var sceneItemsResponse =
await connection.OBS.SceneItemsRequests.GetSceneItemListAsync(currentSceneResponse
.CurrentProgramSceneName);
foreach (JObject sceneItem in sceneItemsResponse.SceneItems)
{
OnSceneItemVisibilityChanged(connection.OBS,
new OBSWebSocket5.Events.SceneItemsEvents.SceneItemEnableStateChangedEventArgs
{
SceneName = currentSceneResponse.CurrentProgramSceneName,
SceneItemId = sceneItem["sceneItemId"].ToObject<int>(),
SceneItemEnabled = sceneItem["sceneItemEnabled"].ToObject<bool>()
},
connection); // Update source state; Render = visisble
}
}
});
}
private void UpdateAllVariables(Connection connection)
{
connection.SetVariable("connected", connection.OBS.IsConnected ? "True" : "False");
_ = Task.Run(async () =>
{
var inputs = await connection.OBS.InputsRequests.GetInputListAsync();
foreach (JObject input in inputs.Inputs)
{
var inputName = input["inputName"]?.ToString();
var muted = await connection.OBS.InputsRequests.GetInputMuteAsync(inputName);
if (muted != null)
{
OnSourceMuteStateChanged(new OBSWebSocket5.Events.InputsEvents.InputMuteStateChangedEventArgs
{
InputName = inputName,
InputMuted = muted.InputMuted
},
connection
); // Update mute state
}
}
var scenes = await connection.OBS.ScenesRequests.GetSceneListAsync();
OnSceneListChanged(new OBSWebSocket5.Events.ScenesEvents.SceneListChangedEventArgs { Scenes = scenes.Scenes }); // Update the scene suggestions
});
//MacroDeck.Variables.VariableManager.SetValue(this.variablePrefix + "current transition", this.obs.GetCurrentTransition().Name, MacroDeck.Variables.VariableType.String, this, false); // TODO
_ = Task.Run(async () =>
{
var profiles = await connection.OBS.ConfigRequests.GetProfileListAsync();
connection.SetVariable("current_profile", profiles.CurrentProfileName);
});
_ = Task.Run(async () =>
{
var scene = await connection.OBS.ScenesRequests.GetCurrentProgramSceneAsync();
connection.SetVariable("current_scene", scene.CurrentProgramSceneName, this.sceneSuggestions);
});
_ = Task.Run(async () =>
{
var status = await connection.OBS.OutputsRequests.GetReplayBufferStatusAsync();
if (status != null)
{
connection.SetVariable("replay_buffer", status.OutputActive ? "True" : "False");
}
});
_ = Task.Run(async () =>
{
var status = await connection.OBS.OutputsRequests.GetVirtualCamStatusAsync();
connection.SetVariable("virtual_camera", status.OutputActive ? "True" : "False");
});
_ = Task.Run(async () =>
{
var status = await connection.OBS.RecordRequests.GetRecordStatusAsync();
connection.SetVariable("recording", status.OutputActive ? "True" : "False");
});
_ = Task.Run(async () =>
{
var status = await connection.OBS.StreamRequests.GetStreamStatusAsync();
connection.SetVariable("streaming", status.OutputActive ? "True" : "False");
});
}
private static void OnVirtualCameraStateChange(OBSWebSocket5.Events.OutputsEvents.VirtualcamStateChangedEventArgs args, Connection connection)
{
connection.SetVariable("virtual_camera", args.OutputActive ? "True" : "False");
}
private static void OnReplayBufferStateChanged(OBSWebSocket5.Events.OutputsEvents.ReplayBufferStateChangedEventArgs args, Connection connection)
{
connection.SetVariable("replay_buffer", args.OutputActive ? "True" : "False");
}
private static void OnRecordingStateChange(OBSWebSocket5.Events.OutputsEvents.RecordStateChangedEventArgs args, Connection connection)
{
connection.SetVariable("recording", args.OutputActive ? "True" : "False");
}
private static void OnStreamingStateChange(OBSWebSocket5.Events.OutputsEvents.StreamStateChangedEventArgs args, Connection connection)
{
connection.SetVariable("streaming", args.OutputActive ? "True" : "False");
}
private static void OnStreamData(OBSWebSocket5.Request.StreamRequests.GetStreamStatusResponse status, Connection connection)
{
TimeSpan streamTime = TimeSpan.FromMilliseconds(status.OutputDuration);
connection.SetVariable("stream_time", string.Format("{0:D2}h:{1:D2}m:{2:D2}s",
streamTime.Hours,
streamTime.Minutes,
streamTime.Seconds)
);
connection.SetVariable("output_mb", (status.OutputBytes / (1024.0f * 1024.0f)).ToString());
connection.SetVariable("dropped_frames", status.OutputSkippedFrames);
connection.SetVariable("total_frames", status.OutputTotalFrames);
}
private static void OnStatsData(OBSWebSocket5.Request.GeneralRequests.GetStatsResponse stats, Connection connection)
{
connection.SetVariable("framerate", (int)stats.ActiveFps);
connection.SetVariable("cpu_usage", stats.CpuUsage);
}
private static void OnTransitionChange(OBSWebSocket5.Events.TransitionsEvents.CurrentSceneTransitionChangedEventArgs args, Connection connection)
{
connection.SetVariable("current_transition", args.TransitionName);
}
private static void OnProfileChange(OBSWebSocket5.Events.ConfigEvents.ProfileChangeEventArgs args, Connection connection)
{
connection.SetVariable("current_profile", args.ProfileName);
}
private void OnSceneChange(OBSWebSocket5.Events.ScenesEvents.CurrentProgramSceneChangedEventArgs args, Connection connection)
{
connection.SetVariable("current_scene", args.SceneName, this.sceneSuggestions);
UpdateAllSourceItems();
}
private void OnDisconnect(Connection connection)
{
ResetVariables(connection);
var numConnected = GetNumConnected();
if (mainWindow != null && !mainWindow.IsDisposed && statusButton != null)
{
mainWindow.BeginInvoke(new Action(() =>
{
statusButton.BackgroundImage = numConnected > 0 ? Properties.Resources.OBS_Online : Properties.Resources.OBS_Offline;
statusToolTip.SetToolTip(statusButton, PluginLanguageManager.PluginStrings.OBSDisconnected);
}));
}
this.statusButton.AlertText = numConnected.ToString();
}
private void OnConnect(Connection connection)
{
UpdateAllVariables(connection);
var numConnected = GetNumConnected();
if (mainWindow != null && !mainWindow.IsDisposed && statusButton != null)
{
mainWindow.BeginInvoke(new Action(() =>
{
statusButton.BackgroundImage = Properties.Resources.OBS_Online;
statusToolTip.SetToolTip(statusButton, PluginLanguageManager.PluginStrings.OBSConnected);
}));
}
this.statusButton.AlertText = numConnected.ToString();
}
public override void OpenConfigurator()
{
using var pluginConfig = new PluginConfig();
pluginConfig.ShowDialog();
}
}
}