-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate-node.js
More file actions
1708 lines (1608 loc) · 62.4 KB
/
Copy pathcreate-node.js
File metadata and controls
1708 lines (1608 loc) · 62.4 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
// @ts-check
/**
* @typedef {{ dspModule: WebAssembly.Module; dspMeta: FaustDspMeta; effectModule?: WebAssembly.Module; effectMeta?: FaustDspMeta; mixerModule?: WebAssembly.Module }} FaustDspDistribution
* @typedef {import("./faustwasm").FaustDspMeta} FaustDspMeta
* @typedef {import("./faustwasm").FaustMonoAudioWorkletNode} FaustMonoAudioWorkletNode
* @typedef {import("./faustwasm").FaustPolyAudioWorkletNode} FaustPolyAudioWorkletNode
* @typedef {import("./faustwasm").FaustMonoScriptProcessorNode} FaustMonoScriptProcessorNode
* @typedef {import("./faustwasm").FaustPolyScriptProcessorNode} FaustPolyScriptProcessorNode
* @typedef {FaustMonoAudioWorkletNode | FaustPolyAudioWorkletNode | FaustMonoScriptProcessorNode | FaustPolyScriptProcessorNode} FaustNode
*/
/**
* Creates a Faust audio node for use in the Web Audio API.
*
* @param {AudioContext} audioContext - The Web Audio API AudioContext to which the Faust audio node will be connected.
* @param {string} [dspName] - The name of the DSP to be loaded.
* @param {number} [voices] - The number of voices to be used for polyphonic DSPs.
* @param {boolean} [sp] - Whether to create a ScriptProcessorNode instead of an AudioWorkletNode.
* @returns {Promise<{ faustNode: FaustNode | null; dspMeta: FaustDspMeta }>} - An object containing the Faust audio node and the DSP metadata.
*/
const createFaustNode = async (audioContext, dspName = "template", voices = 0, sp = false, bufferSize = 512) => {
// Set to true if the DSP has an effect
const FAUST_DSP_HAS_EFFECT = false;
// Import necessary Faust modules and data
const { FaustMonoDspGenerator, FaustPolyDspGenerator } = await import("./faustwasm/index.js");
// Load DSP metadata from JSON
/** @type {FaustDspMeta} */
const dspMeta = await (await fetch("./dsp-meta.json")).json();
// Compile the DSP module from WebAssembly binary data
const dspModule = await WebAssembly.compileStreaming(await fetch("./dsp-module.wasm"));
// Create an object representing Faust DSP with metadata and module
/** @type {FaustDspDistribution} */
const faustDsp = { dspMeta, dspModule };
/** @type {FaustNode | null} */
let faustNode = null;
// Create either a polyphonic or monophonic Faust audio node based on the number of voices
if (voices > 0) {
// Try to load optional mixer and effect modules
faustDsp.mixerModule = await WebAssembly.compileStreaming(await fetch("./mixer-module.wasm"));
if (FAUST_DSP_HAS_EFFECT) {
faustDsp.effectMeta = await (await fetch("./effect-meta.json")).json();
faustDsp.effectModule = await WebAssembly.compileStreaming(await fetch("./effect-module.wasm"));
}
// Create a polyphonic Faust audio node
const generator = new FaustPolyDspGenerator();
faustNode = await generator.createNode(
audioContext,
voices,
dspName,
{ module: faustDsp.dspModule, json: JSON.stringify(faustDsp.dspMeta), soundfiles: {} },
faustDsp.mixerModule,
faustDsp.effectModule ? { module: faustDsp.effectModule, json: JSON.stringify(faustDsp.effectMeta), soundfiles: {} } : undefined,
sp,
bufferSize
);
} else {
// Create a standard Faust audio node
const generator = new FaustMonoDspGenerator();
const sp = true; // Force ScriptProcessor mode — avoids COOP/COEP header requirement
faustNode = await generator.createNode(
audioContext,
dspName,
{ module: faustDsp.dspModule, json: JSON.stringify(faustDsp.dspMeta), soundfiles: {} },
sp,
bufferSize
);
}
// Return an object with the Faust audio node and the DSP metadata
return { faustNode, dspMeta };
}
/**
* Connects an audio input stream to a Faust WebAudio node.
*
* @param {AudioContext} audioContext - The Web Audio API AudioContext to which the Faust audio node is connected.
* @param {string} id - The ID of the audio input device to connect.
* @param {FaustNode} faustNode - The Faust audio node to which the audio input stream will be connected.
* @param {MediaStreamAudioSourceNode} oldInputStreamNode - The old audio input stream node to be disconnected from the Faust audio node.
* @returns {Promise<MediaStreamAudioSourceNode>} - The new audio input stream node connected to the Faust audio node.
*/
async function connectToAudioInput(audioContext, id, faustNode, oldInputStreamNode) {
// Create an audio input stream node
const constraints = {
audio: {
echoCancellation: false,
noiseSuppression: false,
autoGainControl: false,
deviceId: id ? { exact: id } : undefined,
},
};
// Get the audio input stream
const stream = await navigator.mediaDevices.getUserMedia(constraints);
if (stream) {
if (oldInputStreamNode) oldInputStreamNode.disconnect();
const newInputStreamNode = audioContext.createMediaStreamSource(stream);
newInputStreamNode.connect(faustNode);
return newInputStreamNode;
} else {
return oldInputStreamNode;
}
};
const HUD_THEMES = Object.freeze({
mobiel_core: Object.freeze({
bg: "rgba(8, 9, 11, 0.86)",
panelBg: "rgba(11, 12, 14, 0.95)",
border: "rgba(220, 224, 228, 0.22)",
borderActive: "rgba(71, 229, 186, 1)",
ink: "rgba(232, 236, 240, 0.92)",
inkSoft: "rgba(208, 212, 216, 0.66)",
off: "rgba(206, 210, 214, 0.12)",
on: "rgba(232, 236, 240, 0.86)",
accent: "rgba(232, 236, 240, 0.86)",
accentSoft: "rgba(220, 224, 228, 0.22)",
grid: "rgba(210, 214, 218, 0.12)",
}),
original: Object.freeze({
bg: "rgba(8, 9, 11, 0.86)",
panelBg: "rgba(11, 12, 14, 0.95)",
border: "rgba(220, 224, 228, 0.22)",
borderActive: "rgba(71, 229, 186, 1)",
ink: "rgba(232, 236, 240, 0.92)",
inkSoft: "rgba(208, 212, 216, 0.66)",
off: "rgba(206, 210, 214, 0.12)",
on: "rgba(232, 236, 240, 0.86)",
accent: "rgba(232, 236, 240, 0.86)",
accentSoft: "rgba(220, 224, 228, 0.22)",
grid: "rgba(210, 214, 218, 0.12)",
}),
lilac_mint: Object.freeze({
bg: "rgba(8, 9, 11, 0.86)",
panelBg: "rgba(11, 12, 14, 0.95)",
border: "rgba(220, 224, 228, 0.22)",
ink: "rgba(232, 236, 240, 0.92)",
inkSoft: "rgba(208, 212, 216, 0.66)",
off: "rgba(206, 210, 214, 0.12)",
on: "rgba(232, 236, 240, 0.86)",
accent: "rgba(232, 236, 240, 0.86)",
accentSoft: "rgba(220, 224, 228, 0.22)",
borderActive: "rgba(71, 229, 186, 1)",
grid: "rgba(210, 214, 218, 0.12)",
}),
neon_lilac: Object.freeze({
bg: "rgba(8, 9, 11, 0.86)",
panelBg: "rgba(11, 12, 14, 0.95)",
border: "rgba(220, 224, 228, 0.22)",
ink: "rgba(232, 236, 240, 0.92)",
inkSoft: "rgba(208, 212, 216, 0.66)",
off: "rgba(206, 210, 214, 0.12)",
on: "rgba(232, 236, 240, 0.86)",
accent: "rgba(232, 236, 240, 0.86)",
accentSoft: "rgba(220, 224, 228, 0.22)",
borderActive: "rgba(71, 229, 186, 1)",
grid: "rgba(210, 214, 218, 0.12)",
}),
});
const DEFAULT_HUD_THEME_ID = "mobiel_core";
const FAUST_UI_MIN_GRID = 34;
const KNOB_TARGET_SIZE = 116;
const KNOB_MIN_COLUMNS = 2;
const KNOB_MAX_COLUMNS = 10;
const KNOB_MANUAL_MIN_COLUMNS = 1;
const KNOB_MIN_COLUMN_PIXEL_WIDTH = 72;
const HUD_BAR_COUNT = 12;
const HUD_SPARK_HISTORY = 24;
const HUD_ASSET_VERSION = "20260521seq4";
const HUD_CONTROL_STRIP_HEIGHT_FALLBACK = 196;
const HUD_FONT_FAMILY = "\"Space Mono\", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace";
const HAPTIC_TICK_DURATION_MS = 120;
const HAPTIC_TICK_MIN_INTERVAL_MS = 60;
const HAPTIC_TICK_BUCKET_COUNT = 48;
const HAPTIC_FALLBACK_TICK_BURST_COUNT = 3;
const IOS_HAPTIC_FALLBACK_SWITCH_ID = "hud-ios-haptic-main";
let iosHapticFallbackSwitch = null;
const HUD_TEXT_SIZES = Object.freeze({
name: "8.4px",
index: "7.8px",
meta: "7.3px",
range: "6.9px",
});
const HUD_CONTROL_FAMILY_SEEDS = Object.freeze({
tone: "#4cd3b7",
ambience: "#68d6f6",
motion: "#5e9ed8",
voice: "#b0a4ed",
harmony: "#8b98e7",
pulse: "#c46bff",
matter: "#7fe0d3",
});
const FAUST_UI_MODULE_SPECS = Object.freeze([
`./faust-ui/index.js?v=${HUD_ASSET_VERSION}`,
"./faust-ui/index.js",
]);
/**
* @typedef {{
* bg: string;
* panelBg: string;
* border: string;
* borderActive: string;
* ink: string;
* inkSoft: string;
* off: string;
* on: string;
* accent: string;
* accentSoft: string;
* grid: string;
* id?: string;
* }} HUDTheme
*/
/**
* @returns {string}
*/
function getHUDThemeId() {
const params = new URLSearchParams(window.location.search);
const raw = (params.get("hudTheme") || params.get("theme") || "")
.trim()
.toLowerCase()
.replace(/[\s-]+/g, "_");
if (raw && raw in HUD_THEMES) return raw;
return DEFAULT_HUD_THEME_ID;
}
/**
* @param {string} themeId
* @returns {HUDTheme}
*/
function applyHUDThemeVars(themeId) {
const theme = HUD_THEMES[themeId] || HUD_THEMES[DEFAULT_HUD_THEME_ID];
const rootStyle = document.documentElement.style;
rootStyle.setProperty("--hud-bg", theme.bg);
rootStyle.setProperty("--hud-panel-bg", theme.panelBg);
rootStyle.setProperty("--hud-border", theme.border);
rootStyle.setProperty("--hud-ink", theme.ink);
rootStyle.setProperty("--hud-ink-soft", theme.inkSoft);
rootStyle.setProperty("--hud-off", theme.off);
rootStyle.setProperty("--hud-on", theme.on);
rootStyle.setProperty("--hud-accent", theme.accent);
rootStyle.setProperty("--hud-accent-soft", theme.accentSoft);
rootStyle.setProperty("--hud-border-active", theme.borderActive);
rootStyle.setProperty("--hud-grid", theme.grid);
rootStyle.setProperty("--hud-theme-id", themeId);
return theme;
}
/**
* @param {string} value
* @returns {{ r: number; g: number; b: number; a: number } | null}
*/
function parseColorString(value) {
if (typeof value !== "string") return null;
const color = value.trim();
if (!color) return null;
if (color.startsWith("#")) {
const hex = color.slice(1);
if (hex.length === 3 || hex.length === 4) {
const [r, g, b, a = "f"] = hex.split("");
return {
r: Number.parseInt(`${r}${r}`, 16),
g: Number.parseInt(`${g}${g}`, 16),
b: Number.parseInt(`${b}${b}`, 16),
a: Number.parseInt(`${a}${a}`, 16) / 255,
};
}
if (hex.length === 6 || hex.length === 8) {
return {
r: Number.parseInt(hex.slice(0, 2), 16),
g: Number.parseInt(hex.slice(2, 4), 16),
b: Number.parseInt(hex.slice(4, 6), 16),
a: hex.length === 8 ? Number.parseInt(hex.slice(6, 8), 16) / 255 : 1,
};
}
return null;
}
const match = color.match(/^rgba?\((.+)\)$/i);
if (!match) return null;
const parts = match[1].split(",").map((part) => part.trim());
if (parts.length < 3) return null;
const [r, g, b, a = "1"] = parts;
const parsed = {
r: Number.parseFloat(r),
g: Number.parseFloat(g),
b: Number.parseFloat(b),
a: Number.parseFloat(a),
};
if (
!Number.isFinite(parsed.r) ||
!Number.isFinite(parsed.g) ||
!Number.isFinite(parsed.b) ||
!Number.isFinite(parsed.a)
) {
return null;
}
return parsed;
}
/**
* @param {{ r: number; g: number; b: number; a: number }} color
* @returns {string}
*/
function formatColorString(color) {
const alpha = Math.max(0, Math.min(1, color.a));
return `rgba(${Math.round(color.r)}, ${Math.round(color.g)}, ${Math.round(color.b)}, ${alpha.toFixed(3)})`;
}
/**
* @param {string} from
* @param {string} to
* @param {number} amount
* @returns {string}
*/
function mixColorStrings(from, to, amount) {
const start = parseColorString(from);
const end = parseColorString(to);
if (!start && !end) return to || from || "rgba(255, 255, 255, 1)";
if (!start) return to;
if (!end) return from;
const t = Math.max(0, Math.min(1, amount));
return formatColorString({
r: start.r + (end.r - start.r) * t,
g: start.g + (end.g - start.g) * t,
b: start.b + (end.b - start.b) * t,
a: start.a + (end.a - start.a) * t,
});
}
/**
* @param {string} value
* @param {number} alpha
* @returns {string}
*/
function setColorAlpha(value, alpha) {
const parsed = parseColorString(value);
if (!parsed) return value;
return formatColorString({
r: parsed.r,
g: parsed.g,
b: parsed.b,
a: Math.max(0, Math.min(1, alpha)),
});
}
/**
* @param {string} name
* @param {string} fallback
* @returns {string}
*/
function readHUDVar(name, fallback) {
const value = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return value || fallback;
}
/**
* @param {string} [themeIdHint]
* @returns {HUDTheme}
*/
function readActiveHUDTheme(themeIdHint = "") {
const root = document.documentElement;
const themeId = (
themeIdHint ||
root.dataset.hudTheme ||
root.style.getPropertyValue("--hud-theme-id") ||
""
).trim().toLowerCase() || DEFAULT_HUD_THEME_ID;
const fallback = HUD_THEMES[themeId] || HUD_THEMES[DEFAULT_HUD_THEME_ID];
return {
id: themeId,
bg: readHUDVar("--hud-bg", fallback.bg),
panelBg: readHUDVar("--hud-panel-bg", fallback.panelBg),
border: readHUDVar("--hud-border", fallback.border),
borderActive: readHUDVar("--hud-border-active", fallback.borderActive),
ink: readHUDVar("--hud-ink", fallback.ink),
inkSoft: readHUDVar("--hud-ink-soft", fallback.inkSoft),
off: readHUDVar("--hud-off", fallback.off),
on: readHUDVar("--hud-on", fallback.on),
accent: readHUDVar("--hud-accent", fallback.accent),
accentSoft: readHUDVar("--hud-accent-soft", fallback.accentSoft),
grid: readHUDVar("--hud-grid", fallback.grid),
};
}
/**
* @param {HUDTheme} theme
* @param {HUDControlPalette | null} [palette]
* @returns {{ low: string; high: string }}
*/
function getKnobIndicatorStops(theme, palette = null) {
if (palette) {
return {
low: palette.indicatorLow,
high: palette.indicatorHigh,
};
}
const lowBase = (theme.id === "noir")
? setColorAlpha(theme.borderActive, 0.7)
: setColorAlpha(theme.accent, 0.74);
const highBase = theme.borderActive;
return {
low: lowBase,
high: highBase,
};
}
/**
* @param {HUDTheme} theme
* @param {HUDControlPalette | null} [palette]
* @returns {{ low: string; high: string }}
*/
function getKnobNeedleStops(theme, palette = null) {
if (palette) {
return {
low: palette.needleLow,
high: palette.needleHigh,
};
}
if (theme.id === "noir") {
return {
low: setColorAlpha(theme.borderActive, 0.96),
high: theme.borderActive,
};
}
return {
low: setColorAlpha(theme.accent, 0.96),
high: theme.borderActive,
};
}
/**
* @param {HUDTheme} theme
* @param {HUDControlPalette | null} [palette]
* @returns {Record<string, string | number | undefined>}
*/
function createKnobStyle(theme, palette = null) {
const indicator = getKnobIndicatorStops(theme, palette);
const needle = getKnobNeedleStops(theme, palette);
return {
labelcolor: palette?.label || theme.ink,
textcolor: palette?.meta || theme.inkSoft,
bgcolor: theme.panelBg,
bordercolor: palette?.border || theme.border,
knobcolor: setColorAlpha(theme.on, 0.08),
knoboncolor: indicator.low,
knoboncolorlow: indicator.low,
knoboncolorhigh: indicator.high,
needlecolor: needle.low,
needlecolorlow: needle.low,
needlecolorhigh: needle.high,
};
}
/**
* @typedef {"tone" | "ambience" | "motion" | "voice" | "harmony" | "pulse" | "matter"} HUDControlFamily
*/
/**
* @typedef {{
* accent: string;
* accentSoft: string;
* border: string;
* grid: string;
* panelTop: string;
* panelGlow: string;
* label: string;
* meta: string;
* value: string;
* barActive: string;
* barTip: string;
* sparkBase: string;
* sparkLine: string;
* indicatorLow: string;
* indicatorHigh: string;
* needleLow: string;
* needleHigh: string;
* }} HUDControlPalette
*/
/**
* @param {string} value
* @returns {string}
*/
function normalizeHUDControlKey(value) {
return String(value || "")
.trim()
.toLowerCase()
.replace(/^.*\//, "")
.replace(/\[[^\]]+\]/g, "")
.replace(/[^a-z0-9]+/g, "");
}
/**
* @param {any} component
* @param {number} index
* @returns {string}
*/
function getHUDControlKey(component, index) {
const state = component && component.state && typeof component.state === "object"
? component.state
: {};
const candidates = [
state.address,
state.shortname,
state.label,
`control_${index + 1}`,
];
for (const candidate of candidates) {
const normalized = normalizeHUDControlKey(candidate);
if (normalized) return normalized;
}
return `control${index + 1}`;
}
/**
* @param {string} controlKey
* @returns {HUDControlFamily}
*/
function getHUDControlFamily(controlKey) {
if (/^(ambi|cathedral)/.test(controlKey)) return "ambience";
if (/^(cameraorbit|mobilerot|motion|zoomin|zoomout|proximityctl|lockctl|stagectl|objectspinctl)/.test(controlKey)) return "motion";
if (/^(chant|organum|attune|boadicea)/.test(controlKey)) return "voice";
if (/^(poly|root)/.test(controlKey)) return "harmony";
if (/^(ritual|percussion|phaser)/.test(controlKey)) return "pulse";
if (/^(material|invisible|transmute|ascend)/.test(controlKey)) return "matter";
return "tone";
}
/**
* @param {HUDTheme} theme
* @param {HUDControlFamily} family
* @returns {HUDControlPalette}
*/
function createHUDControlPalette(theme, family) {
const seed = HUD_CONTROL_FAMILY_SEEDS[family] || theme.borderActive;
const accentCore = mixColorStrings(seed, theme.borderActive, 0.26);
const accent = mixColorStrings(accentCore, theme.on, 0.08);
const accentSoft = setColorAlpha(mixColorStrings(theme.accentSoft, accentCore, 0.82), 0.24);
const border = setColorAlpha(mixColorStrings(theme.border, accentCore, 0.52), 0.3);
const grid = setColorAlpha(mixColorStrings(theme.grid, accentCore, 0.48), 0.18);
const panelTop = setColorAlpha(mixColorStrings(theme.accentSoft, accentCore, 0.84), 0.34);
const panelGlow = setColorAlpha(mixColorStrings(accentCore, theme.panelBg, 0.14), 0.24);
const label = mixColorStrings(theme.ink, accentCore, 0.16);
const meta = mixColorStrings(theme.inkSoft, accentCore, 0.24);
const value = mixColorStrings(theme.on, accentCore, 0.34);
const barActive = setColorAlpha(mixColorStrings(accentCore, theme.on, 0.12), 0.92);
const barTip = mixColorStrings(theme.on, accentCore, 0.68);
const sparkBase = setColorAlpha(mixColorStrings(theme.grid, accentCore, 0.3), 0.24);
const sparkLine = mixColorStrings(accentCore, theme.on, 0.24);
const indicatorLow = setColorAlpha(accentCore, theme.id === "noir" ? 0.84 : 0.78);
const indicatorHigh = mixColorStrings(accentCore, theme.on, 0.12);
const needleLow = setColorAlpha(mixColorStrings(accentCore, theme.on, 0.08), 0.98);
const needleHigh = mixColorStrings(accentCore, theme.on, 0.18);
return {
accent,
accentSoft,
border,
grid,
panelTop,
panelGlow,
label,
meta,
value,
barActive,
barTip,
sparkBase,
sparkLine,
indicatorLow,
indicatorHigh,
needleLow,
needleHigh,
};
}
/**
* @param {unknown} faustUIModule
* @returns {any | null}
*/
function getFaustUIConstructor(faustUIModule) {
if (!faustUIModule || typeof faustUIModule !== "object") return null;
if (typeof faustUIModule.FaustUI === "function") return faustUIModule.FaustUI;
if (typeof faustUIModule.default === "function") return faustUIModule.default;
return null;
}
/**
* @returns {Promise<any>}
*/
async function loadFaustUIConstructor() {
/** @type {string[]} */
const diagnostics = [];
/** @type {unknown} */
let lastImportError = null;
for (const spec of FAUST_UI_MODULE_SPECS) {
try {
const faustUIModule = await import(spec);
const FaustUI = getFaustUIConstructor(faustUIModule);
const keys = Object.keys(faustUIModule || {});
diagnostics.push(`${spec}: exports [${keys.join(", ")}]`);
if (FaustUI) return FaustUI;
} catch (error) {
lastImportError = error;
diagnostics.push(`${spec}: import failed (${error instanceof Error ? error.message : String(error)})`);
}
}
let byteDiagnostic = "";
try {
const response = await fetch(`./faust-ui/index.js?v=${Date.now()}`, { cache: "no-store" });
const source = await response.text();
byteDiagnostic = ` index.js bytes=${source.length}`;
} catch (error) {
byteDiagnostic = ` index.js fetch failed (${error instanceof Error ? error.message : String(error)})`;
}
const message = [
"UI failed to load: faust-ui/index.js did not export a FaustUI constructor.",
`Attempted: ${FAUST_UI_MODULE_SPECS.join(", ")}.`,
diagnostics.join(" | "),
byteDiagnostic,
lastImportError ? `Last import error: ${lastImportError instanceof Error ? lastImportError.message : String(lastImportError)}` : "",
].filter(Boolean).join(" ");
throw new TypeError(message);
}
/**
* @param {number} width
* @param {number} totalControls
* @returns {number}
*/
function getKnobColumnCount(width, totalControls) {
const estimatedColumns = Math.max(1, Math.floor(width / KNOB_TARGET_SIZE));
return Math.max(
KNOB_MIN_COLUMNS,
Math.min(KNOB_MAX_COLUMNS, Math.min(totalControls, estimatedColumns))
);
}
/**
* @param {number} width
* @param {number} totalControls
* @returns {number}
*/
function getKnobMaxColumnsForWidth(width, totalControls) {
const widthBound = Math.max(1, Math.floor(width / KNOB_MIN_COLUMN_PIXEL_WIDTH));
return Math.max(
KNOB_MANUAL_MIN_COLUMNS,
Math.min(KNOB_MAX_COLUMNS, Math.min(totalControls, widthBound))
);
}
/**
* @param {number} value
* @param {number} min
* @param {number} max
* @returns {number}
*/
function normalize(value, min, max) {
if (!Number.isFinite(value) || !Number.isFinite(min) || !Number.isFinite(max)) return 0;
const range = max - min;
if (!Number.isFinite(range) || range === 0) return 0;
return Math.max(0, Math.min(1, (value - min) / range));
}
/**
* @param {number} normalized
* @returns {string}
*/
function getSignalState(normalized) {
if (normalized < 0.2) return "IDLE";
if (normalized < 0.4) return "SCAN";
if (normalized < 0.6) return "SYNC";
if (normalized < 0.8) return "PULSE";
return "PEAK";
}
/**
* @param {number} value
* @returns {string}
*/
function formatValue(value) {
if (!Number.isFinite(value)) return "--";
const abs = Math.abs(value);
if (abs >= 10) return value.toFixed(1);
if (abs >= 1) return value.toFixed(2);
return value.toFixed(3);
}
/**
* @returns {boolean}
*/
function canUseTouchHaptics() {
if (hasNativeVibrationSupport()) return true;
return typeof document !== "undefined";
}
/**
* @returns {boolean}
*/
function hasNativeVibrationSupport() {
return typeof navigator !== "undefined" && typeof navigator.vibrate === "function";
}
/**
* @returns {boolean}
*/
function isLikelyIOSTouchDevice() {
if (typeof navigator === "undefined") return false;
const ua = String(navigator.userAgent || "");
const platform = String(navigator.platform || "");
const touchPoints = Number(navigator.maxTouchPoints || 0);
if (/iPad|iPhone|iPod/i.test(ua)) return true;
return platform === "MacIntel" && touchPoints > 1;
}
/**
* @returns {{ input: HTMLInputElement; label: HTMLLabelElement } | null}
*/
function ensureIOSHapticFallbackSwitch() {
if (iosHapticFallbackSwitch) return iosHapticFallbackSwitch;
if (typeof document === "undefined" || !document.body) return null;
let label = document.querySelector(`label[for="${IOS_HAPTIC_FALLBACK_SWITCH_ID}"]`);
if (!(label instanceof HTMLLabelElement)) {
label = document.createElement("label");
label.setAttribute("for", IOS_HAPTIC_FALLBACK_SWITCH_ID);
label.textContent = "Haptic feedback";
label.style.position = "fixed";
label.style.left = "-9999px";
label.style.top = "0";
label.style.width = "1px";
label.style.height = "1px";
label.style.opacity = "0";
label.style.pointerEvents = "none";
label.style.overflow = "hidden";
document.body.appendChild(label);
}
let input = label.querySelector("input");
if (!(input instanceof HTMLInputElement)) {
const existingInput = document.getElementById(IOS_HAPTIC_FALLBACK_SWITCH_ID);
if (existingInput instanceof HTMLInputElement) {
input = existingInput;
} else {
input = document.createElement("input");
input.type = "checkbox";
input.id = IOS_HAPTIC_FALLBACK_SWITCH_ID;
input.setAttribute("switch", "");
}
input.style.all = "initial";
input.style.appearance = "auto";
input.style.webkitAppearance = "auto";
input.style.position = "absolute";
input.style.left = "0";
input.style.top = "0";
input.style.width = "1px";
input.style.height = "1px";
input.style.opacity = "0";
input.style.pointerEvents = "none";
label.appendChild(input);
}
iosHapticFallbackSwitch = { input, label };
return iosHapticFallbackSwitch;
}
/**
* @returns {boolean}
*/
function primeIOSHapticFallback() {
const fallbackSwitch = ensureIOSHapticFallbackSwitch();
if (!fallbackSwitch) return false;
fallbackSwitch.label.click();
fallbackSwitch.input.click();
return true;
}
/**
* @param {number} durationMs
* @returns {boolean}
*/
function triggerTouchHapticTick(durationMs) {
let fired = false;
if (hasNativeVibrationSupport()) {
navigator.vibrate(Math.max(1, Math.floor(durationMs)));
fired = true;
}
const fallbackSwitch = ensureIOSHapticFallbackSwitch();
if (fallbackSwitch) {
for (let i = 0; i < HAPTIC_FALLBACK_TICK_BURST_COUNT; i += 1) {
fallbackSwitch.label.click();
fallbackSwitch.input.click();
}
fired = true;
}
return fired;
}
/**
* @param {HTMLCanvasElement} canvas
* @param {number[]} history
* @param {string} baselineColor
* @param {string} strokeColor
*/
function paintSparkline(canvas, history, baselineColor, strokeColor) {
const ctx = canvas.getContext("2d");
if (!ctx) return;
const dpr = window.devicePixelRatio || 1;
const width = Math.max(60, Math.floor(canvas.clientWidth || 72));
const height = Math.max(10, Math.floor(canvas.clientHeight || 14));
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = baselineColor;
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, height - 0.5);
ctx.lineTo(width, height - 0.5);
ctx.stroke();
if (history.length < 2) return;
ctx.strokeStyle = strokeColor;
ctx.lineWidth = 1;
ctx.beginPath();
history.forEach((sample, i) => {
const x = (i / (history.length - 1)) * (width - 1);
const y = (1 - sample) * (height - 2) + 1;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
});
ctx.stroke();
}
/**
* @param {Array<Record<string, unknown>> | undefined} metaIn
* @returns {Array<Record<string, unknown>>}
*/
function appendKnobMeta(metaIn) {
const cleanedMeta = [];
if (Array.isArray(metaIn)) {
metaIn.forEach((meta) => {
if (!meta || typeof meta !== "object") return;
if ("style" in meta) {
const { style, ...rest } = meta;
if (Object.keys(rest).length > 0) cleanedMeta.push(rest);
return;
}
cleanedMeta.push({ ...meta });
});
}
return [{ style: "knob" }, ...cleanedMeta];
}
/**
* @param {any[]} items
* @param {any[]} out
* @returns {any[]}
*/
function collectControlItems(items, out = []) {
items.forEach((item) => {
if (item && typeof item === "object" && "items" in item && Array.isArray(item.items)) {
collectControlItems(item.items, out);
return;
}
out.push(item);
});
return out;
}
const HUD_GLOBAL_ONLY_KEYS = new Set(["gain"]);
/**
* @param {any} item
* @returns {string}
*/
function controlKeyForItem(item) {
const address = item && typeof item === "object" ? item.address : "";
if (typeof address !== "string") return "";
const parts = address.split("/").filter(Boolean);
return (parts.at(-1) || "").toLowerCase();
}
/**
* @param {any[]} items
* @returns {any[]}
*/
function collectGridControlItems(items) {
return collectControlItems(items, []).filter((item) => !HUD_GLOBAL_ONLY_KEYS.has(controlKeyForItem(item)));
}
/**
* @param {any} item
* @returns {any}
*/
function toKnobControl(item) {
if (!item || typeof item !== "object") return item;
if (item.type === "hslider" || item.type === "vslider" || item.type === "nentry") {
return {
...item,
type: "knob",
meta: appendKnobMeta(item.meta),
};
}
return { ...item };
}
/**
* Keep the default Faust order, but promote key controls when needed.
*
* @param {any[]} controls
* @returns {any[]}
*/
function orderKnobControls(controls) {
if (!Array.isArray(controls) || controls.length < 2) return Array.isArray(controls) ? controls.slice() : [];
const prioritizedKeys = ["gain"];
const remaining = controls.slice();
const ordered = [];
prioritizedKeys.forEach((key) => {
const index = remaining.findIndex((item) => controlKeyForItem(item) === key);
if (index >= 0) {
ordered.push(remaining.splice(index, 1)[0]);
}
});
return [...ordered, ...remaining];
}
/**
* Build a vertical stack of horizontal rows to create a knob grid.
*
* @param {any[]} sourceUI
* @param {number} columns
* @returns {{ ui: any[]; paths: string[] }}
*/
function buildKnobGridUI(sourceUI, columns) {
const controls = orderKnobControls(collectGridControlItems(sourceUI).map(toKnobControl));
const rows = [];
for (let i = 0; i < controls.length; i += columns) {
rows.push({
type: "hgroup",
label: "",
items: controls.slice(i, i + columns),
});
}
return {
ui: [{
type: "vgroup",
label: "",
items: rows,
}],
paths: controls
.map((item) => item && typeof item === "object" ? item.address : undefined)
.filter((address) => typeof address === "string"),
};
}
/**
* Render a visible error in the UI container instead of a blank screen.
*
* @param {HTMLElement} divFaustUI
* @param {string} message
*/
function renderUIError(divFaustUI, message) {
const $error = document.createElement("div");
$error.style.padding = "16px";
$error.style.color = "rgba(232, 236, 240, 0.92)";
$error.style.background = "rgba(8, 9, 11, 0.94)";
$error.style.border = "1px solid rgba(71, 229, 186, 1)";
$error.style.fontFamily = HUD_FONT_FAMILY;
$error.style.fontWeight = "700";
$error.style.fontSize = "14px";
$error.style.whiteSpace = "pre-wrap";
$error.textContent = message;
divFaustUI.replaceChildren($error);
}
/**
* Apply HUD styles to knob components.
*
* @param {any} faustUI
* @param {HUDTheme} theme
*/
function applyHUDStyles(faustUI, theme) {
const $root = faustUI && faustUI.faustUIRoot && faustUI.faustUIRoot.container;