-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathscreen.js
More file actions
4825 lines (4502 loc) · 234 KB
/
Copy pathscreen.js
File metadata and controls
4825 lines (4502 loc) · 234 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
// ── Desktop-bridge back-compat ──────────────────────────────────────────────
// The host renamed window.slopsmithDesktop → window.feedBackDesktop
// (got-feedback/feedBack-desktop#40). On desktop builds that still expose only
// the legacy name, alias it so the feedBackDesktop reads below work on every
// desktop in any release order. No-op in the browser and on the new bridge.
try {
if (typeof window !== 'undefined' && !window.feedBackDesktop && window.slopsmithDesktop) {
window.feedBackDesktop = window.slopsmithDesktop;
}
} catch (_) { /* frozen window — ignore */ }
(function () {
'use strict';
/* ======================================================================
* Split Screen Plugin
* Creates 2-4 independent highway panels, each showing a different
* arrangement from the same song. All panels sync to the shared
* <audio> element.
* ====================================================================== */
const LAYOUTS = {
'top-bottom': { panels: 2, style: 'flex-col' },
'left-right': { panels: 2, style: 'flex-row' },
'tri-top': { panels: 3, style: 'grid-tri' },
'tri-bottom': { panels: 3, style: 'grid-tri' },
'quad': { panels: 4, style: 'grid-2x2' },
};
const OFF_CLASS = 'px-3 py-1.5 bg-dark-600 hover:bg-dark-500 rounded-lg text-xs text-gray-300 transition';
const ON_CLASS = 'px-3 py-1.5 bg-blue-900/50 hover:bg-blue-900/60 rounded-lg text-xs text-blue-300 transition';
// v3 host exposes a stable plugin-control slot (the Plugins rail popover).
function _ssIsV3() {
return !!(window.slopsmith && window.slopsmith.uiVersion === 'v3');
}
// Returns the slot element in v3, or null (classic UI / unavailable).
function _ssPlayerControlSlot() {
if (!(_ssIsV3() && window.slopsmith.ui && typeof window.slopsmith.ui.playerControlSlot === 'function')) return null;
try { const s = window.slopsmith.ui.playerControlSlot(); return s instanceof Element ? s : null; }
catch (_e) { return null; }
}
const STORAGE_KEY = 'splitscreenPanelPrefs';
const LYRICS_VALUE = '__lyrics__';
const JUMPING_TAB_VALUE = '__jumping_tab__';
const VIZ_PREFIX = '__viz__';
// Per-panel input channel selection. Keys stay strings for backward-compat with
// saved prefs and to keep the `|| 'mono'` defaults safe (channel 0 would be a
// falsy integer). 'left'/'right' are input channels 1/2; 'M' = mono mix.
// DETECT_CHANNEL_VALUE maps each to the engine channel index (-1 = mono mix, else
// 0-based). Multi-channel selection (channels 3+ of one interface) is DEFERRED —
// it needs the device's real channel count + capture-mode-aware gating in the
// detector; the validated multi-device flow binds ONE device per panel via the
// device picker, so mono/left/right is sufficient. A saved 'ch3'+ pref clamps to
// mono on load (see setupDetect).
const DETECT_CHANNEL_CYCLE = ['mono', 'left', 'right'];
const DETECT_CHANNEL_LABELS = { mono: 'M', left: '1', right: '2' };
const DETECT_CHANNEL_VALUE = { mono: -1, left: 0, right: 1 };
// Phase 2 multi-device: lazily assign a stable engine deviceKey (1..3) to each
// distinct ADDITIONAL input device a panel picks, so two panels on two separate
// interfaces each get their own own-clock source. "Main" (the primary input)
// stays deviceKey 0 and is never bound here. The engine caps extra devices at 3.
const SS_MAX_EXTRA_DEVICES = 3;
const _ssDeviceKeyByName = new Map(); // device name -> deviceKey (1..3)
let _ssMainDetectWasOn = false; // restore the main-player detector on teardown
// Whether split mode currently owns detection (the default singleton is suppressed).
// Splitscreen-owned (don't read note_detect's internal flag), so a rebuild knows to
// KEEP the captured _ssMainDetectWasOn instead of re-capturing it after the
// singleton was already disabled (which would lose the original on-state).
let _ssDetectSuppressed = false;
// True while teardownPanels() runs as part of a REBUILD (resize / arrangement
// switch) that immediately restarts. In that case we must NOT release the extra
// input devices or restore the main detector: doing so unbinds the interfaces and
// then rebinds them a tick later (async unbind racing the rebind can hand a panel
// a stale device), plus blips the main HUD. Real stops leave it false → full
// cleanup. Set only by rebuildLayout(), around its synchronous teardown.
let _ssTransientTeardown = false;
// Resolves when the previous session's extra-device unbinds have completed.
// A teardown fires unbindInputDevice() (async) and frees the deviceKeys; the next
// session must NOT rebind a key before its old device is actually released, or the
// late-completing unbind tears down the freshly-rebound device. _ssApplyDevice()
// awaits this before binding. Resolved (no-op) when nothing is pending.
let _ssDeviceReleaseBarrier = Promise.resolve();
// Bumped on every REAL stop (full teardown, not a rebuild). An in-flight
// _ssApplyDeviceImpl captures it and, if it finds itself on a detached panel,
// uses it to tell a real stop (release the device it just bound — the stop's
// unbind-all ran before this late bind) from a rebuild (the binding is preserved
// + likely reused by the new panel, so leave it).
let _ssRealStopGen = 0;
// Allocate the lowest free deviceKey (reusing keys freed by unbind), so
// switching devices doesn't leak keys until the pool is exhausted.
function _ssResolveDeviceKey(name) {
if (_ssDeviceKeyByName.has(name)) return _ssDeviceKeyByName.get(name);
const used = new Set(_ssDeviceKeyByName.values());
for (let k = 1; k <= SS_MAX_EXTRA_DEVICES; k++)
if (!used.has(k)) { _ssDeviceKeyByName.set(name, k); return k; }
return -1; // all keys in use
}
const _ssAudio = () =>
(typeof window !== 'undefined' && window.feedBackDesktop && window.feedBackDesktop.audio) || null;
// Suppress / restore the note_detect default singleton (so it doesn't render a
// duplicate HUD over panel 1 in split mode). Prefer the plugin's own setter so the
// mechanism stays owned by note_detect; fall back to the shared flag on an older build.
function _ssSetDefaultSuppressed(v) {
const cnd = (typeof window !== 'undefined') ? window.createNoteDetector : null;
if (cnd && typeof cnd.setDefaultSuppressed === 'function') cnd.setDefaultSuppressed(v);
else if (typeof window !== 'undefined') window.__ndSuppressDefault = !!v;
}
// Unbind an extra device once NO panel is using it, freeing its engine slot +
// deviceKey. Called when a panel switches away from a device (or is torn down),
// so re-picking devices can't accumulate stale binds (which crossed sources +
// duplicated scores). No-op for "" (Main) or a device another panel still uses.
async function _ssMaybeUnbindDevice(name) {
if (!name) return;
// Still in use if a panel currently has it OR is mid-bind to it (an in-flight
// handoff hasn't written detectDeviceName yet — without _ssPendingDeviceName we
// would unbind the device a concurrently-binding panel is about to depend on).
if (panels.some(p => p && (p.detectDeviceName === name || p._ssPendingDeviceName === name)))
return;
const key = _ssDeviceKeyByName.get(name);
_ssDeviceKeyByName.delete(name);
const audio = _ssAudio();
if (key != null && audio && typeof audio.unbindInputDevice === 'function') {
// Register the unbind in the release barrier BEFORE awaiting, so a quick
// switch back to this device (its key is now free) waits for the old
// unbind to finish instead of rebinding the key and then having the late
// unbind tear the fresh binding down (the A→B→A race).
const p = Promise.resolve(audio.unbindInputDevice(key)).catch(() => {});
_ssDeviceReleaseBarrier = Promise.allSettled([_ssDeviceReleaseBarrier, p]);
await p;
}
}
let active = false;
let controlsHidden = false;
let layout = localStorage.getItem('splitscreenLayout') || 'top-bottom';
let alwaysSplit = localStorage.getItem('splitscreenAlwaysSplit') === 'true';
let panels = []; // { hw, canvas, ws, arrIndex, controls }
let wrap = null;
let currentFilename = null;
let arrangements = []; // arrangement list from song_info
let vizPlugins = []; // {id, name, ...} — type=visualization plugins from /api/plugins
let _starting = false; // re-entrancy guard for startSplitScreen
let _pendingRebuild = false; // rebuildLayout requested while a start is in flight
// Redock requests ({popupId, finalState}) that arrived while a start was in
// flight — drained in startSplitScreen()'s finally, same pattern as
// _pendingRebuild. Without this a popup's `docked` message landing during
// the post-pop-out rebuild would teardown the half-built layout mid-flight.
let _pendingRedocks = [];
// Core swaps a panel's <canvas> element when a renderer needs a different
// context type than the one the canvas is bound to (browsers lock a canvas
// to its first getContext type) — e.g. installing 3D Highway (webgl2) on a
// freshly-2D canvas. After the swap our panel.canvas points at the detached
// old element, so every later hw.resize() (bar toggle, window resize,
// layout change) writes geometry to a dead node and the live canvas stays
// frozen at its init-time size — leaving an empty strip at the panel bottom.
// Re-bind to the new element and re-fit. Registered once; harmless when no
// panel owns the swapped canvas (e.g. the main-player highway swapping).
if (window.slopsmith && typeof window.slopsmith.on === 'function') {
window.slopsmith.on('highway:canvas-replaced', (e) => {
const d = e && e.detail;
if (!d || !d.oldCanvas || !d.newCanvas) return;
const p = panels.find((pp) => pp.canvas === d.oldCanvas);
if (!p) return;
p.canvas = d.newCanvas;
try { p.hw.resize(); } catch (_) { /* highway may be mid-teardown */ }
});
// Broadcast song changes to any popped-out follower windows. This
// used to live inside the post-`await _play()` `_onReady` callback
// in our playSong wrapper, but an upstream wrapper that throws
// (capo's _capoInjectBadge has been seen failing in v3) would
// skip the entire post-await block — popups stayed stuck on the
// old chart and the song-change toast never appeared. core's
// `song:ready` event fires from highway.js directly on the WS
// `ready` message, independent of any wrapper, so subscribing
// here keeps the broadcast firing even when the wrapper chain
// throws. The popup's `currentFilename !== msg.filename` guard
// already absorbs the no-op case (initial pop-out, where popup
// and main agree on the song).
window.slopsmith.on('song:ready', () => {
if (FOLLOWER) return;
if (!currentFilename) return;
const msg = { type: 'song-changed', filename: currentFilename };
if (typeof ssChannel !== 'undefined' && ssChannel && popups && popups.size) {
try { ssChannel.postMessage(msg); }
catch (e) { console.warn('[splitscreen] song-changed broadcast failed:', e); }
}
_lanSend(msg); // no-op unless a LAN share is active
});
}
// Focus model — which panel currently "owns" multi-instance plugin
// resources (MIDI input routing for piano, settings-gear placement, etc).
// Defaults to panel 0; clicking another panel transfers focus.
let focusedPanelIdx = 0;
const focusListeners = new Set();
function _focusedPanel() {
if (!active || !panels.length) return null;
if (focusedPanelIdx >= panels.length) focusedPanelIdx = 0;
return panels[focusedPanelIdx];
}
function _emitFocusChange() {
for (const fn of focusListeners) {
try { fn(); } catch (_) { /* listener errors must not break peers */ }
}
}
function _applyFocusBorder() {
for (let i = 0; i < panels.length; i++) {
panels[i].panelDiv.style.borderColor = i === focusedPanelIdx ? '#4080e0' : '#333';
}
}
function _setFocusedPanel(idx) {
if (idx < 0 || idx >= panels.length) return;
if (idx === focusedPanelIdx) return;
focusedPanelIdx = idx;
_applyFocusBorder();
_emitFocusChange();
}
function _findPanelIdxByCanvas(canvas) {
if (!canvas) return -1;
for (let i = 0; i < panels.length; i++) {
if (panels[i].canvas === canvas) return i;
}
return -1;
}
// Viz factory globals were renamed `window.slopsmithViz_<id>` ->
// `window.feedBackViz_<id>` in the feedBack rename (core's main-player picker
// and highway_3d register under the new name; core keeps the legacy name as a
// compat shim for third-party viz). Resolve BOTH so the per-panel picker finds
// a viz whether it registered under the new or the legacy global — otherwise a
// migrated viz (e.g. highway_3d) never shows up here.
const VIZ_FACTORY_PREFIXES = ['feedBackViz_', 'slopsmithViz_'];
function vizFactory(id) {
for (let i = 0; i < VIZ_FACTORY_PREFIXES.length; i++) {
const f = window[VIZ_FACTORY_PREFIXES[i] + id];
if (typeof f === 'function') return f;
}
return undefined;
}
function hasVizFactory(id) { return typeof vizFactory(id) === 'function'; }
let _vizPluginsFetchFailed = false;
async function fetchVizPlugins() {
try {
const resp = await fetch('/api/plugins');
const all = await resp.json();
// Store metadata for all viz plugins; factory presence is checked at
// populateSelect() time (not at fetch time), so the window['slopsmithViz_*']
// globals are evaluated when the dropdown is first built.
vizPlugins = (all || []).filter(p => p?.type === 'visualization');
} catch (_) {
// /api/plugins unavailable — fall back to scanning window for any
// slopsmithViz_* factories that are already loaded so viz options
// remain available even when the plugin registry can't be fetched.
// Mark fetch as failed so populateSelect re-scans on every build,
// preserving the "deferred plugin scripts are reflected" property
// even without a registry endpoint.
_vizPluginsFetchFailed = true;
_rescanVizPluginsFromWindow();
}
}
function _rescanVizPluginsFromWindow() {
const seen = new Set();
const found = [];
Object.keys(window).forEach(k => {
for (let i = 0; i < VIZ_FACTORY_PREFIXES.length; i++) {
const pfx = VIZ_FACTORY_PREFIXES[i];
if (k.startsWith(pfx) && typeof window[k] === 'function') {
const id = k.slice(pfx.length);
if (!seen.has(id)) { seen.add(id); found.push({ id, name: id }); }
break;
}
}
});
vizPlugins = found;
}
// Bounded poll for viz factories that register AFTER the picker is
// first built. /api/plugins returns metadata for every type:visualization
// plugin immediately, but each plugin's window.slopsmithViz_<id> factory
// only exists after the host has loaded and executed that plugin's
// screen.js. The host loads plugin scripts sequentially in loadPlugins()
// (alphabetical by directory). Two cases leave the picker missing
// entries when populateSelect() runs:
// - Plugins alphabetically after 'splitscreen' (tab_view, tuner, …)
// simply haven't been loaded yet when our IIFE runs.
// - Async plugins (e.g. highway_3d's `await import(CDN)` for Three.js)
// register their factory after their <script> onload fires, so even
// an alphabetically-earlier plugin can lag.
// Without this watch, the picker stays incomplete until the user
// triggers another populateSelect (song change, layout change) — which
// is exactly why "split-then-unsplit in the popup" used to be the only
// way to surface the missing viz options.
const _seenVizFactoryIds = new Set();
let _vizFactoryWatchTimer = null;
function _startVizFactoryWatch() {
if (_vizFactoryWatchTimer) return;
// Seed with factories already present so the first tick only fires
// on factories that appear AFTER we start watching.
vizPlugins.forEach(vp => {
if (hasVizFactory(vp.id)) {
_seenVizFactoryIds.add(vp.id);
}
});
const INTERVAL_MS = 200;
const MAX_TICKS = 60; // ~12 s — covers slow async plugins
let ticks = 0;
_vizFactoryWatchTimer = setInterval(() => {
ticks++;
let added = false;
vizPlugins.forEach(vp => {
if (!_seenVizFactoryIds.has(vp.id) && hasVizFactory(vp.id)) {
_seenVizFactoryIds.add(vp.id);
added = true;
}
});
if (added) {
// Re-populate every live panel's picker so the new viz
// options become available. populateSelect honours each
// panel's vizMode / lyricsMode / jumpingTabMode + arrIndex,
// so the user's current selection is preserved across the
// rebuild.
panels.forEach(p => {
if (p && p.select) populateSelect(p, p.arrIndex || 0);
});
}
const allPresent = vizPlugins.every(vp => hasVizFactory(vp.id));
if (allPresent || ticks >= MAX_TICKS) {
clearInterval(_vizFactoryWatchTimer);
_vizFactoryWatchTimer = null;
}
}, INTERVAL_MS);
}
// Keep the promise so startSplitScreen / loadSongInFollower can await it —
// panels are never populated before the list is ready even on a fast first
// interaction.
const _vizPluginsReady = fetchVizPlugins();
// ── LAN share helpers (splitscreen#21) ──
// Declared ABOVE the FOLLOWER/REMOTE_JOIN parse and the settings-sync
// block, both of which call into these during IIFE evaluation (the
// ROOM_KEY_* consts would otherwise be in their temporal dead zone).
// WS URL for the core session-sync relay endpoint (feedBack#1030).
function getSyncUrl(key) {
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
return `${proto}//${location.host}/ws/sync/${key}`;
}
// Room-key alphabet: unambiguity-filtered (no 0/O, 1/I/L, U) so a key can
// be read aloud across the room and typed on a TV remote without lookalike
// errors. 6 chars ≈ 30 bits — plenty for a trusted LAN: a wrong key just
// lands in an empty relay room, and the relay rate-caps scanning.
const ROOM_KEY_ALPHABET = 'ABCDEFGHJKMNPQRSTVWXYZ23456789';
const ROOM_KEY_LENGTH = 6;
function generateRoomKey() {
let out = '';
try {
const buf = new Uint32Array(ROOM_KEY_LENGTH);
crypto.getRandomValues(buf);
for (let i = 0; i < ROOM_KEY_LENGTH; i++) out += ROOM_KEY_ALPHABET[buf[i] % ROOM_KEY_ALPHABET.length];
} catch (_) {
for (let i = 0; i < ROOM_KEY_LENGTH; i++) out += ROOM_KEY_ALPHABET[Math.floor(Math.random() * ROOM_KEY_ALPHABET.length)];
}
return out;
}
// Case-insensitive entry: trim + uppercase, then validate against the
// alphabet. The filtered alphabet is what makes lookalike tolerance work —
// a generated key can never contain 0/O/1/I/L/U, so there is nothing to
// mis-map. Returns the canonical uppercase key, or null.
function normalizeRoomKey(raw) {
if (typeof raw !== 'string') return null;
const key = raw.trim().toUpperCase();
if (key.length !== ROOM_KEY_LENGTH) return null;
for (const c of key) {
if (ROOM_KEY_ALPHABET.indexOf(c) === -1) return null;
}
return key;
}
// The persistent per-install room key (splitscreen#21: saved and reused so
// viewer bookmarks keep working across sessions; rotate via the settings
// page's Regenerate button).
function ensureRoomKey() {
let key = null;
try { key = normalizeRoomKey(localStorage.getItem('splitscreenRoomKey')); } catch (_) {}
if (!key) {
key = generateRoomKey();
try { localStorage.setItem('splitscreenRoomKey', key); } catch (_) {}
}
return key;
}
function buildShareUrl(origin, key) {
return String(origin).replace(/\/+$/, '') + '/?ss=' + key;
}
// Build the FOLLOWER config for a remote viewer from a relay `config`
// message. Mirrors the URL-param parse shape, with two deliberate
// differences: `remote: true` (gates dock/close semantics) and the
// note-detect fields stripped — viewers are passive mirrors and must
// never inherit the host's mic/device bindings.
function makeRemoteFollowerCfg(msg, popupId) {
const cfg = (msg && msg.cfg) || {};
return {
remote: true,
popupId: popupId || '',
filename: msg.filename,
arrangement: parseInt(cfg.arrangement, 10) || 0,
name: cfg.name || '',
mode: cfg.mode || '2d',
inverted: cfg.inverted === 1 || cfg.inverted === true,
lefty: cfg.lefty === 1 || cfg.lefty === true,
mastery: Number.isFinite(cfg.mastery) ? cfg.mastery : NaN,
lyrics: !!cfg.lyrics,
barHidden: !!cfg.barHidden,
detectChannel: 'mono',
detectDeviceName: '',
detectVerifierOffsetMs: 0,
};
}
// ══════════════════════════════════════════════════════════════════════
// Pop-out / follower-mode (multi-monitor support).
//
// When the user clicks "Pop Out" on a panel in the main window, we open
// this same slopsmith app in a new browser window with `ssFollower=1`
// and a serialized panel config in URL params. The popup boots normally
// (loads app.js + all plugins) but the splitscreen IIFE detects the
// follower flag and instead of running the usual auto-Split UI, it
// builds a single full-window panel slaved to the main window's audio
// via BroadcastChannel('slopsmith-ss').
//
// popups: in the main window, tracks every popup we've spawned so we
// can re-instate the panel when the popup posts a `docked` message.
// Keyed by popupId. Entry: { popup, originalConfig } — `popup` is the
// window handle (so the broadcaster can reap a popup that died without
// firing beforeunload); `originalConfig` is the panel state at pop-out time.
//
// FOLLOWER: parsed once on script load. Truthy in the popup window
// only. Carries the panel config received from the opener.
// ══════════════════════════════════════════════════════════════════════
const popups = new Map();
// `let`, not `const`: a REMOTE (LAN) viewer boots with only `?ss=<room key>`
// in the URL and receives its panel config over the sync relay — FOLLOWER
// is assigned there (bootRemoteJoin), always before bootFollowerMode runs.
let FOLLOWER = (function () {
try {
const params = new URLSearchParams(window.location.search);
if (params.get('ssFollower') !== '1') return null;
const cfg = {
popupId: params.get('popupId') || '',
filename: params.get('filename') || '',
arrangement: parseInt(params.get('arrangement'), 10) || 0,
name: params.get('name') || '',
mode: params.get('mode') || '2d',
inverted: params.get('inverted') === '1',
lefty: params.get('lefty') === '1',
mastery: parseFloat(params.get('mastery')),
// User-driven per-panel toggles forwarded by the spawning
// window so the popup mirrors the source panel's state.
lyrics: params.get('lyrics') === '1',
barHidden: params.get('barHidden') === '1',
detectChannel: params.get('detectChannel') || 'mono',
detectDeviceName: params.get('detectDeviceName') || '',
detectVerifierOffsetMs: parseFloat(params.get('detectVerifierOffsetMs')) || 0,
};
if (!cfg.filename) return null;
return cfg;
} catch (_) {
return null;
}
})();
// Remote (LAN) viewer join key — `?ss=<room key>` (splitscreen#21). The
// URL carries ONLY the key so it stays hand-typeable; the panel config
// arrives over the server's /ws/sync relay (feedBack#1030) via the
// hello/config handshake in bootRemoteJoin. Null when absent/invalid.
const REMOTE_JOIN = (function () {
try {
if (FOLLOWER) return null; // explicit follower params win
const params = new URLSearchParams(window.location.search);
return normalizeRoomKey(params.get('ss'));
} catch (_) {
return null;
}
})();
const SS_CHANNEL_NAME = 'slopsmith-ss';
let ssChannel = null; // shared BroadcastChannel (lazily opened)
function _ssChannel() {
if (!ssChannel && typeof BroadcastChannel === 'function') {
ssChannel = new BroadcastChannel(SS_CHANNEL_NAME);
}
return ssChannel;
}
// Public API for plugins that want per-panel state (e.g. 3D Highway reads
// its per-panel palette/background settings via localStorage keys keyed
// by panel index, and calls panelIndexFor(canvas) to resolve which panel
// a canvas belongs to).
window.slopsmithSplitscreen = {
// Active state — false during normal main-player operation. Plugins
// gate their splitscreen-aware code paths on this so they fall back
// to the single-instance main-player path when the user isn't split.
isActive() { return active; },
// Identify a panel by the highway canvas its renderer received in init().
panelIndexFor(canvas) {
if (!active) return null;
const i = _findPanelIdxByCanvas(canvas);
return i === -1 ? null : i;
},
// Container element for per-panel chrome/overlays. Plugins that mount
// their own DOM (piano overlay canvas, drums HUD) anchor against this
// so the overlay sizes to the panel rect, not the whole #player.
panelChromeFor(canvas) {
if (!active) return null;
const i = _findPanelIdxByCanvas(canvas);
return i === -1 ? null : panels[i].panelDiv;
},
// Anchor for per-panel settings buttons (e.g. piano gear button).
// The mini control bar is the natural place — already visible, already
// panel-scoped, already used for invert/lyrics/tab/detect toggles.
settingsAnchorFor(canvas) {
if (!active) return null;
const i = _findPanelIdxByCanvas(canvas);
return i === -1 ? null : panels[i].bar;
},
// True when this canvas's panel is the focused one. Plugins use this
// to route shared input (e.g. MIDI keyboard) to a single instance.
isCanvasFocused(canvas) {
if (!active) return true; // no panels => main-player single instance
const i = _findPanelIdxByCanvas(canvas);
if (i === -1) return false;
if (focusedPanelIdx >= panels.length) focusedPanelIdx = 0;
return i === focusedPanelIdx;
},
onFocusChange(fn) {
if (typeof fn === 'function') focusListeners.add(fn);
},
offFocusChange(fn) {
focusListeners.delete(fn);
},
// Panel enumeration for cross-plugin consumers (e.g. Camera Director's
// panel selector). `name` is user-editable via the per-panel bar and
// persists; changes fire `splitscreen:panels-changed` on window.feedBack.
getPanels() {
if (!active) return [];
return panels.map((p, i) => ({
index: i, name: p.name || ('P' + (i + 1)),
canvas: p.canvas, focused: i === focusedPanelIdx, poppedOut: false,
}));
},
panelName(i) { return (panels[i] && panels[i].name) || (i != null ? ('P' + (i + 1)) : ''); },
setPanelName(i, name) {
if (!panels[i]) return;
const nm = String(name || '').trim().slice(0, 40) || ('P' + (i + 1));
panels[i].name = nm;
if (panels[i].nameInput) panels[i].nameInput.value = nm;
savePanelPrefs(); _emitPanelsChanged();
},
};
// Alias under the canonical name (slopsmith → feedBack rename in flight).
// Consumers should read `window.feedBackSplitscreen || window.slopsmithSplitscreen`.
window.feedBackSplitscreen = window.slopsmithSplitscreen;
// 3D Highway palette IDs. Mirrors the PALETTES registry in the 3dhighway
// plugin's screen.js — kept as a plain list here to avoid a runtime
// dependency on the plugin being loaded.
const H3D_PALETTES = [
{ id: 'default', label: 'Default' },
{ id: 'neon', label: 'Neon' },
{ id: 'pastel', label: 'Pastel' },
];
// Per-panel viz controls surfaced in a panel's "3D ⚙" popover. Each entry:
// { key, label, type:'toggle'|'range'|'select', default, min?, max?, step?, options? }
// `key` is the localStorage suffix the viz plugin reads per-panel. For
// highway_3d that's h3d_bg_panel<N>_<key>, falling back to the global
// h3d_bg_<key> (see the plugin's _bgReadSetting). A viz plugin can override
// this list at runtime by exposing `window.slopsmithViz_highway_3d.panelControls`
// (same shape) — that takes precedence so the plugin owns the up-to-date
// list without splitscreen needing edits when it adds options.
// For `range`: min/max default to 0..1 and step to 0.05 when omitted.
const VIZ_PANEL_CONTROLS = {
highway_3d: [
{ key: 'palette', label: 'Palette', type: 'select', default: 'default', options: H3D_PALETTES },
{ key: 'cameraSmoothing', label: 'Camera smoothing (X-pan)', type: 'range', default: 0.5, min: 0, max: 1, step: 0.05 },
{ key: 'cameraLockLow', label: 'Lock camera at frets 1–12',type: 'toggle', default: false },
{ key: 'cameraLockZoom', label: 'Locked zoom (In ↔ Out)', type: 'range', default: 0.5, min: 0, max: 1, step: 0.05 },
],
};
// Range-control bounds with defaults (min/max/step are optional in the descriptor).
function _ctlRange(ctl) {
return {
lo: Number.isFinite(ctl.min) ? ctl.min : 0,
hi: Number.isFinite(ctl.max) ? ctl.max : 1,
st: Number.isFinite(ctl.step) ? ctl.step : 0.05,
};
}
function getPanelControlsFor(pluginId) {
// v1: only highway_3d is wired — _vizPanelGet/_vizPanelSet use its
// localStorage scheme (h3d_bg_panel<N>_<key>) and its window.h3dBgSet*
// setters. The popover stays hidden for other viz plugins until the
// descriptor carries per-plugin storage/setter info (or read/write fns).
// A plugin can still customize *which* controls show via
// window.slopsmithViz_highway_3d.panelControls.
if (pluginId !== 'highway_3d') return null;
const fac = vizFactory(pluginId);
// An array (even empty) is an intentional override — empty = opt out of
// per-panel controls. _showVizControls hides the button on an empty list.
if (fac && Array.isArray(fac.panelControls)) return fac.panelControls;
return VIZ_PANEL_CONTROLS[pluginId] || null;
}
// ── Settings sync ──
const layoutSelect = document.getElementById('splitscreen-default-layout');
if (layoutSelect) {
layoutSelect.value = layout;
layoutSelect.addEventListener('change', () => {
layout = layoutSelect.value;
localStorage.setItem('splitscreenLayout', layout);
if (active) rebuildLayout();
});
}
const alwaysSplitCheckbox = document.getElementById('splitscreen-always-split');
if (alwaysSplitCheckbox) {
alwaysSplitCheckbox.checked = alwaysSplit;
alwaysSplitCheckbox.addEventListener('change', () => {
alwaysSplit = alwaysSplitCheckbox.checked;
localStorage.setItem('splitscreenAlwaysSplit', alwaysSplit);
});
}
// LAN room key (splitscreen#21) — display + Regenerate. The key is
// persistent by design (viewer bookmarks stay valid across sessions);
// regenerating rotates it and stops any live share, since its viewers
// would otherwise keep waiting on a room the host will never rejoin.
const roomKeyEl = document.getElementById('splitscreen-room-key');
if (roomKeyEl) {
roomKeyEl.textContent = ensureRoomKey();
const regenBtn = document.getElementById('splitscreen-room-key-regen');
if (regenBtn) {
regenBtn.addEventListener('click', () => {
const next = generateRoomKey();
try { localStorage.setItem('splitscreenRoomKey', next); } catch (_) {}
roomKeyEl.textContent = next;
if (_lanShare) {
stopLanShare();
_showMainToast('Room key regenerated — LAN sharing stopped. Share again to use the new key.');
}
});
}
}
// ── Panel preference persistence ──
// Snapshot a live panel into the splitscreenPanelPrefs entry shape. Mode is
// encoded into arrName (LYRICS_VALUE / JUMPING_TAB_VALUE:<arr> /
// VIZ_PREFIX:<id>:<arr> / plain arrangement name). Single source of truth
// for the encoding — used by savePanelPrefs (persist to localStorage),
// captureCurrentPrefs (in-memory, for rebuildLayout / _redockPanel) and
// popOutPanel (snapshot of the panels left behind). Keep all three on this
// helper so a new per-panel field is added once, not three times.
function panelToPrefs(p) {
return {
arrName: p.jumpingTabMode
? JUMPING_TAB_VALUE + ':' + (arrangements[p.arrIndex]?.name || '')
: p.vizMode
? VIZ_PREFIX + ':' + p.vizMode + ':' + (arrangements[p.arrIndex]?.name || '')
: p.lyricsMode ? LYRICS_VALUE : (arrangements[p.arrIndex]?.name || ''),
lyrics: !!p.lyricsOverlayOn,
inverted: p.hw.getInverted(),
lefty: p.hw.getLefty(),
detectChannel: p.detectChannel || 'mono',
detectDeviceName: p.detectDeviceName || '',
detectVerifierOffsetMs: p.detectVerifierOffsetMs || 0,
barHidden: p.bar.style.display === 'none',
mastery: p.hw.getMastery(),
name: p.name || '',
};
}
function savePanelPrefs() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(panels.map(panelToPrefs)));
}
// Notify cross-plugin consumers (e.g. Camera Director's panel selector) that
// the panel set or a panel name changed, via the window.feedBack event bus.
function _emitPanelsChanged() {
try { if (window.feedBack && typeof window.feedBack.emit === 'function') window.feedBack.emit('splitscreen:panels-changed'); } catch (_) { /* ignore */ }
}
// Commit an edited panel name (from the bar input): sanitize, store on the
// panel, persist, and notify. Empty falls back to the positional default.
function _commitPanelName(panelDiv, raw) {
const i = panels.findIndex((p) => p.panelDiv === panelDiv);
if (i === -1) return;
const name = String(raw || '').trim().slice(0, 40) || `P${i + 1}`;
if (panels[i].name === name) return;
panels[i].name = name;
if (panels[i].nameInput && panels[i].nameInput.value !== name) panels[i].nameInput.value = name;
savePanelPrefs();
_emitPanelsChanged();
}
function loadPanelPrefs() {
try {
return JSON.parse(localStorage.getItem(STORAGE_KEY)) || null;
} catch (_) {
return null;
}
}
// Migration version marker so one-time resets (e.g. the lyrics-overlay
// semantics flip) only run on prefs written by older code. Without this
// gate, a per-load migration would clobber the user's actual toggle
// state every reload — the overlay-on choice could never persist.
const PREFS_MIGRATION_KEY = 'splitscreenPrefsMigrationV';
const PREFS_CURRENT_V = 2;
function migratePanelPrefs(prefs) {
if (!Array.isArray(prefs)) return prefs;
let v = 0;
try { v = parseInt(localStorage.getItem(PREFS_MIGRATION_KEY) || '0', 10) || 0; }
catch (_) {}
const needsLyricsReset = v < 2;
const out = prefs.map(p => {
const next = { ...p };
// v < 2: previous `lyrics` field tracked highway's built-in
// setLyricsVisible (defaulted to true). The new overlay-driven
// toggle inherits that field, so existing users would otherwise
// see overlay-on everywhere on first load. Reset once; from then
// on the user-driven value round-trips normally.
if (needsLyricsReset) next.lyrics = false;
// Legacy 3D-Highway sentinel migration (pre-PR-36).
if (next.arrName?.startsWith('__3d_highway__:')) {
next.arrName = VIZ_PREFIX + ':highway_3d:' + next.arrName.slice('__3d_highway__:'.length);
}
return next;
});
if (v < PREFS_CURRENT_V) {
try { localStorage.setItem(PREFS_MIGRATION_KEY, String(PREFS_CURRENT_V)); }
catch (_) {}
}
return out;
}
function resolveArrIndex(arrName) {
if (!arrName || arrName === LYRICS_VALUE || arrName.startsWith(JUMPING_TAB_VALUE) || arrName.startsWith(VIZ_PREFIX + ':')) return -1;
const lower = arrName.toLowerCase();
for (let i = 0; i < arrangements.length; i++) {
if ((arrangements[i].name || '').toLowerCase() === lower) return i;
}
return -1;
}
// ── Helpers ──
function getWsUrl(filename, arrangement) {
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const arrParam = arrangement !== undefined ? `?arrangement=${arrangement}` : '';
// Match core highway.js (`decodeURIComponent(filename)` before
// building the WS URL — static/highway.js:3575). v3's songs.js
// calls `playSong(encodeURIComponent(localFilename))`, so
// `currentFilename` carries percent-encoded path separators
// (e.g. `sloppak%2Fperfouts.sloppak`). FastAPI's path-parameter
// router does NOT decode `%2F` into `/`, so the encoded form
// misses the route and the server returns "File not found",
// closing every panel WS instantly. Decode here to match the
// contract the rest of splitscreen already documents (CLAUDE.md
// "getWsUrl() handles this internally for highway connections").
//
// `currentFilename` is always the ENCODED form in both v2 and v3 — the
// grid renders `data-play="<encodeURIComponent(localFilename)>"`
// (app.js), v3's songs.js calls `playSong(enc(localFilename))`, and
// app.js's `player.start()` normalizes any raw name to the encoded
// form before calling playSong. So a single unconditional decode here
// mirrors core highway.js:3575 exactly and never sees a raw or
// malformed `%` (no try/catch needed — core doesn't guard it either).
const decoded = decodeURIComponent(filename);
return `${proto}//${location.host}/ws/highway/${decoded}${arrParam}`;
}
function getDefaultArrangements(count) {
// Assign arrangements intelligently: lead, rhythm, bass, then wrap
const defaults = [];
const byName = {};
arrangements.forEach((a, i) => {
const n = (a.name || '').toLowerCase();
if (n.includes('lead') && !byName.lead) byName.lead = i;
else if (n.includes('rhythm') && !byName.rhythm) byName.rhythm = i;
else if (n.includes('bass') && !byName.bass) byName.bass = i;
});
const order = [byName.lead, byName.rhythm, byName.bass].filter(i => i !== undefined);
// Fill remaining with whatever's available
for (let i = 0; i < arrangements.length; i++) {
if (!order.includes(i)) order.push(i);
}
for (let i = 0; i < count; i++) {
defaults.push(order[i % order.length]);
}
return defaults;
}
// ══════════════════════════════════════════════════════════════════════
// Lyrics-only pane renderer
// ══════════════════════════════════════════════════════════════════════
function createLyricsPane(container, opts) {
const overlay = !!(opts && opts.overlay);
const el = document.createElement('div');
el.className = overlay ? 'splitscreen-lyrics-overlay' : 'splitscreen-lyrics-pane';
// Overlay mode: top-anchored translucent band that floats above
// whatever renderer owns the canvas (default 2D, piano, drums, 3D
// Highway, ...). z-index 9 sits above bar (7) and barToggleBtn (8)
// so lyrics are always on top regardless of viz. pointer-events:none
// so toggles/clicks under it (including the canvas) still work.
// Full-pane mode: opaque, fills the panel — used for lyrics-only
// mode (canvas hidden), unchanged from before.
el.style.cssText = overlay
? 'position:absolute;top:0;left:0;right:0;height:auto;' +
'display:flex;flex-direction:column;justify-content:center;align-items:center;' +
'background:rgba(8,8,16,0.78);padding:10px 16px;overflow:hidden;' +
'pointer-events:none;z-index:9;'
: 'position:absolute;top:0;left:0;right:0;bottom:0;' +
'display:flex;flex-direction:column;justify-content:center;align-items:center;' +
'background:#08080e;padding:24px;overflow:hidden;';
container.appendChild(el);
let lyrics = [];
let lines = null;
let ws = null;
let raf = null;
function parseLyrics(data) {
lyrics = data;
lines = null;
if (!lyrics.length) return;
const result = [];
let line = null, word = null;
const flushWord = () => {
if (word && word.length) line.words.push(word);
word = null;
};
const flushLine = () => {
flushWord();
if (line && line.words.length) result.push(line);
line = null;
};
for (let i = 0; i < lyrics.length; i++) {
const l = lyrics[i];
const raw = l.w || '';
const endsLine = raw.endsWith('+');
const continuesWord = raw.endsWith('-');
if (line && i > 0) {
const prev = lyrics[i - 1];
if (l.t - (prev.t + prev.d) > 4.0) flushLine();
}
if (!line) line = { words: [], start: l.t, end: l.t + l.d };
if (!word) word = [];
word.push(l);
line.end = Math.max(line.end, l.t + l.d);
if (!continuesWord) flushWord();
if (endsLine) flushLine();
}
flushLine();
lines = result;
}
function syllableText(s) {
const t = s.w || '';
return (t.endsWith('+') || t.endsWith('-')) ? t.slice(0, -1) : t;
}
function renderLine(lineData, currentTime) {
const frag = document.createDocumentFragment();
for (const word of lineData.words) {
for (const syl of word) {
const span = document.createElement('span');
span.textContent = syllableText(syl);
const active = currentTime >= syl.t && currentTime < syl.t + syl.d;
const past = currentTime >= syl.t + syl.d;
if (active) {
span.style.color = '#60a0ff';
span.style.textShadow = '0 0 12px rgba(96,160,255,0.5)';
} else if (past) {
span.style.color = '#9ca3af';
} else {
span.style.color = '#555';
}
frag.appendChild(span);
}
const space = document.createDocumentFragment();
space.appendChild(document.createTextNode(' '));
frag.appendChild(space);
}
return frag;
}
function render() {
raf = requestAnimationFrame(render);
if (!lines || !lines.length) {
if (!el.dataset.empty) {
el.innerHTML = '<span style="color:#555;font-style:italic">No lyrics</span>';
el.dataset.empty = '1';
}
return;
}
delete el.dataset.empty;
const audio = document.getElementById('audio');
const t = audio ? audio.currentTime : 0;
let currentIdx = -1;
for (let i = 0; i < lines.length; i++) {
if (lines[i].start <= t) currentIdx = i;
else break;
}
if (currentIdx === -1) {
if (lines[0].start - t > 3.0) {
el.innerHTML = '';
return;
}
currentIdx = 0;
}
const currentLine = lines[currentIdx];
const nextLine = lines[currentIdx + 1] || null;
const gapToNext = nextLine ? (nextLine.start - currentLine.end) : Infinity;
if (t > currentLine.end + 1.0 && gapToNext > 4.0) {
el.innerHTML = '';
return;
}
el.innerHTML = '';
const curDiv = document.createElement('div');
curDiv.style.cssText = overlay
? 'font-size:clamp(14px, 2vw, 22px);font-weight:600;text-align:center;line-height:1.3;transition:opacity 0.3s;'
: 'font-size:clamp(20px, 4vw, 48px);font-weight:600;text-align:center;line-height:1.4;transition:opacity 0.3s;';
curDiv.appendChild(renderLine(currentLine, t));
el.appendChild(curDiv);
if (nextLine && gapToNext <= 4.0) {
const nextDiv = document.createElement('div');
nextDiv.style.cssText = overlay
? 'font-size:clamp(11px, 1.5vw, 17px);font-weight:400;text-align:center;line-height:1.3;margin-top:4px;color:#444;'
: 'font-size:clamp(16px, 3vw, 36px);font-weight:400;text-align:center;line-height:1.4;margin-top:16px;color:#444;';
nextDiv.appendChild(renderLine(nextLine, t));
el.appendChild(nextDiv);
}
}
function connect(filename, arrangement) {
destroy();
ws = new WebSocket(getWsUrl(filename, arrangement));
ws.onmessage = (ev) => {
const msg = JSON.parse(ev.data);
if (msg.type === 'lyrics') parseLyrics(msg.data);
};
ws.onerror = () => {};
ws.onclose = () => { ws = null; };
raf = requestAnimationFrame(render);
}
function destroy() {
if (raf) { cancelAnimationFrame(raf); raf = null; }
if (ws) { ws.close(); ws = null; }
lyrics = [];
lines = null;
el.innerHTML = '';
}
return { el, connect, destroy };
}
// ══════════════════════════════════════════════════════════════════════
// ── Layout ──
function createWrap() {
if (wrap) wrap.remove();
const player = document.getElementById('player');