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