@avoid.quest/audio 0.1.0 → 0.1.1-beta.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 (41) hide show
  1. package/README.md +30 -2
  2. package/dist/effects/index.d.ts +21 -72
  3. package/dist/effects/index.js +212 -505
  4. package/dist/effects/index.js.map +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +1 -1
  7. package/dist/midi/index.d.ts +0 -24
  8. package/dist/midi/index.js +222 -258
  9. package/dist/midi/index.js.map +1 -1
  10. package/dist/native-Bern4_PB.js +172 -0
  11. package/dist/native-Bern4_PB.js.map +1 -0
  12. package/dist/pcm-buffer-DSzGHbon.js +436 -0
  13. package/dist/pcm-buffer-DSzGHbon.js.map +1 -0
  14. package/dist/playback/index.d.ts +60 -114
  15. package/dist/playback/index.js +899 -1062
  16. package/dist/playback/index.js.map +1 -1
  17. package/dist/queue/index.d.ts +8 -19
  18. package/dist/queue/index.js +461 -960
  19. package/dist/queue/index.js.map +1 -1
  20. package/dist/recognize/index.d.ts +37 -74
  21. package/dist/recognize/index.js +172 -2715
  22. package/dist/recognize/index.js.map +1 -1
  23. package/dist/routing/index.d.ts +3 -34
  24. package/dist/routing/index.js +413 -536
  25. package/dist/routing/index.js.map +1 -1
  26. package/dist/shazam-gBrX1NEY.d.ts +27 -0
  27. package/dist/sync/index.d.ts +9 -77
  28. package/dist/sync/index.js +320 -542
  29. package/dist/sync/index.js.map +1 -1
  30. package/dist/{worklet-loader-BvEW0oVO.d.ts → worklet-loader-BabwPALw.d.ts} +4 -7
  31. package/dist/{worklet-loader-S7R8ZAmP.js → worklet-loader-f741D1tk.js} +37 -52
  32. package/dist/worklet-loader-f741D1tk.js.map +1 -0
  33. package/dist/worklets/couch-live.js +110 -192
  34. package/dist/worklets/couch-live.js.map +1 -1
  35. package/dist/worklets/meter.js +14 -20
  36. package/dist/worklets/meter.js.map +1 -1
  37. package/dist/worklets/pcm-capture.d.ts +6 -0
  38. package/dist/worklets/pcm-capture.js +52 -0
  39. package/dist/worklets/pcm-capture.js.map +1 -0
  40. package/package.json +8 -3
  41. package/dist/worklet-loader-S7R8ZAmP.js.map +0 -1
@@ -1,5 +1,6 @@
1
- import { i as loadAudioWorklet, n as createWorkletBlobUrl, r as createWorkletModuleUrl, t as VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE } from "../worklet-loader-S7R8ZAmP.js";
1
+ import { i as loadAudioWorklet, n as createWorkletBlobUrl, r as createWorkletModuleUrl, t as VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE } from "../worklet-loader-f741D1tk.js";
2
2
  import { Effect, Fiber, Scope, Semaphore } from "effect";
3
+ import { a as clampFinite, f as disconnectEdge, m as setParamTarget } from "../native-Bern4_PB.js";
3
4
  import { s as AudioRoutingError } from "../errors-BT9HxDLn.js";
4
5
  // src/worklets/meter.ts
5
6
  const METER_PROCESSOR_NAME = "avoid-meter";
@@ -19,17 +20,15 @@ if (typeof registerProcessor === "function") registerProcessor(METER_PROCESSOR_N
19
20
  };
20
21
  constructor(options) {
21
22
  super(options);
22
- const intervalMs = options?.processorOptions?.reportIntervalMs ?? 50;
23
- const clampedMs = Math.max(10, Math.min(1e3, intervalMs));
23
+ const clampedMs = Math.max(10, Math.min(1e3, options?.processorOptions?.reportIntervalMs ?? 50));
24
24
  this.reportSamples = Math.max(DEFAULT_QUANTUM_FRAMES, Math.round(sampleRate * clampedMs / 1e3));
25
25
  this.port.addEventListener("message", (event) => {
26
26
  if (event.data === "poll") this.flushMeter();
27
27
  });
28
- if (typeof this.port.start === "function") this.port.start();
28
+ this.port.start?.();
29
29
  }
