@gamepadly/sdk 0.1.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +163 -8
  2. package/dist/audio/index.d.ts +10 -0
  3. package/dist/audio/index.d.ts.map +1 -0
  4. package/dist/audio/index.js +15 -0
  5. package/dist/audio/index.js.map +7 -0
  6. package/dist/audio/routing.d.ts +40 -0
  7. package/dist/audio/routing.d.ts.map +1 -0
  8. package/dist/audio/routing.js +26 -0
  9. package/dist/audio/routing.js.map +7 -0
  10. package/dist/audio/sampleBank.d.ts +29 -0
  11. package/dist/audio/sampleBank.d.ts.map +1 -0
  12. package/dist/audio/sampleBank.js +354 -0
  13. package/dist/audio/sampleBank.js.map +7 -0
  14. package/dist/bridge/index.js +5 -93
  15. package/dist/bridge/index.js.map +3 -3
  16. package/dist/bridge/profiles.js +89 -0
  17. package/dist/bridge/profiles.js.map +7 -0
  18. package/dist/browser.d.ts +6 -2
  19. package/dist/browser.d.ts.map +1 -1
  20. package/dist/browser.js +2654 -68
  21. package/dist/browser.js.map +4 -4
  22. package/dist/browser.min.js +1 -1
  23. package/dist/diagnostics/circularity.d.ts +26 -0
  24. package/dist/diagnostics/circularity.d.ts.map +1 -0
  25. package/dist/diagnostics/circularity.js +56 -0
  26. package/dist/diagnostics/circularity.js.map +7 -0
  27. package/dist/diagnostics/index.d.ts +15 -0
  28. package/dist/diagnostics/index.d.ts.map +1 -0
  29. package/dist/diagnostics/index.js +31 -0
  30. package/dist/diagnostics/index.js.map +7 -0
  31. package/dist/diagnostics/stick.d.ts +73 -0
  32. package/dist/diagnostics/stick.d.ts.map +1 -0
  33. package/dist/diagnostics/stick.js +134 -0
  34. package/dist/diagnostics/stick.js.map +7 -0
  35. package/dist/diagnostics/telemetry.d.ts +65 -0
  36. package/dist/diagnostics/telemetry.d.ts.map +1 -0
  37. package/dist/diagnostics/telemetry.js +98 -0
  38. package/dist/diagnostics/telemetry.js.map +7 -0
  39. package/dist/game/host.d.ts +40 -0
  40. package/dist/game/host.d.ts.map +1 -0
  41. package/dist/game/host.js +206 -0
  42. package/dist/game/host.js.map +7 -0
  43. package/dist/game/index.d.ts +12 -0
  44. package/dist/game/index.d.ts.map +1 -0
  45. package/dist/game/index.js +27 -0
  46. package/dist/game/index.js.map +7 -0
  47. package/dist/game/mock.d.ts +35 -0
  48. package/dist/game/mock.d.ts.map +1 -0
  49. package/dist/game/mock.js +221 -0
  50. package/dist/game/mock.js.map +7 -0
  51. package/dist/game/seats.d.ts +27 -0
  52. package/dist/game/seats.d.ts.map +1 -0
  53. package/dist/game/seats.js +66 -0
  54. package/dist/game/seats.js.map +7 -0
  55. package/dist/game/types.d.ts +85 -0
  56. package/dist/game/types.d.ts.map +1 -0
  57. package/dist/game/types.js +7 -0
  58. package/dist/game/types.js.map +7 -0
  59. package/dist/haptics/presets.js +133 -0
  60. package/dist/haptics/presets.js.map +7 -0
  61. package/dist/haptics/router.d.ts +16 -0
  62. package/dist/haptics/router.d.ts.map +1 -1
  63. package/dist/haptics/router.js +146 -0
  64. package/dist/haptics/router.js.map +7 -0
  65. package/dist/haptics/samples.d.ts +68 -0
  66. package/dist/haptics/samples.d.ts.map +1 -0
  67. package/dist/haptics/samples.js +124 -0
  68. package/dist/haptics/samples.js.map +7 -0
  69. package/dist/haptics/triggerWrites.d.ts +41 -0
  70. package/dist/haptics/triggerWrites.d.ts.map +1 -0
  71. package/dist/haptics/triggerWrites.js +127 -0
  72. package/dist/haptics/triggerWrites.js.map +7 -0
  73. package/dist/hid/index.d.ts +20 -2
  74. package/dist/hid/index.d.ts.map +1 -1
  75. package/dist/{chunks/chunk-GMU2WEFE.js → hid/index.js} +120 -172
  76. package/dist/hid/index.js.map +7 -0
  77. package/dist/hub.d.ts +26 -2
  78. package/dist/hub.d.ts.map +1 -1
  79. package/dist/hub.js +472 -0
  80. package/dist/hub.js.map +7 -0
  81. package/dist/index.d.ts +13 -3
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +45 -793
  84. package/dist/index.js.map +4 -4
  85. package/dist/input/actions.js +244 -0
  86. package/dist/input/actions.js.map +7 -0
  87. package/dist/input/motion.d.ts +70 -0
  88. package/dist/input/motion.d.ts.map +1 -0
  89. package/dist/input/motion.js +175 -0
  90. package/dist/input/motion.js.map +7 -0
  91. package/dist/input/slotSwitcher.d.ts +31 -0
  92. package/dist/input/slotSwitcher.d.ts.map +1 -0
  93. package/dist/input/slotSwitcher.js +118 -0
  94. package/dist/input/slotSwitcher.js.map +7 -0
  95. package/dist/input/touchpad.d.ts +92 -0
  96. package/dist/input/touchpad.d.ts.map +1 -0
  97. package/dist/input/touchpad.js +268 -0
  98. package/dist/input/touchpad.js.map +7 -0
  99. package/dist/lifecycle.d.ts +37 -0
  100. package/dist/lifecycle.d.ts.map +1 -0
  101. package/dist/lifecycle.js +55 -0
  102. package/dist/lifecycle.js.map +7 -0
  103. package/dist/link/connect.d.ts +67 -0
  104. package/dist/link/connect.d.ts.map +1 -0
  105. package/dist/link/connect.js +123 -0
  106. package/dist/link/connect.js.map +7 -0
  107. package/dist/link/engine.d.ts +7 -1
  108. package/dist/link/engine.d.ts.map +1 -1
  109. package/dist/link/engine.js +985 -0
  110. package/dist/link/engine.js.map +7 -0
  111. package/dist/link/index.d.ts +15 -4
  112. package/dist/link/index.d.ts.map +1 -1
  113. package/dist/link/index.js +29 -958
  114. package/dist/link/index.js.map +4 -4
  115. package/dist/loop/index.js +0 -1
  116. package/dist/loop/index.js.map +1 -1
  117. package/dist/mic/blow.d.ts +72 -0
  118. package/dist/mic/blow.d.ts.map +1 -0
  119. package/dist/mic/blow.js +152 -0
  120. package/dist/mic/blow.js.map +7 -0
  121. package/dist/mic/index.d.ts +9 -0
  122. package/dist/mic/index.d.ts.map +1 -0
  123. package/dist/mic/index.js +23 -0
  124. package/dist/mic/index.js.map +7 -0
  125. package/dist/mic/input.d.ts +37 -0
  126. package/dist/mic/input.d.ts.map +1 -0
  127. package/dist/mic/input.js +109 -0
  128. package/dist/mic/input.js.map +7 -0
  129. package/dist/mic/level.d.ts +33 -0
  130. package/dist/mic/level.d.ts.map +1 -0
  131. package/dist/mic/level.js +61 -0
  132. package/dist/mic/level.js.map +7 -0
  133. package/package.json +17 -1
  134. package/dist/chunks/chunk-GMU2WEFE.js.map +0 -7
