-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tish
More file actions
3150 lines (3064 loc) · 127 KB
/
Copy pathApp.tish
File metadata and controls
3150 lines (3064 loc) · 127 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
import { useState, useRef, useEffect, h, Fragment, memo } from '@tishlang/lattish'
import { projectToJson, projectFromJson } from '../model/Project.tish'
import { channelDeck, crossfadeValue, crossfadeValueY } from '../model/DeckRouting.tish'
import { freshSetEnergy, freshActiveDecks, foldSetEnergyStep } from '../model/SetEnergy.tish'
import { loadDefaultDeckardProject, loadProjectFromTpl } from '../model/ProjectLoad.tish'
import { loadUserInstrumentPresets } from '../model/InstrumentPresets.tish'
import { createStationPresets } from '../core/StationPresets.tish'
import { cancelTtsVocal } from '@spacedevin/deck-synths'
import { emitLevel, retargetTpl } from '../core/Levels.tish'
import { createSetLibrary, emitSet, loadSet, freeDecks, emitSetStream, parseSetStream, isStreamSet } from '../core/SetLibrary.tish'
import { loadDeckSet, deckSetCatalog } from '../model/DeckSets.tish'
import { levelPresetList, addLevelPreset, findLevelPreset, removeLevelPreset } from '../model/LevelPresets.tish'
import { PresetBar } from './PresetBar.tish'
import { promptName, alertModal } from './PromptModal.tish'
import { IkSelect } from './InstrumentKit.tish'
import { emitProject, emitLivePlayback } from '../deckfile/Emit.tish'
import { CodeDebugView } from './CodeDebugView.tish'
import { migrateProjectGenerators } from '../model/Migrate.tish'
import { ensureAudio, updateMixerFromProject, resyncAllChannelBuses, applyCueRouting, applyOutputDevices, setCueLevel, setCueSyncOffset, setMainAutoSync, ensureCueOutput, suspendDrawsAround, drawsSuspended, setDrawDisabled, triggerMasterFxEcho, triggerMasterFxFilter, playHitAt, applyChannelFilterAutomation } from '../audio/Engine.tish'
import { createAudioDeviceSettings } from '../core/AudioDeviceSettings.tish'
import { AudioRackPanel } from './AudioRackPanel.tish'
import { MidiPanel } from './MidiPanel.tish'
import { SongBrowser } from './SongBrowser.tish'
import { loadScratchBuffer, setScratchRate, setScratchVolume, setScratchDucking, scratchHasBuffer, setScratchPos, setScratchCut, scratchSpin } from '../audio/Engine.tish'
import { renderDeckLoopToBuffer } from '../audio/Playback.tish'
import { createMidiController } from '../midi/Midi.tish'
import { transportTick } from '../audio/Playback.tish'
import { generatorChannelAtBeat } from '../audio/ParamAtBeat.tish'
import { secondsPerStep } from '../audio/Scheduler.tish'
import { createIngest, bumpAllRev, ensureProjectRev } from '../core/Ingest.tish'
import { createEditor } from '../core/Edit.tish'
import { createSignals } from '../core/Signals.tish'
import { createTransport } from '../audio/Transport.tish'
import { tplLoopResetAll } from '../deckfile/LoopState.tish'
import { TransportBar } from './Transport.tish'
import { collectActorLanes, channelActorLane, ensureActorMixerEntries } from '../model/MixerRouting.tish'
import { InstrumentStack } from './InstrumentStack.tish'
import { CoDjPanel } from './CoDjPanel.tish'
import { launchSceneDirective, transportDirective, fxDirective, cueDirective, deckMoveDirective } from '../codj/Launch.tish'
import { coDjClockPayload, coDjShouldFollow, coDjClockAlign, coDjIsFollower, coDjOwnDeckLetter } from '../codj/Transport.tish'
import {
PianoRollCanvas,
PianoRollZoomBar,
attachPianoRoll,
drawRackPianoPreview,
pianoRollVisualSig,
rackPianoPreviewSig,
updatePianoRollCtx
} from './PianoRoll.tish'
import { drawScopeCanvas, drawSpectrumCanvas, drawMiniWave, busPeakLevel, drawSetWaveLane, drawSetWaveOverlay } from './Scope.tish'
import { StepGridPanel, gridBarsForProject } from './grid/StepGrid.tish'
import { DeckMixer, applyDeckEq, ensureDeckEq, DeckJog, VinylRow, deckEntries, DeckChannelStrip } from './deck/DeckMixer.tish'
import { PatternBank } from './PatternBank.tish'
import { coDjInitWebMidi } from '../codj/MidiProfiles.tish'
import {
coDjFlushScheduledForStep,
coDjStepsPerBar,
coDjStepsUntilBarBoundary,
coDjEnsureSchedule
} from '../codj/Schedule.tish'
import { pruneStaleTracks, coDjTrackExpirySequences } from '../codj/Prune.tish'
import { createDeckardRuntime } from './DeckardRuntime.tish'
import { setChannelGain, setChannelPan, setChannelEq } from '../model/Edits.tish'
import {
ensureProjectSession,
sessionArmScene,
sessionCommitQueued,
sessionQueueScene,
sceneSlotClipId,
sessionPlayingSceneIndex,
sessionWriteRackToSceneClip,
sessionWriteRackBarToSceneClip,
loadSceneIntoRack,
loadSceneBarIntoRack,
firstSongScene,
nextSongScene,
songStart,
songAdvance,
sceneBarLength,
armSceneWithOverrides,
mirrorStepToggleToMainClip,
mirrorClearStepToMainClip,
syncActiveClipsInstrumentsFromChannels
} from '../model/Session.tish'
import { SessionView } from './SessionView.tish'
import { PlaylistView } from './PlaylistView.tish'
// Memo'd channel rack (the heaviest panel). It re-renders only when the grid actually changes — gridGen
// (bar page / expand / step bumps), the selected channel, the project's channels-rev, or the promote UI.
// A crossfader move bumps NONE of those, so the rack memo-skips instead of re-rendering all the cells.
// memo() is created ONCE at module scope (in-render memo() would reset its cache every render).
fn stepGridEq(a, b) {
return a.gridGen === b.gridGen && a.selectedCh === b.selectedCh && a.channelsRev === b.channelsRev && a.seqPromoteUi === b.seqPromoteUi && a.activeDeck === b.activeDeck
}
let StepGridMemo = memo((p) => StepGridPanel(p.project, p.selectedCh, p.setProjectFromUI, p.setSelectedCh, p.rt, p.headerRight, p.activeDeck), stepGridEq)
// Same scoping for the other PURE panels (no internal useState — CodeDebugView/CoDjPanel DO have internal
// hooks, so they are NOT memo'd: Lattish memo skips on equal props regardless of internal state, which
// would freeze their self-driven updates). areEqual compares only the scalar dep list; volatile props
// (freshly-built header vnodes, callbacks, the project ref) are intentionally ignored.
fn sessionEq(a, b) {
return a.sessionUiGen === b.sessionUiGen && a.seqPromoteUi === b.seqPromoteUi && a.sessionRev === b.sessionRev && a.channelsRev === b.channelsRev && a.playing === b.playing && a.activeDeck === b.activeDeck
}
let SessionViewMemo = memo((p) => SessionView(p.project, p.rt, p.setProjectFromUI, p.playing, p.bumpSessionUi, p.patternBank, p.headerRight, p.activeDeck), sessionEq)
fn playlistEq(a, b) {
return a.timelineGen === b.timelineGen && a.setLibGen === b.setLibGen && a.channelsRev === b.channelsRev
}
// A press in the left deck strip selects that deck — but NOT when it lands on a control (jog, faders, EQ knobs,
// vinyl/CUE buttons, crossfader, XY pad). Only presses on the deck's empty area / title row select it. Bound to
// mousedown (NOT click): at press time e.target is the exact element under the cursor, so a control is caught
// reliably. A knob/fader DRAG ends with mouseup off the control, which would synthesize a `click` on the deck
// container (target = deck div, not the knob) and slip past this gate — pressing is unambiguous, so we gate that.
fn deckBgClick(e, deck, setActiveDeck) {
let t = e !== null ? e.target : null
if ((t !== null) && (t.closest !== null) && t.closest("button, input, select, textarea, canvas, .dk-jog, .dk-xfade, .dk-xypad, [class*='knob'], [class*='lever'], [class*='fader']") !== null) {
return
}
setActiveDeck(deck)
}
let PlaylistMemo = memo((p) => PlaylistView(p.project, p.rt, p.props), playlistEq)
fn instrumentEq(a, b) {
return a.selectedCh === b.selectedCh && a.channelsRev === b.channelsRev && a.activeDeck === b.activeDeck
}
let InstrumentStackMemo = memo((p) => InstrumentStack(p.project, p.selectedCh, p.setProjectFromUI, p.tplMirrorFlush, p.rt, p.activeDeck), instrumentEq)
fn deckMixerEq(a, b) {
let ap = a.project
let bp = b.project
let abpm = ap ? ap.bpm : 120
let bbpm = bp ? bp.bpm : 120
return a.xfadeX === b.xfadeX && a.xfadeY === b.xfadeY && a.channelsRev === b.channelsRev && a.deckMixRev === b.deckMixRev && a.playing === b.playing && abpm === bbpm
}
let DeckMixerMemo = memo((p) => DeckMixer(p.project, p.setProjectFromUI, p.touchMixer, p.rt), deckMixerEq)
let initialDeckardBoot = loadDefaultDeckardProject()
// Restore the user's saved instrument presets from localStorage (the factory ones come from the boot project).
loadUserInstrumentPresets(initialDeckardBoot.project)
if (initialDeckardBoot.errors.length > 0 && typeof console !== "undefined" && console.warn) {
let ei = 0
while (ei < initialDeckardBoot.errors.length) {
console.warn("default deck L" + String(initialDeckardBoot.errors[ei].line) + ": " + initialDeckardBoot.errors[ei].msg)
ei = ei + 1
}
}
let audioStore = {}
// The lookahead scheduler + clock + draw loop now live in the Transport projection (src/audio/Transport.tish).
// Preview runs on its OWN clock, fully independent of the live (Sequence/Session) transport.
let previewTimer = null
let previewTick = 0
// rAF coalescing flag for the per-deck mixer (EQ knobs / deck volume) — those mutate project.deckEq in
// place and must NOT reconcile+re-render synchronously per mousemove (that saturates the main thread and
// starves the audio clock). One reconcile + one DeckMixer-only re-render per frame instead.
let deckMixPending = false
// --- OffscreenCanvas scope worker (Tier 1): the heaviest per-frame canvas drawing (master spectrum +
// per-stem waveforms) runs on a WORKER thread, so it never competes with the main thread (audio reconfig,
// DOM patching, Lattish render). The main thread only reads the analyser bytes + postMessages them. The
// meters/playhead stay on the main thread (DOM, can't go to a worker). Capability-gated; falls back to
// drawing on the main thread when OffscreenCanvas/Worker aren't available.
let scopeWorker = null
let scopeWorkerTried = false
let scopeTransferred = null
fn ensureScopeWorker() {
if (scopeWorkerTried) {
return scopeWorker
}
scopeWorkerTried = true
if (typeof Worker === "undefined" || typeof OffscreenCanvas === "undefined" || typeof WeakSet === "undefined") {
return null
}
if (typeof HTMLCanvasElement === "undefined" || !HTMLCanvasElement.prototype || typeof HTMLCanvasElement.prototype.transferControlToOffscreen !== "function") {
return null
}
try {
scopeWorker = new Worker("/scope-worker.js")
scopeTransferred = new WeakSet()
} catch (e) {
scopeWorker = null
}
return scopeWorker
}
// Transfer a canvas's rendering to the worker ONCE (idempotent via the WeakSet). Lattish never re-applies the
// canvas's constant width/height/class props (it skips unchanged props), so the transferred canvas is never
// re-touched → no InvalidStateError. Returns true once the canvas is worker-owned.
fn scopeRegister(cv, id) {
if (!scopeWorker || !cv) {
return false
}
if (scopeTransferred.has(cv)) {
return true
}
let dpr = (typeof window !== "undefined" && window.devicePixelRatio) ? window.devicePixelRatio : 1
if (dpr > 2.5) {
dpr = 2.5
}
let cssW = cv.offsetWidth
let cssH = cv.offsetHeight
if (cssW < 4) {
cssW = cv.width > 0 ? cv.width : 64
}
if (cssH < 4) {
cssH = cv.height > 0 ? cv.height : 34
}
let off = null
try {
off = cv.transferControlToOffscreen()
} catch (e) {
return false
}
scopeTransferred.add(cv)
scopeWorker.postMessage({ type: "register", id: id, cssW: cssW, cssH: cssH, dpr: dpr, canvas: off }, [off])
return true
}
// Per-stem scope colour = the channel's DECK colour (matches --deck-a/b/c/d), so a deck's waveforms read in
// its own hue instead of all cyan.
fn deckWaveColorHex(deck) {
if (deck === "B") {
return "#e879f9"
}
if (deck === "C") {
return "#f59e0b"
}
if (deck === "D") {
return "#4ade80"
}
return "#22d3ee"
}
fn renderDeckPips(project, deckLetter) {
let active = []
let i = 0
while (i < 16) {
active.push(false)
i = i + 1
}
if (project && project.channels) {
let j = 0
let chs = project.channels
let len = chs.length
while (j < len) {
let ch = chs[j]
if (ch && channelDeck(project, ch) === deckLetter && ch.steps) {
let si = 0
let slen = ch.steps.length
while (si < 16) {
if (si < slen) {
let s = ch.steps[si]
if (s && s.on) {
active[si] = true
}
}
si = si + 1
}
}
j = j + 1
}
}
let pips = []
let stepIdx = 0
while (stepIdx < 16) {
let on = active[stepIdx]
pips.push(<span class={"deck-nav-indicator-sq" + (on ? " deck-nav-indicator-on" : "")}></span>)
stepIdx = stepIdx + 1
}
return <div class="deck-nav-indicators">{pips}</div>
}
export fn App() {
let [project, setProject] = useState(initialDeckardBoot.project)
migrateProjectGenerators(project)
let tplInit = emitProject(project)
let [tplText, setTplText] = useState(tplInit)
let [activeDeck, setActiveDeck] = useState("A")
let [selectedCh, setSelectedCh] = useState(3)
let [playing, setPlaying] = useState(false)
let [previewing, setPreviewing] = useState(false)
// The live transport's source — "sequence" (FL rack as the live song) or "song" (the session clips).
// Sequence and Session share ONE clock; toggling between them while playing never restarts it.
let [playMode, setPlayMode] = useState("song")
let [sessionUiGen, setSessionUiGen] = useState(0)
let [seqPromoteUi, setSeqPromoteUi] = useState(0)
let [midiGen, setMidiGen] = useState(0)
let midiRenderRaf = useRef(false)
let [songBrowserOpen, setSongBrowserOpen] = useState(false)
let [songQuery, setSongQuery] = useState("")
let [scratchGen, setScratchGen] = useState(0)
let [gridGen, setGridGen] = useState(0)
let [deckMixRev, setDeckMixRev] = useState(0)
// MUST use the functional updater (like bumpSeqPromoteUi/bumpGrid below): this is called from the
// long-lived scheduleStep closure (created once per Play press), so `sessionUiGen` captured by value
// is frozen at that render. The value form re-set the SAME number each launch commit → SessionViewMemo's
// sessionUiGen dep never changed → the memo skipped the queued→playing repaint and the cell stayed
// stuck orange/blinking instead of turning green. The functional form always increments the latest slot.
fn bumpSessionUi() {
setSessionUiGen((x) => x + 1)
}
fn touchMixer() {
updateMixerFromProject(project, audioStore)
}
let rtRef = useRef(null)
if (!rtRef.current) {
rtRef.current = createDeckardRuntime()
}
let rt = rtRef.current
rt.bumpSeqPromoteUi = () => {
setSeqPromoteUi((x) => x + 1)
}
// Per-deck EQ/volume reconcile, rAF-coalesced + DeckMixer-scoped (deckMixRev only — NOT bumpAllRev, so the
// step grid / session / instrument panels don't re-render on a deck fader move). Audio + the lever/knob
// visual both land once per frame, however fast the user drags.
rt.scheduleDeckMix = () => {
if (deckMixPending) {
return
}
deckMixPending = true
requestAnimationFrame(() => {
deckMixPending = false
// Isolate the audio reconcile so a transitional-graph throw can't skip the booth-strip repaint.
try {
if (audioStore.ctx) {
updateMixerFromProject(rtRef.current.project, audioStore)
}
} catch (eDm) {}
setDeckMixRev((x) => x + 1)
})
}
// The BROADCASTING deck-mix commit door: a local booth EQ/volume edit recomputes the per-channel eq, repaints
// the strip (rAF-coalesced via scheduleDeckMix), AND rides the websocket through the same debounced gate as
// every other edit (host → state.snapshot with deck_mix lines; follower → deck.put with its owned deck_mix).
// The per-pixel drag stays smooth (scheduleDeckMix is rAF, coDjScheduleEditBroadcast is 200ms-debounced).
rt.commitDeckMix = (deck) => {
let p = rtRef.current && rtRef.current.project ? rtRef.current.project : project
applyDeckEq(p, deck)
rt.scheduleDeckMix()
coDjScheduleEditBroadcast()
}
// Receiver hook: after adopting a snapshot / deck.put that carried deck_mix, recompute the per-channel eq for
// ALL decks and repaint the booth strip (DeckMixerMemo keys on deckMixRev, NOT the bumpAllRev slice counters).
rt.reconcileDeckMix = () => {
let p = rtRef.current && rtRef.current.project ? rtRef.current.project : project
let dd = ["A", "B", "C", "D"]
let i = 0
while (i < dd.length) {
applyDeckEq(p, dd[i])
i = i + 1
}
if (audioStore.ctx) {
updateMixerFromProject(p, audioStore)
}
setDeckMixRev((x) => x + 1)
}
rt.bumpGrid = () => {
setGridGen((x) => x + 1)
}
rt.touchMixer = touchMixer
// Exposed so the Co-DJ panel can force a full re-render (bumpAllRev) when the connection state changes —
// e.g. so the deck-routing lock visibly engages/releases on connect/disconnect.
rt.setProjectFromUI = setProjectFromUI
rt.mirrorStepToSessionClip = (ch, si) => {
mirrorStepToggleToMainClip(ch, si)
}
rt.mirrorClearStepToSessionClip = (ch, si) => {
mirrorClearStepToMainClip(ch, si)
}
rt.project = project
// Per-slice rev counters (bumped in place at the ingest boundary / by setProjectFromUI) feed the memo'd
// panels' areEqual so they re-render only when their slice changed.
let pRev = ensureProjectRev(project)
let channelsRev = pRev ? pRev.channels : 0
let sessionRev = pRev ? pRev.session : 0
let xfadeX = typeof project.transportCrossfade === "number" ? project.transportCrossfade : -1
let xfadeY = typeof project.transportCrossfadeY === "number" ? project.transportCrossfadeY : -1
rt.setProject = setProject
rt.setTplText = setTplText
rt.selectedCh = selectedCh
rt.setSelectedCh = setSelectedCh
rt.playing = playing
rt.playMode = playMode
// Launch quantize lives on the project (source of truth) so it round-trips in deck and syncs to every
// player via the host snapshot / stream — same value, same UI everywhere. 16 steps = 1 bar default.
let launchQuant = (project.launchQuant !== null) && Math.floor(Number(project.launchQuant)) >= 1
? Math.floor(Number(project.launchQuant))
: 16
rt.launchQuantSteps = launchQuant
// ---- The ONE write door (rearch): ingest + editor. Every UI edit emits a deck fragment through here
// instead of mutating `project` directly. Local, co-DJ, and agent all share this gated path. ----
let storeRef = useRef(null)
if (!storeRef.current) {
storeRef.current = { project: project, runtime: rt }
}
storeRef.current.project = project
// Local actor ctx: single-player = "human" (the default-project owner) with master rights; co-DJ
// overrides coDjActorId / coDjLocalSkillIds when a session assigns a narrower role.
fn localCtx() {
let r = rtRef.current
return {
actorId: r.coDjActorId ? r.coDjActorId : "human",
skillIds: r.coDjLocalSkillIds ? r.coDjLocalSkillIds : ["master_mixer"],
perfStep: r.perfStep !== null ? r.perfStep : 0
}
}
let ingestRef = useRef(null)
if (!ingestRef.current) {
ingestRef.current = createIngest(storeRef.current)
// On stream-advance: reconcile audio (LIVE), re-render, mirror to the deck editor. A continuous control
// (crossfader / faders) fires an emit on every mousemove pixel, so the re-render and the heavy
// emitProject deck-serialize MUST be coalesced — otherwise each pixel re-renders the whole tree + rebuilds
// the full project deck, which scales with channel count and lags hard once decks have content. The audio
// reconcile stays per-emit (you must hear the move now); the render coalesces to one per frame, and the
// deck mirror trails on a debounce (it's a reflection, not needed at interaction rate).
let advancePending = false
let tplMirrorTimer = null
ingestRef.current.onAdvance((v) => {
let r = rtRef.current
if (!r.project) {
return
}
// Coalesce the audio reconcile + re-render to one per animation frame: a 60fps crossfade is smooth and
// a full-tree re-render per mousemove pixel is what lags. Per-emit work is now just scheduling.
if (!advancePending) {
advancePending = true
requestAnimationFrame(() => {
advancePending = false
let rr = rtRef.current
if (rr.project) {
// The audio reconcile can throw on a transitional graph (analyser detached mid deck-load, a bus
// mid-resync). It must NOT skip setProject — otherwise that edit never repaints and the UI looks
// stuck. Isolate the reconcile so the re-render always lands.
try {
if (audioStore.ctx) {
updateMixerFromProject(rr.project, audioStore)
}
} catch (eMix) {}
setProject(rr.project)
}
})
}
// The deck-editor mirror (heavy emitProject serialize) trails on a debounce — a reflection, not needed
// at interaction rate.
if (tplMirrorTimer) {
clearTimeout(tplMirrorTimer)
}
tplMirrorTimer = setTimeout(() => {
let rr = rtRef.current
if (rr.project) {
syncProjectToTplEditor(rr.project)
}
}, 140)
// Stream this LOCAL emit-path edit (knobs, steps, pattern, etc.) to peers, debounced + independent of
// the transport. onAdvance fires ONLY for local edits (received peer edits apply through CoDjPanel, not
// this ingest), so this never echoes. Without it a follower's knob/step edits never reach the host.
coDjScheduleEditBroadcast()
})
}
let editorRef = useRef(null)
if (!editorRef.current) {
editorRef.current = createEditor(storeRef.current, ingestRef.current.ingest, localCtx)
}
rt.emit = (addr, val) => editorRef.current.emit(addr, val)
rt.directive = (line) => editorRef.current.directive(line)
rt.directiveUndoable = (fwd, inv, addr) => editorRef.current.directiveUndoable(fwd, inv, addr)
// Apply an arbitrary deck fragment (e.g. a preset's deck) through the one gated write door.
rt.applyTpl = (tpl) => editorRef.current.directive(tpl)
// Undo / redo: re-ingest the inverse / forward deck through the same gated door (ownership-checked,
// broadcast, round-trip-safe). ingest re-renders via onAdvance, so the toolbar buttons refresh.
rt.undo = () => editorRef.current.undo()
rt.redo = () => editorRef.current.redo()
rt.canUndo = () => editorRef.current.canUndo()
rt.canRedo = () => editorRef.current.canRedo()
// Let the co-DJ connect flow land a joining follower on its OWN deck (so it sees its own loop, not the
// host's Deck A). Exposed here because setActiveDeck (useState) is only in scope in the App component.
rt.setActiveDeck = (d) => {
if (d === "A" || d === "B" || d === "C" || d === "D") {
setActiveDeck(d)
}
}
// Add a new channel: emit a bare `track` header on the ACTIVE deck (the ingest creates it via makeChannel
// with an empty 16-step pattern), undoable (inverse = remove it), and select it.
rt.onAddTrack = () => {
let p = rtRef.current.project
// Mint a doc-unique id (don't collide with existing channels — agents prefix theirs, the host uses c<N>).
let n = p.channels.length
let id = "c" + String(n)
let conflict = true
while (conflict) {
conflict = false
let i = 0
while (i < p.channels.length) {
if (p.channels[i].id === id) {
conflict = true
}
i = i + 1
}
if (conflict) {
n = n + 1
id = "c" + String(n)
}
}
// In a live session each player owns ONE deck; a new track must land on MY deck by OWNERSHIP — NOT on
// whatever deck I happen to be viewing. activeDeck defaults to "A" and is never synced to a follower's
// own deck, so authoring `deck A slot 0` here pinned every guest's first instrument onto the host's
// Deck A (channelPlayerIndex reads deckSlot before ownership). Omitting the deck line lets ownership
// (the local actor stamped on ingest) route it to my own deck. Solo keeps the activeDeck placement.
let pl = p.coDjPlayers
let inSession = Array.isArray(pl) && pl.length > 1
// In a live session a FOLLOWER's new track needs a globally-unique, owned id — a bare c<N> would collide
// with the host's c<N> (and any other client's) and be owner-denied on the host, so the added instrument
// would never sync. Prefix it with my actorId. The host keeps c<N> (it owns Deck A, the canonical ids).
let amHostNow = rtRef.current && rtRef.current.coDjIsHost === true
let aidNow = rtRef.current && rtRef.current.coDjActorId ? String(rtRef.current.coDjActorId) : ""
if (inSession && !amHostNow && aidNow.length > 0) {
id = aidNow + "_" + id
}
let slot = activeDeck === "B" ? 1 : (activeDeck === "C" ? 2 : (activeDeck === "D" ? 3 : 0))
let fwd = inSession
? ("track Track id " + id + " gen basic_osc")
: ("track Track id " + id + " gen basic_osc\n deck " + activeDeck + " slot " + String(slot))
rt.directiveUndoable(fwd, "remove_track " + id, "track/" + id + "/add")
setSelectedCh(rtRef.current.project.channels.length - 1)
}
// Delete a channel: capture its full deck as the undo inverse BEFORE removing (so undo recreates exactly it,
// not a project snapshot), emit `remove_track`, then rebuild the index-keyed audio buses (a splice misaligns
// them) and clamp the selection if it ran off the end.
rt.onDeleteTrack = (chId) => {
let p = rtRef.current.project
let inv = emitLevel(p, "channel", chId)
rt.directiveUndoable("remove_track " + chId, inv, "track/" + chId + "/del")
let p2 = rtRef.current.project
if (audioStore.ctx) {
resyncAllChannelBuses(p2, audioStore)
updateMixerFromProject(p2, audioStore)
}
if (typeof rt.selectedCh === "number" && rt.selectedCh >= p2.channels.length) {
setSelectedCh(p2.channels.length > 0 ? p2.channels.length - 1 : 0)
}
}
// ---- MIDI: keyboard notes audition the SELECTED instrument; a learned CC drives a control via emit (the
// same gated/broadcast/round-tripping deck a UI drag emits → multiplayer-native).
// A MIDI note-on plays the selected channel's voice live (a monitor).
fn midiNote(note, vel) {
ensureAudio(project, audioStore)
let ctx = audioStore.ctx
if (!ctx || !audioStore.buses) {
return
}
let sc = typeof rt.selectedCh === "number" ? Math.floor(rt.selectedCh) : 0
let bus = audioStore.buses[sc]
let ch = project.channels[sc]
if (!bus || !ch) {
return
}
let gch = generatorChannelAtBeat(project, ch, 0)
playHitAt(ctx, bus, ctx.currentTime + 0.005, note, vel, 0.5, gch, 0, null)
}
// A mapped CC (value 0..1) → resolve its target. Keep these ids in sync with midiTargetList. EVERY target
// drives a control that is VISIBLE on screen and moves with the hardware (the rule: nothing audible-but-invisible).
fn midiControl(targetId, v01) {
let ed = editorRef.current
if (!ed) {
return
}
let p = rtRef.current.project
// `scoped` targets repaint themselves (deck booth knobs via scheduleDeckMix → deckMixRev) or need no React
// paint at all (scratch = audio + a canvas jog), so they skip the broad bumpAllRev re-render below.
let scoped = false
if (targetId === "bpm") {
ed.emit("bpm", Math.round(40 + v01 * 200))
} else if (targetId === "scratch") {
// A centered pitch fader / spring knob scrubs DECK A's scratch: 0.5 = stop, ends = ±max reverse/forward.
// (A controller scrubs one platter — deck A by convention; the on-screen jogs cover the rest.)
if (rt.scratchRate) {
rt.scratchRate("A", (v01 - 0.5) * 16)
}
scoped = true
} else if (targetId === "master_lo") {
ed.emit("master/eq_lo", Math.round((-12 + v01 * 24) * 10) / 10)
} else if (targetId === "master_mid") {
ed.emit("master/eq_mid", Math.round((-12 + v01 * 24) * 10) / 10)
} else if (targetId === "master_hi") {
ed.emit("master/eq_hi", Math.round((-12 + v01 * 24) * 10) / 10)
} else if (targetId === "xfade_x") {
ed.emit("xfade", [v01, p.transportCrossfadeY !== null ? p.transportCrossfadeY : 0])
} else if (targetId === "xfade_y") {
ed.emit("xfade", [p.transportCrossfade !== null ? p.transportCrossfade : 0.5, v01])
} else if (String(targetId).indexOf("deck:") === 0) {
// deck:<X>:<band> — the per-deck booth HI/MID/LO/FILTER knobs + volume fader. Drive them through the EXACT
// path the on-screen knobs use (mutate deckEq → applyDeckEq → scheduleDeckMix), so the visible knob tracks
// the hardware (deckMixRev re-renders just that strip) and the audio reconciles once per frame.
let parts = String(targetId).split(":")
let dk = parts[1]
let band = parts[2]
ensureDeckEq(p)
let de = p.deckEq[dk]
if (de !== null) {
if (band === "vol") {
de.vol = Math.round(v01 * 1000) / 1000
} else if (band === "flt") {
de.flt = Math.round((-1 + v01 * 2) / 0.02) * 0.02
} else {
// hi / mid / lo — ±12 dB, integer detents (matches the knob's step)
de[band] = Math.round(-12 + v01 * 24)
}
applyDeckEq(p, dk)
if (rt.scheduleDeckMix) {
rt.scheduleDeckMix()
}
}
scoped = true
} else if (String(targetId).indexOf("track:") === 0) {
ed.emit("track/" + String(targetId).substring(6) + "/mix/gain", Math.round(v01 * 1000) / 1000)
}
// The remaining emits go through the gated door (which bumps slice revs) but never call a React setter, so the
// UI knob/fader never followed the hardware. Coalesce a re-render to once per frame so it tracks the move.
if (!scoped && !midiRenderRaf.current) {
midiRenderRaf.current = true
requestAnimationFrame(() => {
midiRenderRaf.current = false
let pr = rtRef.current.project
if (pr) { bumpAllRev(pr) }
setMidiGen((x) => x + 1)
})
}
}
let midiRef = useRef(null)
if (!midiRef.current) {
midiRef.current = createMidiController({
onNote: (note, vel) => midiNote(note, vel),
onControl: (targetId, v01) => midiControl(targetId, v01),
onChange: () => setMidiGen((x) => x + 1)
})
}
rt.midi = midiRef.current
// Set presets: named, saveable copies of the WHOLE workspace (the one level a global load fits — it
// replaces everything, no target). Built-in "Default" is always present (loading it resets the set).
let setPresetsRef = useRef(null)
if (!setPresetsRef.current) {
setPresetsRef.current = createStationPresets()
}
let setPresets = setPresetsRef.current
let [setListGen, setSetListGen] = useState(0)
// Set library: TIME-aware, per-player bundles (the new "Set"). Loading one fills the free deck slots
// with its players (ghosts you can jam alongside) and restores its `song` arrangement; you can also drop
// one onto a single deck from the deck picker. Seeded from the deck-set catalog so it's never empty.
let setLibraryRef = useRef(null)
if (!setLibraryRef.current) {
setLibraryRef.current = createSetLibrary()
}
let setLibrary = setLibraryRef.current
let [setLibGen, setSetLibGen] = useState(0)
// I/O Rack: persisted speaker/headphone output device choice. Cue state (which decks → headphones) is on
// rt.cuedDecks; share the same object with the audio store so updateMixerFromProject can reconcile it.
let audioDevicesRef = useRef(null)
if (!audioDevicesRef.current) {
audioDevicesRef.current = createAudioDeviceSettings()
}
let audioDevices = audioDevicesRef.current
audioStore.cuedDecks = rt.cuedDecks
let [cueGen, setCueGen] = useState(0)
// ---- Transport/Clock projection + signal bus (rearch step 4). The scheduler publishes step position
// and health on `signals`; the playhead / grid / BPM readout SUBSCRIBE here (decoupled from timing). ----
let signalsRef = useRef(null)
if (!signalsRef.current) {
signalsRef.current = createSignals()
}
let signals = signalsRef.current
let transportRef = useRef(null)
if (!transportRef.current) {
transportRef.current = createTransport(audioStore, signals)
signals.subscribe("transport.position", (step) => {
let r = rtRef.current
if (step < 0) {
if (r.setPlaybackHighlight) {
r.setPlaybackHighlight(0, false)
}
if (r.updateGridPlayhead) {
r.updateGridPlayhead(0, false)
}
if (r.updateTimelinePlayhead) {
r.updateTimelinePlayhead(0, false)
}
return
}
// Honour the draw gate (user-disabled, or an audio-source-switch quiet window): the playhead is a
// draw call too. The rAF/position stream keeps running, so it resumes the moment the gate clears.
if (drawsSuspended(audioStore)) {
return
}
if (r.setPlaybackHighlight) {
r.setPlaybackHighlight(step % 16, true)
}
if (r.updateGridPlayhead) {
r.updateGridPlayhead(step, true)
}
if (r.updateTimelinePlayhead) {
// The Set Recorder is a TAKE-relative timeline (waveform x = step since the take's origin), so the
// playhead + auto-scroll use the same relative coordinate. tplViewOrigin = the global step at the
// recorder's 0 marker (the take start, or 0 during replay; re-zeroed by New).
let origin = r.tplViewOrigin !== null ? Math.floor(r.tplViewOrigin) : 0
let prel = step - origin
if (prel < 0) {
prel = 0
}
r.updateTimelinePlayhead(prel, true)
}
})
signals.subscribe("transport.health", (hh) => {
let r = rtRef.current
if (r.setBpmReadout) {
r.setBpmReadout(hh.target, hh.trueBpm, hh.marginMs, hh.underruns)
}
})
}
let transport = transportRef.current
fn setLaunchQuant(q) {
let v = Math.floor(Number(q))
if (v < 1 || v !== v) {
v = 16
}
rt.emit("launch_quant", v)
}
// Transport hotkeys: Space = Play/Stop Sequence (monitor the rack), Enter = Play/Stop Song (live
// arrangement). Ignored while typing in an input / textarea / contenteditable.
useEffect(() => {
if (typeof window === "undefined") {
return () => {}
}
fn onKey(e) {
let r = rtRef.current
if (!r) {
return
}
// Escape closes any open overlay/modal — the patch/gen editor first, then a sequencer grid overlay
// (piano / locks / EUCLID), then the song browser. Handled BEFORE the typing-field guard so it works
// from a focused field inside a modal. An open IkSelect dropdown stops Escape from reaching here (it
// closes itself first), so this only fires for actual modals.
if (e.key === "Escape") {
if (r.genModal !== null) {
r.genModal = null
if (r.setProjectFromUI) { r.setProjectFromUI(r.project) }
if (e.preventDefault) { e.preventDefault() }
return
}
let anyOverlay = false
let ovMaps = [r.gridExpanded, r.gridLocks, r.gridPianoLocks, r.gridAuto, r.gridEuclid, r.gridLyrics]
let omi = 0
while (omi < ovMaps.length) {
let m = ovMaps[omi]
if (m !== null && Object.keys(m).length > 0) {
anyOverlay = true
}
omi = omi + 1
}
if (anyOverlay) {
r.gridExpanded = {}
r.gridLocks = {}
r.gridPianoLocks = {}
r.gridAuto = {}
r.gridEuclid = {}
r.gridLyrics = {}
if (r.bumpGrid) { r.bumpGrid() }
if (e.preventDefault) { e.preventDefault() }
return
}
setSongBrowserOpen(false)
return
}
let tgt = e.target
let tag = tgt && tgt.tagName ? String(tgt.tagName).toLowerCase() : ""
if (tag === "input" || tag === "textarea" || tag === "select" || (tgt && tgt.isContentEditable)) {
return
}
// Undo / redo first (they own the Cmd/Ctrl+Z chord). Cmd/Ctrl+Z = undo, +Shift (or Cmd/Ctrl+Y) = redo.
if ((e.metaKey || e.ctrlKey) && (e.key === "z" || e.key === "Z" || e.key === "y" || e.key === "Y")) {
e.preventDefault()
let isRedo = (e.key === "y" || e.key === "Y") || ((e.key === "z" || e.key === "Z") && e.shiftKey)
if (isRedo) {
if (r.redo) { r.redo() }
} else {
if (r.undo) { r.undo() }
}
return
}
// A plain modifier+key chord that we don't handle (e.g. Cmd+C copy) — let the browser have it.
if (e.metaKey || e.ctrlKey || e.altKey) {
return
}
if (e.code === "Space" || e.key === " ") {
// Space = Preview: audition the rack on its own clock (separate from the live transport).
e.preventDefault()
if (r.onPreview) {
r.onPreview()
}
} else if (e.key === "Enter") {
// Enter = live Play / Stop (in the current Sequence/Session mode).
e.preventDefault()
if (r.onPlayStop) {
r.onPlayStop()
}
} else if (e.key === "e" || e.key === "E") {
// Hold E = ECHO FX throw: engage on the first keydown (ignore auto-repeat), release on keyup.
if (!e.repeat && r.onFxThrow) {
r.onFxThrow("echo", true)
}
} else if (e.key === "f" || e.key === "F") {
// Hold F = FILTER FX throw (master lowpass sweep).
if (!e.repeat && r.onFxThrow) {
r.onFxThrow("filter", true)
}
} else if (e.key === "c" || e.key === "C") {
// C = cue / un-cue the active scene on the private preview (launch a scene to take it live).
if (!e.repeat && r.onCueActive) {
r.onCueActive()
}
} else if (e.key === "v" || e.key === "V") {
// Hold V = CUT the actively-jogged deck — the two-handed transformer/chirp: jog with the mouse, cut
// with V. Targets r.activeScratchDeck (set when you grab a jog / vinyl move). Routes through the
// `@ deck` directive so the cut broadcasts to peers, same as the buttons.
if (!e.repeat && r.onDeckMove && r.activeScratchDeck) {
r.onDeckMove(r.activeScratchDeck, "cut", true)
}
}
}
fn onKeyUp(e) {
let r = rtRef.current
if (!r) {
return
}
let tgt = e.target
let tag = tgt && tgt.tagName ? String(tgt.tagName).toLowerCase() : ""
if (tag === "input" || tag === "textarea" || tag === "select" || (tgt && tgt.isContentEditable)) {
return
}
if ((e.key === "e" || e.key === "E") && r.onFxThrow) {
r.onFxThrow("echo", false)
} else if ((e.key === "f" || e.key === "F") && r.onFxThrow) {
r.onFxThrow("filter", false)
} else if ((e.key === "v" || e.key === "V") && r.scratchCut && r.activeScratchDeck) {
r.scratchCut(r.activeScratchDeck, false)
}
}
// Suppress the browser's native right-click menu everywhere EXCEPT text fields (right-click is a real
// editing gesture here — clear a step, delete a note — so the OS menu just gets in the way). Text
// inputs/textarea/contenteditable keep their native menu so the deck editor still has copy/paste.
fn onCtx(e) {
let tgt = e.target
let tag = tgt && tgt.tagName ? String(tgt.tagName).toLowerCase() : ""
if (tag === "input" || tag === "textarea" || tag === "select" || (tgt && tgt.isContentEditable)) {
return
}
if (e.preventDefault) {
e.preventDefault()
}
}
window.addEventListener("keydown", onKey)
window.addEventListener("keyup", onKeyUp)
window.addEventListener("contextmenu", onCtx)
let lastTime = 0
let spinRafId = 0
fn jogSpinFrame(timestamp) {
if (typeof document === "undefined") {
return
}
if (lastTime === 0) {
lastTime = timestamp
}
let dt = (timestamp - lastTime) / 1000
lastTime = timestamp
if (dt > 0.1) {
dt = 0.1
}
let markers = document.querySelectorAll(".dk-jog-marker")
let i = 0
while (i < markers.length) {
let mk = markers[i]
let deck = null
if (mk) {
if (mk.classList.contains("dk-marker-A")) { deck = "A" }
else if (mk.classList.contains("dk-marker-B")) { deck = "B" }
else if (mk.classList.contains("dk-marker-C")) { deck = "C" }
else if (mk.classList.contains("dk-marker-D")) { deck = "D" }
}
let r = rtRef.current
if (mk && deck && r) {
if (!r.deckRot) {
r.deckRot = { A: 0, B: 0, C: 0, D: 0 }
}
if (!r.deckBrakeTime) {
r.deckBrakeTime = { A: 0, B: 0, C: 0, D: 0 }
}
if (!r.deckSpinTime) {
r.deckSpinTime = { A: 0, B: 0, C: 0, D: 0 }
}
let grabbed = false
let activeMove = ""
if (r.scratchHold && r.scratchHold[deck]) {
let keys = Object.keys(r.scratchHold[deck])
if (keys.length > 0) {
grabbed = true
if (keys.indexOf("jog") >= 0) {
activeMove = "jog"
} else if (keys.indexOf("spin") >= 0) {
activeMove = "spin"
} else if (keys.indexOf("brake") >= 0) {
activeMove = "brake"
} else if (keys.indexOf("rev") >= 0) {
activeMove = "rev"
}
}
}
if (activeMove !== "jog") {
let rate = 0
if (activeMove === "rev") {
rate = -1
} else if (activeMove === "brake") {
r.deckBrakeTime[deck] = r.deckBrakeTime[deck] + dt
let progress = r.deckBrakeTime[deck] / 0.5
if (progress > 1) {
progress = 1
}
rate = 1 - progress
} else if (activeMove === "spin") {
r.deckSpinTime[deck] = r.deckSpinTime[deck] + dt
let progress = r.deckSpinTime[deck] / 0.35
if (progress > 1) {
progress = 1
}
rate = -10 * (1 - progress)
} else {
r.deckBrakeTime[deck] = 0
r.deckSpinTime[deck] = 0
if (r.playing) {
rate = 1
}
}
let bpm = r.project && typeof r.project.bpm === "number" ? r.project.bpm : 120
let revsPerSecond = bpm / 60 / 4
let dAngle = rate * revsPerSecond * 2 * Math.PI * dt
r.deckRot[deck] = r.deckRot[deck] + dAngle
mk.style.transform = "translateX(-50%) rotate(" + String(r.deckRot[deck]) + "rad)"
}
}
i = i + 1
}
spinRafId = requestAnimationFrame(jogSpinFrame)
}
spinRafId = requestAnimationFrame(jogSpinFrame)
return () => {
window.removeEventListener("keydown", onKey)
window.removeEventListener("keyup", onKeyUp)
window.removeEventListener("contextmenu", onCtx)
if (spinRafId) {
cancelAnimationFrame(spinRafId)
}
}
}, [])
rt.ensureStreamSeeded = () => {
if (!rt.coDjWs || rt.coDjWs.readyState !== 1 || !Array.isArray(rt.tplSessionStream) || rt.tplSessionStream.length > 0) {
return
}
let cur = ""
if (rt.getSongText) {
cur = rt.getSongText()
}
if (!cur || cur.trim().length === 0) {
return
}
let lineArr = cur.split("\n")
let step = typeof rt.perfStep === "number" ? rt.perfStep : 0
rt.tplSessionStream.push({ lines: lineArr, effectivePerfStep: step })
}
rt.appendStreamedBlock = (lineArray, effectivePerfStep) => {
if (!lineArray || lineArray.length === 0) {
return