@tensamin/audio 0.1.2 → 0.1.3

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.
package/dist/index.js CHANGED
@@ -96,32 +96,60 @@ var RNNoisePlugin = class {
96
96
  async createNode(context, config) {
97
97
  const { loadRnnoise, RnnoiseWorkletNode } = await import("@sapphi-red/web-noise-suppressor");
98
98
  if (!config?.enabled) {
99
+ console.log("Noise suppression disabled, using passthrough node");
99
100
  const pass = context.createGain();
100
101
  return pass;
101
102
  }
102
103
  if (!config?.wasmUrl || !config?.simdUrl || !config?.workletUrl) {
103
- throw new Error(
104
- "RNNoisePlugin requires 'wasmUrl', 'simdUrl', and 'workletUrl' to be configured. Please download the assets and provide the URLs."
104
+ const error = new Error(
105
+ `RNNoisePlugin requires 'wasmUrl', 'simdUrl', and 'workletUrl' to be configured. Please download the assets from @sapphi-red/web-noise-suppressor and provide the URLs in the config. Current config: wasmUrl=${config?.wasmUrl}, simdUrl=${config?.simdUrl}, workletUrl=${config?.workletUrl}
106
+ To disable noise suppression, set noiseSuppression.enabled to false.`
105
107
  );
108
+ console.error(error.message);
109
+ throw error;
106
110
  }
107
- if (!this.wasmBuffer) {
108
- this.wasmBuffer = await loadRnnoise({
109
- url: config.wasmUrl,
110
- simdUrl: config.simdUrl
111
- });
111
+ try {
112
+ if (!this.wasmBuffer) {
113
+ console.log("Loading RNNoise WASM binary...");
114
+ this.wasmBuffer = await loadRnnoise({
115
+ url: config.wasmUrl,
116
+ simdUrl: config.simdUrl
117
+ });
118
+ console.log("RNNoise WASM loaded successfully");
119
+ }
120
+ } catch (error) {
121
+ const err = new Error(
122
+ `Failed to load RNNoise WASM binary: ${error instanceof Error ? error.message : String(error)}`
123
+ );
124
+ console.error(err);
125
+ throw err;
112
126
  }
113
127
  const workletUrl = config.workletUrl;
114
128
  try {
115
129
  await context.audioWorklet.addModule(workletUrl);
130
+ console.log("RNNoise worklet loaded successfully");
116
131
  } catch (e) {
117
- console.warn("Failed to add RNNoise worklet module:", e);
132
+ const error = new Error(
133
+ `Failed to load RNNoise worklet from ${workletUrl}: ${e instanceof Error ? e.message : String(e)}. Ensure the workletUrl points to a valid RNNoise worklet script.`
134
+ );
135
+ console.error(error.message);
136
+ throw error;
137
+ }
138
+ try {
139
+ const node = new RnnoiseWorkletNode(context, {
140
+ wasmBinary: this.wasmBuffer,
141
+ maxChannels: 1
142
+ // Mono for now
143
+ });
144
+ console.log("RNNoise worklet node created successfully");
145
+ return node;
146
+ } catch (error) {
147
+ const err = new Error(
148
+ `Failed to create RNNoise worklet node: ${error instanceof Error ? error.message : String(error)}`
149
+ );
150
+ console.error(err);
151
+ throw err;
118
152
  }
119
- const node = new RnnoiseWorkletNode(context, {
120
- wasmBinary: this.wasmBuffer,
121
- maxChannels: 1
122
- // Mono for now
123
- });
124
- return node;
125
153
  }
126
154
  };
127
155
 
@@ -169,22 +197,52 @@ registerProcessor('energy-vad-processor', EnergyVadProcessor);
169
197
  var EnergyVADPlugin = class {
170
198
  name = "energy-vad";
171
199
  async createNode(context, config, onDecision) {
200
+ if (!config?.enabled) {
201
+ console.log("VAD disabled, using passthrough node");
202
+ const pass = context.createGain();
203
+ return pass;
204
+ }
172
205
  const blob = new Blob([energyVadWorkletCode], {
173
206
  type: "application/javascript"
174
207
  });
175
208
  const url = URL.createObjectURL(blob);
176
209
  try {
177
210
  await context.audioWorklet.addModule(url);
211
+ console.log("Energy VAD worklet loaded successfully");
178
212
  } catch (e) {
179
- console.warn("Failed to add Energy VAD worklet:", e);
180
- throw e;
181
- } finally {
213
+ const error = new Error(
214
+ `Failed to load Energy VAD worklet: ${e instanceof Error ? e.message : String(e)}`
215
+ );
216
+ console.error(error.message);
182
217
  URL.revokeObjectURL(url);
218
+ throw error;
219
+ }
220
+ URL.revokeObjectURL(url);
221
+ let node;
222
+ try {
223
+ node = new AudioWorkletNode(context, "energy-vad-processor");
224
+ console.log("Energy VAD node created successfully");
225
+ } catch (e) {
226
+ const error = new Error(
227
+ `Failed to create Energy VAD node: ${e instanceof Error ? e.message : String(e)}`
228
+ );
229
+ console.error(error.message);
230
+ throw error;
183
231
  }
184
- const node = new AudioWorkletNode(context, "energy-vad-processor");
185
232
  node.port.onmessage = (event) => {
186
- const { probability } = event.data;
187
- onDecision(probability);
233
+ try {
234
+ const { probability } = event.data;
235
+ if (typeof probability === "number" && !isNaN(probability)) {
236
+ onDecision(probability);
237
+ } else {
238
+ console.warn("Invalid VAD probability received:", event.data);
239
+ }
240
+ } catch (error) {
241
+ console.error("Error in VAD message handler:", error);
242
+ }
243
+ };
244
+ node.port.onmessageerror = (event) => {
245
+ console.error("VAD port message error:", event);
188
246
  };
189
247
  return node;
190
248
  }
@@ -284,42 +342,84 @@ var VADStateMachine = class {
284
342
  async function createAudioPipeline(sourceTrack, config = {}) {
285
343
  const context = getAudioContext();
286
344
  registerPipeline();
345
+ const nsEnabled = config.noiseSuppression?.enabled !== false && Boolean(config.noiseSuppression?.wasmUrl && config.noiseSuppression?.simdUrl && config.noiseSuppression?.workletUrl);
346
+ const vadEnabled = config.vad?.enabled !== false;
287
347
  const fullConfig = {
288
- noiseSuppression: { enabled: true, ...config.noiseSuppression },
289
- vad: { enabled: true, ...config.vad },
348
+ noiseSuppression: {
349
+ enabled: nsEnabled,
350
+ ...config.noiseSuppression
351
+ },
352
+ vad: {
353
+ enabled: vadEnabled,
354
+ ...config.vad
355
+ },
290
356
  output: {
291
357
  speechGain: 1,
292
- silenceGain: 0,
358
+ silenceGain: vadEnabled ? 0 : 1,
359
+ // If no VAD, always output audio
293
360
  gainRampTime: 0.02,
294
361
  ...config.output
295
362
  },
296
363
  livekit: { manageTrackMute: false, ...config.livekit }
297
364
  };
365
+ console.log("Audio pipeline config:", {
366
+ noiseSuppression: fullConfig.noiseSuppression?.enabled,
367
+ vad: fullConfig.vad?.enabled,
368
+ output: fullConfig.output
369
+ });
370
+ if (!sourceTrack || sourceTrack.kind !== "audio") {
371
+ throw new Error("createAudioPipeline requires a valid audio MediaStreamTrack");
372
+ }
373
+ if (sourceTrack.readyState === "ended") {
374
+ throw new Error("Cannot create pipeline from an ended MediaStreamTrack");
375
+ }
298
376
  const sourceStream = new MediaStream([sourceTrack]);
299
377
  const sourceNode = context.createMediaStreamSource(sourceStream);
300
- const nsPlugin = getNoiseSuppressionPlugin(
301
- fullConfig.noiseSuppression?.pluginName
302
- );
303
- const nsNode = await nsPlugin.createNode(
304
- context,
305
- fullConfig.noiseSuppression
306
- );
307
- const vadPlugin = getVADPlugin(fullConfig.vad?.pluginName);
308
- const vadStateMachine = new VADStateMachine(fullConfig.vad);
378
+ let nsNode;
379
+ let vadNode;
309
380
  const emitter = (0, import_mitt.default)();
310
- const vadNode = await vadPlugin.createNode(
311
- context,
312
- fullConfig.vad,
313
- (prob) => {
314
- const timestamp = context.currentTime * 1e3;
315
- const newState = vadStateMachine.processFrame(prob, timestamp);
316
- if (newState.state !== lastVadState.state || Math.abs(newState.probability - lastVadState.probability) > 0.1) {
317
- emitter.emit("vadChange", newState);
318
- lastVadState = newState;
319
- updateGain(newState);
381
+ try {
382
+ const nsPlugin = getNoiseSuppressionPlugin(
383
+ fullConfig.noiseSuppression?.pluginName
384
+ );
385
+ nsNode = await nsPlugin.createNode(
386
+ context,
387
+ fullConfig.noiseSuppression
388
+ );
389
+ } catch (error) {
390
+ const err = error instanceof Error ? error : new Error(String(error));
391
+ console.error("Failed to create noise suppression node:", err);
392
+ emitter.emit("error", err);
393
+ throw err;
394
+ }
395
+ const vadStateMachine = new VADStateMachine(fullConfig.vad);
396
+ try {
397
+ const vadPlugin = getVADPlugin(fullConfig.vad?.pluginName);
398
+ vadNode = await vadPlugin.createNode(
399
+ context,
400
+ fullConfig.vad,
401
+ (prob) => {
402
+ try {
403
+ const timestamp = context.currentTime * 1e3;
404
+ const newState = vadStateMachine.processFrame(prob, timestamp);
405
+ if (newState.state !== lastVadState.state || Math.abs(newState.probability - lastVadState.probability) > 0.1) {
406
+ emitter.emit("vadChange", newState);
407
+ lastVadState = newState;
408
+ updateGain(newState);
409
+ }
410
+ } catch (vadError) {
411
+ const err = vadError instanceof Error ? vadError : new Error(String(vadError));
412
+ console.error("Error in VAD callback:", err);
413
+ emitter.emit("error", err);
414
+ }
320
415
  }
321
- }
322
- );
416
+ );
417
+ } catch (error) {
418
+ const err = error instanceof Error ? error : new Error(String(error));
419
+ console.error("Failed to create VAD node:", err);
420
+ emitter.emit("error", err);
421
+ throw err;
422
+ }
323
423
  let lastVadState = {
324
424
  isSpeaking: false,
325
425
  probability: 0,
@@ -335,34 +435,98 @@ async function createAudioPipeline(sourceTrack, config = {}) {
335
435
  const gainNode = context.createGain();
336
436
  gainNode.gain.value = fullConfig.output?.silenceGain ?? 0;
337
437
  const destination = context.createMediaStreamDestination();
338
- splitter.connect(delayNode);
339
- delayNode.connect(gainNode);
340
- gainNode.connect(destination);
438
+ try {
439
+ splitter.connect(delayNode);
440
+ delayNode.connect(gainNode);
441
+ gainNode.connect(destination);
442
+ } catch (error) {
443
+ const err = error instanceof Error ? error : new Error(String(error));
444
+ console.error("Failed to wire audio pipeline:", err);
445
+ emitter.emit("error", err);
446
+ throw err;
447
+ }
341
448
  function updateGain(state) {
342
- const { speechGain, silenceGain, gainRampTime } = fullConfig.output;
343
- const targetGain = state.isSpeaking ? speechGain ?? 1 : silenceGain ?? 0;
344
- const now = context.currentTime;
345
- gainNode.gain.setTargetAtTime(targetGain, now, gainRampTime ?? 0.02);
449
+ try {
450
+ const { speechGain, silenceGain, gainRampTime } = fullConfig.output;
451
+ const targetGain = state.isSpeaking ? speechGain ?? 1 : silenceGain ?? 0;
452
+ const now = context.currentTime;
453
+ gainNode.gain.setTargetAtTime(targetGain, now, gainRampTime ?? 0.02);
454
+ } catch (error) {
455
+ const err = error instanceof Error ? error : new Error(String(error));
456
+ console.error("Failed to update gain:", err);
457
+ emitter.emit("error", err);
458
+ }
346
459
  }
460
+ const audioTracks = destination.stream.getAudioTracks();
461
+ console.log("Destination stream tracks:", {
462
+ count: audioTracks.length,
463
+ tracks: audioTracks.map((t) => ({
464
+ id: t.id,
465
+ label: t.label,
466
+ enabled: t.enabled,
467
+ readyState: t.readyState
468
+ }))
469
+ });
470
+ if (audioTracks.length === 0) {
471
+ const err = new Error(
472
+ "Failed to create processed audio track: destination stream has no audio tracks. This may indicate an issue with the audio graph connection."
473
+ );
474
+ console.error(err);
475
+ emitter.emit("error", err);
476
+ throw err;
477
+ }
478
+ const processedTrack = audioTracks[0];
479
+ if (!processedTrack || processedTrack.readyState === "ended") {
480
+ const err = new Error("Processed audio track is invalid or ended");
481
+ console.error(err);
482
+ emitter.emit("error", err);
483
+ throw err;
484
+ }
485
+ console.log("Audio pipeline created successfully:", {
486
+ sourceTrack: {
487
+ id: sourceTrack.id,
488
+ label: sourceTrack.label,
489
+ readyState: sourceTrack.readyState
490
+ },
491
+ processedTrack: {
492
+ id: processedTrack.id,
493
+ label: processedTrack.label,
494
+ readyState: processedTrack.readyState
495
+ },
496
+ config: {
497
+ noiseSuppression: fullConfig.noiseSuppression?.enabled,
498
+ vad: fullConfig.vad?.enabled
499
+ }
500
+ });
347
501
  function dispose() {
348
- sourceNode.disconnect();
349
- nsNode.disconnect();
350
- splitter.disconnect();
351
- vadNode.disconnect();
352
- delayNode.disconnect();
353
- gainNode.disconnect();
354
- destination.stream.getTracks().forEach((t) => t.stop());
355
- unregisterPipeline();
502
+ try {
503
+ sourceNode.disconnect();
504
+ nsNode.disconnect();
505
+ splitter.disconnect();
506
+ vadNode.disconnect();
507
+ delayNode.disconnect();
508
+ gainNode.disconnect();
509
+ destination.stream.getTracks().forEach((t) => t.stop());
510
+ unregisterPipeline();
511
+ } catch (error) {
512
+ console.error("Error during pipeline disposal:", error);
513
+ }
356
514
  }
357
515
  return {
358
- processedTrack: destination.stream.getAudioTracks()[0],
516
+ processedTrack,
359
517
  events: emitter,
360
518
  get state() {
361
519
  return lastVadState;
362
520
  },
363
521
  setConfig: (newConfig) => {
364
- if (newConfig.vad) {
365
- vadStateMachine.updateConfig(newConfig.vad);
522
+ try {
523
+ if (newConfig.vad) {
524
+ vadStateMachine.updateConfig(newConfig.vad);
525
+ }
526
+ } catch (error) {
527
+ const err = error instanceof Error ? error : new Error(String(error));
528
+ console.error("Failed to update config:", err);
529
+ emitter.emit("error", err);
366
530
  }
367
531
  },
368
532
  dispose
@@ -371,31 +535,84 @@ async function createAudioPipeline(sourceTrack, config = {}) {
371
535
 
372
536
  // src/livekit/integration.ts
373
537
  async function attachProcessingToTrack(track, config = {}) {
538
+ if (!track) {
539
+ throw new Error("attachProcessingToTrack requires a valid LocalAudioTrack");
540
+ }
374
541
  const originalTrack = track.mediaStreamTrack;
375
- const pipeline = await createAudioPipeline(originalTrack, config);
376
- await track.replaceTrack(pipeline.processedTrack);
542
+ if (!originalTrack) {
543
+ throw new Error("LocalAudioTrack has no underlying MediaStreamTrack");
544
+ }
545
+ if (originalTrack.readyState === "ended") {
546
+ throw new Error("Cannot attach processing to an ended MediaStreamTrack");
547
+ }
548
+ let pipeline;
549
+ try {
550
+ console.log("Creating audio processing pipeline...");
551
+ pipeline = await createAudioPipeline(originalTrack, config);
552
+ console.log("Audio processing pipeline created successfully");
553
+ } catch (error) {
554
+ const err = new Error(
555
+ `Failed to create audio pipeline: ${error instanceof Error ? error.message : String(error)}`
556
+ );
557
+ console.error(err);
558
+ throw err;
559
+ }
560
+ if (!pipeline.processedTrack) {
561
+ throw new Error("Pipeline did not return a processed track");
562
+ }
563
+ try {
564
+ console.log("Replacing LiveKit track with processed track...");
565
+ await track.replaceTrack(pipeline.processedTrack);
566
+ console.log("LiveKit track replaced successfully");
567
+ } catch (error) {
568
+ pipeline.dispose();
569
+ const err = new Error(
570
+ `Failed to replace LiveKit track: ${error instanceof Error ? error.message : String(error)}`
571
+ );
572
+ console.error(err);
573
+ throw err;
574
+ }
377
575
  if (config.livekit?.manageTrackMute) {
378
576
  let isVadMuted = false;
379
577
  pipeline.events.on("vadChange", async (state) => {
380
- if (state.isSpeaking) {
381
- if (isVadMuted) {
382
- await track.unmute();
383
- isVadMuted = false;
384
- }
385
- } else {
386
- if (!track.isMuted) {
387
- await track.mute();
388
- isVadMuted = true;
578
+ try {
579
+ if (state.isSpeaking) {
580
+ if (isVadMuted) {
581
+ await track.unmute();
582
+ isVadMuted = false;
583
+ }
584
+ } else {
585
+ if (!track.isMuted) {
586
+ await track.mute();
587
+ isVadMuted = true;
588
+ }
389
589
  }
590
+ } catch (error) {
591
+ console.error("Error handling VAD-based track muting:", error);
390
592
  }
391
593
  });
392
594
  }
595
+ pipeline.events.on("error", (error) => {
596
+ console.error("Audio pipeline error:", error);
597
+ });
393
598
  const originalDispose = pipeline.dispose;
394
599
  pipeline.dispose = () => {
395
- if (originalTrack.readyState === "live") {
396
- track.replaceTrack(originalTrack).catch(console.error);
600
+ try {
601
+ if (originalTrack.readyState === "live") {
602
+ console.log("Restoring original track...");
603
+ track.replaceTrack(originalTrack).catch((error) => {
604
+ console.error("Failed to restore original track:", error);
605
+ });
606
+ }
607
+ originalDispose();
608
+ } catch (error) {
609
+ console.error("Error during pipeline disposal:", error);
610
+ try {
611
+ originalDispose();
612
+ } catch (disposeError) {
613
+ console.error("Error calling original dispose:", disposeError);
614
+ }
397
615
  }
398
- originalDispose();
399
616
  };
400
617
  return pipeline;
401
618
  }
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import "./chunk-WBQAMGXK.mjs";
2
2
  import {
3
3
  attachProcessingToTrack
4
- } from "./chunk-HFSKQ33X.mjs";
4
+ } from "./chunk-XMTQPMQ6.mjs";
5
5
  import {
6
6
  createAudioPipeline
7
- } from "./chunk-QU7E5HBA.mjs";
7
+ } from "./chunk-EXH2PNUE.mjs";
8
8
  import {
9
9
  VADStateMachine
10
10
  } from "./chunk-JJASCVEW.mjs";
@@ -21,13 +21,13 @@ import {
21
21
  getVADPlugin,
22
22
  registerNoiseSuppressionPlugin,
23
23
  registerVADPlugin
24
- } from "./chunk-FS635GMR.mjs";
24
+ } from "./chunk-6P2RDBW5.mjs";
25
25
  import {
26
26
  RNNoisePlugin
27
- } from "./chunk-SDTOKWM2.mjs";
27
+ } from "./chunk-XO6B3D4A.mjs";
28
28
  import {
29
29
  EnergyVADPlugin
30
- } from "./chunk-UMU2KIB6.mjs";
30
+ } from "./chunk-R5JVHKWA.mjs";
31
31
  export {
32
32
  EnergyVADPlugin,
33
33
  RNNoisePlugin,