@@ -0,0 +1,985 @@
1
+ const COMPANION_HTTP_BASE = "http://127.0.0.1:5178";
2
+ const COMPANION_WS_BASE = "ws://127.0.0.1:5178";
3
+ class ThreeLayerAudioEngine {
4
+ httpBase;
5
+ wsBase;
6
+ // Layer 1: PC Main Speakers / Headset
7
+ pcCtx = null;
8
+ pcSinkId = "";
9
+ pcSinkLabel = "PC Default Speakers";
10
+ pcMasterGain = null;
11
+ pcAnalysers = [];
12
+ pcNoiseBuffer = null;
13
+ // Layer 2 & 3: DualSense 4-Channel Endpoint
14
+ dsMode = "none";
15
+ dsCtx = null;
16
+ dsSinkId = "";
17
+ dsSinkLabel = "";
18
+ dsMaxChannelCount = 2;
19
+ dsActiveChannelCount = 2;
20
+ dsWs = null;
21
+ dsWorklet = null;
22
+ dsMerger = null;
23
+ dsChGains = [];
24
+ // [0: SpkL, 1: SpkR, 2: VcmL, 3: VcmR]
25
+ dsAnalysers = [];
26
+ dsNoiseBuffer = null;
27
+ // Master Gains
28
+ pcGainValue = 0.8;
29
+ dsSpeakerGainValue = 0.95;
30
+ dsHapticGainValue = 0.95;
31
+ audioMuted = false;
32
+ constructor(options = {}) {
33
+ this.httpBase = (options.httpBase || COMPANION_HTTP_BASE).replace(/\/+$/, "");
34
+ this.wsBase = (options.wsBase || COMPANION_WS_BASE).replace(/\/+$/, "");
35
+ }
36
+ /**
37
+ * Mutes or unmutes audible outputs (PC speakers & controller speaker) while keeping tactile VCM haptics active.
38
+ */
39
+ setAudioMuted(muted) {
40
+ this.audioMuted = muted;
41
+ if (this.pcMasterGain && this.pcCtx) {
42
+ this.pcMasterGain.gain.setTargetAtTime(muted ? 0 : this.pcGainValue, this.pcCtx.currentTime, 0.015);
43
+ }
44
+ if (this.dsChGains.length >= 2 && this.dsCtx) {
45
+ const spk = muted ? 0 : this.dsSpeakerGainValue;
46
+ this.dsChGains[0].gain.setTargetAtTime(spk, this.dsCtx.currentTime, 0.015);
47
+ this.dsChGains[1].gain.setTargetAtTime(spk, this.dsCtx.currentTime, 0.015);
48
+ }
49
+ }
50
+ // Track active continuous handles & graph lifecycle subscribers
51
+ activeContinuous = /* @__PURE__ */ new Set();
52
+ audioGraphListeners = /* @__PURE__ */ new Set();
53
+ onAudioGraphChange(listener) {
54
+ this.audioGraphListeners.add(listener);
55
+ return () => {
56
+ this.audioGraphListeners.delete(listener);
57
+ };
58
+ }
59
+ getAudioRouting() {
60
+ return {
61
+ pcCtx: this.pcCtx,
62
+ pcMasterGain: this.pcMasterGain,
63
+ dsCtx: this.dsCtx,
64
+ dsChGains: this.dsChGains
65
+ };
66
+ }
67
+ emitAudioGraph(event) {
68
+ for (const fn of this.audioGraphListeners) {
69
+ try {
70
+ fn(event);
71
+ } catch {
72
+ }
73
+ }
74
+ }
75
+ // Companion WebSocket lifecycle & auto-reconnect
76
+ companionToken = "";
77
+ intentionalWsClose = false;
78
+ reconnectAttempts = 0;
79
+ reconnectTimer = null;
80
+ streamStateListeners = /* @__PURE__ */ new Set();
81
+ onCompanionStreamState(fn) {
82
+ this.streamStateListeners.add(fn);
83
+ return () => this.streamStateListeners.delete(fn);
84
+ }
85
+ emitStreamState(state, message) {
86
+ for (const fn of this.streamStateListeners) {
87
+ try {
88
+ fn(state, message);
89
+ } catch {
90
+ }
91
+ }
92
+ }
93
+ static isLoopbackOrigin() {
94
+ if (typeof window === "undefined") return true;
95
+ const h = window.location.hostname;
96
+ return h === "localhost" || h === "127.0.0.1" || h === "[::1]";
97
+ }
98
+ /**
99
+ * Checks Chrome 142+/147+ Local Network Access (`loopback-network`) permission state.
100
+ * Prevents unsolicited browser permission popups on initial page load for public HTTPS visitors!
101
+ */
102
+ static async getLoopbackPermissionState() {
103
+ if (ThreeLayerAudioEngine.isLoopbackOrigin()) return "local_exempt";
104
+ if (typeof navigator === "undefined" || !navigator.permissions?.query) return "unknown";
105
+ for (const permName of ["loopback-network", "local-network-access"]) {
106
+ try {
107
+ const res = await navigator.permissions.query({ name: permName });
108
+ if (res.state === "granted" || res.state === "prompt" || res.state === "denied") {
109
+ return res.state;
110
+ }
111
+ } catch {
112
+ }
113
+ }
114
+ return "unknown";
115
+ }
116
+ /**
117
+ * Fetch wrapper targeting 127.0.0.1 with Chrome LNA `targetAddressSpace: 'loopback'`.
118
+ */
119
+ async loopbackFetch(url, init = {}) {
120
+ const lnaInit = { ...init, targetAddressSpace: "loopback" };
121
+ try {
122
+ return await fetch(url, lnaInit);
123
+ } catch (err) {
124
+ if (err instanceof TypeError && !String(err.message).toLowerCase().includes("fetch")) {
125
+ return fetch(url, init);
126
+ }
127
+ throw err;
128
+ }
129
+ }
130
+ static checkBrowserCapabilities() {
131
+ if (typeof window === "undefined") {
132
+ return {
133
+ hasWebAudio: false,
134
+ hasSetSinkId: false,
135
+ hasAudioWorklet: false,
136
+ isSecureContext: true
137
+ };
138
+ }
139
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
140
+ return {
141
+ hasWebAudio: Boolean(AudioCtx),
142
+ hasSetSinkId: Boolean(AudioCtx && "setSinkId" in AudioCtx.prototype),
143
+ hasAudioWorklet: Boolean(AudioCtx && "audioWorklet" in AudioCtx.prototype),
144
+ isSecureContext: Boolean(window.isSecureContext)
145
+ };
146
+ }
147
+ async probeCompanion(timeoutMs = 700) {
148
+ const ctrl = new AbortController();
149
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
150
+ try {
151
+ const res = await this.loopbackFetch(`${this.httpBase}/api/health`, {
152
+ cache: "no-store",
153
+ signal: ctrl.signal
154
+ });
155
+ if (!res.ok) return { online: false };
156
+ const data = await res.json();
157
+ return {
158
+ online: Boolean(data.ok),
159
+ version: data.version,
160
+ protocolVersion: typeof data.protocolVersion === "number" ? data.protocolVersion : 1,
161
+ platform: data.platform
162
+ };
163
+ } catch {
164
+ return { online: false };
165
+ } finally {
166
+ clearTimeout(timer);
167
+ }
168
+ }
169
+ /**
170
+ * Acquires a short-lived cryptographic session token from Gamepadly Link v2+ (`POST /api/session`).
171
+ * Uses a custom header (`X-Gamepadly-Client: web`) so browsers enforce CORS preflight.
172
+ */
173
+ async acquireCompanionSession() {
174
+ const res = await this.loopbackFetch(`${this.httpBase}/api/session`, {
175
+ method: "POST",
176
+ headers: { "X-Gamepadly-Client": "web" },
177
+ cache: "no-store"
178
+ });
179
+ if (res.status === 404) {
180
+ this.companionToken = "";
181
+ return "";
182
+ }
183
+ if (!res.ok) {
184
+ throw new Error(`Gamepadly Link rejected session request (HTTP ${res.status}).`);
185
+ }
186
+ const data = await res.json();
187
+ this.companionToken = typeof data.token === "string" ? data.token : "";
188
+ return this.companionToken;
189
+ }
190
+ async listCompanionDevices() {
191
+ const res = await this.loopbackFetch(`${this.httpBase}/api/devices`, { cache: "no-store" });
192
+ if (!res.ok) throw new Error("Gamepadly Link companion did not respond.");
193
+ const data = await res.json();
194
+ return Array.isArray(data.devices) ? data.devices : [];
195
+ }
196
+ async openWindowsSoundPanelViaCompanion() {
197
+ try {
198
+ const token = this.companionToken || await this.acquireCompanionSession();
199
+ const headers = {};
200
+ if (token) headers["X-Gamepadly-Token"] = token;
201
+ const res = await this.loopbackFetch(`${this.httpBase}/api/open-sound-panel`, {
202
+ method: "POST",
203
+ headers
204
+ });
205
+ return res.ok;
206
+ } catch {
207
+ return false;
208
+ }
209
+ }
210
+ async unlockBrowserDeviceLabels() {
211
+ if (!navigator.mediaDevices?.getUserMedia) return false;
212
+ try {
213
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
214
+ for (const t of stream.getTracks()) t.stop();
215
+ return true;
216
+ } catch {
217
+ return false;
218
+ }
219
+ }
220
+ async listBrowserOutputDevices() {
221
+ if (!navigator.mediaDevices?.enumerateDevices) return [];
222
+ const all = await navigator.mediaDevices.enumerateDevices();
223
+ return all.filter((d) => d.kind === "audiooutput").map((d) => ({
224
+ deviceId: d.deviceId,
225
+ label: d.label || (d.deviceId === "default" ? "System Default" : `Audio Output (${d.deviceId.slice(0, 8)})`),
226
+ isLikelyDualSense: /wireless controller|dualsense|ps5|dsx/i.test(d.label || "")
227
+ }));
228
+ }
229
+ // =========================================================================
230
+ // OUTPUT A: PC MAIN SPEAKERS / HEADPHONES
231
+ // =========================================================================
232
+ async initPcOutput(sinkId = "", sinkLabel = "PC Default Speakers") {
233
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
234
+ if (!this.pcCtx) {
235
+ this.pcCtx = new AudioCtx({ latencyHint: "interactive" });
236
+ }
237
+ const ctxWithSink = this.pcCtx;
238
+ if (sinkId && typeof ctxWithSink.setSinkId === "function") {
239
+ await ctxWithSink.setSinkId(sinkId);
240
+ }
241
+ if (this.pcCtx.state === "suspended") {
242
+ await this.pcCtx.resume();
243
+ }
244
+ if (!this.pcMasterGain) {
245
+ this.buildPcGraph();
246
+ }
247
+ this.pcSinkId = sinkId;
248
+ this.pcSinkLabel = sinkLabel;
249
+ return { sinkId: this.pcSinkId, sinkLabel: this.pcSinkLabel, sampleRate: this.pcCtx.sampleRate };
250
+ }
251
+ buildPcGraph() {
252
+ const ctx = this.pcCtx;
253
+ this.pcMasterGain = ctx.createGain();
254
+ this.pcMasterGain.gain.value = this.audioMuted ? 0 : this.pcGainValue;
255
+ const comp = ctx.createDynamicsCompressor();
256
+ comp.threshold.value = -4;
257
+ comp.knee.value = 8;
258
+ comp.ratio.value = 6;
259
+ const splitter = ctx.createChannelSplitter(2);
260
+ const anL = ctx.createAnalyser();
261
+ const anR = ctx.createAnalyser();
262
+ anL.fftSize = 256;
263
+ anR.fftSize = 256;
264
+ anL.smoothingTimeConstant = 0.55;
265
+ anR.smoothingTimeConstant = 0.55;
266
+ this.pcMasterGain.connect(comp);
267
+ comp.connect(ctx.destination);
268
+ comp.connect(splitter);
269
+ splitter.connect(anL, 0);
270
+ splitter.connect(anR, 1);
271
+ this.pcAnalysers = [anL, anR];
272
+ this.pcNoiseBuffer = this.createNoiseBuffer(ctx);
273
+ this.emitAudioGraph("pc_ready");
274
+ }
275
+ // =========================================================================
276
+ // OUTPUT B: DUALSENSE 4CH (MODE 1: GAMEPADLY LINK COMPANION WASAPI)
277
+ // =========================================================================
278
+ async openCompanionWebSocket(deviceId) {
279
+ const token = await this.acquireCompanionSession();
280
+ const params = new URLSearchParams();
281
+ if (token) params.set("token", token);
282
+ if (deviceId) params.set("device", deviceId);
283
+ const qs = params.toString();
284
+ const wsUrl = `${this.wsBase}/ws/haptics${qs ? `?${qs}` : ""}`;
285
+ return new Promise((resolve, reject) => {
286
+ const ws = new WebSocket(wsUrl);
287
+ ws.binaryType = "arraybuffer";
288
+ const timer = setTimeout(() => {
289
+ ws.close();
290
+ reject(new Error("Gamepadly Link WASAPI handshake timeout."));
291
+ }, 5e3);
292
+ ws.onmessage = (evt) => {
293
+ if (typeof evt.data !== "string") return;
294
+ try {
295
+ const msg = JSON.parse(evt.data);
296
+ if (msg.type === "ready") {
297
+ clearTimeout(timer);
298
+ resolve({ ws, ready: msg });
299
+ } else if (msg.type === "error") {
300
+ clearTimeout(timer);
301
+ ws.close();
302
+ reject(new Error(msg.message || "WASAPI renderer failed to initialize."));
303
+ }
304
+ } catch {
305
+ }
306
+ };
307
+ ws.onerror = () => {
308
+ clearTimeout(timer);
309
+ reject(new Error("Failed to connect to Gamepadly Link WebSocket (check LNA loopback permission)."));
310
+ };
311
+ });
312
+ }
313
+ attachWsReconnectHandler(ws, deviceId) {
314
+ ws.onclose = () => {
315
+ if (this.dsWs !== ws) return;
316
+ this.dsWs = null;
317
+ if (this.intentionalWsClose || this.dsMode !== "companion") {
318
+ this.emitStreamState("idle");
319
+ return;
320
+ }
321
+ if (this.reconnectAttempts >= 3) {
322
+ this.emitStreamState("disconnected", "Gamepadly Link connection lost. Click Connect to retry.");
323
+ return;
324
+ }
325
+ const delayMs = 800 * Math.pow(2, this.reconnectAttempts);
326
+ this.reconnectAttempts++;
327
+ this.emitStreamState("reconnecting", `Reconnecting to Gamepadly Link (${this.reconnectAttempts}/3)...`);
328
+ this.reconnectTimer = window.setTimeout(async () => {
329
+ this.reconnectTimer = null;
330
+ if (this.intentionalWsClose || this.dsMode !== "companion") return;
331
+ try {
332
+ const { ws: newWs } = await this.openCompanionWebSocket(deviceId);
333
+ this.dsWs = newWs;
334
+ this.reconnectAttempts = 0;
335
+ this.attachWsReconnectHandler(newWs, deviceId);
336
+ this.emitStreamState("connected", "Gamepadly Link reconnected.");
337
+ } catch {
338
+ if (this.reconnectAttempts < 3) {
339
+ this.attachWsReconnectHandler(ws, deviceId);
340
+ ws.onclose?.(new CloseEvent("close"));
341
+ } else {
342
+ this.emitStreamState("disconnected", "Gamepadly Link offline.");
343
+ }
344
+ }
345
+ }, delayMs);
346
+ };
347
+ }
348
+ async connectDualSenseCompanion(deviceId = "", deviceLabel = "DualSense WASAPI") {
349
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
350
+ await this.teardownDsOutput();
351
+ this.intentionalWsClose = false;
352
+ this.reconnectAttempts = 0;
353
+ const { ws, ready } = await this.openCompanionWebSocket(deviceId);
354
+ this.dsWs = ws;
355
+ this.attachWsReconnectHandler(ws, ready.id || deviceId);
356
+ this.emitStreamState("connected");
357
+ const sr = ready.sampleRate || 48e3;
358
+ this.dsCtx = new AudioCtx({ sampleRate: sr, latencyHint: "interactive" });
359
+ if (this.dsCtx.state === "suspended") {
360
+ await this.dsCtx.resume();
361
+ }
362
+ await this.dsCtx.audioWorklet.addModule("/haptic-worklet.js");
363
+ this.dsMode = "companion";
364
+ this.dsSinkId = ready.id || deviceId;
365
+ this.dsSinkLabel = ready.name || deviceLabel;
366
+ this.dsMaxChannelCount = ready.channels || 4;
367
+ this.dsActiveChannelCount = Math.min(4, this.dsMaxChannelCount);
368
+ this.buildDsGraph(false);
369
+ this.dsWorklet = new AudioWorkletNode(this.dsCtx, "gamepadly-wasapi-capture", {
370
+ numberOfInputs: 1,
371
+ numberOfOutputs: 1,
372
+ outputChannelCount: [1],
373
+ channelCount: 4,
374
+ channelCountMode: "explicit",
375
+ channelInterpretation: "discrete"
376
+ });
377
+ const muteSink = this.dsCtx.createGain();
378
+ muteSink.gain.value = 0;
379
+ this.dsMerger.connect(this.dsWorklet);
380
+ this.dsWorklet.connect(muteSink);
381
+ muteSink.connect(this.dsCtx.destination);
382
+ this.dsWorklet.port.onmessage = (evt) => {
383
+ if (this.dsWs && this.dsWs.readyState === WebSocket.OPEN) {
384
+ this.dsWs.send(evt.data);
385
+ }
386
+ };
387
+ return {
388
+ mode: "companion",
389
+ sinkId: this.dsSinkId,
390
+ sinkLabel: this.dsSinkLabel,
391
+ sampleRate: this.dsCtx.sampleRate,
392
+ maxChannelCount: this.dsMaxChannelCount,
393
+ activeChannelCount: this.dsActiveChannelCount,
394
+ isQuadraphonicReady: this.dsMaxChannelCount >= 4,
395
+ state: this.dsCtx.state
396
+ };
397
+ }
398
+ // =========================================================================
399
+ // OUTPUT B: DUALSENSE 4CH (MODE 2: ZERO-INSTALL BROWSER setSinkId)
400
+ // =========================================================================
401
+ async connectDualSenseBrowserSink(sinkId, sinkLabel) {
402
+ if (!sinkId) {
403
+ throw new Error("DualSense audio output device ID is empty.");
404
+ }
405
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
406
+ await this.teardownDsOutput();
407
+ try {
408
+ this.dsCtx = new AudioCtx({
409
+ latencyHint: "interactive",
410
+ sinkId
411
+ });
412
+ } catch {
413
+ this.dsCtx = new AudioCtx({ latencyHint: "interactive" });
414
+ }
415
+ const ctxWithSink = this.dsCtx;
416
+ if (typeof ctxWithSink.setSinkId === "function" && ctxWithSink.sinkId !== sinkId) {
417
+ await ctxWithSink.setSinkId(sinkId);
418
+ }
419
+ if (this.dsCtx.state === "suspended") {
420
+ await this.dsCtx.resume();
421
+ }
422
+ const dest = this.dsCtx.destination;
423
+ this.dsMaxChannelCount = dest.maxChannelCount;
424
+ const target = this.dsMaxChannelCount >= 4 ? 4 : Math.min(2, this.dsMaxChannelCount);
425
+ dest.channelCountMode = "explicit";
426
+ dest.channelInterpretation = "discrete";
427
+ dest.channelCount = target;
428
+ this.dsActiveChannelCount = dest.channelCount;
429
+ this.dsMode = "setsinkid";
430
+ this.dsSinkId = sinkId;
431
+ this.dsSinkLabel = sinkLabel;
432
+ this.buildDsGraph(true);
433
+ return {
434
+ mode: "setsinkid",
435
+ sinkId: this.dsSinkId,
436
+ sinkLabel: this.dsSinkLabel,
437
+ sampleRate: this.dsCtx.sampleRate,
438
+ maxChannelCount: this.dsMaxChannelCount,
439
+ activeChannelCount: this.dsActiveChannelCount,
440
+ isQuadraphonicReady: this.dsMaxChannelCount >= 4,
441
+ state: this.dsCtx.state
442
+ };
443
+ }
444
+ buildDsGraph(connectDirectlyToDest) {
445
+ const ctx = this.dsCtx;
446
+ this.dsMerger = ctx.createChannelMerger(4);
447
+ this.dsChGains = [];
448
+ this.dsAnalysers = [];
449
+ for (let ch = 0; ch < 4; ch++) {
450
+ const gain = ctx.createGain();
451
+ gain.gain.value = ch < 2 ? this.dsSpeakerGainValue : this.dsHapticGainValue;
452
+ let chainHead = gain;
453
+ if (ch >= 2) {
454
+ const dcBlocker = ctx.createBiquadFilter();
455
+ dcBlocker.type = "highpass";
456
+ dcBlocker.frequency.value = 20;
457
+ dcBlocker.Q.value = 0.707;
458
+ gain.connect(dcBlocker);
459
+ chainHead = dcBlocker;
460
+ }
461
+ const comp = ctx.createDynamicsCompressor();
462
+ comp.threshold.value = -3;
463
+ comp.knee.value = 6;
464
+ comp.ratio.value = 12;
465
+ comp.attack.value = 15e-4;
466
+ comp.release.value = 0.05;
467
+ const analyser = ctx.createAnalyser();
468
+ analyser.fftSize = 256;
469
+ analyser.smoothingTimeConstant = 0.5;
470
+ chainHead.connect(comp);
471
+ comp.connect(analyser);
472
+ analyser.connect(this.dsMerger, 0, ch);
473
+ this.dsChGains.push(gain);
474
+ this.dsAnalysers.push(analyser);
475
+ }
476
+ if (connectDirectlyToDest) {
477
+ this.dsMerger.connect(ctx.destination);
478
+ }
479
+ this.dsNoiseBuffer = this.createNoiseBuffer(ctx);
480
+ this.emitAudioGraph("ds_ready");
481
+ }
482
+ async teardownDsOutput() {
483
+ this.intentionalWsClose = true;
484
+ if (this.reconnectTimer !== null) {
485
+ window.clearTimeout(this.reconnectTimer);
486
+ this.reconnectTimer = null;
487
+ }
488
+ this.stopAllContinuous();
489
+ this.emitAudioGraph("ds_teardown");
490
+ if (this.dsWorklet) {
491
+ try {
492
+ this.dsWorklet.port.onmessage = null;
493
+ this.dsWorklet.disconnect();
494
+ } catch {
495
+ }
496
+ this.dsWorklet = null;
497
+ }
498
+ if (this.dsWs) {
499
+ try {
500
+ this.dsWs.close();
501
+ } catch {
502
+ }
503
+ this.dsWs = null;
504
+ }
505
+ if (this.dsCtx) {
506
+ try {
507
+ await this.dsCtx.close();
508
+ } catch {
509
+ }
510
+ this.dsCtx = null;
511
+ }
512
+ this.dsMerger = null;
513
+ this.dsChGains = [];
514
+ this.dsAnalysers = [];
515
+ this.dsNoiseBuffer = null;
516
+ this.dsMode = "none";
517
+ }
518
+ createNoiseBuffer(ctx) {
519
+ const len = ctx.sampleRate * 2;
520
+ const buf = ctx.createBuffer(1, len, ctx.sampleRate);
521
+ const ch = buf.getChannelData(0);
522
+ for (let i = 0; i < len; i++) ch[i] = Math.random() * 2 - 1;
523
+ return buf;
524
+ }
525
+ async resumeAll() {
526
+ if (!this.pcCtx) {
527
+ await this.initPcOutput("", this.pcSinkLabel);
528
+ }
529
+ if (this.pcCtx && this.pcCtx.state === "suspended") await this.pcCtx.resume();
530
+ if (this.dsCtx && this.dsCtx.state === "suspended") await this.dsCtx.resume();
531
+ }
532
+ setGains(gains) {
533
+ if (gains.pc !== void 0) {
534
+ this.pcGainValue = Math.max(0, Math.min(1.4, gains.pc));
535
+ if (this.pcMasterGain && this.pcCtx) {
536
+ this.pcMasterGain.gain.setTargetAtTime(this.pcGainValue, this.pcCtx.currentTime, 0.02);
537
+ }
538
+ }
539
+ if (gains.dsSpeaker !== void 0) {
540
+ this.dsSpeakerGainValue = Math.max(0, Math.min(1.3, gains.dsSpeaker));
541
+ if (this.dsChGains.length >= 2 && this.dsCtx) {
542
+ this.dsChGains[0].gain.setTargetAtTime(this.dsSpeakerGainValue, this.dsCtx.currentTime, 0.02);
543
+ this.dsChGains[1].gain.setTargetAtTime(this.dsSpeakerGainValue, this.dsCtx.currentTime, 0.02);
544
+ }
545
+ }
546
+ if (gains.dsHaptic !== void 0) {
547
+ this.dsHapticGainValue = Math.max(0, Math.min(1.4, gains.dsHaptic));
548
+ if (this.dsChGains.length >= 4 && this.dsCtx) {
549
+ this.dsChGains[2].gain.setTargetAtTime(this.dsHapticGainValue, this.dsCtx.currentTime, 0.02);
550
+ this.dsChGains[3].gain.setTargetAtTime(this.dsHapticGainValue, this.dsCtx.currentTime, 0.02);
551
+ }
552
+ }
553
+ }
554
+ getWaveforms() {
555
+ const read = (an) => {
556
+ if (!an) return null;
557
+ const arr = new Float32Array(an.fftSize);
558
+ an.getFloatTimeDomainData(arr);
559
+ return arr;
560
+ };
561
+ return {
562
+ pcL: read(this.pcAnalysers[0]),
563
+ pcR: read(this.pcAnalysers[1]),
564
+ dsCh0: read(this.dsAnalysers[0]),
565
+ dsCh1: read(this.dsAnalysers[1]),
566
+ dsCh2: read(this.dsAnalysers[2]),
567
+ dsCh3: read(this.dsAnalysers[3])
568
+ };
569
+ }
570
+ getHapticEnergy() {
571
+ if (this.dsAnalysers.length < 4) return { left: 0, right: 0 };
572
+ const rms = (an) => {
573
+ const buf = new Float32Array(an.fftSize);
574
+ an.getFloatTimeDomainData(buf);
575
+ let s = 0;
576
+ for (let i = 0; i < buf.length; i++) s += buf[i] * buf[i];
577
+ return Math.min(1, Math.sqrt(s / buf.length) * 3.5);
578
+ };
579
+ return { left: rms(this.dsAnalysers[2]), right: rms(this.dsAnalysers[3]) };
580
+ }
581
+ stopAllContinuous() {
582
+ for (const h of Array.from(this.activeContinuous)) {
583
+ try {
584
+ h.stop();
585
+ } catch {
586
+ }
587
+ }
588
+ this.activeContinuous.clear();
589
+ }
590
+ // =========================================================================
591
+ // LOW-LEVEL ROUTING HELPERS
592
+ // =========================================================================
593
+ routePc(node, pan = 0, gain = 1) {
594
+ if (!this.pcCtx || !this.pcMasterGain) return;
595
+ const g = this.pcCtx.createGain();
596
+ g.gain.value = gain;
597
+ const panner = this.pcCtx.createStereoPanner();
598
+ panner.pan.value = Math.max(-1, Math.min(1, pan));
599
+ node.connect(g);
600
+ g.connect(panner);
601
+ panner.connect(this.pcMasterGain);
602
+ }
603
+ routeDsSpeakerMonoSafe(node, gain = 0.9) {
604
+ if (!this.dsCtx || this.dsChGains.length < 2) return;
605
+ const g = this.dsCtx.createGain();
606
+ g.gain.value = gain;
607
+ node.connect(g);
608
+ g.connect(this.dsChGains[0]);
609
+ g.connect(this.dsChGains[1]);
610
+ }
611
+ routeDsVcm(node, pan = 0, gain = 1) {
612
+ if (!this.dsCtx || this.dsChGains.length < 4) return;
613
+ const p = Math.max(-1, Math.min(1, pan));
614
+ const gL = this.dsCtx.createGain();
615
+ const gR = this.dsCtx.createGain();
616
+ gL.gain.value = Math.cos((p + 1) * Math.PI / 4) * gain;
617
+ gR.gain.value = Math.sin((p + 1) * Math.PI / 4) * gain;
618
+ node.connect(gL);
619
+ node.connect(gR);
620
+ gL.connect(this.dsChGains[2]);
621
+ gR.connect(this.dsChGains[3]);
622
+ }
623
+ // =========================================================================
624
+ // SEMANTIC 3-LAYER SYNTHESIS PRIMITIVES (USED BY @gamepadly/game-sdk)
625
+ // =========================================================================
626
+ playPcTone(spec) {
627
+ if (!this.pcCtx) return;
628
+ const ctx = this.pcCtx;
629
+ const start = ctx.currentTime + (spec.delayMs || 0) / 1e3;
630
+ const dur = Math.max(0.015, spec.durationMs / 1e3);
631
+ const osc = ctx.createOscillator();
632
+ osc.type = spec.wave || "sine";
633
+ osc.frequency.setValueAtTime(Math.max(20, spec.freqHz), start);
634
+ if (spec.endFreqHz && spec.endFreqHz > 0) {
635
+ osc.frequency.exponentialRampToValueAtTime(Math.max(20, spec.endFreqHz), start + dur);
636
+ }
637
+ const env = ctx.createGain();
638
+ const amp = Math.max(1e-3, Math.min(1, spec.intensity ?? 0.45));
639
+ env.gain.setValueAtTime(1e-4, start);
640
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(0.012, dur * 0.2));
641
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
642
+ osc.connect(env);
643
+ this.routePc(env, spec.pan ?? 0, 1);
644
+ osc.start(start);
645
+ osc.stop(start + dur + 0.02);
646
+ }
647
+ playPcNoiseBurst(opts) {
648
+ if (!this.pcCtx || !this.pcNoiseBuffer) return;
649
+ const ctx = this.pcCtx;
650
+ const start = ctx.currentTime + (opts.delayMs || 0) / 1e3;
651
+ const dur = Math.max(0.02, opts.durationMs / 1e3);
652
+ const src = ctx.createBufferSource();
653
+ src.buffer = this.pcNoiseBuffer;
654
+ const flt = ctx.createBiquadFilter();
655
+ flt.type = opts.filterType || "bandpass";
656
+ flt.Q.value = opts.q ?? 2;
657
+ flt.frequency.setValueAtTime(opts.freqHz, start);
658
+ if (opts.endFreqHz) {
659
+ flt.frequency.exponentialRampToValueAtTime(Math.max(30, opts.endFreqHz), start + dur);
660
+ }
661
+ const env = ctx.createGain();
662
+ const amp = Math.max(1e-3, Math.min(1, opts.intensity ?? 0.5));
663
+ env.gain.setValueAtTime(1e-4, start);
664
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(0.015, dur * 0.15));
665
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
666
+ src.connect(flt);
667
+ flt.connect(env);
668
+ this.routePc(env, opts.pan ?? 0, 1);
669
+ src.start(start);
670
+ src.stop(start + dur + 0.03);
671
+ }
672
+ playControllerSpeakerTone(spec) {
673
+ if (!this.dsCtx || this.dsChGains.length < 2) {
674
+ this.playPcTone({ ...spec, intensity: (spec.intensity ?? 0.5) * 0.45 });
675
+ return;
676
+ }
677
+ const ctx = this.dsCtx;
678
+ const start = ctx.currentTime + (spec.delayMs || 0) / 1e3;
679
+ const dur = Math.max(0.015, spec.durationMs / 1e3);
680
+ const osc = ctx.createOscillator();
681
+ osc.type = spec.wave || "triangle";
682
+ osc.frequency.setValueAtTime(Math.max(60, spec.freqHz), start);
683
+ if (spec.endFreqHz && spec.endFreqHz > 0) {
684
+ osc.frequency.exponentialRampToValueAtTime(Math.max(60, spec.endFreqHz), start + dur);
685
+ }
686
+ const env = ctx.createGain();
687
+ const amp = Math.max(1e-3, Math.min(1, spec.intensity ?? 0.75));
688
+ env.gain.setValueAtTime(1e-4, start);
689
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(6e-3, dur * 0.18));
690
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
691
+ osc.connect(env);
692
+ this.routeDsSpeakerMonoSafe(env, 0.95);
693
+ osc.start(start);
694
+ osc.stop(start + dur + 0.02);
695
+ }
696
+ playHapticPulse(spec) {
697
+ if (!this.dsCtx || this.dsChGains.length < 4) return;
698
+ const ctx = this.dsCtx;
699
+ const start = ctx.currentTime + (spec.delayMs || 0) / 1e3;
700
+ const dur = Math.max(0.012, spec.durationMs / 1e3);
701
+ const osc = ctx.createOscillator();
702
+ osc.type = spec.wave || "sine";
703
+ osc.frequency.setValueAtTime(Math.max(22, spec.freqHz), start);
704
+ if (spec.endFreqHz && spec.endFreqHz > 0) {
705
+ osc.frequency.exponentialRampToValueAtTime(Math.max(22, spec.endFreqHz), start + dur);
706
+ }
707
+ const env = ctx.createGain();
708
+ const amp = Math.max(1e-3, Math.min(1, spec.intensity));
709
+ env.gain.setValueAtTime(1e-4, start);
710
+ env.gain.linearRampToValueAtTime(amp, start + Math.min(4e-3, dur * 0.2));
711
+ env.gain.exponentialRampToValueAtTime(1e-4, start + dur);
712
+ osc.connect(env);
713
+ this.routeDsVcm(env, spec.pan ?? 0, 1);
714
+ osc.start(start);
715
+ osc.stop(start + dur + 0.02);
716
+ }
717
+ playHapticSweep(spec) {
718
+ if (!this.dsCtx || this.dsChGains.length < 4) return;
719
+ const ctx = this.dsCtx;
720
+ const now = ctx.currentTime;
721
+ const dur = Math.max(0.04, spec.durationMs / 1e3);
722
+ const osc = ctx.createOscillator();
723
+ osc.type = spec.wave || "sine";
724
+ osc.frequency.setValueAtTime(Math.max(25, spec.fromHz), now);
725
+ osc.frequency.exponentialRampToValueAtTime(Math.max(25, spec.toHz), now + dur);
726
+ const p0 = Math.max(-1, Math.min(1, spec.fromPan));
727
+ const p1 = Math.max(-1, Math.min(1, spec.toPan));
728
+ const gL = ctx.createGain();
729
+ const gR = ctx.createGain();
730
+ gL.gain.setValueAtTime(Math.cos((p0 + 1) * Math.PI / 4) * spec.intensity, now);
731
+ gL.gain.linearRampToValueAtTime(Math.cos((p1 + 1) * Math.PI / 4) * spec.intensity, now + dur);
732
+ gR.gain.setValueAtTime(Math.sin((p0 + 1) * Math.PI / 4) * spec.intensity, now);
733
+ gR.gain.linearRampToValueAtTime(Math.sin((p1 + 1) * Math.PI / 4) * spec.intensity, now + dur);
734
+ osc.connect(gL);
735
+ osc.connect(gR);
736
+ gL.connect(this.dsChGains[2]);
737
+ gR.connect(this.dsChGains[3]);
738
+ osc.start(now);
739
+ osc.stop(now + dur + 0.02);
740
+ }
741
+ createContinuous(preset) {
742
+ let stopped = false;
743
+ let dsNodes = null;
744
+ let pcNodes = null;
745
+ const cleanupDsNodes = () => {
746
+ if (!dsNodes) return;
747
+ try {
748
+ dsNodes.osc.stop();
749
+ dsNodes.noise?.stop();
750
+ dsNodes.master.disconnect();
751
+ dsNodes.spkGain.disconnect();
752
+ } catch {
753
+ }
754
+ dsNodes = null;
755
+ };
756
+ const cleanupPcNodes = () => {
757
+ if (!pcNodes) return;
758
+ try {
759
+ pcNodes.osc.stop();
760
+ pcNodes.gain.disconnect();
761
+ } catch {
762
+ }
763
+ pcNodes = null;
764
+ };
765
+ const ensureNodes = () => {
766
+ if (stopped) return;
767
+ if (dsNodes && dsNodes.ctx !== this.dsCtx) {
768
+ cleanupDsNodes();
769
+ }
770
+ if (!dsNodes && this.dsCtx && this.dsChGains.length >= 4) {
771
+ const ctx = this.dsCtx;
772
+ const osc = ctx.createOscillator();
773
+ const filter = ctx.createBiquadFilter();
774
+ const master = ctx.createGain();
775
+ const gL = ctx.createGain();
776
+ const gR = ctx.createGain();
777
+ const spkGain = ctx.createGain();
778
+ master.gain.value = 1e-4;
779
+ gL.gain.value = 0.7;
780
+ gR.gain.value = 0.7;
781
+ spkGain.gain.value = 1e-4;
782
+ const baseCfg = {
783
+ ice: { wave: "triangle", f: 240, filtF: 310, spk: 0.25 },
784
+ metal: { wave: "sine", f: 150, filtF: 180, spk: 0.35 },
785
+ gravel: { wave: "sawtooth", f: 82, filtF: 150, spk: 0.2 },
786
+ grass: { wave: "sine", f: 65, filtF: 110, spk: 0.1 },
787
+ water: { wave: "sine", f: 48, filtF: 85, spk: 0.18 },
788
+ engine: { wave: "sawtooth", f: 42, filtF: 160, spk: 0.05 },
789
+ tension: { wave: "sawtooth", f: 78, filtF: 210, spk: 0.4 }
790
+ };
791
+ const c = baseCfg[preset];
792
+ osc.type = c.wave;
793
+ osc.frequency.value = c.f;
794
+ filter.type = "lowpass";
795
+ filter.frequency.value = c.filtF;
796
+ let noise;
797
+ if (this.dsNoiseBuffer && (preset === "water" || preset === "gravel" || preset === "ice")) {
798
+ noise = ctx.createBufferSource();
799
+ noise.buffer = this.dsNoiseBuffer;
800
+ noise.loop = true;
801
+ const nGain = ctx.createGain();
802
+ nGain.gain.value = 0.45;
803
+ noise.connect(nGain);
804
+ nGain.connect(filter);
805
+ noise.start();
806
+ }
807
+ osc.connect(filter);
808
+ filter.connect(master);
809
+ master.connect(gL);
810
+ master.connect(gR);
811
+ gL.connect(this.dsChGains[2]);
812
+ gR.connect(this.dsChGains[3]);
813
+ master.connect(spkGain);
814
+ spkGain.connect(this.dsChGains[0]);
815
+ spkGain.connect(this.dsChGains[1]);
816
+ spkGain.gain.value = c.spk;
817
+ osc.start();
818
+ dsNodes = { ctx, osc, noise, filter, master, gL, gR, spkGain };
819
+ }
820
+ if (pcNodes && pcNodes.ctx !== this.pcCtx) {
821
+ cleanupPcNodes();
822
+ }
823
+ if (!pcNodes && this.pcCtx && this.pcMasterGain && (preset === "engine" || preset === "tension" || preset === "water")) {
824
+ const ctx = this.pcCtx;
825
+ const osc = ctx.createOscillator();
826
+ osc.type = preset === "water" ? "sine" : "triangle";
827
+ osc.frequency.value = preset === "engine" ? 75 : preset === "tension" ? 210 : 120;
828
+ const gain = ctx.createGain();
829
+ gain.gain.value = 1e-4;
830
+ const panner = ctx.createStereoPanner();
831
+ osc.connect(gain);
832
+ gain.connect(panner);
833
+ panner.connect(this.pcMasterGain);
834
+ osc.start();
835
+ pcNodes = { ctx, osc, gain, panner };
836
+ }
837
+ };
838
+ ensureNodes();
839
+ const handle = {
840
+ update: ({ intensity = 0, speed = 0.5, pan = 0, freqScale = 1 } = {}) => {
841
+ if (stopped) return;
842
+ if (intensity > 5e-3) {
843
+ ensureNodes();
844
+ }
845
+ const amp = Math.max(1e-4, Math.min(1, intensity));
846
+ const p = Math.max(-1, Math.min(1, pan));
847
+ if (dsNodes && this.dsCtx && dsNodes.ctx === this.dsCtx) {
848
+ const now = this.dsCtx.currentTime;
849
+ dsNodes.master.gain.setTargetAtTime(amp * 0.85, now, 0.025);
850
+ dsNodes.gL.gain.setTargetAtTime(Math.cos((p + 1) * Math.PI / 4), now, 0.025);
851
+ dsNodes.gR.gain.setTargetAtTime(Math.sin((p + 1) * Math.PI / 4), now, 0.025);
852
+ const baseF = preset === "tension" ? 68 + speed * 150 : preset === "engine" ? 35 + speed * 95 : 85 + speed * 140;
853
+ dsNodes.osc.frequency.setTargetAtTime(Math.max(25, baseF * freqScale), now, 0.03);
854
+ }
855
+ if (pcNodes && this.pcCtx && pcNodes.ctx === this.pcCtx) {
856
+ const now = this.pcCtx.currentTime;
857
+ pcNodes.gain.gain.setTargetAtTime(amp * 0.22, now, 0.03);
858
+ pcNodes.panner.pan.setTargetAtTime(p * 0.7, now, 0.03);
859
+ const pcF = preset === "tension" ? 180 + speed * 260 : 70 + speed * 160;
860
+ pcNodes.osc.frequency.setTargetAtTime(Math.max(30, pcF * freqScale), now, 0.03);
861
+ }
862
+ },
863
+ stop: () => {
864
+ if (stopped) return;
865
+ stopped = true;
866
+ this.activeContinuous.delete(handle);
867
+ cleanupDsNodes();
868
+ cleanupPcNodes();
869
+ }
870
+ };
871
+ this.activeContinuous.add(handle);
872
+ return handle;
873
+ }
874
+ playComboPreset(id, pan = 0) {
875
+ switch (id) {
876
+ case "ratchet_tick":
877
+ this.playHapticPulse({ pan, freqHz: 215, endFreqHz: 115, durationMs: 18, intensity: 0.52, wave: "triangle" });
878
+ this.playControllerSpeakerTone({ freqHz: 2100, endFreqHz: 1150, durationMs: 16, intensity: 0.45, wave: "triangle" });
879
+ break;
880
+ case "lock_sweet_spot":
881
+ this.playHapticPulse({ pan: -0.45, freqHz: 145, endFreqHz: 68, durationMs: 65, intensity: 0.95, wave: "sine" });
882
+ this.playHapticPulse({ pan: 0.45, freqHz: 285, endFreqHz: 170, durationMs: 48, intensity: 0.75, wave: "triangle", delayMs: 14 });
883
+ this.playControllerSpeakerTone({ freqHz: 1480, endFreqHz: 860, durationMs: 75, intensity: 0.85, wave: "sine" });
884
+ this.playPcTone({ freqHz: 440, endFreqHz: 330, durationMs: 110, intensity: 0.28, pan, wave: "sine" });
885
+ break;
886
+ case "lock_unlock":
887
+ this.playHapticSweep({ fromPan: -0.95, toPan: 0.95, fromHz: 65, toHz: 185, durationMs: 260, intensity: 0.95 });
888
+ this.playControllerSpeakerTone({ freqHz: 980, endFreqHz: 1560, durationMs: 120, intensity: 0.85, wave: "triangle" });
889
+ this.playControllerSpeakerTone({ freqHz: 1560, endFreqHz: 2093, durationMs: 180, intensity: 0.8, delayMs: 120, wave: "sine" });
890
+ this.playPcNoiseBurst({ durationMs: 520, filterType: "lowpass", freqHz: 280, endFreqHz: 65, intensity: 0.85 });
891
+ this.playPcTone({ freqHz: 523.25, endFreqHz: 783.99, durationMs: 360, intensity: 0.38, delayMs: 90, wave: "triangle" });
892
+ break;
893
+ case "fish_bite":
894
+ this.playHapticPulse({ pan, freqHz: 95, endFreqHz: 42, durationMs: 110, intensity: 0.95, wave: "sine" });
895
+ this.playHapticPulse({ pan: -pan * 0.5, freqHz: 165, endFreqHz: 75, durationMs: 75, intensity: 0.8, delayMs: 85 });
896
+ this.playControllerSpeakerTone({ freqHz: 1250, endFreqHz: 780, durationMs: 95, intensity: 0.85, wave: "sawtooth" });
897
+ this.playPcNoiseBurst({ durationMs: 240, filterType: "bandpass", freqHz: 1400, endFreqHz: 500, intensity: 0.6, pan });
898
+ break;
899
+ case "fish_splash":
900
+ this.playHapticSweep({ fromPan: pan, toPan: -pan, fromHz: 140, toHz: 52, durationMs: 220, intensity: 0.85 });
901
+ this.playPcNoiseBurst({ durationMs: 420, filterType: "bandpass", freqHz: 1800, endFreqHz: 420, intensity: 0.72, pan });
902
+ this.playControllerSpeakerTone({ freqHz: 1600, endFreqHz: 620, durationMs: 110, intensity: 0.55, wave: "triangle" });
903
+ break;
904
+ case "pistol":
905
+ this.playHapticPulse({ pan: 0.2, freqHz: 145, endFreqHz: 42, durationMs: 80, intensity: 1 });
906
+ this.playHapticPulse({ pan: 0.6, freqHz: 260, endFreqHz: 135, durationMs: 36, intensity: 0.68, delayMs: 55, wave: "triangle" });
907
+ this.playControllerSpeakerTone({ freqHz: 1850, endFreqHz: 620, durationMs: 48, intensity: 0.85, delayMs: 50, wave: "triangle" });
908
+ this.playPcNoiseBurst({ durationMs: 190, filterType: "lowpass", freqHz: 3200, endFreqHz: 240, intensity: 0.75 });
909
+ break;
910
+ case "shotgun":
911
+ this.playHapticPulse({ pan: 0, freqHz: 115, endFreqHz: 28, durationMs: 210, intensity: 1 });
912
+ this.playHapticPulse({ pan: -0.85, freqHz: 210, endFreqHz: 105, durationMs: 50, intensity: 0.85, delayMs: 260, wave: "sawtooth" });
913
+ this.playHapticPulse({ pan: 0.85, freqHz: 265, endFreqHz: 130, durationMs: 50, intensity: 0.85, delayMs: 390, wave: "sawtooth" });
914
+ this.playControllerSpeakerTone({ freqHz: 1100, endFreqHz: 520, durationMs: 55, intensity: 0.85, delayMs: 260, wave: "sawtooth" });
915
+ this.playControllerSpeakerTone({ freqHz: 1450, endFreqHz: 740, durationMs: 55, intensity: 0.85, delayMs: 390, wave: "sawtooth" });
916
+ this.playPcNoiseBurst({ durationMs: 420, filterType: "lowpass", freqHz: 2800, endFreqHz: 110, intensity: 0.95 });
917
+ break;
918
+ case "bow_release":
919
+ this.playHapticPulse({ pan: -0.35, freqHz: 240, endFreqHz: 72, durationMs: 150, intensity: 0.95, wave: "triangle" });
920
+ this.playControllerSpeakerTone({ freqHz: 920, endFreqHz: 360, durationMs: 120, intensity: 0.85, wave: "triangle" });
921
+ this.playPcNoiseBurst({ durationMs: 210, filterType: "bandpass", freqHz: 2200, endFreqHz: 600, intensity: 0.55 });
922
+ break;
923
+ case "thunder":
924
+ this.playPcNoiseBurst({ durationMs: 1650, filterType: "lowpass", freqHz: 520, endFreqHz: 68, intensity: 0.95, pan });
925
+ this.playHapticPulse({ pan, freqHz: 82, endFreqHz: 28, durationMs: 950, intensity: 1, wave: "sawtooth" });
926
+ break;
927
+ }
928
+ }
929
+ // =========================================================================
930
+ // CALIBRATION & HARDWARE SELF-TESTS
931
+ // =========================================================================
932
+ async testPcSpeakersLoud() {
933
+ await this.resumeAll();
934
+ this.playPcTone({ freqHz: 523.25, durationMs: 240, intensity: 0.55, pan: -0.85, wave: "sine" });
935
+ this.playPcTone({ freqHz: 659.25, durationMs: 260, intensity: 0.55, pan: 0.85, delayMs: 260, wave: "sine" });
936
+ }
937
+ async testDualSenseSpeakerLoud() {
938
+ await this.resumeAll();
939
+ if (!this.dsCtx || this.dsChGains.length < 2) {
940
+ throw new Error("DualSense 4-channel audio is not connected yet.");
941
+ }
942
+ const notes = [880, 1174.66, 1318.51];
943
+ notes.forEach((f, idx) => {
944
+ this.playControllerSpeakerTone({ freqHz: f, durationMs: 200, intensity: 0.95, delayMs: idx * 210, wave: "triangle" });
945
+ });
946
+ }
947
+ async testDualSenseVcmLoud() {
948
+ await this.resumeAll();
949
+ if (!this.dsCtx || this.dsChGains.length < 4) {
950
+ throw new Error("DualSense 4-channel audio is not connected yet.");
951
+ }
952
+ this.playHapticPulse({ pan: -0.95, freqHz: 55, endFreqHz: 180, durationMs: 520, intensity: 0.95 });
953
+ this.playHapticPulse({ pan: 0.95, freqHz: 180, endFreqHz: 55, durationMs: 520, intensity: 0.95, delayMs: 560 });
954
+ }
955
+ async runThreeLayerCalibration(onStep) {
956
+ await this.resumeAll();
957
+ onStep(1);
958
+ this.playPcTone({ freqHz: 523.25, durationMs: 320, intensity: 0.5, pan: -0.9 });
959
+ this.playPcTone({ freqHz: 659.25, durationMs: 320, intensity: 0.5, pan: 0.9, delayMs: 340 });
960
+ setTimeout(() => {
961
+ onStep(2);
962
+ this.playControllerSpeakerTone({ freqHz: 880, endFreqHz: 1174.66, durationMs: 480, intensity: 0.95, wave: "triangle" });
963
+ }, 760);
964
+ setTimeout(() => {
965
+ onStep(3);
966
+ this.playHapticPulse({ pan: -1, freqHz: 45, endFreqHz: 210, durationMs: 650, intensity: 0.95 });
967
+ }, 1350);
968
+ setTimeout(() => {
969
+ onStep(4);
970
+ this.playHapticPulse({ pan: 1, freqHz: 210, endFreqHz: 45, durationMs: 650, intensity: 0.95 });
971
+ }, 2100);
972
+ setTimeout(() => {
973
+ onStep(5);
974
+ this.playHapticSweep({ fromPan: -1, toPan: 1, fromHz: 110, toHz: 145, durationMs: 850, intensity: 0.95 });
975
+ this.playPcTone({ freqHz: 392, endFreqHz: 523.25, durationMs: 820, intensity: 0.35, wave: "triangle" });
976
+ }, 2850);
977
+ setTimeout(() => onStep(6), 3800);
978
+ }
979
+ }
980
+ export {
981
+ COMPANION_HTTP_BASE,
982
+ COMPANION_WS_BASE,
983
+ ThreeLayerAudioEngine
984
+ };
985
+ //# sourceMappingURL=engine.js.map