30
30
  flushMeter() {
31
- const count = this.sampleCount;
32
- const inv = count > 0 ? 1 / count : 0;
31
+ const inv = this.sampleCount > 0 ? 1 / this.sampleCount : 0;
33
32
  this.payload.leftPeak = this.leftPeak;
34
33
  this.payload.rightPeak = this.rightPeak;
35
34
  this.payload.leftRms = Math.sqrt(this.leftSumSq * inv);
@@ -41,33 +40,29 @@ if (typeof registerProcessor === "function") registerProcessor(METER_PROCESSOR_N
41
40
  this.rightSumSq = 0;
42
41
  this.sampleCount = 0;
43
42
  }
44
- recordSilence(outputs) {
45
- const outputLen = (outputs?.[0])?.[0]?.length ?? 0;
46
- this.sampleCount += outputLen > 0 ? outputLen : DEFAULT_QUANTUM_FRAMES;
47
- if (this.sampleCount >= this.reportSamples) this.flushMeter();
48
- }
49
43
  process(inputs, outputs) {
50
- const [input] = inputs;
51
- const left = input && input.length > 0 ? input[0] : void 0;
44
+ const left = inputs[0]?.[0];
52
45
  if (!left || left.length === 0) {
53
- this.recordSilence(outputs);
46
+ const outLen = outputs?.[0]?.[0]?.length ?? 0;
47
+ this.sampleCount += outLen > 0 ? outLen : DEFAULT_QUANTUM_FRAMES;
48
+ if (this.sampleCount >= this.reportSamples) this.flushMeter();
54
49
  return true;
55
50
  }
56
- const right = input && input.length > 1 && input[1] ? input[1] : left;
51
+ const right = inputs[0]?.[1] ?? left;
57
52
  const frames = left.length;
58
53
  let lPeak = this.leftPeak;
59
54
  let rPeak = this.rightPeak;
60
55
  let lSumSq = this.leftSumSq;
61
56
  let rSumSq = this.rightSumSq;
62
57
  for (let i = 0; i < frames; i += 1) {
63
- const lSample = left[i] ?? 0;
64
- const rSample = right[i] ?? 0;
65
- const lAbs = lSample < 0 ? -lSample : lSample;
66
- const rAbs = rSample < 0 ? -rSample : rSample;
58
+ const l = left[i] ?? 0;
59
+ const r = right[i] ?? 0;
60
+ const lAbs = l < 0 ? -l : l;
61
+ const rAbs = r < 0 ? -r : r;
67
62
  if (lAbs > lPeak) lPeak = lAbs;
68
63
  if (rAbs > rPeak) rPeak = rAbs;
69
- lSumSq += lSample * lSample;
70
- rSumSq += rSample * rSample;
64
+ lSumSq += l * l;
65
+ rSumSq += r * r;
71
66
  }
72
67
  this.leftPeak = lPeak;
73
68
  this.rightPeak = rPeak;
@@ -82,22 +77,12 @@ if (typeof registerProcessor === "function") registerProcessor(METER_PROCESSOR_N
82
77
  const DEFAULT_METER_FLOOR_DB = -60;
83
78
  const DEFAULT_METER_INTERVAL_MS = 50;
84
79
  const DEFAULT_ANALYSER_FFT_SIZE = 256;
85
- /**
86
- * Converts a linear amplitude `[0, ∞)` to decibels (`-120 dB` floor for silence).
87
- */
88
80
  function linearToDb(amplitude) {
89
81
  return 20 * Math.log10(Math.max(Math.abs(amplitude), 1e-6));
90
82
  }
91
- /**
92
- * Normalizes a dB level against a noise floor (default `-60 dB`) into `[0, 1]`.
93
- */
94
83
  function dbToNormalized(db, floorDb = -60) {
95
- if (floorDb >= 0) return 0;
96
- return Math.max(0, Math.min(1, (db - floorDb) / -floorDb));
84
+ return floorDb >= 0 ? 0 : Math.max(0, Math.min(1, (db - floorDb) / -floorDb));
97
85
  }
98
- /**
99
- * Computes sample peak and RMS over a time-domain buffer.
100
- */
101
86
  function computePeakAndRms(samples) {
102
87
  if (samples.length === 0) return {
103
88
  peak: 0,
@@ -135,10 +120,6 @@ const ZERO_READING = buildStereoMeterReading({
135
120
  rightPeak: 0,
136
121
  rightRms: 0
137
122
  });
138
- /**
139
- * Loads the standalone `@avoid.quest/audio/worklets/meter` AudioWorklet module
140
- * into `context` with Blob-URL fallback support.
141
- */
142
123
  function loadMeterWorklet(context, options = {}) {
143
124
  return loadAudioWorklet(context, {
144
125
  fallbackToBlob: options.fallbackToBlob ?? true,
@@ -148,529 +129,425 @@ function loadMeterWorklet(context, options = {}) {
148
129
  processorName: METER_PROCESSOR_NAME
149
130
  });
150
131
  }
151
- function noopUnsubscribe() {}
152
- function buildStereoMeter(context, source, scope, options = {}) {
153
- const mode = options.mode ?? "auto";
154
- const intervalMs = options.intervalMs ?? 50;
155
- const fftSize = options.fftSize ?? 256;
156
- const floorDb = options.floorDb ?? -60;
157
- const listeners = /* @__PURE__ */ new Set();
158
- let latest = ZERO_READING;
159
- let active = false;
160
- let disposed = false;
161
- let teardownImpl;
162
- const emit = (reading) => {
163
- latest = reading;
164
- for (const listener of listeners) listener(reading);
165
- };
166
- const startAnalyser = () => {
167
- const splitter = context.createChannelSplitter(2);
168
- const leftAnalyser = context.createAnalyser();
169
- const rightAnalyser = context.createAnalyser();
170
- leftAnalyser.fftSize = fftSize;
171
- rightAnalyser.fftSize = fftSize;
172
- const leftBuffer = new Float32Array(fftSize);
173
- const rightBuffer = new Float32Array(fftSize);
174
- source.connect(splitter);
175
- splitter.connect(leftAnalyser, 0);
176
- splitter.connect(rightAnalyser, 1);
177
- const timer = setInterval(() => {
178
- leftAnalyser.getFloatTimeDomainData(leftBuffer);
179
- rightAnalyser.getFloatTimeDomainData(rightBuffer);
180
- const left = computePeakAndRms(leftBuffer);
181
- const right = computePeakAndRms(rightBuffer);
182
- emit(buildStereoMeterReading({
183
- leftPeak: left.peak,
184
- leftRms: left.rms,
185
- rightPeak: right.peak,
186
- rightRms: right.rms
187
- }, floorDb));
188
- }, intervalMs);
189
- return () => {
190
- clearInterval(timer);
191
- try {
192
- source.disconnect(splitter);
193
- } catch {}
194
- splitter.disconnect();
195
- leftAnalyser.disconnect();
196
- rightAnalyser.disconnect();
197
- };
198
- };
199
- const startWorklet = () => {
200
- let cancelled = false;
201
- let workletNode;
202
- let silentSink;
203
- let fallbackTeardown;
204
- const onWorkletMessage = (event) => {
205
- if (!cancelled && event.data) emit(buildStereoMeterReading(event.data, floorDb));
206
- };
207
- const activateFallback = () => {
208
- if (!cancelled && mode === "auto" && !fallbackTeardown) fallbackTeardown = startAnalyser();
209
- };
210
- const startupEffect = loadMeterWorklet(context, options.workletOptions).pipe(Effect.match({
211
- onFailure: () => {
212
- activateFallback();
213
- },
214
- onSuccess: () => {
215
- if (cancelled || typeof globalThis.AudioWorkletNode !== "function") return;
216
- try {
217
- workletNode = new globalThis.AudioWorkletNode(context, METER_PROCESSOR_NAME, {
218
- numberOfInputs: 1,
219
- numberOfOutputs: 1,
220
- outputChannelCount: [1],
221
- processorOptions: { reportIntervalMs: intervalMs }
222
- });
223
- silentSink = context.createGain();
224
- silentSink.gain.value = 0;
225
- workletNode.port.addEventListener("message", onWorkletMessage);
226
- if (typeof workletNode.port.start === "function") workletNode.port.start();
227
- source.connect(workletNode);
228
- workletNode.connect(silentSink);
229
- if (context.destination) silentSink.connect(context.destination);
230
- } catch {
231
- if (workletNode) {
232
- workletNode.port.removeEventListener("message", onWorkletMessage);
233
- if (typeof workletNode.port.close === "function") workletNode.port.close();
234
- try {
235
- source.disconnect(workletNode);
236
- } catch {}
237
- workletNode.disconnect();
238
- }
239
- workletNode = void 0;
240
- silentSink?.disconnect();
241
- silentSink = void 0;
242
- activateFallback();
243
- }
244
- }
245
- }));
246
- const startupFiber = Fiber.runIn(scope)(Effect.runFork(startupEffect));
247
- return () => {
248
- cancelled = true;
249
- startupFiber.interruptUnsafe();
250
- if (workletNode) {
251
- workletNode.port.removeEventListener("message", onWorkletMessage);
252
- if (typeof workletNode.port.close === "function") workletNode.port.close();
253
- try {
254
- source.disconnect(workletNode);
255
- } catch {}
256
- workletNode.disconnect();
257
- workletNode = void 0;
258
- }
259
- if (silentSink) {
260
- silentSink.disconnect();
261
- silentSink = void 0;
262
- }
263
- fallbackTeardown?.();
264
- fallbackTeardown = void 0;
265
- };
266
- };
267
- const activate = () => {
268
- if (active) return;
269
- active = true;
270
- teardownImpl = mode !== "analyser" && typeof globalThis.AudioWorkletNode === "function" && Boolean(context.audioWorklet) ? startWorklet() : startAnalyser();
132
+ const noop = () => {};
133
+ function startAnalyserMeter(context, source, opts, emit) {
134
+ const fftSize = opts.fftSize ?? 256;
135
+ const floorDb = opts.floorDb ?? -60;
136
+ const splitter = context.createChannelSplitter(2);
137
+ const leftAn = context.createAnalyser();
138
+ const rightAn = context.createAnalyser();
139
+ leftAn.fftSize = fftSize;
140
+ rightAn.fftSize = fftSize;
141
+ const lBuf = new Float32Array(fftSize);
142
+ const rBuf = new Float32Array(fftSize);
143
+ source.connect(splitter);
144
+ splitter.connect(leftAn, 0);
145
+ splitter.connect(rightAn, 1);
146
+ const timer = setInterval(() => {
147
+ leftAn.getFloatTimeDomainData(lBuf);
148
+ rightAn.getFloatTimeDomainData(rBuf);
149
+ const l = computePeakAndRms(lBuf);
150
+ const r = computePeakAndRms(rBuf);
151
+ emit(buildStereoMeterReading({
152
+ leftPeak: l.peak,
153
+ leftRms: l.rms,
154
+ rightPeak: r.peak,
155
+ rightRms: r.rms
156
+ }, floorDb));
157
+ }, opts.intervalMs ?? 50);
158
+ return () => {
159
+ clearInterval(timer);
160
+ disconnectEdge(source, splitter);
161
+ splitter.disconnect();
162
+ leftAn.disconnect();
163
+ rightAn.disconnect();
271
164
  };
272
- const deactivate = () => {
273
- if (!active) return;
274
- active = false;
275
- teardownImpl?.();
276
- teardownImpl = void 0;
165
+ }
166
+ function startWorkletMeter(context, source, scope, opts, emit, startFallback) {
167
+ const floorDb = opts.floorDb ?? -60;
168
+ let cancelled = false;
169
+ let node;
170
+ let sink;
171
+ let fallback;
172
+ const onMsg = (ev) => {
173
+ if (!cancelled && ev.data) emit(buildStereoMeterReading(ev.data, floorDb));
277
174
  };
278
- const subscribe = (listener) => {
279
- if (disposed) return noopUnsubscribe;
280
- listeners.add(listener);
281
- if (listeners.size === 1) activate();
282
- return () => {
283
- listeners.delete(listener);
284
- if (listeners.size === 0) deactivate();
285
- };
175
+ const cleanupNodes = () => {
176
+ if (node) {
177
+ node.port.removeEventListener("message", onMsg);
178
+ node.port.close?.();
179
+ disconnectEdge(source, node);
180
+ node.disconnect();
181
+ node = void 0;
182
+ }
183
+ sink?.disconnect();
184
+ sink = void 0;
286
185
  };
287
- const dispose = () => {
288
- disposed = true;
289
- listeners.clear();
290
- deactivate();
186
+ const activateFallback = () => {
187
+ if (!cancelled && (opts.mode ?? "auto") === "auto" && !fallback) fallback = startFallback();
291
188
  };
292
- return {
293
- dispose,
294
- getLatest: () => latest,
295
- isActive: () => active,
296
- subscribe
189
+ const fiber = Fiber.runIn(scope)(Effect.runFork(loadMeterWorklet(context, opts.workletOptions).pipe(Effect.match({
190
+ onFailure: activateFallback,
191
+ onSuccess: () => {
192
+ if (cancelled || typeof globalThis.AudioWorkletNode !== "function") return;
193
+ try {
194
+ node = new globalThis.AudioWorkletNode(context, METER_PROCESSOR_NAME, {
195
+ numberOfInputs: 1,
196
+ numberOfOutputs: 1,
197
+ outputChannelCount: [1],
198
+ processorOptions: { reportIntervalMs: opts.intervalMs ?? 50 }
199
+ });
200
+ sink = context.createGain();
201
+ sink.gain.value = 0;
202
+ node.port.addEventListener("message", onMsg);
203
+ node.port.start?.();
204
+ source.connect(node);
205
+ node.connect(sink);
206
+ if (context.destination) sink.connect(context.destination);
207
+ } catch {
208
+ cleanupNodes();
209
+ activateFallback();
210
+ }
211
+ }
212
+ }))));
213
+ return () => {
214
+ cancelled = true;
215
+ fiber.interruptUnsafe();
216
+ cleanupNodes();
217
+ fallback?.();
218
+ fallback = void 0;
297
219
  };
298
220
  }
299
- /**
300
- * Scoped subscriber-driven stereo peak/RMS meter supporting both the standalone
301
- * `"avoid-meter"` AudioWorklet (wired through a zero-gain sink for Safari/Firefox
302
- * pull-graph compatibility) and a zero-worklet `ChannelSplitter(2) -> 2x AnalyserNode` fallback.
303
- * Activates DSP metering only while `listeners.size > 0` and guarantees deterministic
304
- * node/worklet/timer teardown when the owning Effect `Scope` closes.
305
- */
306
221
  function createStereoMeter(context, source, options = {}) {
307
222
  return Effect.gen(function* () {
308
223
  const scope = yield* Scope.Scope;
309
- const meter = buildStereoMeter(context, source, scope, options);
310
- yield* Scope.addFinalizer(scope, Effect.sync(() => {
311
- meter.dispose();
312
- }));
313
- return meter;
314
- });
315
- }
316
- // src/routing/multi-sink.ts
317
- const MAX_OUTPUT_DELAY_MS = 500;
318
- const DELAY_RAMP_TIME_CONSTANT_S = .02;
319
- /**
320
- * Separately detects `AudioContext.prototype.setSinkId` (Chromium) and
321
- * `HTMLMediaElement.prototype.setSinkId` (Chromium + Firefox).
322
- */
323
- function detectSinkIdCapabilities() {
324
- return {
325
- audioContextSetSinkId: globalThis.AudioContext !== void 0 && "setSinkId" in globalThis.AudioContext.prototype,
326
- mediaElementSetSinkId: globalThis.HTMLMediaElement !== void 0 && "setSinkId" in globalThis.HTMLMediaElement.prototype
327
- };
328
- }
329
- function clampOutputDelayMs(delayMs, maxDelayMs = 500) {
330
- if (!Number.isFinite(delayMs)) return 0;
331
- return Math.max(0, Math.min(maxDelayMs, delayMs));
332
- }
333
- function applyDelayParam(delayNode, context, delayMs) {
334
- const seconds = delayMs / 1e3;
335
- if (typeof delayNode.delayTime.setTargetAtTime === "function") delayNode.delayTime.setTargetAtTime(seconds, context.currentTime, DELAY_RAMP_TIME_CONSTANT_S);
336
- else delayNode.delayTime.value = seconds;
337
- }
338
- function createDefaultElement() {
339
- return new globalThis.Audio();
340
- }
341
- /**
342
- * Creates a `Scope`-managed transactional multi-sink router supporting:
343
- * - Main output bus (`mainInput -> mainDelay -> context.destination`) + `realtimeInput` bypass
344
- * - Dedicated headphone CUE bus (`cueInput -> cueDelay -> cueGain -> MediaStreamDestination -> <audio>.setSinkId`)
345
- * - Arbitrary multi-device output sinks with per-output delay compensation and atomic swap on attach
346
- * - Effect `Semaphore` serialization and full transactional rollback when `setSinkId` or `element.play()` fails.
347
- */
348
- function createMultiSinkRouter(context, options = {}) {
349
- return Effect.gen(function* () {
350
- const maxDelayMs = options.maxDelayMs ?? 500;
351
- const maxDelaySeconds = maxDelayMs / 1e3;
352
- const createElement = options.createAudioElement ?? createDefaultElement;
353
- const capabilities = {
354
- audioContextSetSinkId: typeof context.setSinkId === "function" || detectSinkIdCapabilities().audioContextSetSinkId,
355
- mediaElementSetSinkId: detectSinkIdCapabilities().mediaElementSetSinkId
356
- };
357
- const mainInput = context.createGain();
358
- const realtimeInput = context.createGain();
359
- const mainDelay = context.createDelay(maxDelaySeconds);
360
- mainDelay.delayTime.value = 0;
361
- mainInput.connect(mainDelay);
362
- mainDelay.connect(context.destination);
363
- realtimeInput.connect(context.destination);
364
- const cueInput = context.createGain();
365
- const cueDelay = context.createDelay(maxDelaySeconds);
366
- cueDelay.delayTime.value = 0;
367
- const cueGain = context.createGain();
368
- cueGain.gain.value = 1;
369
- cueInput.connect(cueDelay);
370
- cueDelay.connect(cueGain);
371
- let cueDestination;
372
- let cueElement;
373
- let mainSinkId = context.sinkId ?? "";
374
- let mainDelayMs = 0;
375
- let cueSinkId;
376
- let cueDelayMs = 0;
377
- let cueVolume = 1;
224
+ const listeners = /* @__PURE__ */ new Set();
225
+ let latest = ZERO_READING;
226
+ let active = false;
378
227
  let disposed = false;
379
- const deviceSinks = /* @__PURE__ */ new Map();
380
- const deviceGenerations = /* @__PURE__ */ new Map();
381
- const deviceSemaphores = /* @__PURE__ */ new Map();
382
- const txSemaphore = yield* Semaphore.make(1);
383
- const getDeviceSemaphore = (nodeId) => {
384
- let sem = deviceSemaphores.get(nodeId);
385
- if (!sem) {
386
- sem = Semaphore.makeUnsafe(1);
387
- deviceSemaphores.set(nodeId, sem);
388
- }
389
- return sem;
228
+ let teardownImpl;
229
+ const emit = (r) => {
230
+ latest = r;
231
+ for (const listener of listeners) listener(r);
390
232
  };
391
- const teardownCueOutput = () => {
392
- if (cueDestination) {
393
- try {
394
- cueGain.disconnect(cueDestination);
395
- } catch {}
396
- cueDestination = void 0;
397
- }
398
- if (cueElement) {
399
- cueElement.pause();
400
- cueElement.srcObject = null;
401
- cueElement = void 0;
233
+ const startAnalyser = () => startAnalyserMeter(context, source, options, emit);
234
+ const deactivate = () => {
235
+ if (active) {
236
+ active = false;
237
+ teardownImpl?.();
238
+ teardownImpl = void 0;
402
239
  }
403
240
  };
404
- const configureCueOutput = async (nextCueSinkId) => {
405
- if (!nextCueSinkId) {
406
- teardownCueOutput();
407
- return;
408
- }
409
- if (typeof context.createMediaStreamDestination !== "function") throw new TypeError("AudioContext.createMediaStreamDestination is not supported.");
410
- const nextDest = context.createMediaStreamDestination();
411
- const nextEl = createElement();
412
- if (typeof nextEl.setSinkId !== "function") throw new TypeError("HTMLMediaElement.setSinkId is not supported.");
413
- nextEl.srcObject = nextDest.stream;
414
- try {
415
- await nextEl.setSinkId(nextCueSinkId);
416
- await nextEl.play();
417
- } catch (error) {
418
- nextEl.pause();
419
- nextEl.srcObject = null;
420
- throw error;
421
- }
422
- teardownCueOutput();
423
- cueDestination = nextDest;
424
- cueElement = nextEl;
425
- cueGain.connect(nextDest);
426
- };
427
- const getState = () => {
428
- const devices = {};
429
- for (const [nodeId, sink] of deviceSinks) devices[nodeId] = {
430
- delayMs: sink.delayMs,
431
- deviceId: sink.deviceId,
432
- status: sink.status
433
- };
434
- return {
435
- cueDelayMs,
436
- cueSinkId,
437
- cueVolume,
438
- deviceSinks: devices,
439
- mainDelayMs,
440
- mainSinkId
441
- };
241
+ const dispose = () => {
242
+ disposed = true;
243
+ listeners.clear();
244
+ deactivate();
442
245
  };
443
- const setMainDelayMs = (delayMs) => {
444
- mainDelayMs = clampOutputDelayMs(delayMs, maxDelayMs);
445
- applyDelayParam(mainDelay, context, mainDelayMs);
446
- return mainDelayMs;
246
+ yield* Scope.addFinalizer(scope, Effect.sync(dispose));
247
+ return {
248
+ dispose,
249
+ getLatest: () => latest,
250
+ isActive: () => active,
251
+ subscribe: (listener) => {
252
+ if (disposed) return noop;
253
+ listeners.add(listener);
254
+ if (!active) {
255
+ active = true;
256
+ teardownImpl = options.mode !== "analyser" && typeof globalThis.AudioWorkletNode === "function" && Boolean(context.audioWorklet) ? startWorkletMeter(context, source, scope, options, emit, startAnalyser) : startAnalyser();
257
+ }
258
+ return () => {
259
+ listeners.delete(listener);
260
+ if (listeners.size === 0) deactivate();
261
+ };
262
+ }
447
263
  };
448
- const setCueDelayMs = (delayMs) => {
449
- cueDelayMs = clampOutputDelayMs(delayMs, maxDelayMs);
450
- applyDelayParam(cueDelay, context, cueDelayMs);
451
- return cueDelayMs;
264
+ });
265
+ }
266
+ // src/routing/multi-sink-helpers.ts
267
+ const MAX_OUTPUT_DELAY_MS = 500;
268
+ const DELAY_RAMP_TIME_CONSTANT_S = .02;
269
+ const detectSinkIdCapabilities = () => ({
270
+ audioContextSetSinkId: globalThis.AudioContext !== void 0 && "setSinkId" in globalThis.AudioContext.prototype,
271
+ mediaElementSetSinkId: globalThis.HTMLMediaElement !== void 0 && "setSinkId" in globalThis.HTMLMediaElement.prototype
272
+ });
273
+ const clampOutputDelayMs = (delayMs, maxDelayMs = 500) => clampFinite(delayMs, 0, maxDelayMs, 0);
274
+ const routingErr = (message, deviceId, rolledBack = true) => new AudioRoutingError({
275
+ deviceId,
276
+ message,
277
+ rolledBack
278
+ });
279
+ const applyOutputDelay = (delayNode, context, delayMs) => setParamTarget(delayNode.delayTime, context, delayMs / 1e3, DELAY_RAMP_TIME_CONSTANT_S);
280
+ const runLocked = (sem, run, deviceId, prefix) => sem.withPermits(1)(Effect.uninterruptible(Effect.tryPromise({
281
+ catch: (error) => error instanceof AudioRoutingError ? error : routingErr(prefix ? `${prefix}: ${String(error)}` : String(error), deviceId),
282
+ try: run
283
+ })));
284
+ async function openMediaStreamSink(context, createElement, sinkId, checkStale) {
285
+ if (typeof context.createMediaStreamDestination !== "function") throw new TypeError("createMediaStreamDestination is not supported.");
286
+ const destination = context.createMediaStreamDestination();
287
+ const element = createElement();
288
+ if (typeof element.setSinkId !== "function") throw new TypeError("HTMLMediaElement.setSinkId is not supported.");
289
+ element.srcObject = destination.stream;
290
+ try {
291
+ await element.setSinkId(sinkId);
292
+ checkStale?.();
293
+ await element.play();
294
+ checkStale?.();
295
+ return {
296
+ destination,
297
+ element
452
298
  };
453
- const setCueVolume = (volume) => {
454
- cueVolume = Math.max(0, Math.min(1, Number.isFinite(volume) ? volume : 1));
455
- cueGain.gain.value = cueVolume;
456
- return cueVolume;
299
+ } catch (error) {
300
+ element.pause();
301
+ element.srcObject = null;
302
+ throw error;
303
+ }
304
+ }
305
+ function teardownDeviceSink(sink) {
306
+ disconnectEdge(sink.source, sink.inputGain);
307
+ sink.inputGain.disconnect();
308
+ sink.delayNode.disconnect();
309
+ sink.element.pause();
310
+ sink.element.srcObject = null;
311
+ }
312
+ async function openAndWireDeviceSink(context, createElement, source, deviceId, clampedDelay, maxDelaySec, assertCurrent) {
313
+ const { destination, element } = await openMediaStreamSink(context, createElement, deviceId, assertCurrent);
314
+ let inputGain;
315
+ let delayNode;
316
+ try {
317
+ inputGain = context.createGain();
318
+ delayNode = context.createDelay(maxDelaySec);
319
+ applyOutputDelay(delayNode, context, clampedDelay);
320
+ source.connect(inputGain);
321
+ inputGain.connect(delayNode);
322
+ delayNode.connect(destination);
323
+ } catch (error) {
324
+ if (inputGain) {
325
+ disconnectEdge(source, inputGain);
326
+ inputGain.disconnect();
327
+ }
328
+ delayNode?.disconnect();
329
+ element.pause();
330
+ element.srcObject = null;
331
+ throw error;
332
+ }
333
+ return {
334
+ delayMs: clampedDelay,
335
+ delayNode,
336
+ destination,
337
+ deviceId,
338
+ element,
339
+ inputGain,
340
+ source,
341
+ status: "ok"
342
+ };
343
+ }
344
+ // src/routing/multi-sink.ts
345
+ function buildMultiSinkRouter(context, txSemaphore, options = {}) {
346
+ const maxDelayMs = options.maxDelayMs ?? 500;
347
+ const maxDelaySec = maxDelayMs / 1e3;
348
+ const createElement = options.createAudioElement ?? (() => new globalThis.Audio());
349
+ const detected = detectSinkIdCapabilities();
350
+ const capabilities = {
351
+ audioContextSetSinkId: typeof context.setSinkId === "function" || detected.audioContextSetSinkId,
352
+ mediaElementSetSinkId: detected.mediaElementSetSinkId
353
+ };
354
+ const mainInput = context.createGain();
355
+ const realtimeInput = context.createGain();
356
+ const mainDelay = context.createDelay(maxDelaySec);
357
+ mainDelay.delayTime.value = 0;
358
+ mainInput.connect(mainDelay);
359
+ mainDelay.connect(context.destination);
360
+ realtimeInput.connect(context.destination);
361
+ const cueInput = context.createGain();
362
+ const cueDelay = context.createDelay(maxDelaySec);
363
+ cueDelay.delayTime.value = 0;
364
+ const cueGain = context.createGain();
365
+ cueGain.gain.value = 1;
366
+ cueInput.connect(cueDelay);
367
+ cueDelay.connect(cueGain);
368
+ let cueDestination;
369
+ let cueElement;
370
+ let mainSinkId = context.sinkId ?? "";
371
+ let mainDelayMs = 0;
372
+ let cueSinkId;
373
+ let cueDelayMs = 0;
374
+ let cueVolume = 1;
375
+ let disposed = false;
376
+ const deviceSinks = /* @__PURE__ */ new Map();
377
+ const deviceGens = /* @__PURE__ */ new Map();
378
+ const deviceSems = /* @__PURE__ */ new Map();
379
+ const nextGen = (id) => {
380
+ const g = (deviceGens.get(id) ?? 0) + 1;
381
+ deviceGens.set(id, g);
382
+ return g;
383
+ };
384
+ const teardownCue = () => {
385
+ if (cueDestination) {
386
+ disconnectEdge(cueGain, cueDestination);
387
+ cueDestination = void 0;
388
+ }
389
+ if (cueElement) {
390
+ cueElement.pause();
391
+ cueElement.srcObject = null;
392
+ cueElement = void 0;
393
+ }
394
+ };
395
+ const configureCue = async (nextSink) => {
396
+ if (!nextSink) {
397
+ teardownCue();
398
+ return;
399
+ }
400
+ const { destination, element } = await openMediaStreamSink(context, createElement, nextSink);
401
+ teardownCue();
402
+ cueDestination = destination;
403
+ cueElement = element;
404
+ cueGain.connect(destination);
405
+ };
406
+ const getState = () => ({
407
+ cueDelayMs,
408
+ cueSinkId,
409
+ cueVolume,
410
+ deviceSinks: Object.fromEntries([...deviceSinks].map(([id, s]) => [id, {
411
+ delayMs: s.delayMs,
412
+ deviceId: s.deviceId,
413
+ status: s.status
414
+ }])),
415
+ mainDelayMs,
416
+ mainSinkId
417
+ });
418
+ const setMainDelayMs = (ms) => {
419
+ mainDelayMs = clampOutputDelayMs(ms, maxDelayMs);
420
+ applyOutputDelay(mainDelay, context, mainDelayMs);
421
+ return mainDelayMs;
422
+ };
423
+ const setCueDelayMs = (ms) => {
424
+ cueDelayMs = clampOutputDelayMs(ms, maxDelayMs);
425
+ applyOutputDelay(cueDelay, context, cueDelayMs);
426
+ return cueDelayMs;
427
+ };
428
+ const setCueVolume = (vol) => {
429
+ cueVolume = clampFinite(vol, 0, 1, 1);
430
+ cueGain.gain.value = cueVolume;
431
+ return cueVolume;
432
+ };
433
+ const rollback = async (prev, mainChanged) => {
434
+ let ok = true;
435
+ if (mainChanged && typeof context.setSinkId === "function") try {
436
+ await context.setSinkId(prev.mainSinkId);
437
+ ({mainSinkId} = prev);
438
+ } catch {
439
+ ok = false;
440
+ }
441
+ else ({mainSinkId} = prev);
442
+ setMainDelayMs(prev.mainDelayMs);
443
+ setCueDelayMs(prev.cueDelayMs);
444
+ setCueVolume(prev.cueVolume);
445
+ if (cueSinkId !== prev.cueSinkId) try {
446
+ await configureCue(prev.cueSinkId);
447
+ ({cueSinkId} = prev);
448
+ } catch {
449
+ ok = false;
450
+ teardownCue();
451
+ cueSinkId = void 0;
452
+ }
453
+ return ok;
454
+ };
455
+ const applyTransaction = (patch) => runLocked(txSemaphore, async () => {
456
+ if (disposed) throw routingErr("Router disposed.", patch.cueSinkId ?? patch.mainSinkId);
457
+ const prev = {
458
+ cueDelayMs,
459
+ cueSinkId,
460
+ cueVolume,
461
+ mainDelayMs,
462
+ mainSinkId
457
463
  };
458
- const rollbackTransaction = async (prev, mainChanged) => {
459
- const { cueDelayMs: prevCueDelayMs, cueSinkId: prevCueSinkId, cueVolume: prevCueVolume, mainDelayMs: prevMainDelayMs, mainSinkId: prevMainSinkId } = prev;
460
- let rolledBack = true;
461
- if (mainChanged && typeof context.setSinkId === "function") try {
462
- await context.setSinkId(prevMainSinkId);
463
- mainSinkId = prevMainSinkId;
464
- } catch {
465
- rolledBack = false;
466
- }
467
- else mainSinkId = prevMainSinkId;
468
- setMainDelayMs(prevMainDelayMs);
469
- setCueDelayMs(prevCueDelayMs);
470
- setCueVolume(prevCueVolume);
471
- if (cueSinkId !== prevCueSinkId) try {
472
- await configureCueOutput(prevCueSinkId);
473
- cueSinkId = prevCueSinkId;
474
- } catch {
475
- rolledBack = false;
476
- teardownCueOutput();
477
- cueSinkId = void 0;
464
+ const targetMain = patch.mainSinkId ?? prev.mainSinkId;
465
+ let targetCue = "cueSinkId" in patch ? patch.cueSinkId : prev.cueSinkId;
466
+ if (targetCue && targetCue === targetMain) targetCue = void 0;
467
+ let mainChanged = false;
468
+ try {
469
+ if (targetMain !== prev.mainSinkId) {
470
+ if (typeof context.setSinkId !== "function") throw new TypeError("AudioContext.setSinkId is not supported.");
471
+ await context.setSinkId(targetMain);
472
+ mainChanged = true;
473
+ mainSinkId = targetMain;
478
474
  }
479
- return rolledBack;
480
- };
481
- const applyTransaction = (patch) => txSemaphore.withPermits(1)(Effect.uninterruptible(Effect.tryPromise({
482
- catch: (error) => {
483
- if (error instanceof AudioRoutingError) return error;
484
- return new AudioRoutingError({
485
- message: String(error),
486
- rolledBack: true
487
- });
488
- },
489
- try: async () => {
490
- if (disposed) throw new AudioRoutingError({
491
- deviceId: patch.cueSinkId ?? patch.mainSinkId,
492
- message: "Multi-sink router has been disposed.",
493
- rolledBack: true
494
- });
495
- const prev = {
496
- cueDelayMs,
497
- cueSinkId,
498
- cueVolume,
499
- mainDelayMs,
500
- mainSinkId
501
- };
502
- const targetMainSinkId = patch.mainSinkId === void 0 ? prev.mainSinkId : patch.mainSinkId;
503
- let targetCueSinkId = "cueSinkId" in patch ? patch.cueSinkId : prev.cueSinkId;
504
- if (targetCueSinkId !== void 0 && targetCueSinkId !== "" && targetCueSinkId === targetMainSinkId) targetCueSinkId = void 0;
505
- let mainChanged = false;
506
- try {
507
- if (targetMainSinkId !== prev.mainSinkId) {
508
- if (typeof context.setSinkId !== "function") throw new TypeError("AudioContext.setSinkId is not supported.");
509
- await context.setSinkId(targetMainSinkId);
510
- mainChanged = true;
511
- mainSinkId = targetMainSinkId;
512
- }
513
- if (targetCueSinkId !== prev.cueSinkId) {
514
- await configureCueOutput(targetCueSinkId);
515
- cueSinkId = targetCueSinkId;
516
- }
517
- if (patch.mainDelayMs !== void 0) setMainDelayMs(patch.mainDelayMs);
518
- if (patch.cueDelayMs !== void 0) setCueDelayMs(patch.cueDelayMs);
519
- if (patch.cueVolume !== void 0) setCueVolume(patch.cueVolume);
520
- return getState();
521
- } catch (error) {
522
- const rolledBack = await rollbackTransaction(prev, mainChanged);
523
- throw new AudioRoutingError({
524
- deviceId: patch.cueSinkId ?? patch.mainSinkId,
525
- message: rolledBack ? `Sink routing transaction failed and rolled back: ${String(error)}` : `Sink routing transaction failed with incomplete rollback: ${String(error)}`,
526
- rolledBack
527
- });
528
- }
475
+ if (targetCue !== prev.cueSinkId) {
476
+ await configureCue(targetCue);
477
+ cueSinkId = targetCue;
529
478
  }
530
- })));
531
- const setMainSink = (sinkId) => applyTransaction({ mainSinkId: sinkId });
532
- const setCueSink = (sinkId) => applyTransaction({ cueSinkId: sinkId });
533
- const nextDeviceGeneration = (nodeId) => {
534
- const nextGen = (deviceGenerations.get(nodeId) ?? 0) + 1;
535
- deviceGenerations.set(nodeId, nextGen);
536
- return nextGen;
537
- };
538
- const teardownDeviceSinkRecord = (sink) => {
539
- try {
540
- sink.source.disconnect(sink.inputGain);
541
- } catch {}
542
- sink.inputGain.disconnect();
543
- sink.delayNode.disconnect();
544
- sink.element.pause();
545
- sink.element.srcObject = null;
546
- };
547
- const detachDeviceSink = (nodeId) => {
548
- nextDeviceGeneration(nodeId);
549
- const existing = deviceSinks.get(nodeId);
550
- if (!existing) return;
479
+ if (patch.mainDelayMs !== void 0) setMainDelayMs(patch.mainDelayMs);
480
+ if (patch.cueDelayMs !== void 0) setCueDelayMs(patch.cueDelayMs);
481
+ if (patch.cueVolume !== void 0) setCueVolume(patch.cueVolume);
482
+ return getState();
483
+ } catch (error) {
484
+ const rolledBack = await rollback(prev, mainChanged);
485
+ throw routingErr(rolledBack ? `Sink transaction rolled back: ${String(error)}` : `Sink transaction failed (incomplete rollback): ${String(error)}`, patch.cueSinkId ?? patch.mainSinkId, rolledBack);
486
+ }
487
+ });
488
+ const detachDeviceSink = (nodeId) => {
489
+ nextGen(nodeId);
490
+ const existing = deviceSinks.get(nodeId);
491
+ if (existing) {
551
492
  deviceSinks.delete(nodeId);
552
- teardownDeviceSinkRecord(existing);
553
- };
554
- const attachDeviceSink = (nodeId, source, deviceId, delayMs = 0) => Effect.suspend(() => {
555
- const myGeneration = nextDeviceGeneration(nodeId);
556
- const isStale = () => disposed || deviceGenerations.get(nodeId) !== myGeneration;
557
- return getDeviceSemaphore(nodeId).withPermits(1)(Effect.uninterruptible(Effect.tryPromise({
558
- catch: (error) => {
559
- if (error instanceof AudioRoutingError) return error;
560
- return new AudioRoutingError({
561
- deviceId,
562
- message: `Failed to attach device sink "${deviceId}": ${String(error)}`,
563
- rolledBack: true
564
- });
565
- },
566
- try: async () => {
567
- if (disposed) throw new AudioRoutingError({
568
- deviceId,
569
- message: "Multi-sink router has been disposed.",
570
- rolledBack: true
571
- });
572
- if (isStale()) throw new AudioRoutingError({
573
- deviceId,
574
- message: `Device sink "${deviceId}" attachment was superseded or cancelled.`,
575
- rolledBack: true
576
- });
577
- if (typeof context.createMediaStreamDestination !== "function") throw new AudioRoutingError({
578
- deviceId,
579
- message: "AudioContext.createMediaStreamDestination is not supported.",
580
- rolledBack: true
581
- });
582
- const clampedDelay = clampOutputDelayMs(delayMs, maxDelayMs);
583
- const destination = context.createMediaStreamDestination();
584
- const element = createElement();
585
- if (typeof element.setSinkId !== "function") throw new AudioRoutingError({
586
- deviceId,
587
- message: "HTMLMediaElement.setSinkId is not supported.",
588
- rolledBack: true
589
- });
590
- const inputGain = context.createGain();
591
- const delayNode = context.createDelay(maxDelaySeconds);
592
- applyDelayParam(delayNode, context, clampedDelay);
593
- const cleanupStaged = () => {
594
- try {
595
- source.disconnect(inputGain);
596
- } catch {}
597
- inputGain.disconnect();
598
- delayNode.disconnect();
599
- element.pause();
600
- element.srcObject = null;
601
- };
602
- try {
603
- element.srcObject = destination.stream;
604
- await element.setSinkId(deviceId);
605
- if (isStale()) throw new AudioRoutingError({
606
- deviceId,
607
- message: `Device sink "${deviceId}" attachment was superseded or cancelled.`,
608
- rolledBack: true
609
- });
610
- await element.play();
611
- if (isStale()) throw new AudioRoutingError({
612
- deviceId,
613
- message: `Device sink "${deviceId}" attachment was superseded or cancelled.`,
614
- rolledBack: true
615
- });
616
- source.connect(inputGain);
617
- inputGain.connect(delayNode);
618
- delayNode.connect(destination);
619
- } catch (error) {
620
- cleanupStaged();
621
- if (error instanceof AudioRoutingError) throw error;
622
- throw new AudioRoutingError({
623
- deviceId,
624
- message: `Failed to attach device sink "${deviceId}": ${String(error)}`,
625
- rolledBack: true
626
- });
627
- }
628
- const previous = deviceSinks.get(nodeId);
629
- deviceSinks.set(nodeId, {
630
- delayMs: clampedDelay,
631
- delayNode,
632
- destination,
633
- deviceId,
634
- element,
635
- inputGain,
636
- source,
637
- status: "ok"
638
- });
639
- if (previous) teardownDeviceSinkRecord(previous);
640
- return "ok";
641
- }
642
- })));
643
- });
644
- const dispose = () => {
645
- disposed = true;
646
- for (const nodeId of deviceSinks.keys()) detachDeviceSink(nodeId);
647
- teardownCueOutput();
648
- mainInput.disconnect();
649
- realtimeInput.disconnect();
650
- mainDelay.disconnect();
651
- cueInput.disconnect();
652
- cueDelay.disconnect();
653
- cueGain.disconnect();
493
+ teardownDeviceSink(existing);
494
+ }
495
+ };
496
+ const attachDeviceSink = (nodeId, source, deviceId, delayMs = 0) => Effect.suspend(() => {
497
+ const gen = nextGen(nodeId);
498
+ const assertCurrent = () => {
499
+ if (disposed || deviceGens.get(nodeId) !== gen) throw routingErr(disposed ? "Router disposed." : `Device sink "${deviceId}" superseded.`, deviceId);
654
500
  };
655
- yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(() => {
656
- dispose();
657
- }));
658
- return {
659
- applyTransaction,
660
- attachDeviceSink,
661
- capabilities,
662
- cueInput,
663
- detachDeviceSink,
664
- dispose,
665
- getState,
501
+ let sem = deviceSems.get(nodeId);
502
+ if (!sem) {
503
+ sem = Semaphore.makeUnsafe(1);
504
+ deviceSems.set(nodeId, sem);
505
+ }
506
+ return runLocked(sem, async () => {
507
+ assertCurrent();
508
+ const managed = await openAndWireDeviceSink(context, createElement, source, deviceId, clampOutputDelayMs(delayMs, maxDelayMs), maxDelaySec, assertCurrent);
509
+ const prev = deviceSinks.get(nodeId);
510
+ deviceSinks.set(nodeId, managed);
511
+ if (prev) teardownDeviceSink(prev);
512
+ return "ok";
513
+ }, deviceId, `Attach sink "${deviceId}" failed`);
514
+ });
515
+ const dispose = () => {
516
+ disposed = true;
517
+ for (const id of deviceSinks.keys()) detachDeviceSink(id);
518
+ teardownCue();
519
+ for (const n of [
666
520
  mainInput,
667
521
  realtimeInput,
668
- setCueDelayMs,
669
- setCueSink,
670
- setCueVolume,
671
- setMainDelayMs,
672
- setMainSink
673
- };
522
+ mainDelay,
523
+ cueInput,
524
+ cueDelay,
525
+ cueGain
526
+ ]) n.disconnect();
527
+ };
528
+ return {
529
+ applyTransaction,
530
+ attachDeviceSink,
531
+ capabilities,
532
+ cueInput,
533
+ detachDeviceSink,
534
+ dispose,
535
+ getState,
536
+ mainInput,
537
+ realtimeInput,
538
+ setCueDelayMs,
539
+ setCueSink: (cue) => applyTransaction({ cueSinkId: cue }),
540
+ setCueVolume,
541
+ setMainDelayMs,
542
+ setMainSink: (main) => applyTransaction({ mainSinkId: main })
543
+ };
544
+ }
545
+ function createMultiSinkRouter(context, options = {}) {
546
+ return Effect.gen(function* () {
547
+ const scope = yield* Scope.Scope;
548
+ const router = buildMultiSinkRouter(context, yield* Semaphore.make(1), options);
549
+ yield* Scope.addFinalizer(scope, Effect.sync(router.dispose));
550
+ return router;
674
551
  });
675
552
  }
676
553
  export { DEFAULT_ANALYSER_FFT_SIZE, DEFAULT_METER_FLOOR_DB, DEFAULT_METER_INTERVAL_MS, DELAY_RAMP_TIME_CONSTANT_S, MAX_OUTPUT_DELAY_MS, METER_PROCESSOR_NAME, VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE, buildStereoMeterReading, clampOutputDelayMs, computePeakAndRms, createMultiSinkRouter, createStereoMeter, createWorkletBlobUrl, createWorkletModuleUrl, dbToNormalized, detectSinkIdCapabilities, linearToDb, loadAudioWorklet, loadMeterWorklet };