forked from steveseguin/vdo.ninja
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobs.html
More file actions
1503 lines (1366 loc) · 63.9 KB
/
obs.html
File metadata and controls
1503 lines (1366 loc) · 63.9 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
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
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VDO.Ninja OBS Control Dock</title>
<style>
body {
font-family: sans-serif;
margin: 5px;
background-color: #13141A;
color: #e0e0e0;
font-size: 13px;
}
.container {
margin-bottom: 10px;
padding: 8px;
background-color: #272A33;
border-radius: 5px;
border: 1px solid #3a3a48;
}
.collapsible {
cursor: pointer;
user-select: none;
padding: 8px 0;
position: relative;
font-weight: bold;
background: rgba(255,255,255,0.03);
margin: -8px -8px 8px -8px;
padding-left: 12px;
border-bottom: 1px solid #3a3a48;
}
.collapsible::after {
content: '▼';
position: absolute;
right: 12px;
font-size: 12px;
color: #8a8a9a;
transition: transform 0.2s ease;
}
.collapsible.collapsed::after {
content: '►';
transform: none;
}
.collapsible:hover {
background: rgba(255,255,255,0.08);
}
.collapsible::before {
content: 'Click to ' attr(data-state);
position: absolute;
right: 30px;
font-size: 10px;
color: #666;
font-weight: normal;
}
.collapsible[data-state="expand"]::before {
content: 'Click to expand';
}
.collapsible[data-state="collapse"]::before {
content: 'Click to collapse';
}
.collapsible-content {
max-height: 1000px;
overflow: hidden;
transition: max-height 0.2s ease-out;
padding-top: 5px;
}
.collapsible-content.collapsed {
max-height: 0;
padding-top: 0;
}
label {
display: block;
margin-bottom: 5px;
}
input[type="text"], input[type="password"], select {
width: calc(100% - 16px);
padding: 5px;
margin-bottom: 8px;
border: 1px solid #424254;
border-radius: 3px;
background-color: #3C404D;
color: #e0e0e0;
}
select {
padding: 6px 5px;
height: auto;
}
button {
padding: 6px 10px;
background-color: #3C404D;
color: white;
border: none;
border-radius: 3px;
cursor: pointer;
margin-right: 3px;
margin-bottom: 3px;
font-size: 12px;
}
button.connected {
background-color: #4C80AF;
}
button.disconnected {
background-color: #484860;
}
button:hover {
background-color: #5a5a7a;
}
.blur-field {
filter: blur(5px);
transition: filter 0.2s ease;
}
.blur-field:focus {
filter: blur(0);
}
#vdoNinjaIframe {
width: 1px;
height: 1px;
position: absolute;
left: -1000px;
top: -1000px;
border: 0;
}
.log-area {
height: 100px;
background-color: #1a1a24;
color: #ccc;
border: 1px solid #424254;
overflow-y: scroll;
padding: 5px;
font-family: monospace;
font-size: 0.9em;
margin-top: 5px;
white-space: pre-wrap;
}
.status-indicator {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-left: 5px;
background-color: #555;
}
.status-indicator.connected {
background-color: #4C80AF;
}
.status-indicator.error {
background-color: #f44336;
}
.stream-list {
max-height: 120px;
overflow-y: auto;
background-color: #1a1a24;
border: 1px solid #424254;
border-radius: 3px;
padding: 5px;
margin-top: 3px;
}
.stream-item {
padding: 4px;
border-bottom: 1px solid #3c3c4a;
font-size: 12px;
word-break: break-word;
}
.stream-item:last-child {
border-bottom: none;
}
h1, h2 {
color: #c8c8c8;
margin: 5px 0;
font-size: 1.1em;
}
h1 {
font-size: 1.2em;
}
small {
color: #8a8a9a;
font-size: 0.85em;
}
.add-stream-btn {
background-color: #4C80AF;
color: white;
padding: 2px 4px;
font-size: 11px;
}
.status-line {
font-size: 12px;
margin-top: 5px;
display: flex;
align-items: center;
}
input[type="checkbox"] {
accent-color: #4C80AF;
margin-right: 5px;
}
.checkbox-label {
display: flex;
align-items: center;
margin-bottom: 3px;
}
.checkbox-label input {
margin-right: 4px;
}
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #1a1a24;
border-radius: 3px;
}
::-webkit-scrollbar-thumb {
background: #3C404D;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #4C80AF;
}
* {
scrollbar-width: thin;
scrollbar-color: #3C404D #1a1a24;
}
.flex-row {
display: flex;
gap: 4px;
flex-wrap: wrap;
}
#obsSceneNameInput {
display: none !important;
}
#loadScenesBtn {
display: inline-block;
margin-left: 5px;
vertical-align: top;
}
</style>
</head>
<body>
<h1>VDO.Ninja OBS Control</h1>
<div class="container">
<h2 class="collapsible" data-state="collapse">OBS WebSocket Connection</h2>
<div class="collapsible-content">
<label for="obsWsUrl">WebSocket URL:</label>
<input type="text" id="obsWsUrl" value="ws://localhost:4455">
<label for="obsWsPassword">Password:</label>
<input type="password" id="obsWsPassword" value="">
<div class="status-line">
<button id="obsConnectBtn">Connect to OBS</button>
<span id="obsConnectionStatus">Status: Disconnected</span>
<span id="obsStatusIndicator" class="status-indicator"></span>
</div>
</div>
</div>
<div class="container">
<h2 class="collapsible" data-state="collapse">VDO.Ninja Settings</h2>
<div class="collapsible-content">
<label for="vdoNinjaRoom">Room Name:</label>
<input type="text" id="vdoNinjaRoom" placeholder="e.g., MyNinjaRoom" class="blur-field">
<label for="vdoNinjaPassword">Password:</label>
<input type="password" id="vdoNinjaPassword" placeholder="Room or &password">
<label for="vdoNinjaStreamIds">Stream IDs:</label>
<input type="text" id="vdoNinjaStreamIds" placeholder="streamId1,streamId2" class="blur-field">
<small>Room Name or Stream ID(s) needed</small>
</div>
</div>
<div class="container">
<h2 class="collapsible" data-state="expand">OBS Target Settings</h2>
<div class="collapsible-content collapsed">
<label for="obsSceneSelect">Target Scene:</label>
<div style="display: flex; align-items: center; gap: 5px;">
<select id="obsSceneSelect" style="flex: 1;">
<option value="">Select a scene...</option>
</select>
<button id="loadScenesBtn">Re-Fetch Scenes</button>
</div>
<input type="text" id="obsSceneNameInput" style="display:none;">
<label for="sourceSizing">New Source Sizing:</label>
<select id="sourceSizing">
<option value="autoGrid">Auto Grid Layout</option>
<option value="bestFit">Best Fit (Preserve Aspect)</option>
<option value="stretchToFill">Stretch to Fill Screen</option>
<option value="defaultSize">Default (1920x1080 at 0,0)</option>
</select>
<div id="autoSourceOptions">
<label class="checkbox-label">
<input type="checkbox" id="autoAddSources" checked>
Auto-add new streams as sources
</label>
<label class="checkbox-label">
<input type="checkbox" id="autoRemoveSources" checked>
Auto-remove sources on disconnect
</label>
</div>
</div>
</div>
<div class="container">
<h2 class="collapsible" data-state="expand">Stream ID Mappings</h2>
<div class="collapsible-content collapsed">
<div id="streamMappingContainer">
<div id="streamMappings"></div>
<button id="addStreamMappingBtn">Add New Mapping</button>
</div>
</div>
</div>
<div class="container">
<h2 class="collapsible" data-state="collapse">Active Streams</h2>
<div class="collapsible-content">
<div id="streamList" class="stream-list">
<div class="stream-item">No active streams</div>
</div>
</div>
</div>
<iframe id="vdoNinjaIframe" allow="encrypted-media;sync-xhr;usb;web-share;cross-origin-isolated;midi *;geolocation;camera *;microphone *;fullscreen;picture-in-picture;display-capture;accelerometer;autoplay;gyroscope;screen-wake-lock;"></iframe>
<div class="container">
<h2 class="collapsible" data-state="expand">Log</h2>
<div class="collapsible-content collapsed">
<div id="logArea" class="log-area"></div>
</div>
</div>
<script>
// DOM elements
const obsWsUrlInput = document.getElementById('obsWsUrl');
const obsWsPasswordInput = document.getElementById('obsWsPassword');
const obsConnectBtn = document.getElementById('obsConnectBtn');
const obsConnectionStatus = document.getElementById('obsConnectionStatus');
const obsStatusIndicator = document.getElementById('obsStatusIndicator');
const vdoNinjaRoomInput = document.getElementById('vdoNinjaRoom');
const vdoNinjaPasswordInput = document.getElementById('vdoNinjaPassword');
const vdoNinjaStreamIdsInput = document.getElementById('vdoNinjaStreamIds');
const vdoNinjaIframe = document.getElementById('vdoNinjaIframe');
const obsSceneNameInput = document.getElementById('obsSceneNameInput');
const obsSceneSelect = document.getElementById('obsSceneSelect');
const sourceSizingSelect = document.getElementById('sourceSizing');
const autoAddSourcesCheckbox = document.getElementById('autoAddSources');
const autoRemoveSourcesCheckbox = document.getElementById('autoRemoveSources');
const streamListContainer = document.getElementById('streamList');
const logArea = document.getElementById('logArea');
const loadScenesBtn = document.getElementById('loadScenesBtn');
let vdoNinjaConnected = false;
// Set up collapsible sections
document.querySelectorAll('.collapsible').forEach(header => {
header.addEventListener('click', function() {
this.classList.toggle('collapsed');
const content = this.nextElementSibling;
if (content.classList.contains('collapsible-content')) {
content.classList.toggle('collapsed');
// Update the data-state attribute
if (content.classList.contains('collapsed')) {
this.setAttribute('data-state', 'expand');
} else {
this.setAttribute('data-state', 'collapse');
}
}
});
});
const vdoNinjaConnectBtn = document.createElement('button');
vdoNinjaConnectBtn.id = 'vdoNinjaConnectBtn';
vdoNinjaConnectBtn.textContent = 'Connect to VDO.Ninja';
vdoNinjaConnectBtn.style.marginTop = '5px';
const vdoNinjaStatusIndicator = document.createElement('span');
vdoNinjaStatusIndicator.id = 'vdoNinjaStatusIndicator';
vdoNinjaStatusIndicator.className = 'status-indicator';
const vdoNinjaConnectionStatus = document.createElement('span');
vdoNinjaConnectionStatus.id = 'vdoNinjaConnectionStatus';
vdoNinjaConnectionStatus.textContent = 'Status: Disconnected';
vdoNinjaConnectionStatus.style.marginLeft = '5px';
// Add these elements after the vdoNinjaPassword input
const vdoNinjaSettingsContainer = document.querySelector('.container:nth-child(2)');
const buttonsDiv = document.createElement('div');
buttonsDiv.style.marginTop = '5px';
buttonsDiv.className = 'status-line';
buttonsDiv.appendChild(vdoNinjaConnectBtn);
buttonsDiv.appendChild(vdoNinjaConnectionStatus);
buttonsDiv.appendChild(vdoNinjaStatusIndicator);
vdoNinjaSettingsContainer.querySelector('.collapsible-content').appendChild(buttonsDiv);
vdoNinjaConnectBtn.addEventListener('click', () => {
if (vdoNinjaConnected) {
disconnectFromVdoNinja();
} else {
connectToVdoNinja();
}
});
// State variables
let obs = null;
let obsConnected = false;
let activeStreams = {};
let obsScenes = [];
let requestCallbacks = {};
let vdoNinjaLastActivityTime = 0;
let vdoNinjaConnectionCheckTimer = null;
// Helper functions
function logMessage(message) {
console.log(message);
const timestamp = new Date().toLocaleTimeString();
logArea.innerHTML += `[${timestamp}] ${message}\n`;
logArea.scrollTop = logArea.scrollHeight;
}
function generateRequestId(type) {
return `${type}-${Date.now()}-${Math.floor(Math.random() * 1000)}`;
}
function toggleVdoNinjaInputs(disabled) {
vdoNinjaRoomInput.disabled = disabled;
vdoNinjaPasswordInput.disabled = disabled;
vdoNinjaStreamIdsInput.disabled = disabled;
}
function updateVdoNinjaButtonState(connected) {
vdoNinjaConnected = connected;
if (connected) {
vdoNinjaConnectBtn.textContent = 'Disconnect';
vdoNinjaConnectBtn.classList.add('connected');
vdoNinjaConnectBtn.classList.remove('disconnected');
vdoNinjaConnectionStatus.textContent = 'Status: Connected';
vdoNinjaStatusIndicator.classList.add('connected');
} else {
vdoNinjaConnectBtn.textContent = 'Connect to VDO.Ninja';
vdoNinjaConnectBtn.classList.remove('connected');
vdoNinjaConnectBtn.classList.add('disconnected');
vdoNinjaConnectionStatus.textContent = 'Status: Disconnected';
vdoNinjaStatusIndicator.classList.remove('connected');
}
// Toggle input fields based on connection state
toggleVdoNinjaInputs(connected);
}
function saveSettings() {
const settings = {
obsWsUrl: obsWsUrlInput.value,
obsWsPassword: obsWsPasswordInput.value,
vdoNinjaRoom: vdoNinjaRoomInput.value,
vdoNinjaPassword: vdoNinjaPasswordInput.value,
vdoNinjaStreamIds: vdoNinjaStreamIdsInput.value,
obsSceneName: obsSceneSelect.value,
sourceSizing: sourceSizingSelect.value,
autoAddSources: autoAddSourcesCheckbox.checked,
autoRemoveSources: autoRemoveSourcesCheckbox.checked,
vdoNinjaConnected: vdoNinjaConnected
// Removed cloneToMainScene if you choose to remove the global checkbox
// cloneToMainScene: document.getElementById('cloneToMainScene')?.checked || false
};
localStorage.setItem('obsNinjaSettings', JSON.stringify(settings));
const mappings = getStreamMappings();
localStorage.setItem('obsNinjaStreamMappings', JSON.stringify(mappings));
}
function calculateGridPositions(totalSources, canvasWidth, canvasHeight) {
const positions = [];
let cols = Math.ceil(Math.sqrt(totalSources));
let rows = Math.ceil(totalSources / cols);
const cellWidth = canvasWidth / cols;
const cellHeight = canvasHeight / rows;
const lastRowItems = totalSources - ((rows - 1) * cols);
const lastRowOffset = (cols - lastRowItems) * (cellWidth / 2);
for (let row = 0; row < rows; row++) {
for (let col = 0; col < cols; col++) {
const index = row * cols + col;
if (index < totalSources) {
let xPos = col * cellWidth;
if (row === rows - 1 && lastRowItems < cols) {
xPos += lastRowOffset;
}
positions.push({
x: xPos,
y: row * cellHeight,
width: cellWidth,
height: cellHeight
});
}
}
}
return positions;
}
function disconnectFromVdoNinja() {
vdoNinjaIframe.src = 'about:blank';
if (vdoNinjaConnectionCheckTimer) {
clearTimeout(vdoNinjaConnectionCheckTimer);
vdoNinjaConnectionCheckTimer = null;
}
activeStreams = {};
updateStreamList();
updateVdoNinjaButtonState(false);
saveSettings();
}
function connectToVdoNinja() {
const room = vdoNinjaRoomInput.value.trim();
const streamIds = vdoNinjaStreamIdsInput.value.trim();
if (!room && !streamIds) {
logMessage("VDO.Ninja Error: Room Name or Stream ID(s) must be provided.");
return;
}
initializeVdoNinjaIframe();
vdoNinjaConnectionStatus.textContent = 'Status: Connecting...';
vdoNinjaConnectBtn.textContent = 'Cancel';
if (vdoNinjaConnectionCheckTimer) {
clearTimeout(vdoNinjaConnectionCheckTimer);
}
vdoNinjaConnectionCheckTimer = setTimeout(() => {
if (Date.now() - vdoNinjaLastActivityTime > 10000) {
logMessage("VDO.Ninja connection timed out. No activity received.");
vdoNinjaConnectionStatus.textContent = 'Status: Connection Failed';
vdoNinjaConnectBtn.textContent = 'Connect to VDO.Ninja';
}
}, 10000);
toggleVdoNinjaInputs(true);
saveSettings();
}
function addNewStreamMapping(streamId = '', label = '', sceneName = '', matchType = 'streamId', shouldClone = true, shouldSwitch = false) {
const streamMappings = document.getElementById('streamMappings');
const mappingDiv = document.createElement('div');
mappingDiv.className = 'stream-mapping';
mappingDiv.style.margin = '5px 0';
mappingDiv.innerHTML = `
<div style="margin-bottom: 5px;">
<label style="font-size: 11px; margin-bottom: 2px; display: block;">Stream Mapping</label>
<div class="flex-row" style="align-items: center; flex-wrap: nowrap; margin-bottom: 2px;">
<input type="text" placeholder="Stream ID" value="${streamId instanceof PointerEvent ? '' : streamId}" class="mapping-stream-id" style="width:80px; margin-right: 4px;">
<input type="text" placeholder="Label (optional)" value="${label}" class="mapping-label" style="width:120px; margin-right: 4px;">
<select class="mapping-match-type" style="width:90px; margin-right: 4px;">
<option value="streamId" ${matchType === 'streamId' ? 'selected' : ''}>ID Only</option>
<option value="label" ${matchType === 'label' ? 'selected' : ''}>Label Only</option>
<option value="both" ${matchType === 'both' ? 'selected' : ''}>Both Required</option>
<option value="either" ${matchType === 'either' ? 'selected' : ''}>Either Match</option>
</select>
<select class="mapping-scene-name" style="width:130px;">
<option value="">Select a scene...</option>
</select>
<button class="remove-mapping-btn" style="width:auto; padding:3px 5px; margin-left: 4px;">×</button>
</div>
<div class="flex-row" style="margin-top: 3px; gap: 8px;">
<label class="checkbox-label" style="margin-bottom: 0;">
<input type="checkbox" class="mapping-clone-to-main" ${shouldClone ? 'checked' : ''}>
Clone to main scene
</label>
<label class="checkbox-label" style="margin-bottom: 0;">
<input type="checkbox" class="mapping-switch-to-scene" ${shouldSwitch ? 'checked' : ''}>
Switch to scene on add
</label>
</div>
<small style="color: #8a8a9a; font-size: 10px; display: block; margin-top: 2px;">
ID Only: Match by Stream ID only | Label Only: Match by label only |
Both Required: Must match both | Either Match: Match if either matches
</small>
</div>
`;
streamMappings.appendChild(mappingDiv);
const sceneDropdown = mappingDiv.querySelector('.mapping-scene-name');
// Populate dropdown with existing scenes
populateSceneDropdown(obsScenes, sceneDropdown);
// Set the scene name if provided and valid
if (sceneName && obsScenes.some(scene => scene.sceneName === sceneName)) {
sceneDropdown.value = sceneName;
}
const removeBtn = mappingDiv.querySelector('.remove-mapping-btn');
removeBtn.addEventListener('click', () => {
mappingDiv.remove();
saveSettings();
});
const inputs = mappingDiv.querySelectorAll('input, select');
inputs.forEach(input => {
input.addEventListener('change', saveSettings);
});
}
function setupStreamMappingUI() {
const streamMappingContainer = document.getElementById('streamMappingContainer');
const addStreamMappingBtn = document.getElementById('addStreamMappingBtn');
// If you decide to remove the global "cloneToMainScene" checkbox, remove the following block
/*
const cloneCheckboxDiv = document.createElement('div');
cloneCheckboxDiv.innerHTML = `
<label class="checkbox-label">
<input type="checkbox" id="cloneToMainScene">
Also clone mapped streams to main scene
</label>
`;
// Ensure streamMappingContainer.parentNode exists if you keep this
if (streamMappingContainer.parentNode) {
streamMappingContainer.parentNode.insertAdjacentElement('afterend', cloneCheckboxDiv);
const cloneCheckbox = document.getElementById('cloneToMainScene');
if (cloneCheckbox) {
cloneCheckbox.addEventListener('change', saveSettings);
}
}
*/
// Corrected event listener for adding new stream mapping
addStreamMappingBtn.addEventListener('click', () => {
addNewStreamMapping(); // Call without arguments
});
loadStreamMappings();
}
function loadSettings() {
const settingsJson = localStorage.getItem('obsNinjaSettings');
if (settingsJson) {
try {
const settings = JSON.parse(settingsJson);
obsWsUrlInput.value = settings.obsWsUrl || '';
obsWsPasswordInput.value = settings.obsWsPassword || '';
vdoNinjaRoomInput.value = settings.vdoNinjaRoom || '';
vdoNinjaPasswordInput.value = settings.vdoNinjaPassword || '';
vdoNinjaStreamIdsInput.value = settings.vdoNinjaStreamIds || '';
obsSceneSelect.value = settings.obsSceneName || '';
sourceSizingSelect.value = settings.sourceSizing || 'autoGrid';
autoAddSourcesCheckbox.checked = settings.autoAddSources !== false;
autoRemoveSourcesCheckbox.checked = settings.autoRemoveSources !== false;
// Removed loading for 'cloneToMainScene' if you remove the global checkbox
/*
if (document.getElementById('cloneToMainScene') && typeof settings.cloneToMainScene !== 'undefined') {
document.getElementById('cloneToMainScene').checked = settings.cloneToMainScene;
}
*/
if (settings.vdoNinjaConnected) {
// connectToVdoNinja(); // User can reconnect manually
}
} catch (e) {
logMessage(`Error loading settings: ${e.message}`);
localStorage.removeItem('obsNinjaSettings');
}
} else {
sourceSizingSelect.value = 'autoGrid';
}
setupStreamMappingUI(); // Call this after other settings are potentially loaded
}
function updateStreamList() {
console.log("Updating stream list with:", activeStreams);
if (Object.keys(activeStreams).length === 0) {
streamListContainer.innerHTML = '<div class="stream-item">No active streams</div>';
return;
}
streamListContainer.innerHTML = '';
for (const streamId in activeStreams) {
const stream = activeStreams[streamId];
const streamDiv = document.createElement('div');
streamDiv.className = 'stream-item';
const targetInfo = getTargetSceneForStream(streamId, stream.label);
const targetSceneName = targetInfo.scene; // This is the scene name string
const isDefaultScene = targetSceneName === getTargetScene();
streamDiv.innerHTML = `
<div style="font-weight: bold;">${stream.label || streamId}</div>
<small>ID: ${streamId}${stream.label ? ` | Label: ${stream.label}` : ''}</small>
<small style="display: block; color: #8a8a9a;">
→ Target Scene: ${targetSceneName} ${isDefaultScene ? '(default)' : '(mapped)'}
</small>
${stream.sourceCreated ? '<span style="color:#4CAF50"> ✓ Added to OBS</span>' : ''}
<button class="add-stream-btn" data-stream-id="${streamId}" style="margin-top: 3px;">Add to OBS</button>
`;
streamListContainer.appendChild(streamDiv);
const btn = streamDiv.querySelector('.add-stream-btn');
btn.addEventListener('click', () => {
// Pass the targetInfo object which contains { scene: sceneName, mapping: mappingObject }
addStreamToObs(streamId, stream.label, targetInfo);
});
}
console.log("Stream list updated:", streamListContainer.innerHTML);
}
obsConnectBtn.addEventListener('click', () => {
if (obsConnected && obs) {
logMessage("Disconnecting from OBS WebSocket...");
if (obs) {
obs.close();
obs = null;
}
} else {
connectToOBS();
}
});
function getTargetSceneForStream(streamId, streamLabel = '') {
const mappings = getStreamMappings();
const defaultTargetScene = getTargetScene(); // The scene selected in the main "Target Scene" dropdown
for (const mapping of mappings) {
let isMatch = false;
switch (mapping.matchType) {
case 'streamId': isMatch = mapping.streamId && streamId === mapping.streamId; break;
case 'label': isMatch = mapping.label && streamLabel && streamLabel === mapping.label; break;
case 'both': isMatch = mapping.streamId && mapping.label && streamId === mapping.streamId && streamLabel === mapping.label; break;
case 'either': isMatch = (mapping.streamId && streamId === mapping.streamId) || (mapping.label && streamLabel && streamLabel === mapping.label); break;
}
if (isMatch && mapping.sceneName) { // Ensure mapping has a scene
return { scene: mapping.sceneName, mapping: mapping }; // Return object with scene name and full mapping
}
}
return { scene: defaultTargetScene, mapping: null }; // Default to main target scene if no match or mapping has no scene
}
function updateSceneDropdowns() {
// Store current values before updating dropdowns
const currentMainValue = obsSceneSelect.value;
const mappingSelects = document.querySelectorAll('.mapping-scene-name');
const currentMappingValues = Array.from(mappingSelects).map(select => select.value);
// Update main scene dropdown
populateSceneDropdown(obsScenes, obsSceneSelect);
// Restore main scene selection if still valid
if (currentMainValue && obsScenes.some(scene => scene.sceneName === currentMainValue)) {
obsSceneSelect.value = currentMainValue;
}
// Update and restore mapping scene dropdowns
mappingSelects.forEach((select, index) => {
populateSceneDropdown(obsScenes, select);
if (currentMappingValues[index] && obsScenes.some(scene => scene.sceneName === currentMappingValues[index])) {
select.value = currentMappingValues[index];
}
});
}
function loadStreamMappings() {
const settingsJson = localStorage.getItem('obsNinjaStreamMappings');
if (settingsJson) {
try {
const mappings = JSON.parse(settingsJson);
for (const mapping of mappings) {
addNewStreamMapping(
mapping.streamId,
mapping.label,
mapping.sceneName,
mapping.matchType,
mapping.cloneToMain !== undefined ? mapping.cloneToMain : true,
mapping.switchToScene !== undefined ? mapping.switchToScene : false
);
}
// If scenes are already loaded, update the dropdowns
if (obsScenes && obsScenes.length > 0) {
updateSceneDropdowns();
}
} catch (e) {
logMessage(`Error loading stream mappings: ${e.message}`);
}
}
}
function getStreamMappings() {
const mappings = [];
const mappingDivs = document.querySelectorAll('.stream-mapping');
mappingDivs.forEach(div => {
const streamId = div.querySelector('.mapping-stream-id').value.trim();
const label = div.querySelector('.mapping-label').value.trim();
const matchType = div.querySelector('.mapping-match-type').value;
const sceneName = div.querySelector('.mapping-scene-name').value.trim();
const cloneToMain = div.querySelector('.mapping-clone-to-main').checked;
const switchToScene = div.querySelector('.mapping-switch-to-scene').checked;
if (sceneName && (streamId || label)) { // Ensure a scene and some identifier exists
mappings.push({ streamId, label, matchType, sceneName, cloneToMain, switchToScene });
}
});
return mappings;
}
async function connectToOBS() {
let url = obsWsUrlInput.value.trim();
const password = obsWsPasswordInput.value;
if (!url) {
logMessage("Error: OBS WebSocket URL is required.");
return;
}
if (!url.startsWith('ws://') && !url.startsWith('wss://')) {
url = 'ws://' + url;
obsWsUrlInput.value = url;
}
obsConnectionStatus.textContent = 'Status: Connecting...';
obsStatusIndicator.classList.remove('connected', 'error');
logMessage(`Attempting to connect to OBS at ${url}...`);
const connectionTimeoutId = setTimeout(() => {
if (obs && obs.readyState !== WebSocket.OPEN) {
logMessage("Connection attempt timed out");
if (obs) { try { obs.close(); } catch (e) {} obs = null; }
obsConnectionStatus.textContent = 'Status: Error - Connection timed out';
obsStatusIndicator.classList.add('error');
}
}, 10000);
try {
obs = new WebSocket(url);
obs.onopen = () => logMessage("WebSocket connection opened. Waiting for Hello message...");
obs.onmessage = async (event) => {
try {
const message = JSON.parse(event.data);
if (message.op === 0) { // Hello
logMessage("Received Hello from OBS WebSocket server");
// logMessage(JSON.stringify(message)); // Optional: raw hello message
try {
const identifyPayload = { op: 1, d: { rpcVersion: 1, eventSubscriptions: (1 << 0) | (1 << 1) } };
if (message.d && message.d.authentication) {
const { challenge, salt } = message.d.authentication;
if (password) {
identifyPayload.d.authentication = await generateAuthResponse(password, salt, challenge);
logMessage("Authentication data prepared");
} else { logMessage("Warning: Server requires authentication but no password provided"); }
}
// logMessage("Sending Identify message: " + JSON.stringify(identifyPayload)); // Optional: raw identify
obs.send(JSON.stringify(identifyPayload));
} catch (error) {
logMessage(`Error during authentication setup: ${error.message}`);
if (obs) obs.close();
}
} else if (message.op === 2) { // Identified (auth success)
clearTimeout(connectionTimeoutId);
logMessage("OBS Authentication successful!");
obsConnected = true;
obsConnectBtn.textContent = 'Disconnect';
obsConnectBtn.classList.add('connected');
obsConnectBtn.classList.remove('disconnected');
obsConnectionStatus.textContent = 'Status: Connected';
obsStatusIndicator.classList.add('connected');
onObsConnected();
} else if (message.op === 7) { // RequestResponse
if (message.d && message.d.requestId && requestCallbacks[message.d.requestId]) {
requestCallbacks[message.d.requestId](message.d);
delete requestCallbacks[message.d.requestId];
}
if (message.d && message.d.requestStatus && message.d.requestStatus.code !== 100) {
logMessage(`OBS Request Error (${message.d.requestType || 'Unknown'}): ${message.d.requestStatus.comment || 'Unknown error'}`);
}
} else if (message.op === 5) { // Event
logMessage(`Received event: ${message.d ? message.d.eventType : 'Unknown'}`);
} else {
// logMessage(`Received message op ${message.op}: ${JSON.stringify(message)}`); // Optional: other messages
}
} catch (error) { logMessage(`Error processing WebSocket message: ${error.message}`); }
};
obs.onerror = (error) => {
clearTimeout(connectionTimeoutId);
logMessage(`OBS WebSocket Error: ${error.message || 'Unknown WebSocket error'}`);
obsStatusIndicator.classList.add('error');
obsConnectionStatus.textContent = 'Status: Error';
};
obs.onclose = (event) => {
clearTimeout(connectionTimeoutId);
let closeReason = event.code ? `Code: ${event.code}` : 'Unknown reason';
if (event.code === 4009) closeReason = 'Authentication Failed - incorrect password';
logMessage(`OBS WebSocket Connection Closed. ${closeReason}`);
obsConnected = false;
obsConnectBtn.textContent = 'Connect to OBS';
obsConnectBtn.classList.remove('connected');
obsConnectBtn.classList.add('disconnected');
obsConnectionStatus.textContent = 'Status: Disconnected';
obsStatusIndicator.classList.remove('connected', 'error');
onObsDisconnected();
};
} catch (error) {
clearTimeout(connectionTimeoutId);
logMessage(`Error creating WebSocket connection: ${error.message}`);
obsConnectionStatus.textContent = 'Status: Error';
obsStatusIndicator.classList.add('error');
}
}
async function generateAuthResponse(password, salt, challenge) {
try {
const encoder = new TextEncoder();
const secretString = password + salt;
const secretData = encoder.encode(secretString);
let secretHash;
if (window.crypto && window.crypto.subtle) {
const hashBuffer = await window.crypto.subtle.digest('SHA-256', secretData);
secretHash = new Uint8Array(hashBuffer);
} else {
await loadJsShaLibrary(); // Ensure jsSHA is loaded
const shaObj = new jsSHA("SHA-256", "TEXT", { encoding: "UTF8" });
shaObj.update(secretString);
const hashHex = shaObj.getHash("HEX");
secretHash = new Uint8Array(hashHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}
const secretBase64 = btoa(String.fromCharCode.apply(null, secretHash));
const authString = secretBase64 + challenge;
const authData = encoder.encode(authString);
let authHash;
if (window.crypto && window.crypto.subtle) {
const hashBuffer = await window.crypto.subtle.digest('SHA-256', authData);
authHash = new Uint8Array(hashBuffer);
} else {
// jsSHA already loaded
const shaObj = new jsSHA("SHA-256", "TEXT", { encoding: "UTF8" });
shaObj.update(authString);
const hashHex = shaObj.getHash("HEX");
authHash = new Uint8Array(hashHex.match(/.{1,2}/g).map(byte => parseInt(byte, 16)));
}
return btoa(String.fromCharCode.apply(null, authHash));
} catch (error) {
logMessage(`Auth generation error: ${error.message}`);
throw error;
}
}
function sendRequest(requestType, requestData = {}) {
return new Promise((resolve, reject) => {
if (!obsConnected || !obs) { reject(new Error("Not connected to OBS")); return; }
const requestId = generateRequestId(requestType);
requestCallbacks[requestId] = (response) => {
if (response.requestStatus.code === 100) resolve(response.responseData || {});
else reject(new Error(`Request ${requestType} failed: ${response.requestStatus.comment}`));
};
const request = { op: 6, d: { requestType, requestId, requestData } };
try { obs.send(JSON.stringify(request)); }
catch (error) { delete requestCallbacks[requestId]; reject(error); }
setTimeout(() => {
if (requestCallbacks[requestId]) {
delete requestCallbacks[requestId];
reject(new Error(`Request timeout for ${requestType}`));
}
}, 5000);
});
}
function onObsConnected() {
logMessage("OBS Connected. Fetching scenes...");
// Fetch scenes first, then handle VDO.Ninja connection
fetchObsScenes().then(() => {
// Now that scenes are loaded, check if VDO.Ninja should be reconnected
const settingsJson = localStorage.getItem('obsNinjaSettings');
if (settingsJson) {
try {
const settings = JSON.parse(settingsJson);
if (settings.vdoNinjaConnected && (settings.vdoNinjaRoom || settings.vdoNinjaStreamIds)) {
connectToVdoNinja();
}
} catch (e) {
logMessage(`Error re-connecting VDO.Ninja: ${e.message}`);
}
}
// Apply auto-grid after everything is loaded
if (sourceSizingSelect.value === 'autoGrid') {
setTimeout(rearrangeAllStreamsInScene, 1000, getTargetScene());
}
});
}
function onObsDisconnected() {
logMessage("OBS Disconnected.");
for (const streamId in activeStreams) {
activeStreams[streamId].sourceCreated = false;
}
updateStreamList();
}
async function fetchObsScenes() {
if (!obsConnected || !obs) return;