forked from shanselman/PowerPointToOBSSceneSwitcher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
262 lines (215 loc) · 11.5 KB
/
Program.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
namespace SceneSwitcher {
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using Humanizer;
using Microsoft.Office.Interop.PowerPoint;
internal class Program {
private static readonly Application PowerPoint = new();
private static readonly string EmbeddedVideoPrefix = "PowerPoint with ";
private static bool skipPtzRequests;
private static int currentSlideNumber;
private static Config config;
private static OBS obs;
private static TallyLight activeTallyLight;
private static void Main(string[] args) {
var argList = new List<string>(args);
// For testing at home
skipPtzRequests = argList.Contains("skipPtzRequests") || argList.Contains("skipAllRequests");
TallyLight.SetSkipRequests(argList.Contains("skipTallyLightRequests") || argList.Contains("skipAllRequests"));
Console.WriteLine("Reading configuration...");
config = JsonSerializer.Deserialize<Config>(File.ReadAllText("config.json"), new JsonSerializerOptions {
PropertyNameCaseInsensitive = true,
});
Console.WriteLine("Connecting to PowerPoint...");
PowerPoint.SlideShowNextSlide += NextSlide;
Console.WriteLine("Connecting to OBS...");
obs = new OBS(config);
obs.SceneChanged += NextScene;
obs.Connect();
config.TallyLights.ForEach(tallyLight => tallyLight.TurnOff());
while (true) {
// Sleep forever while the OBS connection responds to events
Thread.Sleep(Timeout.Infinite);
}
}
private static void NextSlide(SlideShowWindow window) {
if (window == null) {
return;
}
int previousSlideNumber = currentSlideNumber;
currentSlideNumber = window.View.Slide.SlideNumber;
Console.WriteLine($"Moved to slide {currentSlideNumber}");
IDictionary<string, string> commands = GetSlideCommands(window.View.Slide);
if (currentSlideNumber != previousSlideNumber + 1) {
// Went back a slide, or jumped to a slide; figure out the previous video and audio that was used
IDictionary<string, string> previousSlideCommands = GetSlideCommands(window.Presentation.Slides[previousSlideNumber]);
string[] videoCommands = ["VIDEO-LONG-DELAY", "VIDEO-SHORT-DELAY", "VIDEO"];
bool ContainsVideoCommand(IDictionary<string, string> commands) => commands.Keys.FirstOrDefault(videoCommands.Contains) != null;
bool ContainsAudioCommand(IDictionary<string, string> commands) => commands.Keys.FirstOrDefault(key => key == "AUDIO") != null;
// If going back one slide, the video or audio will already be correct if the previous slide didn't change video or audio respectively.
bool wentBackOneSlide = currentSlideNumber == previousSlideNumber - 1;
bool foundVideoCommand = wentBackOneSlide && !ContainsVideoCommand(previousSlideCommands);
bool foundAudioCommand = wentBackOneSlide && !ContainsAudioCommand(previousSlideCommands);
int i = currentSlideNumber;
IDictionary<string, string> backCommands = new Dictionary<string, string>();
while (i > 0 && !(foundVideoCommand && foundAudioCommand)) {
commands = GetSlideCommands(window.Presentation.Slides[i--]);
if (!foundVideoCommand && ContainsVideoCommand(commands)) {
foundVideoCommand = true;
string lastVideoCommand = videoCommands.First(commands.Keys.Contains);
// Use the last video command immediately.
backCommands["VIDEO"] = commands[lastVideoCommand];
}
if (!foundAudioCommand && ContainsAudioCommand(commands)) {
foundAudioCommand = true;
backCommands["AUDIO"] = commands["AUDIO"];
}
}
commands = backCommands;
}
foreach (var command in commands) {
var argument = command.Value;
switch (command.Key) {
case "AUDIO":
List<string> audioSources = ParseListArgument(argument);
Console.WriteLine($" Switching audio to {audioSources.Humanize(source => $"\"{source}\"")}");
obs.SetAudioSources(audioSources);
break;
case "VIDEO":
ExecuteVideoCommand(command.Key, argument, commands, currentSlideNumber);
break;
case "VIDEO-SHORT-DELAY":
Task.Delay(config.ShortDelay).ContinueWith(t => {
Console.WriteLine($" (short delay)");
ExecuteVideoCommand(command.Key, argument, commands, currentSlideNumber);
});
break;
case "VIDEO-LONG-DELAY":
Task.Delay(config.LongDelay).ContinueWith(t => {
Console.WriteLine($" (long delay)");
ExecuteVideoCommand(command.Key, argument, commands, currentSlideNumber);
});
break;
default:
WriteError($"Skipping invalid command \"{command.Key}:{command.Value}\"");
break;
}
}
}
private static List<string> ParseListArgument(string argument) {
return argument.Split(",").Select(s => s.Trim()).ToList();
}
private static void ExecuteVideoCommand(string command, string argument, IDictionary<string, string> currentSlideCommands, int currentSlideNumber) {
Console.WriteLine($" Switching video to \"{argument}\"");
string currentPreset = argument.Replace(EmbeddedVideoPrefix, string.Empty);
string nextPreset = (GetNextVideoCommandArgument(command, currentSlideCommands, currentSlideNumber) ?? string.Empty)
.Replace(EmbeddedVideoPrefix, string.Empty);
string currentPtzCamera = GetPtzCamera(currentPreset);
string nextPtzCamera = nextPreset != null ? GetPtzCamera(nextPreset) : null;
if (nextPtzCamera != null && nextPtzCamera != currentPtzCamera) {
// The next scene is from a PTZ camera, which is not used to display the current scene.
// Prime the PTZ camera with the next scene it will display to avoid camera movement getting livestreamed.
PTZ(nextPtzCamera, nextPreset);
}
if (currentPtzCamera != null) {
PTZ(currentPtzCamera, currentPreset);
}
string scene = currentPtzCamera != null && !argument.StartsWith(EmbeddedVideoPrefix) ? currentPtzCamera : argument;
Console.WriteLine($" Switching OBS to \"{scene}\"");
if (obs.HasScene(scene)) {
obs.ChangeScene(scene);
} else {
WriteError($"No video scene named \"{scene}\" exists");
}
}
private static string GetNextVideoCommandArgument(string currentVideoCommand, IDictionary<string, string> currentSlideCommands, int currentSlideNumber) {
string[] remainingVideoCommands;
if (currentVideoCommand == "VIDEO") {
remainingVideoCommands = ["VIDEO-SHORT-DELAY", "VIDEO-LONG-DELAY"];
} else if (currentVideoCommand == "VIDEO-SHORT-DELAY") {
remainingVideoCommands = ["VIDEO-LONG-DELAY"];
} else if (currentVideoCommand == "VIDEO-LONG-DELAY") {
remainingVideoCommands = [];
} else {
remainingVideoCommands = ["VIDEO", "VIDEO-SHORT-DELAY", "VIDEO-LONG-DELAY"];
}
foreach (var command in remainingVideoCommands) {
if (currentVideoCommand != command && currentSlideCommands.TryGetValue(command, out string argument)) {
return argument;
}
}
if (currentSlideNumber == PowerPoint.ActivePresentation.Slides.Count) {
return null;
}
return GetNextVideoCommandArgument(null, GetSlideCommands(PowerPoint.ActivePresentation.Slides[currentSlideNumber + 1]), currentSlideNumber + 1);
}
private static string GetPtzCamera(string preset) {
return config.PtzScenes.Keys.FirstOrDefault(scene => config.PtzScenes[scene].ContainsKey(preset));
}
private static string NormalizeWhitespace(string argument) {
// Remove any zero width spaces, and normalize any remaining consecutive whitespace to a single space.
var zeroWidthSpace = "\u200B";
var consecutiveWhitespacePattern = @"\s+";
return Regex.Replace(argument.Replace(zeroWidthSpace, string.Empty), consecutiveWhitespacePattern, " ");
}
private static IDictionary<string, string> GetSlideCommands(Slide slide) {
// Text starts at index 2 ¯\_(ツ)_/¯
string note;
try {
note = slide.NotesPage.Shapes[2].TextFrame.TextRange.Text;
} catch {
// Slide has no notes
return ImmutableDictionary<string, string>.Empty;
}
string line;
IDictionary<string, string> commands = new Dictionary<string, string>();
var noteReader = new StringReader(note);
while ((line = noteReader.ReadLine()) != null) {
var parts = NormalizeWhitespace(line).Split(':', 2);
if (parts.Length == 2) {
commands[parts[0].ToUpper().Trim()] = parts[1].Trim();
} else {
WriteError($"Invalid command \"{line}\" on slide {slide.SlideNumber}");
}
}
return commands;
}
private static void NextScene(object sender, string scene) {
Console.WriteLine($" OBS scene changed to \"{scene}\"");
SetTallyLightScene(scene);
}
private static void SetTallyLightScene(string scene) {
var sceneSources = obs.GetSceneSources(scene);
var liveTallyLight = config.TallyLights.FirstOrDefault(tallyLight => tallyLight.ObsScene == scene);
if (activeTallyLight == liveTallyLight) {
return;
}
activeTallyLight?.TurnOff();
liveTallyLight?.TurnOn();
activeTallyLight = liveTallyLight;
}
private static async void PTZ(string camera, string preset) {
var httpCgiUrl = config.PtzScenes[camera][preset];
Console.WriteLine($" Setting \"{camera}\" camera to \"{preset}\" preset");
if (skipPtzRequests) {
return;
}
try {
await httpCgiUrl.GetAsync();
} catch (FlurlHttpException ex) {
WriteError(ex.Message);
}
}
private static void WriteError(string message) {
Console.Error.WriteLine($" ERROR: {message}");
}
}
}