@cc-livekit/audio-pipeline-plugin 1.1.5 → 1.1.7

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/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
13
  - DeepFilter wasm source package: `DeepFilterNet/libDF/pkg/df.js` + `df_bg.wasm`.
14
14
  - Artifact generator: `node ./scripts/build-deepfilter-artifacts.mjs`.
15
- - Generated files: `src/dist/deepfilter-bindgen.js`, `src/dist/deepfilter-wasm-base64.js`, `src/dist/deepfilter-sync.js`.
15
+ - Generated files: `src/dist/deepfilter-bindgen.js`, `src/dist/rnnoise-sync.js`, `dist/deepfilter.wasm`.
16
16
  - `build:js` runs artifact generation first, then bundles worklet + library outputs.
17
17
 
18
18
  ## Example
@@ -28,17 +28,16 @@ const processor = new AudioPipelineTrackProcessor({
28
28
  moduleConfigs: {
29
29
  rnnoise: {
30
30
  vadLogs: true,
31
- bufferOverflowMs: 1000,
31
+ vadLogIntervalMs: 1000,
32
32
  },
33
33
  deepfilternet: {
34
- modelUrl: "/assets/DeepFilterNet3_onnx.tar.gz",
35
34
  attenLimDb: 100,
36
35
  postFilterBeta: 0,
37
36
  },
38
37
  },
39
38
  })
40
39
 
41
- await processor.setModuleConfig("rnnoise", { vadLogs: true, bufferOverflowMs: 800 })
40
+ await processor.setModuleConfig("rnnoise", { vadLogs: true, vadLogIntervalMs: 800 })
42
41
  await processor.setModuleConfig("deepfilternet", { attenLimDb: 30, postFilterBeta: 0.02 })
43
42
  await processor.setStageModule("denoise", "deepfilternet")
44
43
  await processor.setStageModule("denoise", "rnnoise")
@@ -47,11 +46,11 @@ await processor.setStageModule("denoise", "rnnoise")
47
46
  ## Runtime Behavior
48
47
 
49
48
  - Single `AudioWorklet` runtime.
50
- - `setStageModule("denoise", ...)` switches denoise module in-place without restart.
51
- - `setModuleConfig("deepfilternet", ...)` supports dynamic model + param update.
52
- - If both `modelBuffer` and `modelUrl` are passed, `modelBuffer` is used.
53
- - `modelUrl` is fetched on the main thread and transferred to worklet.
54
- - `vadLogs` and `bufferOverflowMs` are `rnnoise`-only configs.
49
+ - **WASM and models are loaded only at init.** Both `rnnoise` and `deepfilternet` WASM binaries are fetched and both modules are created during `init()`. No model or WASM is loaded when switching modules or when calling `setModuleConfig` later.
50
+ - `setStageModule("denoise", ...)` switches the active denoise module in-place (rnnoise ↔ deepfilternet). Only the already-loaded active module is used; no extra loading.
51
+ - `setModuleConfig("deepfilternet", ...)` after init only updates parameters (`attenLimDb`, `postFilterBeta`). DeepFilter uses the **built-in model only** (no custom model loading).
52
+ - `setModuleConfig("rnnoise", ...)` updates rnnoise-only config.
53
+ - `vadLogs` and `vadLogIntervalMs` are `rnnoise`-only configs.
55
54
  - They are ignored by `deepfilternet`.
56
55
  - Updating rnnoise config while deepfilter is active is cached and applied when switching back to rnnoise.
57
56
  - Input audio must be **48 kHz**; the pipeline does not perform sample-rate conversion.
@@ -3,7 +3,6 @@ import type { AudioProcessorOptions, Room, TrackProcessor } from "livekit-client
3
3
  import type { AudioPipelineOptions, DeepFilterModuleConfig, DenoiseModuleId, PipelineStage, RnnoiseModuleConfig } from "./options";
4
4
  export declare class AudioPipelineTrackProcessor implements TrackProcessor<Track.Kind.Audio, AudioProcessorOptions> {
5
5
  private static readonly _loadedContexts;
6
- private static readonly _loadedWorkletUrls;
7
6
  readonly name = "audio-pipeline-filter";
8
7
  processedTrack?: MediaStreamTrack | undefined;
9
8
  private _audioOpts?;
@@ -12,8 +11,7 @@ export declare class AudioPipelineTrackProcessor implements TrackProcessor<Track
12
11
  private _worker?;
13
12
  private _enabled;
14
13
  private _options;
15
- private _nextRequestId;
16
- private _pendingCommands;
14
+ private readonly _commandTransport;
17
15
  private _operationQueue;
18
16
  constructor(options: AudioPipelineOptions);
19
17
  static isSupported(): boolean;
@@ -33,16 +31,12 @@ export declare class AudioPipelineTrackProcessor implements TrackProcessor<Track
33
31
  private _ensureWorkletLoaded;
34
32
  private _waitForWorkerInit;
35
33
  private _closeInternal;
36
- private _fetchWasmBinaries;
37
- private _resolveModelBuffer;
38
- private _fetchBinary;
39
34
  private readonly _handleRuntimeMessage;
40
35
  private _handleLog;
36
+ private _handleCommandError;
41
37
  private _runSerial;
38
+ private _createModuleConfigs;
42
39
  private _sendCommand;
43
- private _resolvePending;
44
- private _rejectPending;
45
- private _rejectAllPendingCommands;
46
40
  private static readonly _LOG_TAG;
47
41
  private _debug;
48
42
  }
@@ -1 +1 @@
1
- "undefined"==typeof self&&(globalThis.self=globalThis),(()=>{"use strict";var e={807:(e,t,n)=>{let r;n.d(t,{A:()=>o}),e=n.hmd(e),function(){const t={};let o,i;"undefined"!=typeof document&&null!==document.currentScript&&(o=new URL(document.currentScript.src,location.href).toString());const a=new Array(128).fill(void 0);function s(e){return a[e]}a.push(void 0,null,!0,!1);let l=a.length;function c(e){const t=s(e);return function(e){e<132||(a[e]=l,l=e)}(e),t}const d="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&d.decode();let u=null;function f(){return null!==u&&0!==u.byteLength||(u=new Uint8Array(i.memory.buffer)),u}function _(e,t){return e>>>=0,d.decode(f().subarray(e,e+t))}function m(e){l===a.length&&a.push(a.length+1);const t=l;return l=a[t],a[t]=e,t}let p=0;t.df_create=function(e,t){const n=function(e,t){const n=t(1*e.length,1)>>>0;return f().set(e,n/1),p=e.length,n}(e,i.__wbindgen_malloc),r=p;return i.df_create(n,r,t)>>>0},t.df_destroy=function(e){i.df_destroy(e)},t.df_set_atten_lim=function(e,t){i.df_set_atten_lim(e,t)};let g=null;function b(e,t){try{return e.apply(this,t)}catch(e){i.__wbindgen_exn_store(m(e))}}t.df_process_frame=function(e,t){const n=function(e,t){const n=t(4*e.length,4)>>>0;return(null!==g&&0!==g.byteLength||(g=new Float32Array(i.memory.buffer)),g).set(e,n/4),p=e.length,n}(t,i.__wbindgen_malloc),r=p;return c(i.df_process_frame(e,n,r))},t.df_set_post_filter_beta=function(e,t){i.df_set_post_filter_beta(e,t)},t.df_get_lookahead=function(e){return i.df_get_lookahead(e)>>>0},t.df_get_frame_length=function(e){return i.df_get_frame_length(e)>>>0},t.df_create_default=function(e){return i.df_create_default(e)>>>0};const h="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((e=>i.__wbg_dfstate_free(e>>>0)));function w(){const t={wbg:{}};return t.wbg.__wbindgen_object_drop_ref=function(e){c(e)},t.wbg.__wbg_crypto_566d7465cdbb6b7a=function(e){return m(s(e).crypto)},t.wbg.__wbindgen_is_object=function(e){const t=s(e);return"object"==typeof t&&null!==t},t.wbg.__wbg_process_dc09a8c7d59982f6=function(e){return m(s(e).process)},t.wbg.__wbg_versions_d98c6400c6ca2bd8=function(e){return m(s(e).versions)},t.wbg.__wbg_node_caaf83d002149bd5=function(e){return m(s(e).node)},t.wbg.__wbindgen_is_string=function(e){return"string"==typeof s(e)},t.wbg.__wbg_require_94a9da52636aacbf=function(){return b((function(){return m(e.require)}),arguments)},t.wbg.__wbindgen_is_function=function(e){return"function"==typeof s(e)},t.wbg.__wbindgen_string_new=function(e,t){return m(_(e,t))},t.wbg.__wbg_msCrypto_0b84745e9245cdf6=function(e){return m(s(e).msCrypto)},t.wbg.__wbg_randomFillSync_290977693942bf03=function(){return b((function(e,t){s(e).randomFillSync(c(t))}),arguments)},t.wbg.__wbg_getRandomValues_260cc23a41afad9a=function(){return b((function(e,t){s(e).getRandomValues(s(t))}),arguments)},t.wbg.__wbg_newnoargs_e258087cd0daa0ea=function(e,t){return m(new Function(_(e,t)))},t.wbg.__wbg_new_63b92bc8671ed464=function(e){return m(new Uint8Array(s(e)))},t.wbg.__wbg_new_9efabd6b6d2ce46d=function(e){return m(new Float32Array(s(e)))},t.wbg.__wbg_buffer_12d079cc21e14bdb=function(e){return m(s(e).buffer)},t.wbg.__wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb=function(e,t,n){return m(new Uint8Array(s(e),t>>>0,n>>>0))},t.wbg.__wbg_newwithlength_e9b4878cebadb3d3=function(e){return m(new Uint8Array(e>>>0))},t.wbg.__wbg_set_a47bac70306a19a7=function(e,t,n){s(e).set(s(t),n>>>0)},t.wbg.__wbg_subarray_a1f73cd4b5b42fe1=function(e,t,n){return m(s(e).subarray(t>>>0,n>>>0))},t.wbg.__wbg_newwithbyteoffsetandlength_4a659d079a1650e0=function(e,t,n){return m(new Float32Array(s(e),t>>>0,n>>>0))},t.wbg.__wbg_self_ce0dbfc45cf2f5be=function(){return b((function(){return m(self.self)}),arguments)},t.wbg.__wbg_window_c6fb939a7f436783=function(){return b((function(){return m(window.window)}),arguments)},t.wbg.__wbg_globalThis_d1e6af4856ba331b=function(){return b((function(){return m(globalThis.globalThis)}),arguments)},t.wbg.__wbg_global_207b558942527489=function(){return b((function(){return m(n.g.global)}),arguments)},t.wbg.__wbindgen_is_undefined=function(e){return void 0===s(e)},t.wbg.__wbg_call_27c0f87801dedf93=function(){return b((function(e,t){return m(s(e).call(s(t)))}),arguments)},t.wbg.__wbindgen_object_clone_ref=function(e){return m(s(e))},t.wbg.__wbg_call_b3ca7c6051f9bec1=function(){return b((function(e,t,n){return m(s(e).call(s(t),s(n)))}),arguments)},t.wbg.__wbindgen_memory=function(){return m(i.memory)},t.wbg.__wbindgen_throw=function(e,t){throw new Error(_(e,t))},t}function y(e,t){return i=e.exports,E.__wbindgen_wasm_module=t,g=null,u=null,i}async function E(e){if(void 0!==i)return i;void 0===e&&void 0!==o&&(e=o.replace(/\.js$/,"_bg.wasm"));const t=w();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await async function(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}(await e,t);return y(n,r)}t.DFState=class{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,h.unregister(this),e}free(){const e=this.__destroy_into_raw();i.__wbg_dfstate_free(e)}},r=Object.assign(E,{initSync:function(e){if(void 0!==i)return i;const t=w();return e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e)),y(new WebAssembly.Instance(e,t),e)}},t)}();const o=r}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={id:r,loaded:!1,exports:{}};return e[r](i,i.exports,n),i.loaded=!0,i.exports}function r(e){return e?e.slice(0):void 0}function o(e){if("string"!=typeof e)return;const t=e.trim();return 0!==t.length?t:void 0}function i(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function a(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function s(e){return Number.isFinite(e)?Math.max(0,e??0):0}function l(e){return{vadLogs:Boolean(e?.vadLogs),bufferOverflowMs:a(e?.bufferOverflowMs)}}function c(e,t){return t?{vadLogs:t.vadLogs??e.vadLogs,bufferOverflowMs:void 0!==t.bufferOverflowMs?a(t.bufferOverflowMs):e.bufferOverflowMs}:{...e}}function d(e,t){if(!t)return{...e,modelBytes:r(e.modelBytes)};let n=o(e.modelUrl),i=r(e.modelBytes);if(!0===t.clearModel&&(n=void 0,i=void 0),void 0!==t.modelUrl&&(n=o(t.modelUrl),i=void 0),void 0!==t.modelBuffer){if(t.modelBuffer.byteLength<=0)throw new Error("DeepFilter modelBuffer is empty");i=new Uint8Array(t.modelBuffer.slice(0))}return{modelUrl:n,modelBytes:i,attenLimDb:void 0!==t.attenLimDb?(a=t.attenLimDb,Number.isFinite(a)?Math.abs(a??100):100):e.attenLimDb,postFilterBeta:void 0!==t.postFilterBeta?s(t.postFilterBeta):e.postFilterBeta};var a}n.m=e,n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.b=self.location+"";class u{_config;constructor(e){this._config=e}}class f extends u{}let _,m=!1;class p extends f{moduleId="deepfilternet";_bindings;_state=0;_frameLength=0;_lookahead=0;_disposed=!1;constructor(e,t){if(super(e),t&&function(e){m||(_=n(807).A,_.initSync(e),m=!0)}(t),!_)throw new Error("DeepFilter WASM not initialized. Provide deepfilterWasm in INIT_PIPELINE.");this._bindings=_,this._createState(this._config)}get frameLength(){return this._frameLength}get lookahead(){return this._lookahead}processFrame(e,t){const n=this._bindings.df_process_frame(this._state,e);if(n.length!==this._frameLength)throw new Error(`DeepFilterNet returned invalid frame size. expected=${this._frameLength}, actual=${n.length}`);t.set(n)}updateConfig(e){this._config={...e},this._bindings.df_set_atten_lim(this._state,e.attenLimDb),this._bindings.df_set_post_filter_beta(this._state,e.postFilterBeta)}dispose(){this._disposed||(this._disposed=!0,this._state&&(this._bindings.df_destroy(this._state),this._state=0))}_createState(e){if(this._state&&(this._bindings.df_destroy(this._state),this._state=0),this._state=this._bindings.df_create_default(e.attenLimDb),!this._state)throw new Error("Failed to create DeepFilterNet state");const t=this._bindings.df_get_frame_length(this._state);if(!Number.isFinite(t)||t<=0)throw this._bindings.df_destroy(this._state),this._state=0,new Error(`Invalid DeepFilterNet frame length: ${t}`);this._frameLength=t,this._lookahead=this._bindings.df_get_lookahead(this._state),this._bindings.df_set_atten_lim(this._state,e.attenLimDb),this._bindings.df_set_post_filter_beta(this._state,e.postFilterBeta)}}var g,b,h=(g="file:///Users/luke/workspace/project/denoise-plugin/js/src/dist/rnnoise-sync.js",function(e={}){var t,r,o,i,a=e,s=(new Promise(((e,t)=>{r=e,o=t})),"object"==typeof window),l="undefined"!=typeof WorkerGlobalScope,c="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&"renderer"!=process.type,d=!s&&!c&&!l,u=Object.assign({},a),f="";if(d){if("object"==typeof process||"object"==typeof window||"undefined"!=typeof WorkerGlobalScope)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");i=e=>{if("function"==typeof readbuffer)return new Uint8Array(readbuffer(e));let t=read(e,"binary");return v("object"==typeof t),t},globalThis.clearTimeout??=e=>{},globalThis.setTimeout??=e=>e(),globalThis.arguments||globalThis.scriptArgs,"undefined"!=typeof print&&(globalThis.console??={},console.log=print,console.warn=console.error=globalThis.printErr??print)}else{if(!s&&!l)throw new Error("environment detection error");if(l?f=self.location.href:"undefined"!=typeof document&&document.currentScript&&(f=document.currentScript.src),g&&(f=g),f=f.startsWith("blob:")?"":f.slice(0,f.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=typeof window&&"undefined"==typeof WorkerGlobalScope)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");l&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)})}var _,m=a.print||console.log.bind(console),p=a.printErr||console.error.bind(console);Object.assign(a,u),u=null,_="fetchSettings",Object.getOwnPropertyDescriptor(a,_)&&N(`\`Module.${_}\` was supplied but \`${_}\` not included in INCOMING_MODULE_JS_API`),a.arguments&&a.arguments,F("arguments","arguments_"),a.thisProgram&&a.thisProgram,F("thisProgram","thisProgram"),v(void 0===a.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),v(void 0===a.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),v(void 0===a.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),v(void 0===a.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),v(void 0===a.read,"Module.read option was removed"),v(void 0===a.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),v(void 0===a.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),v(void 0===a.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),v(void 0===a.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),F("asm","wasmExports"),F("readAsync","readAsync"),F("readBinary","readBinary"),F("setWindowTitle","setWindowTitle"),v(!c,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable.");var b,h=a.wasmBinary;F("wasmBinary","wasmBinary"),"object"!=typeof WebAssembly&&p("no native wasm support detected");var w,y,E=!1;function v(e,t){e||N("Assertion failed"+(t?": "+t:""))}var T=!1;function S(){if(!E){var e=ee();0==e&&(e+=4);var t=y[e>>>2>>>0],n=y[e+4>>>2>>>0];34821223==t&&2310721022==n||N(`Stack overflow! Stack cookie has been overwritten at ${H(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${H(n)} ${H(t)}`),1668509029!=y[0]&&N("Runtime error: The application has corrupted its heap memory area (address zero)!")}}if((()=>{var e=new Int16Array(1),t=new Int8Array(e.buffer);if(e[0]=25459,115!==t[0]||99!==t[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})(),a.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");function F(e,t,n=!0){Object.getOwnPropertyDescriptor(a,e)||Object.defineProperty(a,e,{configurable:!0,get(){N(`\`Module.${e}\` has been replaced by \`${t}\``+(n?" (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)":""))}})}function A(e){Object.getOwnPropertyDescriptor(a,e)||Object.defineProperty(a,e,{configurable:!0,set(){N(`Attempt to set \`Module.${e}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`)}})}function I(e){return"FS_createPath"===e||"FS_createDataFile"===e||"FS_createPreloadedFile"===e||"FS_unlink"===e||"addRunDependency"===e||"FS_createLazyFile"===e||"FS_createDevice"===e||"removeRunDependency"===e}function M(e,t){"undefined"==typeof globalThis||Object.getOwnPropertyDescriptor(globalThis,e)||Object.defineProperty(globalThis,e,{configurable:!0,get(){t()}})}function L(e,t){M(e,(()=>{z(`\`${e}\` is not longer defined by emscripten. ${t}`)}))}function R(e){Object.getOwnPropertyDescriptor(a,e)||Object.defineProperty(a,e,{configurable:!0,get(){var t=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;I(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),N(t)}})}function O(){var e=b.buffer;a.HEAP8=new Int8Array(e),a.HEAP16=new Int16Array(e),a.HEAPU8=w=new Uint8Array(e),a.HEAPU16=new Uint16Array(e),a.HEAP32=new Int32Array(e),a.HEAPU32=y=new Uint32Array(e),a.HEAPF32=new Float32Array(e),a.HEAPF64=new Float64Array(e),a.HEAP64=new BigInt64Array(e),a.HEAPU64=new BigUint64Array(e)}L("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),L("asm","Please use wasmExports instead"),v(!a.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),v("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),v(!a.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),v(!a.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically");var P=0,C=null,k={},D=null;function N(e){a.onAbort?.(e),p(e="Aborted("+e+")"),E=!0;var t=new WebAssembly.RuntimeError(e);throw o(t),t}var U,x={error(){N("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM")},init(){x.error()},createDataFile(){x.error()},createPreloadedFile(){x.error()},createLazyFile(){x.error()},open(){x.error()},mkdev(){x.error()},registerDevice(){x.error()},analyzePath(){x.error()},ErrnoError(){x.error()}};function B(e,t){return(...n)=>{v(T,`native function \`${e}\` called before runtime initialization`);var r=Z[e];return v(r,`exported native function \`${e}\` not found`),v(n.length<=t,`native function \`${e}\` called with ${n.length} args but expects ${t}`),r(...n)}}a.FS_createDataFile=x.createDataFile,a.FS_createPreloadedFile=x.createPreloadedFile;var W=e=>{for(;e.length>0;)e.shift()(a)},j=[],G=[];a.noExitRuntime;var $,H=e=>(v("number"==typeof e),"0x"+e.toString(16).padStart(8,"0")),z=e=>{z.shown||={},z.shown[e]||(z.shown[e]=1,p(e))},Y="undefined"!=typeof TextDecoder?new TextDecoder:void 0,V=(e,t=0,n=NaN)=>{for(var r=(t>>>=0)+n,o=t;e[o]&&!(o>=r);)++o;if(o-t>16&&e.buffer&&Y)return Y.decode(e.subarray(t,o));for(var i="";t<o;){var a=e[t++];if(128&a){var s=63&e[t++];if(192!=(224&a)){var l=63&e[t++];if(224==(240&a)?a=(15&a)<<12|s<<6|l:(240!=(248&a)&&z("Invalid UTF-8 leading byte "+H(a)+" encountered when deserializing a UTF-8 string in wasm memory to a JS string!"),a=(7&a)<<18|s<<12|l<<6|63&e[t++]),a<65536)i+=String.fromCharCode(a);else{var c=a-65536;i+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else i+=String.fromCharCode((31&a)<<6|s)}else i+=String.fromCharCode(a)}return i},J=(e,t)=>(v("number"==typeof e,`UTF8ToString expects a number (got ${typeof e})`),(e>>>=0)?V(w,e,t):""),K=e=>{var t=b.buffer,n=(e-t.byteLength+65535)/65536|0;try{return b.grow(n),O(),1}catch(n){p(`growMemory: Attempted to grow heap from ${t.byteLength} bytes to ${e} bytes, but got error: ${n}`)}},q=[null,[],[]],X={__assert_fail:function(e,t,n,r){return t>>>=0,r>>>=0,N(`Assertion failed: ${J(e>>>=0)}, at: `+[t?J(t):"unknown filename",n,r?J(r):"unknown function"])},emscripten_resize_heap:function(e){e>>>=0;var t=w.length;v(e>t);var n,r=4294901760;if(e>r)return p(`Cannot enlarge memory, requested ${e} bytes, but the limit is 4294901760 bytes!`),!1;for(var o=1;o<=4;o*=2){var i=t*(1+.2/o);i=Math.min(i,e+100663296);var a=Math.min(r,(n=Math.max(e,i),v(65536,"alignment argument is required"),65536*Math.ceil(n/65536)));if(K(a))return!0}return p(`Failed to grow the heap from ${t} bytes to ${a} bytes, not enough memory!`),!1},fd_write:function(e,t,n,r){t>>>=0,n>>>=0,r>>>=0;for(var o=0,i=0;i<n;i++){var a=y[t>>>2>>>0],s=y[t+4>>>2>>>0];t+=8;for(var l=0;l<s;l++)c=e,d=w[a+l>>>0],u=void 0,v(u=q[c]),0===d||10===d?((1===c?m:p)(V(u)),u.length=0):u.push(d);o+=s}var c,d,u;return y[r>>>2>>>0]=o,0}},Z=function(){function e(e,t){return Z=function(e){var t,n=e=>t=>e(t)>>>0,r=e=>()=>e()>>>0;return(e=Object.assign({},e)).malloc=n(e.malloc),e.strerror=(t=e.strerror,e=>t(e)>>>0),e.emscripten_stack_get_base=r(e.emscripten_stack_get_base),e.emscripten_stack_get_end=r(e.emscripten_stack_get_end),e._emscripten_stack_alloc=n(e._emscripten_stack_alloc),e.emscripten_stack_get_current=r(e.emscripten_stack_get_current),e}(Z=e.exports),v(b=Z.memory,"memory not found in wasm exports"),O(),function(e){if(P--,a.monitorRunDependencies?.(P),e?(v(k[e]),delete k[e]):p("warning: run dependency removed without ID"),0==P&&(null!==D&&(clearInterval(D),D=null),C)){var t=C;C=null,t()}}("wasm-instantiate"),Z}var t;t="wasm-instantiate",P++,a.monitorRunDependencies?.(P),t?(v(!k[t]),k[t]=1,null===D&&"undefined"!=typeof setInterval&&(D=setInterval((()=>{if(E)return clearInterval(D),void(D=null);var e=!1;for(var t in k)e||(e=!0,p("still waiting on run dependencies:")),p(`dependency: ${t}`);e&&p("(end of list)")}),1e4))):p("warning: run dependency added without ID");var r,o={env:X,wasi_snapshot_preview1:X};return a.instantiateWasm?new Promise(((t,n)=>{try{a.instantiateWasm(o,((n,r)=>{e(n),t(n.exports)}))}catch(e){p(`Module.instantiateWasm callback failed with error: ${e}`),n(e)}})):(U??=a.locateFile?(r="rnnoise-sync.wasm",a.locateFile?a.locateFile(r,f):f+r):d?"rnnoise-sync.wasm":new URL(Object(function(){var e=new Error("Cannot find module 'rnnoise-sync.wasm'");throw e.code="MODULE_NOT_FOUND",e}()),n.b).href,e(function(e,t){var n,r=function(e){if(e==U&&h)return new Uint8Array(h);if(i)return i(e);throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);return n=new WebAssembly.Module(r),[new WebAssembly.Instance(n,t),n]}(U,o)[0]))}(),Q=(B("__wasm_call_ctors",0),a._malloc=B("malloc",1),a._free=B("free",1),a._rnnoise_init=B("rnnoise_init",2),a._rnnoise_create=B("rnnoise_create",1),a._rnnoise_destroy=B("rnnoise_destroy",1),a._rnnoise_process_frame=B("rnnoise_process_frame",3),B("fflush",1),B("strerror",1),Z.emscripten_stack_init),ee=(Z.emscripten_stack_get_free,Z.emscripten_stack_get_base,Z.emscripten_stack_get_end);if(Z._emscripten_stack_restore,Z._emscripten_stack_alloc,Z.emscripten_stack_get_current,["writeI53ToI64","writeI53ToI64Clamped","writeI53ToI64Signaling","writeI53ToU64Clamped","writeI53ToU64Signaling","readI53FromI64","readI53FromU64","convertI32PairToI53","convertI32PairToI53Checked","convertU32PairToI53","stackAlloc","getTempRet0","setTempRet0","zeroMemory","exitJS","strError","inetPton4","inetNtop4","inetPton6","inetNtop6","readSockaddr","writeSockaddr","emscriptenLog","readEmAsmArgs","jstoi_q","getExecutableName","listenOnce","autoResumeAudioContext","getDynCaller","dynCall","handleException","keepRuntimeAlive","runtimeKeepalivePush","runtimeKeepalivePop","callUserCallback","maybeExit","asmjsMangle","asyncLoad","mmapAlloc","HandleAllocator","getNativeTypeSize","addOnInit","addOnPostCtor","addOnPreMain","addOnExit","STACK_SIZE","STACK_ALIGN","POINTER_SIZE","ASSERTIONS","getCFunc","ccall","cwrap","uleb128Encode","sigToWasmTypes","generateFuncType","convertJsFunctionToWasm","getEmptyTableSlot","updateTableMap","getFunctionAddress","addFunction","removeFunction","reallyNegative","unSign","strLen","reSign","formatString","stringToUTF8Array","stringToUTF8","lengthBytesUTF8","intArrayFromString","intArrayToString","AsciiToString","stringToAscii","UTF16ToString","stringToUTF16","lengthBytesUTF16","UTF32ToString","stringToUTF32","lengthBytesUTF32","stringToNewUTF8","stringToUTF8OnStack","writeArrayToMemory","registerKeyEventCallback","maybeCStringToJsString","findEventTarget","getBoundingClientRect","fillMouseEventData","registerMouseEventCallback","registerWheelEventCallback","registerUiEventCallback","registerFocusEventCallback","fillDeviceOrientationEventData","registerDeviceOrientationEventCallback","fillDeviceMotionEventData","registerDeviceMotionEventCallback","screenOrientation","fillOrientationChangeEventData","registerOrientationChangeEventCallback","fillFullscreenChangeEventData","registerFullscreenChangeEventCallback","JSEvents_requestFullscreen","JSEvents_resizeCanvasForFullscreen","registerRestoreOldStyle","hideEverythingExceptGivenElement","restoreHiddenElements","setLetterbox","softFullscreenResizeWebGLRenderTarget","doRequestFullscreen","fillPointerlockChangeEventData","registerPointerlockChangeEventCallback","registerPointerlockErrorEventCallback","requestPointerLock","fillVisibilityChangeEventData","registerVisibilityChangeEventCallback","registerTouchEventCallback","fillGamepadEventData","registerGamepadEventCallback","registerBeforeUnloadEventCallback","fillBatteryEventData","battery","registerBatteryEventCallback","setCanvasElementSize","getCanvasElementSize","jsStackTrace","getCallstack","convertPCtoSourceLocation","getEnvStrings","checkWasiClock","wasiRightsToMuslOFlags","wasiOFlagsToMuslOFlags","initRandomFill","randomFill","safeSetTimeout","setImmediateWrapped","safeRequestAnimationFrame","clearImmediateWrapped","registerPostMainLoop","registerPreMainLoop","getPromise","makePromise","idsToPromises","makePromiseCallback","ExceptionInfo","findMatchingCatch","Browser_asyncPrepareDataCounter","isLeapYear","ydayFromDate","arraySum","addDays","getSocketFromFD","getSocketAddress","FS_createPreloadedFile","FS_modeStringToFlags","FS_getMode","FS_stdin_getChar","FS_unlink","FS_createDataFile","FS_mkdirTree","_setNetworkCallback","heapObjectForWebGLType","toTypedArrayIndex","webgl_enable_ANGLE_instanced_arrays","webgl_enable_OES_vertex_array_object","webgl_enable_WEBGL_draw_buffers","webgl_enable_WEBGL_multi_draw","webgl_enable_EXT_polygon_offset_clamp","webgl_enable_EXT_clip_control","webgl_enable_WEBGL_polygon_mode","emscriptenWebGLGet","computeUnpackAlignedImageSize","colorChannelsInGlTextureFormat","emscriptenWebGLGetTexPixelData","emscriptenWebGLGetUniform","webglGetUniformLocation","webglPrepareUniformLocationsBeforeFirstUse","webglGetLeftBracePos","emscriptenWebGLGetVertexAttrib","__glGetActiveAttribOrUniform","writeGLArray","registerWebGlEventCallback","runAndAbortIfError","ALLOC_NORMAL","ALLOC_STACK","allocate","writeStringToMemory","writeAsciiToMemory","setErrNo","demangle","stackTrace"].forEach((function(e){M(e,(()=>{var t=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,n=e;n.startsWith("_")||(n="$"+e),t+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${n}')`,I(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),z(t)})),R(e)})),["run","addRunDependency","removeRunDependency","out","err","callMain","abort","wasmMemory","wasmExports","writeStackCookie","checkStackCookie","INT53_MAX","INT53_MIN","bigintToI53Checked","stackSave","stackRestore","ptrToString","getHeapMax","growMemory","ENV","ERRNO_CODES","DNS","Protocols","Sockets","timers","warnOnce","readEmAsmArgsArray","jstoi_s","alignMemory","wasmTable","noExitRuntime","addOnPreRun","addOnPostRun","freeTableIndexes","functionsInTableMap","setValue","getValue","PATH","PATH_FS","UTF8Decoder","UTF8ArrayToString","UTF8ToString","UTF16Decoder","JSEvents","specialHTMLTargets","findCanvasEventTarget","currentFullscreenStrategy","restoreOldWindowedStyle","UNWIND_CACHE","ExitStatus","flush_NO_FILESYSTEM","emSetImmediate","emClearImmediate_deps","emClearImmediate","promiseMap","uncaughtExceptionCount","exceptionLast","exceptionCaught","Browser","getPreloadedImageData__data","wget","MONTH_DAYS_REGULAR","MONTH_DAYS_LEAP","MONTH_DAYS_REGULAR_CUMULATIVE","MONTH_DAYS_LEAP_CUMULATIVE","SYSCALLS","preloadPlugins","FS_stdin_getChar_buffer","FS_createPath","FS_createDevice","FS_readFile","FS","FS_createLazyFile","MEMFS","TTY","PIPEFS","SOCKFS","tempFixedLengthArray","miniTempWebGLFloatBuffers","miniTempWebGLIntBuffers","GL","AL","GLUT","EGL","GLEW","IDBStore","SDL","SDL_gfx","allocateUTF8","allocateUTF8OnStack","print","printErr"].forEach(R),a.preInit)for("function"==typeof a.preInit&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();A("preInit"),function e(){function t(){v(!$),$=!0,a.calledRun=!0,E||(v(!T),T=!0,S(),Z.__wasm_call_ctors(),r(a),a.onRuntimeInitialized?.(),A("onRuntimeInitialized"),v(!a._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){if(S(),a.postRun)for("function"==typeof a.postRun&&(a.postRun=[a.postRun]);a.postRun.length;)e=a.postRun.shift(),j.unshift(e);var e;A("postRun"),W(j)}())}var n;P>0?C=e:(Q(),v(!(3&(n=ee()))),0==n&&(n+=4),y[n>>>2>>>0]=34821223,y[n+4>>>2>>>0]=2310721022,y[0]=1668509029,function(){if(a.preRun)for("function"==typeof a.preRun&&(a.preRun=[a.preRun]);a.preRun.length;)e=a.preRun.shift(),G.unshift(e);var e;A("preRun"),W(G)}(),P>0?C=e:(a.setStatus?(a.setStatus("Running..."),setTimeout((()=>{setTimeout((()=>a.setStatus("")),1),t()}),1)):t(),S()))}(),t=a;for(const t of Object.keys(a))t in e||Object.defineProperty(e,t,{configurable:!0,get(){N(`Access to module property ('${t}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)}});return t});b=h;const w=h=function(e){if(new.target)throw new Error("createRNNWasmModuleSync() should not be called with `new createRNNWasmModuleSync()`");return b(e)},y=480;class E extends f{moduleId="rnnoise";frameLength=y;_module;_context;_inputPtr;_outputPtr;_inputHeap;_outputHeap;_disposed=!1;constructor(e,t){if(super(e),this._module=w(t?{wasmBinary:t,locateFile:()=>"rnnoise-sync.wasm"}:{}),this._context=this._module._rnnoise_create(),!this._context)throw new Error("Failed to initialize RNNoise context");if(this._inputPtr=this._module._malloc(y*Float32Array.BYTES_PER_ELEMENT),this._outputPtr=this._module._malloc(y*Float32Array.BYTES_PER_ELEMENT),!this._inputPtr||!this._outputPtr)throw this._inputPtr&&this._module._free(this._inputPtr),this._outputPtr&&this._module._free(this._outputPtr),this._module._rnnoise_destroy(this._context),new Error("Failed to allocate RNNoise heap buffers");const n=this._inputPtr>>2,r=this._outputPtr>>2;this._inputHeap=this._module.HEAPF32.subarray(n,n+y),this._outputHeap=this._module.HEAPF32.subarray(r,r+y)}processFrame(e,t){for(let t=0;t<y;t+=1)this._inputHeap[t]=32768*e[t];const n=this._module._rnnoise_process_frame(this._context,this._outputPtr,this._inputPtr),r=1/32768;for(let e=0;e<y;e+=1)t[e]=this._outputHeap[e]*r;return n}updateConfig(e){this._config={...e}}dispose(){this._disposed||(this._disposed=!0,this._module._rnnoise_destroy(this._context),this._module._free(this._inputPtr),this._module._free(this._outputPtr))}}let v,T,S,F=!1,A="rnnoise",I=!0,M=l(),L={modelUrl:void 0,modelBytes:void 0,attenLimDb:100,postFilterBeta:0};const R="[AudioPipeline:Worker]";function O(e,t){F&&v?.postMessage({type:"LOG",level:"info",tag:R,text:e,data:t})}function P(e,t){v?.postMessage(e,t??[])}function C(e){const t=e instanceof Error?e.message:String(e);var n;n=t,v?.postMessage({type:"LOG",level:"error",tag:R,text:n,data:undefined}),P({type:"ERROR",error:t})}function k(){return"deepfilternet"===A?S:T}function D(e){A=e;const t=k();return O(`MODULE_ACTIVE:${e}`,{frameLength:t.frameLength}),{frameLength:t.frameLength,lookahead:t instanceof p?t.lookahead:0}}function N(e){const t=e.data;if(t?.type)try{switch(t.type){case"INIT":!function(e){const t=performance.now();F=e.debugLogs??!1,A=i(e.moduleId),M=c(l(),e.moduleConfigs?.rnnoise),L=d({modelUrl:void 0,modelBytes:void 0,attenLimDb:100,postFilterBeta:0},e.moduleConfigs?.deepfilternet),function(e){const t=performance.now();T||(T=new E(M,e.rnnoiseWasm),O("PRE_INIT rnnoise",{elapsed:`${(performance.now()-t).toFixed(2)}ms`}));const n=performance.now();S||(S=new p(L,e.deepfilterWasm),O("PRE_INIT deepfilternet",{elapsed:`${(performance.now()-n).toFixed(2)}ms`})),O("PRE_INIT all modules done",{totalElapsed:`${(performance.now()-t).toFixed(2)}ms`})}(e.wasmBinaries);const n=D(A);P({type:"INIT_OK",frameLength:n.frameLength,lookahead:n.lookahead}),O("WORKER_READY",{elapsed:`${(performance.now()-t).toFixed(2)}ms`})}(t);break;case"PROCESS_FRAME":!function(e){const t=e.inputBuffer,n=k();if(!I||!n){const e=new Float32Array(t.length);return e.set(t),void P({type:"FRAME_RESULT",outputBuffer:e},[e.buffer])}if(t.length<n.frameLength)C(`Input buffer too small: ${t.length} < ${n.frameLength}`);else try{const e=new Float32Array(n.frameLength);P({type:"FRAME_RESULT",outputBuffer:e,vadScore:n.processFrame(t,e)},[e.buffer])}catch(e){C(e)}}(t);break;case"SET_MODULE":!function(e){const t=performance.now(),n=i(e.moduleId);if(n===A)return void O("SET_MODULE (already active)",{moduleId:n});const r=D(n);O("SET_MODULE (switch)",{to:n,elapsed:`${(performance.now()-t).toFixed(2)}ms`}),P({type:"MODULE_CHANGED",frameLength:r.frameLength,lookahead:r.lookahead})}(t);break;case"SET_CONFIG":!function(e){const t=performance.now();if("rnnoise"===e.moduleId)return M=c(M,e.config),T?.updateConfig(M),void O("SET_CONFIG rnnoise",{elapsed:`${(performance.now()-t).toFixed(2)}ms`});L=d(L,e.config),S&&S&&S.updateConfig(L),O("SET_CONFIG deepfilternet",{elapsed:`${(performance.now()-t).toFixed(2)}ms`})}(t);break;case"SET_ENABLED":I=t.enable,O(t.enable?"PROCESSING_ENABLED":"PROCESSING_DISABLED");break;case"DESTROY":T?.dispose(),S?.dispose(),T=void 0,S=void 0,O("WORKER_DESTROYED")}}catch(e){C(e)}}globalThis.onmessage=e=>{const t=e.data;if("CONNECT_PORT"===t?.type)return v=t.port,v.onmessage=N,void O("WORKER_PORT_CONNECTED");"SET_DEBUG"!==t?.type||(F=Boolean(t.debugLogs))}})();
1
+ "undefined"==typeof self&&(globalThis.self=globalThis),(()=>{"use strict";var e={807:(e,t,n)=>{let r;n.d(t,{A:()=>o}),e=n.hmd(e),function(){const t={};let o,i;"undefined"!=typeof document&&null!==document.currentScript&&(o=new URL(document.currentScript.src,location.href).toString());const s=new Array(128).fill(void 0);function a(e){return s[e]}s.push(void 0,null,!0,!1);let l=s.length;function c(e){const t=a(e);return function(e){e<132||(s[e]=l,l=e)}(e),t}const d="undefined"!=typeof TextDecoder?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};"undefined"!=typeof TextDecoder&&d.decode();let u=null;function _(){return null!==u&&0!==u.byteLength||(u=new Uint8Array(i.memory.buffer)),u}function f(e,t){return e>>>=0,d.decode(_().subarray(e,e+t))}function g(e){l===s.length&&s.push(s.length+1);const t=l;return l=s[t],s[t]=e,t}function h(e){return null==e}t.df_get_lookahead=function(e){return i.df_get_lookahead(e)>>>0},t.df_create_default=function(e,t,n,r){return i.df_create_default(e,!h(t),h(t)?0:t,!h(n),h(n)?0:n,!h(r),h(r)?0:r)>>>0},t.df_destroy=function(e){i.df_destroy(e)},t.df_set_atten_lim=function(e,t){i.df_set_atten_lim(e,t)};let p=null,m=0;function b(e,t){try{return e.apply(this,t)}catch(e){i.__wbindgen_exn_store(g(e))}}t.df_process_frame=function(e,t){const n=function(e,t){const n=t(4*e.length,4)>>>0;return(null!==p&&0!==p.byteLength||(p=new Float32Array(i.memory.buffer)),p).set(e,n/4),m=e.length,n}(t,i.__wbindgen_malloc),r=m;return c(i.df_process_frame(e,n,r))},t.df_create=function(e,t){const n=function(e,t){const n=t(1*e.length,1)>>>0;return _().set(e,n/1),m=e.length,n}(e,i.__wbindgen_malloc),r=m;return i.df_create(n,r,t)>>>0},t.df_set_post_filter_beta=function(e,t){i.df_set_post_filter_beta(e,t)},t.df_get_frame_length=function(e){return i.df_get_frame_length(e)>>>0};const w="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry((e=>i.__wbg_dfstate_free(e>>>0)));function y(){const t={wbg:{}};return t.wbg.__wbindgen_object_drop_ref=function(e){c(e)},t.wbg.__wbg_crypto_566d7465cdbb6b7a=function(e){return g(a(e).crypto)},t.wbg.__wbindgen_is_object=function(e){const t=a(e);return"object"==typeof t&&null!==t},t.wbg.__wbg_process_dc09a8c7d59982f6=function(e){return g(a(e).process)},t.wbg.__wbg_versions_d98c6400c6ca2bd8=function(e){return g(a(e).versions)},t.wbg.__wbg_node_caaf83d002149bd5=function(e){return g(a(e).node)},t.wbg.__wbindgen_is_string=function(e){return"string"==typeof a(e)},t.wbg.__wbg_require_94a9da52636aacbf=function(){return b((function(){return g(e.require)}),arguments)},t.wbg.__wbindgen_is_function=function(e){return"function"==typeof a(e)},t.wbg.__wbindgen_string_new=function(e,t){return g(f(e,t))},t.wbg.__wbg_msCrypto_0b84745e9245cdf6=function(e){return g(a(e).msCrypto)},t.wbg.__wbg_randomFillSync_290977693942bf03=function(){return b((function(e,t){a(e).randomFillSync(c(t))}),arguments)},t.wbg.__wbg_getRandomValues_260cc23a41afad9a=function(){return b((function(e,t){a(e).getRandomValues(a(t))}),arguments)},t.wbg.__wbg_newnoargs_e258087cd0daa0ea=function(e,t){return g(new Function(f(e,t)))},t.wbg.__wbg_new_63b92bc8671ed464=function(e){return g(new Uint8Array(a(e)))},t.wbg.__wbg_new_9efabd6b6d2ce46d=function(e){return g(new Float32Array(a(e)))},t.wbg.__wbg_buffer_12d079cc21e14bdb=function(e){return g(a(e).buffer)},t.wbg.__wbg_newwithbyteoffsetandlength_aa4a17c33a06e5cb=function(e,t,n){return g(new Uint8Array(a(e),t>>>0,n>>>0))},t.wbg.__wbg_newwithlength_e9b4878cebadb3d3=function(e){return g(new Uint8Array(e>>>0))},t.wbg.__wbg_set_a47bac70306a19a7=function(e,t,n){a(e).set(a(t),n>>>0)},t.wbg.__wbg_subarray_a1f73cd4b5b42fe1=function(e,t,n){return g(a(e).subarray(t>>>0,n>>>0))},t.wbg.__wbg_newwithbyteoffsetandlength_4a659d079a1650e0=function(e,t,n){return g(new Float32Array(a(e),t>>>0,n>>>0))},t.wbg.__wbg_self_ce0dbfc45cf2f5be=function(){return b((function(){return g(self.self)}),arguments)},t.wbg.__wbg_window_c6fb939a7f436783=function(){return b((function(){return g(window.window)}),arguments)},t.wbg.__wbg_globalThis_d1e6af4856ba331b=function(){return b((function(){return g(globalThis.globalThis)}),arguments)},t.wbg.__wbg_global_207b558942527489=function(){return b((function(){return g(n.g.global)}),arguments)},t.wbg.__wbindgen_is_undefined=function(e){return void 0===a(e)},t.wbg.__wbg_call_27c0f87801dedf93=function(){return b((function(e,t){return g(a(e).call(a(t)))}),arguments)},t.wbg.__wbindgen_object_clone_ref=function(e){return g(a(e))},t.wbg.__wbg_call_b3ca7c6051f9bec1=function(){return b((function(e,t,n){return g(a(e).call(a(t),a(n)))}),arguments)},t.wbg.__wbindgen_memory=function(){return g(i.memory)},t.wbg.__wbindgen_throw=function(e,t){throw new Error(f(e,t))},t}function E(e,t){return i=e.exports,T.__wbindgen_wasm_module=t,p=null,u=null,i}async function T(e){if(void 0!==i)return i;void 0===e&&void 0!==o&&(e=o.replace(/\.js$/,"_bg.wasm"));const t=y();("string"==typeof e||"function"==typeof Request&&e instanceof Request||"function"==typeof URL&&e instanceof URL)&&(e=fetch(e));const{instance:n,module:r}=await async function(e,t){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,t)}catch(t){if("application/wasm"==e.headers.get("Content-Type"))throw t;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",t)}const n=await e.arrayBuffer();return await WebAssembly.instantiate(n,t)}{const n=await WebAssembly.instantiate(e,t);return n instanceof WebAssembly.Instance?{instance:n,module:e}:n}}(await e,t);return E(n,r)}t.DFState=class{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,w.unregister(this),e}free(){const e=this.__destroy_into_raw();i.__wbg_dfstate_free(e)}},r=Object.assign(T,{initSync:function(e){if(void 0!==i)return i;const t=y();return e instanceof WebAssembly.Module||(e=new WebAssembly.Module(e)),E(new WebAssembly.Instance(e,t),e)}},t)}();const o=r}},t={};function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={id:r,loaded:!1,exports:{}};return e[r](i,i.exports,n),i.loaded=!0,i.exports}function r(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function o(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function i(e){return Number.isFinite(e)?Math.abs(e??100):100}function s(e){return Number.isFinite(e)?Math.max(0,e??0):0}function a(e,t){return Number.isFinite(e)?e:t}function l(e){return{vadLogs:Boolean(e?.vadLogs),vadLogIntervalMs:o(e?.vadLogIntervalMs)}}function c(e,t){return t?{vadLogs:t.vadLogs??e.vadLogs,vadLogIntervalMs:void 0!==t.vadLogIntervalMs?o(t.vadLogIntervalMs):e.vadLogIntervalMs}:{...e}}function d(e){return{attenLimDb:i(e?.attenLimDb),postFilterBeta:s(e?.postFilterBeta),minDbThresh:a(e?.minDbThresh,-15),maxDbErbThresh:a(e?.maxDbErbThresh,35),maxDbDfThresh:a(e?.maxDbDfThresh,35)}}function u(e,t){return t?{attenLimDb:void 0!==t.attenLimDb?i(t.attenLimDb):e.attenLimDb,postFilterBeta:void 0!==t.postFilterBeta?s(t.postFilterBeta):e.postFilterBeta,minDbThresh:a(t.minDbThresh,e.minDbThresh),maxDbErbThresh:a(t.maxDbErbThresh,e.maxDbErbThresh),maxDbDfThresh:a(t.maxDbDfThresh,e.maxDbDfThresh)}:{...e}}n.m=e,n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.b=self.location+"";class _{_pool=[];_size;constructor(e,t=128){this._size=e;for(let n=0;n<t;n++)this._pool.push(new Float32Array(e).fill(0))}acquire(){const e=this._pool.pop();return e?(e.fill(0),e):new Float32Array(this._size).fill(0)}release(e){e.length===this._size&&0!==e.buffer.byteLength&&this._pool.push(e)}resize(e){e!==this._size&&(this._size=e,this._pool.length=0)}}class f{_config;constructor(e){this._config=e}}let g,h=!1;class p extends f{moduleId="deepfilternet";_bindings;_state=0;_frameLength=0;_lookahead=0;_disposed=!1;constructor(e,t){if(super(e),t&&function(e){h||(g=n(807).A,g.initSync(e),h=!0)}(t),!g)throw new Error("DeepFilter WASM not initialized. Provide deepfilterWasm in INIT_PIPELINE.");this._bindings=g,this._createState(this._config)}get frameLength(){return this._frameLength}get lookahead(){return this._lookahead}processFrame(e,t){const n=this._bindings.df_process_frame(this._state,e);if(n.length!==this._frameLength)throw new Error(`DeepFilterNet returned invalid frame size. expected=${this._frameLength}, actual=${n.length}`);t.set(n)}updateConfig(e){this._config={...e},this._bindings.df_set_atten_lim(this._state,e.attenLimDb),this._bindings.df_set_post_filter_beta(this._state,e.postFilterBeta)}dispose(){this._disposed||(this._disposed=!0,this._state&&(this._bindings.df_destroy(this._state),this._state=0))}_createState(e){if(this._state&&(this._bindings.df_destroy(this._state),this._state=0),this._state=this._bindings.df_create_default(e.attenLimDb,e.minDbThresh??-15,e.maxDbErbThresh??35,e.maxDbDfThresh??35),!this._state)throw new Error("Failed to create DeepFilterNet state");const t=this._bindings.df_get_frame_length(this._state);if(!Number.isFinite(t)||t<=0)throw this._bindings.df_destroy(this._state),this._state=0,new Error(`Invalid DeepFilterNet frame length: ${t}`);this._frameLength=t,this._lookahead=this._bindings.df_get_lookahead(this._state),this._bindings.df_set_atten_lim(this._state,e.attenLimDb),this._bindings.df_set_post_filter_beta(this._state,e.postFilterBeta)}}var m,b,w=(m="file:///Users/luke/workspace/project/denoise-plugin/js/src/dist/rnnoise-sync.js",function(e={}){var t,r,o,i,s=e,a=(new Promise(((e,t)=>{r=e,o=t})),"object"==typeof window),l="undefined"!=typeof WorkerGlobalScope,c="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node&&"renderer"!=process.type,d=!a&&!c&&!l,u=Object.assign({},s),_="";if(d){if("object"==typeof process||"object"==typeof window||"undefined"!=typeof WorkerGlobalScope)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");i=e=>{if("function"==typeof readbuffer)return new Uint8Array(readbuffer(e));let t=read(e,"binary");return T("object"==typeof t),t},globalThis.clearTimeout??=e=>{},globalThis.setTimeout??=e=>e(),globalThis.arguments||globalThis.scriptArgs,"undefined"!=typeof print&&(globalThis.console??={},console.log=print,console.warn=console.error=globalThis.printErr??print)}else{if(!a&&!l)throw new Error("environment detection error");if(l?_=self.location.href:"undefined"!=typeof document&&document.currentScript&&(_=document.currentScript.src),m&&(_=m),_=_.startsWith("blob:")?"":_.slice(0,_.replace(/[?#].*/,"").lastIndexOf("/")+1),"object"!=typeof window&&"undefined"==typeof WorkerGlobalScope)throw new Error("not compiled for this environment (did you build to HTML and try to run it not on the web, or set ENVIRONMENT to something - like node - and run it someplace else - like on the web?)");l&&(i=e=>{var t=new XMLHttpRequest;return t.open("GET",e,!1),t.responseType="arraybuffer",t.send(null),new Uint8Array(t.response)})}var f,g=s.print||console.log.bind(console),h=s.printErr||console.error.bind(console);Object.assign(s,u),u=null,f="fetchSettings",Object.getOwnPropertyDescriptor(s,f)&&N(`\`Module.${f}\` was supplied but \`${f}\` not included in INCOMING_MODULE_JS_API`),s.arguments&&s.arguments,S("arguments","arguments_"),s.thisProgram&&s.thisProgram,S("thisProgram","thisProgram"),T(void 0===s.memoryInitializerPrefixURL,"Module.memoryInitializerPrefixURL option was removed, use Module.locateFile instead"),T(void 0===s.pthreadMainPrefixURL,"Module.pthreadMainPrefixURL option was removed, use Module.locateFile instead"),T(void 0===s.cdInitializerPrefixURL,"Module.cdInitializerPrefixURL option was removed, use Module.locateFile instead"),T(void 0===s.filePackagePrefixURL,"Module.filePackagePrefixURL option was removed, use Module.locateFile instead"),T(void 0===s.read,"Module.read option was removed"),T(void 0===s.readAsync,"Module.readAsync option was removed (modify readAsync in JS)"),T(void 0===s.readBinary,"Module.readBinary option was removed (modify readBinary in JS)"),T(void 0===s.setWindowTitle,"Module.setWindowTitle option was removed (modify emscripten_set_window_title in JS)"),T(void 0===s.TOTAL_MEMORY,"Module.TOTAL_MEMORY has been renamed Module.INITIAL_MEMORY"),S("asm","wasmExports"),S("readAsync","readAsync"),S("readBinary","readBinary"),S("setWindowTitle","setWindowTitle"),T(!c,"node environment detected but not enabled at build time. Add `node` to `-sENVIRONMENT` to enable.");var p,b=s.wasmBinary;S("wasmBinary","wasmBinary"),"object"!=typeof WebAssembly&&h("no native wasm support detected");var w,y,E=!1;function T(e,t){e||N("Assertion failed"+(t?": "+t:""))}var v=!1;function F(){if(!E){var e=ee();0==e&&(e+=4);var t=y[e>>>2>>>0],n=y[e+4>>>2>>>0];34821223==t&&2310721022==n||N(`Stack overflow! Stack cookie has been overwritten at ${H(e)}, expected hex dwords 0x89BACDFE and 0x2135467, but received ${H(n)} ${H(t)}`),1668509029!=y[0]&&N("Runtime error: The application has corrupted its heap memory area (address zero)!")}}if((()=>{var e=new Int16Array(1),t=new Int8Array(e.buffer);if(e[0]=25459,115!==t[0]||99!==t[1])throw"Runtime error: expected the system to be little-endian! (Run with -sSUPPORT_BIG_ENDIAN to bypass)"})(),s.ENVIRONMENT)throw new Error("Module.ENVIRONMENT has been deprecated. To force the environment, use the ENVIRONMENT compile-time option (for example, -sENVIRONMENT=web or -sENVIRONMENT=node)");function S(e,t,n=!0){Object.getOwnPropertyDescriptor(s,e)||Object.defineProperty(s,e,{configurable:!0,get(){N(`\`Module.${e}\` has been replaced by \`${t}\``+(n?" (the initial value can be provided on Module, but after startup the value is only looked for on a local variable of that name)":""))}})}function M(e){Object.getOwnPropertyDescriptor(s,e)||Object.defineProperty(s,e,{configurable:!0,set(){N(`Attempt to set \`Module.${e}\` after it has already been processed. This can happen, for example, when code is injected via '--post-js' rather than '--pre-js'`)}})}function I(e){return"FS_createPath"===e||"FS_createDataFile"===e||"FS_createPreloadedFile"===e||"FS_unlink"===e||"addRunDependency"===e||"FS_createLazyFile"===e||"FS_createDevice"===e||"removeRunDependency"===e}function A(e,t){"undefined"==typeof globalThis||Object.getOwnPropertyDescriptor(globalThis,e)||Object.defineProperty(globalThis,e,{configurable:!0,get(){t()}})}function L(e,t){A(e,(()=>{z(`\`${e}\` is not longer defined by emscripten. ${t}`)}))}function R(e){Object.getOwnPropertyDescriptor(s,e)||Object.defineProperty(s,e,{configurable:!0,get(){var t=`'${e}' was not exported. add it to EXPORTED_RUNTIME_METHODS (see the Emscripten FAQ)`;I(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),N(t)}})}function C(){var e=p.buffer;s.HEAP8=new Int8Array(e),s.HEAP16=new Int16Array(e),s.HEAPU8=w=new Uint8Array(e),s.HEAPU16=new Uint16Array(e),s.HEAP32=new Int32Array(e),s.HEAPU32=y=new Uint32Array(e),s.HEAPF32=new Float32Array(e),s.HEAPF64=new Float64Array(e),s.HEAP64=new BigInt64Array(e),s.HEAPU64=new BigUint64Array(e)}L("buffer","Please use HEAP8.buffer or wasmMemory.buffer"),L("asm","Please use wasmExports instead"),T(!s.STACK_SIZE,"STACK_SIZE can no longer be set at runtime. Use -sSTACK_SIZE at link time"),T("undefined"!=typeof Int32Array&&"undefined"!=typeof Float64Array&&null!=Int32Array.prototype.subarray&&null!=Int32Array.prototype.set,"JS engine does not provide full typed array support"),T(!s.wasmMemory,"Use of `wasmMemory` detected. Use -sIMPORTED_MEMORY to define wasmMemory externally"),T(!s.INITIAL_MEMORY,"Detected runtime INITIAL_MEMORY setting. Use -sIMPORTED_MEMORY to define wasmMemory dynamically");var P=0,D=null,O={},k=null;function N(e){s.onAbort?.(e),h(e="Aborted("+e+")"),E=!0;var t=new WebAssembly.RuntimeError(e);throw o(t),t}var x,U={error(){N("Filesystem support (FS) was not included. The problem is that you are using files from JS, but files were not used from C/C++, so filesystem support was not auto-included. You can force-include filesystem support with -sFORCE_FILESYSTEM")},init(){U.error()},createDataFile(){U.error()},createPreloadedFile(){U.error()},createLazyFile(){U.error()},open(){U.error()},mkdev(){U.error()},registerDevice(){U.error()},analyzePath(){U.error()},ErrnoError(){U.error()}};function B(e,t){return(...n)=>{T(v,`native function \`${e}\` called before runtime initialization`);var r=Z[e];return T(r,`exported native function \`${e}\` not found`),T(n.length<=t,`native function \`${e}\` called with ${n.length} args but expects ${t}`),r(...n)}}s.FS_createDataFile=U.createDataFile,s.FS_createPreloadedFile=U.createPreloadedFile;var W=e=>{for(;e.length>0;)e.shift()(s)},j=[],G=[];s.noExitRuntime;var $,H=e=>(T("number"==typeof e),"0x"+e.toString(16).padStart(8,"0")),z=e=>{z.shown||={},z.shown[e]||(z.shown[e]=1,h(e))},Y="undefined"!=typeof TextDecoder?new TextDecoder:void 0,V=(e,t=0,n=NaN)=>{for(var r=(t>>>=0)+n,o=t;e[o]&&!(o>=r);)++o;if(o-t>16&&e.buffer&&Y)return Y.decode(e.subarray(t,o));for(var i="";t<o;){var s=e[t++];if(128&s){var a=63&e[t++];if(192!=(224&s)){var l=63&e[t++];if(224==(240&s)?s=(15&s)<<12|a<<6|l:(240!=(248&s)&&z("Invalid UTF-8 leading byte "+H(s)+" encountered when deserializing a UTF-8 string in wasm memory to a JS string!"),s=(7&s)<<18|a<<12|l<<6|63&e[t++]),s<65536)i+=String.fromCharCode(s);else{var c=s-65536;i+=String.fromCharCode(55296|c>>10,56320|1023&c)}}else i+=String.fromCharCode((31&s)<<6|a)}else i+=String.fromCharCode(s)}return i},q=(e,t)=>(T("number"==typeof e,`UTF8ToString expects a number (got ${typeof e})`),(e>>>=0)?V(w,e,t):""),J=e=>{var t=p.buffer,n=(e-t.byteLength+65535)/65536|0;try{return p.grow(n),C(),1}catch(n){h(`growMemory: Attempted to grow heap from ${t.byteLength} bytes to ${e} bytes, but got error: ${n}`)}},K=[null,[],[]],X={__assert_fail:function(e,t,n,r){return t>>>=0,r>>>=0,N(`Assertion failed: ${q(e>>>=0)}, at: `+[t?q(t):"unknown filename",n,r?q(r):"unknown function"])},emscripten_resize_heap:function(e){e>>>=0;var t=w.length;T(e>t);var n,r=4294901760;if(e>r)return h(`Cannot enlarge memory, requested ${e} bytes, but the limit is 4294901760 bytes!`),!1;for(var o=1;o<=4;o*=2){var i=t*(1+.2/o);i=Math.min(i,e+100663296);var s=Math.min(r,(n=Math.max(e,i),T(65536,"alignment argument is required"),65536*Math.ceil(n/65536)));if(J(s))return!0}return h(`Failed to grow the heap from ${t} bytes to ${s} bytes, not enough memory!`),!1},fd_write:function(e,t,n,r){t>>>=0,n>>>=0,r>>>=0;for(var o=0,i=0;i<n;i++){var s=y[t>>>2>>>0],a=y[t+4>>>2>>>0];t+=8;for(var l=0;l<a;l++)c=e,d=w[s+l>>>0],u=void 0,T(u=K[c]),0===d||10===d?((1===c?g:h)(V(u)),u.length=0):u.push(d);o+=a}var c,d,u;return y[r>>>2>>>0]=o,0}},Z=function(){function e(e,t){return Z=function(e){var t,n=e=>t=>e(t)>>>0,r=e=>()=>e()>>>0;return(e=Object.assign({},e)).malloc=n(e.malloc),e.strerror=(t=e.strerror,e=>t(e)>>>0),e.emscripten_stack_get_base=r(e.emscripten_stack_get_base),e.emscripten_stack_get_end=r(e.emscripten_stack_get_end),e._emscripten_stack_alloc=n(e._emscripten_stack_alloc),e.emscripten_stack_get_current=r(e.emscripten_stack_get_current),e}(Z=e.exports),T(p=Z.memory,"memory not found in wasm exports"),C(),function(e){if(P--,s.monitorRunDependencies?.(P),e?(T(O[e]),delete O[e]):h("warning: run dependency removed without ID"),0==P&&(null!==k&&(clearInterval(k),k=null),D)){var t=D;D=null,t()}}("wasm-instantiate"),Z}var t;t="wasm-instantiate",P++,s.monitorRunDependencies?.(P),t?(T(!O[t]),O[t]=1,null===k&&"undefined"!=typeof setInterval&&(k=setInterval((()=>{if(E)return clearInterval(k),void(k=null);var e=!1;for(var t in O)e||(e=!0,h("still waiting on run dependencies:")),h(`dependency: ${t}`);e&&h("(end of list)")}),1e4))):h("warning: run dependency added without ID");var r,o={env:X,wasi_snapshot_preview1:X};return s.instantiateWasm?new Promise(((t,n)=>{try{s.instantiateWasm(o,((n,r)=>{e(n),t(n.exports)}))}catch(e){h(`Module.instantiateWasm callback failed with error: ${e}`),n(e)}})):(x??=s.locateFile?(r="rnnoise-sync.wasm",s.locateFile?s.locateFile(r,_):_+r):d?"rnnoise-sync.wasm":new URL(Object(function(){var e=new Error("Cannot find module 'rnnoise-sync.wasm'");throw e.code="MODULE_NOT_FOUND",e}()),n.b).href,e(function(e,t){var n,r=function(e){if(e==x&&b)return new Uint8Array(b);if(i)return i(e);throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}(e);return n=new WebAssembly.Module(r),[new WebAssembly.Instance(n,t),n]}(x,o)[0]))}(),Q=(B("__wasm_call_ctors",0),s._malloc=B("malloc",1),s._free=B("free",1),s._rnnoise_init=B("rnnoise_init",2),s._rnnoise_create=B("rnnoise_create",1),s._rnnoise_destroy=B("rnnoise_destroy",1),s._rnnoise_process_frame=B("rnnoise_process_frame",3),B("fflush",1),B("strerror",1),Z.emscripten_stack_init),ee=(Z.emscripten_stack_get_free,Z.emscripten_stack_get_base,Z.emscripten_stack_get_end);if(Z._emscripten_stack_restore,Z._emscripten_stack_alloc,Z.emscripten_stack_get_current,["writeI53ToI64","writeI53ToI64Clamped","writeI53ToI64Signaling","writeI53ToU64Clamped","writeI53ToU64Signaling","readI53FromI64","readI53FromU64","convertI32PairToI53","convertI32PairToI53Checked","convertU32PairToI53","stackAlloc","getTempRet0","setTempRet0","zeroMemory","exitJS","strError","inetPton4","inetNtop4","inetPton6","inetNtop6","readSockaddr","writeSockaddr","emscriptenLog","readEmAsmArgs","jstoi_q","getExecutableName","listenOnce","autoResumeAudioContext","getDynCaller","dynCall","handleException","keepRuntimeAlive","runtimeKeepalivePush","runtimeKeepalivePop","callUserCallback","maybeExit","asmjsMangle","asyncLoad","mmapAlloc","HandleAllocator","getNativeTypeSize","addOnInit","addOnPostCtor","addOnPreMain","addOnExit","STACK_SIZE","STACK_ALIGN","POINTER_SIZE","ASSERTIONS","getCFunc","ccall","cwrap","uleb128Encode","sigToWasmTypes","generateFuncType","convertJsFunctionToWasm","getEmptyTableSlot","updateTableMap","getFunctionAddress","addFunction","removeFunction","reallyNegative","unSign","strLen","reSign","formatString","stringToUTF8Array","stringToUTF8","lengthBytesUTF8","intArrayFromString","intArrayToString","AsciiToString","stringToAscii","UTF16ToString","stringToUTF16","lengthBytesUTF16","UTF32ToString","stringToUTF32","lengthBytesUTF32","stringToNewUTF8","stringToUTF8OnStack","writeArrayToMemory","registerKeyEventCallback","maybeCStringToJsString","findEventTarget","getBoundingClientRect","fillMouseEventData","registerMouseEventCallback","registerWheelEventCallback","registerUiEventCallback","registerFocusEventCallback","fillDeviceOrientationEventData","registerDeviceOrientationEventCallback","fillDeviceMotionEventData","registerDeviceMotionEventCallback","screenOrientation","fillOrientationChangeEventData","registerOrientationChangeEventCallback","fillFullscreenChangeEventData","registerFullscreenChangeEventCallback","JSEvents_requestFullscreen","JSEvents_resizeCanvasForFullscreen","registerRestoreOldStyle","hideEverythingExceptGivenElement","restoreHiddenElements","setLetterbox","softFullscreenResizeWebGLRenderTarget","doRequestFullscreen","fillPointerlockChangeEventData","registerPointerlockChangeEventCallback","registerPointerlockErrorEventCallback","requestPointerLock","fillVisibilityChangeEventData","registerVisibilityChangeEventCallback","registerTouchEventCallback","fillGamepadEventData","registerGamepadEventCallback","registerBeforeUnloadEventCallback","fillBatteryEventData","battery","registerBatteryEventCallback","setCanvasElementSize","getCanvasElementSize","jsStackTrace","getCallstack","convertPCtoSourceLocation","getEnvStrings","checkWasiClock","wasiRightsToMuslOFlags","wasiOFlagsToMuslOFlags","initRandomFill","randomFill","safeSetTimeout","setImmediateWrapped","safeRequestAnimationFrame","clearImmediateWrapped","registerPostMainLoop","registerPreMainLoop","getPromise","makePromise","idsToPromises","makePromiseCallback","ExceptionInfo","findMatchingCatch","Browser_asyncPrepareDataCounter","isLeapYear","ydayFromDate","arraySum","addDays","getSocketFromFD","getSocketAddress","FS_createPreloadedFile","FS_modeStringToFlags","FS_getMode","FS_stdin_getChar","FS_unlink","FS_createDataFile","FS_mkdirTree","_setNetworkCallback","heapObjectForWebGLType","toTypedArrayIndex","webgl_enable_ANGLE_instanced_arrays","webgl_enable_OES_vertex_array_object","webgl_enable_WEBGL_draw_buffers","webgl_enable_WEBGL_multi_draw","webgl_enable_EXT_polygon_offset_clamp","webgl_enable_EXT_clip_control","webgl_enable_WEBGL_polygon_mode","emscriptenWebGLGet","computeUnpackAlignedImageSize","colorChannelsInGlTextureFormat","emscriptenWebGLGetTexPixelData","emscriptenWebGLGetUniform","webglGetUniformLocation","webglPrepareUniformLocationsBeforeFirstUse","webglGetLeftBracePos","emscriptenWebGLGetVertexAttrib","__glGetActiveAttribOrUniform","writeGLArray","registerWebGlEventCallback","runAndAbortIfError","ALLOC_NORMAL","ALLOC_STACK","allocate","writeStringToMemory","writeAsciiToMemory","setErrNo","demangle","stackTrace"].forEach((function(e){A(e,(()=>{var t=`\`${e}\` is a library symbol and not included by default; add it to your library.js __deps or to DEFAULT_LIBRARY_FUNCS_TO_INCLUDE on the command line`,n=e;n.startsWith("_")||(n="$"+e),t+=` (e.g. -sDEFAULT_LIBRARY_FUNCS_TO_INCLUDE='${n}')`,I(e)&&(t+=". Alternatively, forcing filesystem support (-sFORCE_FILESYSTEM) can export this for you"),z(t)})),R(e)})),["run","addRunDependency","removeRunDependency","out","err","callMain","abort","wasmMemory","wasmExports","writeStackCookie","checkStackCookie","INT53_MAX","INT53_MIN","bigintToI53Checked","stackSave","stackRestore","ptrToString","getHeapMax","growMemory","ENV","ERRNO_CODES","DNS","Protocols","Sockets","timers","warnOnce","readEmAsmArgsArray","jstoi_s","alignMemory","wasmTable","noExitRuntime","addOnPreRun","addOnPostRun","freeTableIndexes","functionsInTableMap","setValue","getValue","PATH","PATH_FS","UTF8Decoder","UTF8ArrayToString","UTF8ToString","UTF16Decoder","JSEvents","specialHTMLTargets","findCanvasEventTarget","currentFullscreenStrategy","restoreOldWindowedStyle","UNWIND_CACHE","ExitStatus","flush_NO_FILESYSTEM","emSetImmediate","emClearImmediate_deps","emClearImmediate","promiseMap","uncaughtExceptionCount","exceptionLast","exceptionCaught","Browser","getPreloadedImageData__data","wget","MONTH_DAYS_REGULAR","MONTH_DAYS_LEAP","MONTH_DAYS_REGULAR_CUMULATIVE","MONTH_DAYS_LEAP_CUMULATIVE","SYSCALLS","preloadPlugins","FS_stdin_getChar_buffer","FS_createPath","FS_createDevice","FS_readFile","FS","FS_createLazyFile","MEMFS","TTY","PIPEFS","SOCKFS","tempFixedLengthArray","miniTempWebGLFloatBuffers","miniTempWebGLIntBuffers","GL","AL","GLUT","EGL","GLEW","IDBStore","SDL","SDL_gfx","allocateUTF8","allocateUTF8OnStack","print","printErr"].forEach(R),s.preInit)for("function"==typeof s.preInit&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();M("preInit"),function e(){function t(){T(!$),$=!0,s.calledRun=!0,E||(T(!v),v=!0,F(),Z.__wasm_call_ctors(),r(s),s.onRuntimeInitialized?.(),M("onRuntimeInitialized"),T(!s._main,'compiled without a main, but one is present. if you added it from JS, use Module["onRuntimeInitialized"]'),function(){if(F(),s.postRun)for("function"==typeof s.postRun&&(s.postRun=[s.postRun]);s.postRun.length;)e=s.postRun.shift(),j.unshift(e);var e;M("postRun"),W(j)}())}var n;P>0?D=e:(Q(),T(!(3&(n=ee()))),0==n&&(n+=4),y[n>>>2>>>0]=34821223,y[n+4>>>2>>>0]=2310721022,y[0]=1668509029,function(){if(s.preRun)for("function"==typeof s.preRun&&(s.preRun=[s.preRun]);s.preRun.length;)e=s.preRun.shift(),G.unshift(e);var e;M("preRun"),W(G)}(),P>0?D=e:(s.setStatus?(s.setStatus("Running..."),setTimeout((()=>{setTimeout((()=>s.setStatus("")),1),t()}),1)):t(),F()))}(),t=s;for(const t of Object.keys(s))t in e||Object.defineProperty(e,t,{configurable:!0,get(){N(`Access to module property ('${t}') is no longer possible via the module constructor argument; Instead, use the result of the module constructor.`)}});return t});b=w;const y=w=function(e){if(new.target)throw new Error("createRNNWasmModuleSync() should not be called with `new createRNNWasmModuleSync()`");return b(e)},E=480;class T extends f{moduleId="rnnoise";frameLength=E;_module;_context;_inputPtr;_outputPtr;_inputHeap;_outputHeap;_disposed=!1;constructor(e,t){if(super(e),this._module=y(t?{wasmBinary:t,locateFile:()=>"rnnoise-sync.wasm"}:{}),this._context=this._module._rnnoise_create(),!this._context)throw new Error("Failed to initialize RNNoise context");if(this._inputPtr=this._module._malloc(E*Float32Array.BYTES_PER_ELEMENT),this._outputPtr=this._module._malloc(E*Float32Array.BYTES_PER_ELEMENT),!this._inputPtr||!this._outputPtr)throw this._inputPtr&&this._module._free(this._inputPtr),this._outputPtr&&this._module._free(this._outputPtr),this._module._rnnoise_destroy(this._context),new Error("Failed to allocate RNNoise heap buffers");const n=this._inputPtr>>2,r=this._outputPtr>>2;this._inputHeap=this._module.HEAPF32.subarray(n,n+E),this._outputHeap=this._module.HEAPF32.subarray(r,r+E)}processFrame(e,t){for(let t=0;t<E;t+=1)this._inputHeap[t]=32768*e[t];const n=this._module._rnnoise_process_frame(this._context,this._outputPtr,this._inputPtr),r=1/32768;for(let e=0;e<E;e+=1)t[e]=this._outputHeap[e]*r;return n}updateConfig(e){this._config={...e}}dispose(){this._disposed||(this._disposed=!0,this._module._rnnoise_destroy(this._context),this._module._free(this._inputPtr),this._module._free(this._outputPtr))}}const v=new class{_port;_debugLogs=!1;_currentModuleId="rnnoise";_processingEnabled=!0;_rnnoiseConfig=l();_deepFilterConfig=d();_rnnoiseModule;_deepFilterModule;_framePool=new _(480);_pendingRecycles=[];handleGlobalMessage(e){const t=e.data;if("CONNECT_PORT"===t?.type){if(!t.port)throw new Error("CONNECT_PORT message is missing a MessagePort");return this._port=t.port,this._port.onmessage=this.handleMessage,void this._logInfo("WORKER_PORT_CONNECTED")}"SET_DEBUG"===t?.type&&(this._debugLogs=Boolean(t.debugLogs))}handleMessage=e=>{const t=e.data;if(t?.type)try{switch(t.type){case"INIT":this._handleInit(t);break;case"PROCESS_FRAME_BATCH":this._handleProcessFrameBatch(t);break;case"SET_MODULE":this._handleSetModule(t);break;case"SET_MODULE_CONFIG":this._handleSetModuleConfig(t);break;case"SET_ENABLED":this._processingEnabled=t.enable,this._logInfo(t.enable?"PROCESSING_ENABLED":"PROCESSING_DISABLED");break;case"DESTROY":this._handleDestroy()}}catch(e){this._respondError(e)}};_handleInit(e){const t=performance.now();this._debugLogs=e.debugLogs??!1,this._currentModuleId=r(e.moduleId),this._rnnoiseConfig=c(l(),e.moduleConfigs?.rnnoise),this._deepFilterConfig=u(d(),e.moduleConfigs?.deepfilternet),this._initAllModules(e.wasmBinaries);const n=this._activateModule(this._currentModuleId);this._respond({type:"INIT_OK",frameLength:n.frameLength,lookahead:n.lookahead}),this._logInfo("WORKER_READY",{elapsed:`${(performance.now()-t).toFixed(2)}ms`})}_handleProcessFrameBatch(e){if(e.recycleBuffers)for(let t=0;t<e.recycleBuffers.length;t++)this._framePool.release(e.recycleBuffers[t]);const t=this._getActiveModule(),n=[],r=[];for(let o=0;o<e.inputBuffers.length;o++){const i=e.inputBuffers[o];if(this._processingEnabled&&t){if(i.length<t.frameLength)return void this._respondError(`Input buffer too small: ${i.length} < ${t.frameLength}`);try{const e=this._framePool.acquire();r.push(t.processFrame(i,e)),n.push(e)}catch(e){return void this._respondError(e)}}else{const e=this._framePool.acquire();e.set(i),n.push(e),r.push(void 0)}this._pendingRecycles.push(i)}const o=this._pendingRecycles.length>0?this._pendingRecycles.splice(0):void 0;this._respond({type:"FRAME_RESULT_BATCH",outputBuffers:n,vadScores:r,recycleBuffers:o},function(e,...t){const n=[];for(let t=0;t<e.length;t++)n.push(e[t].buffer);for(let e=0;e<t.length;e++){const r=t[e];if(r)for(let e=0;e<r.length;e++)n.push(r[e].buffer)}return n}(n,o))}_handleSetModule(e){const t=performance.now(),n=r(e.moduleId);if(n===this._currentModuleId)return void this._logInfo("SET_MODULE (already active)",{moduleId:n});const o=this._activateModule(n);this._logInfo("SET_MODULE (switch)",{to:n,elapsed:`${(performance.now()-t).toFixed(2)}ms`}),this._respond({type:"MODULE_CHANGED",frameLength:o.frameLength,lookahead:o.lookahead})}_handleSetModuleConfig(e){const t=performance.now();if("rnnoise"===e.moduleId)return this._rnnoiseConfig=c(this._rnnoiseConfig,e.config),this._rnnoiseModule?.updateConfig(this._rnnoiseConfig),void this._logInfo("SET_MODULE_CONFIG rnnoise",{config:e.config,elapsed:`${(performance.now()-t).toFixed(2)}ms`});this._deepFilterConfig=u(this._deepFilterConfig,e.config),this._deepFilterModule?.updateConfig(this._deepFilterConfig),this._logInfo("SET_MODULE_CONFIG deepfilternet",{config:e.config,elapsed:`${(performance.now()-t).toFixed(2)}ms`})}_handleDestroy(){this._rnnoiseModule?.dispose(),this._deepFilterModule?.dispose(),this._rnnoiseModule=void 0,this._deepFilterModule=void 0,this._currentModuleId="rnnoise",this._processingEnabled=!0,this._rnnoiseConfig=l(),this._deepFilterConfig=d(),this._framePool=new _(480),this._pendingRecycles=[],this._logInfo("WORKER_DESTROYED")}_getActiveModule(){return"deepfilternet"===this._currentModuleId?this._deepFilterModule:this._rnnoiseModule}_initAllModules(e){const t=performance.now();this._rnnoiseModule||(this._rnnoiseModule=new T(this._rnnoiseConfig,e.rnnoiseWasm),this._logInfo("PRE_INIT rnnoise",{elapsed:`${(performance.now()-t).toFixed(2)}ms`}));const n=performance.now();this._deepFilterModule||(this._deepFilterModule=new p(this._deepFilterConfig,e.deepfilterWasm),this._logInfo("PRE_INIT deepfilternet",{elapsed:`${(performance.now()-n).toFixed(2)}ms`})),this._logInfo("PRE_INIT all modules done",{totalElapsed:`${(performance.now()-t).toFixed(2)}ms`})}_activateModule(e){this._currentModuleId=e;const t=this._getActiveModule();if(!t)throw new Error(`Denoise module is not available: ${e}`);const n=t instanceof p?t.lookahead:0;return this._framePool.resize(t.frameLength),this._logInfo(`MODULE_ACTIVE:${e}`,{frameLength:t.frameLength,lookahead:n}),{frameLength:t.frameLength,lookahead:n}}_respond(e,t){this._port?.postMessage(e,t??[])}_respondError(e){const t=e instanceof Error?e.message:String(e);this._logError(t),this._respond({type:"ERROR",error:t})}_postLog(e,t,n){const r={type:"LOG",level:e,tag:"[AudioPipeline:Worker]",text:t,data:n};this._port?.postMessage(r)}_logInfo(e,t){this._debugLogs&&this._postLog("info",e,t)}_logError(e,t){this._postLog("error",e,t)}};globalThis.onmessage=e=>{v.handleGlobalMessage(e)}})();
@@ -1 +1 @@
1
- "undefined"==typeof self&&(globalThis.self=globalThis),(()=>{"use strict";function e(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}class t{_data;_readIndex=0;_writeIndex=0;_framesAvailable=0;constructor(e){this._data=new Float32Array(e)}get framesAvailable(){return this._framesAvailable}get capacity(){return this._data.length}push(e){const t=this._data.length,s=e.length;if(0===s)return;const r=t-this._writeIndex;s<=r?this._data.set(e,this._writeIndex):(this._data.set(e.subarray(0,r),this._writeIndex),this._data.set(e.subarray(r),0)),this._writeIndex=(this._writeIndex+s)%t,this._framesAvailable=Math.min(this._framesAvailable+s,t)}pull(e){const t=e.length;if(this._framesAvailable<t)return!1;const s=this._data.length,r=s-this._readIndex;return t<=r?e.set(this._data.subarray(this._readIndex,this._readIndex+t)):(e.set(this._data.subarray(this._readIndex,s)),e.set(this._data.subarray(0,t-r),r)),this._readIndex=(this._readIndex+t)%s,this._framesAvailable-=t,!0}drainInto(e){const t=this._framesAvailable;if(0===t)return;const s=this._data.length,r=s-this._readIndex;t<=r?e.push(this._data.subarray(this._readIndex,this._readIndex+t)):(e.push(this._data.subarray(this._readIndex,s)),e.push(this._data.subarray(0,t-r))),this._readIndex=(this._readIndex+t)%s,this._framesAvailable=0}clear(){this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._data.fill(0)}}class s extends AudioWorkletProcessor{_messageChain=Promise.resolve();_debugLogs=!1;_destroyed=!1;_shouldProcess=!0;_workerReady=!1;_currentModuleId="rnnoise";_frameLength=480;_prefilled=!1;_workerPort;_inputQueue=new t(30720);_outputQueue=new t(30720);_lastVadScore;_lastVadLogAtMs=0;_vadLogIntervalMs=1e3;_vadLogsEnabled=!1;constructor(e){super(),this._debugLogs=e.processorOptions?.debugLogs??!1,this._setupMessageHandler(),this._logInfo("AUDIO_PIPELINE_WORKLET_INIT")}process(e,t){if(this._destroyed)return!1;const s=e[0]?.[0],r=t[0]?.[0];if(!s||!r)return!0;this._inputQueue.push(s);const o=this._workerReady&&this._workerPort;for(;this._inputQueue.framesAvailable>=this._frameLength;){const e=new Float32Array(this._frameLength);this._inputQueue.pull(e),o?this._workerPort.postMessage({type:"PROCESS_FRAME",inputBuffer:e},[e.buffer]):this._outputQueue.push(e)}this._outputQueue.pull(r);const a=t[0];for(let e=1;e<a.length;e++)a[e].set(r);return!0}_setupMessageHandler(){this.port.onmessage=e=>{const t=e.data;this._messageChain=this._messageChain.then((()=>this._dispatch(t))).catch((e=>{this._respondError(t?.requestId,t?.message??"UNKNOWN",e)}))}}async _dispatch(e){if(!e?.message)return;const t=this._nowMs();switch(e.message){case"INIT_PIPELINE":this._initPipeline(e);break;case"SET_ENABLED":this._setEnabled(e.enable);break;case"SET_STAGE_MODULE":this._handleSetStageModule(e);break;case"SET_MODULE_CONFIG":this._handleSetModuleConfig(e);break;case"DESTROY":this._destroy();break;default:throw new Error(`Unknown command: ${String(e.message)}`)}this._logInfo(`${e.message} dispatch`,{elapsed:`${(this._nowMs()-t).toFixed(2)}ms`}),this._respondOk(e.requestId,e.message)}_initPipeline(t){if(this._debugLogs=t.debugLogs??this._debugLogs,this._currentModuleId=e(t.stages?.denoise),this._shouldProcess=t.enable??this._shouldProcess,this._vadLogIntervalMs=t.moduleConfigs?.rnnoise?.bufferOverflowMs??1e3,this._vadLogsEnabled=t.moduleConfigs?.rnnoise?.vadLogs??!1,t.workerPort){this._workerPort=t.workerPort,this._setupWorkerPort();const e=t.frameLength??480;this._onWorkerInitOk(e)}this._logInfo(`AUDIO_PIPELINE_WORKLET_READY:${this._currentModuleId}`)}_setupWorkerPort(){this._workerPort&&(this._workerPort.onmessage=e=>{const t=e.data;if(t?.type)switch(t.type){case"INIT_OK":this._onWorkerInitOk(t.frameLength);break;case"FRAME_RESULT":this._onFrameResult(t.outputBuffer,t.vadScore);break;case"MODULE_CHANGED":this._onModuleChanged(t.frameLength,t.lookahead);break;case"ERROR":this._logError(`WORKER_ERROR:${t.error}`);break;case"LOG":this._forwardLog(t.level,t.tag,t.text,t.data)}})}_onWorkerInitOk(e){this._frameLength=e,this._rebuildForFrameLength(e),this._workerReady=!0,this._logInfo("WORKER_INIT_OK",{frameLength:e})}_onFrameResult(e,t){this._outputQueue.push(e),this._maybeEmitVadLog(t)}_onModuleChanged(e,t){e!==this._frameLength&&(this._frameLength=e,this._rebuildForFrameLength(e)),this._logInfo("MODULE_CHANGED",{frameLength:e})}_rebuildForFrameLength(e){const s=64*Math.max(e,128),r=this._inputQueue,o=this._outputQueue;if(this._inputQueue=new t(s),this._outputQueue=new t(s),r.drainInto(this._inputQueue),o.drainInto(this._outputQueue),!this._prefilled){this._prefilled=!0;const t=128*Math.ceil(2*e/128);this._outputQueue.push(new Float32Array(t)),this._logInfo("PREFILL",{frameLength:e,prefill:t})}this._logInfo("REBUILD_QUEUES",{frameLength:e,queueCapacity:s})}_setEnabled(e){this._shouldProcess=e,this._lastVadLogAtMs=0,this._workerPort?.postMessage({type:"SET_ENABLED",enable:e}),this._logInfo(e?"AUDIO_PIPELINE_ENABLED":"AUDIO_PIPELINE_DISABLED")}_handleSetStageModule(t){if("denoise"!==t.stage)throw new Error(`Unsupported stage: ${t.stage}`);const s=e(t.moduleId);this._logInfo("MODULE_SWITCH_START",{from:this._currentModuleId,to:s}),this._currentModuleId=s,this._workerPort?.postMessage({type:"SET_MODULE",moduleId:s})}_handleSetModuleConfig(e){if("rnnoise"===e.moduleId){const t=e.config;t?.bufferOverflowMs&&(this._vadLogIntervalMs=t.bufferOverflowMs)}this._workerPort?.postMessage({type:"SET_CONFIG",moduleId:e.moduleId,config:e.config})}_destroy(){this._destroyed||(this._destroyed=!0,this._workerReady=!1,this._workerPort?.postMessage({type:"DESTROY"}),this._workerPort?.close(),this._workerPort=void 0,this._inputQueue.clear(),this._outputQueue.clear(),this._logInfo("AUDIO_PIPELINE_WORKLET_DESTROYED"))}_respondOk(e,t){if(void 0===e)return;const s={message:"COMMAND_OK",requestId:e,command:t};this.port.postMessage(s)}_respondError(e,t,s){const r=s instanceof Error?s.message:String(s),o={message:"COMMAND_ERROR",requestId:e,command:t,error:r};this.port.postMessage(o),this._logError(`${t}:${r}`)}_maybeEmitVadLog(e){if(!this._debugLogs||"rnnoise"!==this._currentModuleId||!this._vadLogsEnabled)return;if(!Number.isFinite(e))return;this._lastVadScore=e;const t=this._nowMs();t-this._lastVadLogAtMs<this._vadLogIntervalMs||(this._lastVadLogAtMs=t,this._logInfo("AUDIO_PIPELINE_RNNOISE_VAD",{vadScore:this._lastVadScore,intervalMs:this._vadLogIntervalMs}))}_nowMs(){return"function"==typeof globalThis.performance?.now?globalThis.performance.now():Date.now()}static _LOG_TAG="[AudioPipeline:Worklet]";_postLog(e,t,s,r){const o={message:"LOG",level:e,tag:t,text:s,data:r};try{this.port.postMessage(o)}catch{}}_forwardLog(e,t,s,r){this._postLog(e,t,s,r)}_logInfo(e,t,r=!1){(r||this._debugLogs)&&this._postLog("info",s._LOG_TAG,e,t)}_logError(e,t){this._postLog("error",s._LOG_TAG,e,t)}}registerProcessor("AudioPipelineWorklet",s)})();
1
+ "undefined"==typeof self&&(globalThis.self=globalThis),(()=>{"use strict";function e(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}class t{_pool=[];_size;constructor(e,t=128){this._size=e;for(let s=0;s<t;s++)this._pool.push(new Float32Array(e).fill(0))}acquire(){const e=this._pool.pop();return e?(e.fill(0),e):new Float32Array(this._size).fill(0)}release(e){e.length===this._size&&0!==e.buffer.byteLength&&this._pool.push(e)}resize(e){e!==this._size&&(this._size=e,this._pool.length=0)}}class s{_data;_readIndex=0;_writeIndex=0;_framesAvailable=0;constructor(e){this._data=new Float32Array(e).fill(0)}get framesAvailable(){return this._framesAvailable}get capacity(){return this._data.length}push(e){const t=this._data.length,s=e.length;if(0===s)return;const r=t-this._writeIndex;s<=r?this._data.set(e,this._writeIndex):(this._data.set(e.subarray(0,r),this._writeIndex),this._data.set(e.subarray(r),0)),this._writeIndex=(this._writeIndex+s)%t,this._framesAvailable=Math.min(this._framesAvailable+s,t)}pull(e){const t=e.length;if(this._framesAvailable<t)return e.fill(0),!1;const s=this._data.length,r=s-this._readIndex;return t<=r?e.set(this._data.subarray(this._readIndex,this._readIndex+t)):(e.set(this._data.subarray(this._readIndex,s)),e.set(this._data.subarray(0,t-r),r)),this._readIndex=(this._readIndex+t)%s,this._framesAvailable-=t,!0}drainInto(e){const t=this._framesAvailable;if(0===t)return;const s=this._data.length,r=s-this._readIndex;t<=r?e.push(this._data.subarray(this._readIndex,this._readIndex+t)):(e.push(this._data.subarray(this._readIndex,s)),e.push(this._data.subarray(0,t-r))),this._readIndex=(this._readIndex+t)%s,this._framesAvailable=0}clear(){this._readIndex=0,this._writeIndex=0,this._framesAvailable=0,this._data.fill(0)}}class r extends AudioWorkletProcessor{_messageChain=Promise.resolve();_debugLogs=!1;_destroyed=!1;_workerReady=!1;_currentModuleId="rnnoise";_frameLength=480;_batchFrames=1;_prefilled=!1;_workerPort;_framePool=new t(480);_pendingRecycles=[];_batchQueue=[];_inputQueue=new s(30720);_outputQueue=new s(30720);_lastVadScore;_lastVadLogAtMs=0;_vadLogIntervalMs=1e3;_vadLogsEnabled=!1;constructor(e){super(),this._debugLogs=e.processorOptions?.debugLogs??!1,this._setupMessageHandler(),this._logInfo("AUDIO_PIPELINE_WORKLET_INIT")}process(e,t){if(this._destroyed)return!1;const s=e[0]?.[0],r=t[0]?.[0];if(!s||!r)return!0;for(let e=0;e<t.length;e++){const s=t[e];for(let e=0;e<s.length;e++)s[e].fill(0)}this._inputQueue.push(s);const i=this._workerReady&&this._workerPort;for(;this._inputQueue.framesAvailable>=this._frameLength;){const e=this._framePool.acquire();this._inputQueue.pull(e),i?this._batchQueue.push(e):(this._outputQueue.push(e),this._framePool.release(e))}i&&this._batchQueue.length>=this._batchFrames&&this._sendBatch(),this._outputQueue.pull(r);const o=t[0];for(let e=1;e<o.length;e++)o[e].set(r);return!0}_setupMessageHandler(){this.port.onmessage=e=>{const t=e.data;this._messageChain=this._messageChain.then((()=>this._dispatch(t))).catch((e=>{this._respondError(t?.requestId,t?.type??"UNKNOWN",e)}))}}async _dispatch(e){if(!e?.type)return;const t=this._nowMs(),s=e.type;switch(s){case"INIT_PIPELINE":this._initPipeline(e);break;case"SET_ENABLED":this._setEnabled(e.enable);break;case"SET_STAGE_MODULE":this._handleSetStageModule(e);break;case"SET_MODULE_CONFIG":this._handleSetModuleConfig(e);break;case"DESTROY":this._destroy()}this._logInfo(`${s} dispatch`,{elapsed:`${(this._nowMs()-t).toFixed(2)}ms`}),this._respondOk(e.requestId,s)}_initPipeline(t){if(this._debugLogs=t.debugLogs??this._debugLogs,this._currentModuleId=e(t.stages?.denoise),this._batchFrames=Math.max(1,t.batchFrames??1),this._vadLogIntervalMs=t.moduleConfigs?.rnnoise?.vadLogIntervalMs??1e3,this._vadLogsEnabled=t.moduleConfigs?.rnnoise?.vadLogs??!1,t.workerPort){this._workerPort=t.workerPort,this._setupWorkerPort();const e=t.frameLength??480;this._onWorkerInitOk(e)}this._logInfo(`AUDIO_PIPELINE_WORKLET_READY:${this._currentModuleId}`)}_setupWorkerPort(){this._workerPort&&(this._workerPort.onmessage=e=>{const t=e.data;if(t?.type)switch(t.type){case"INIT_OK":this._onWorkerInitOk(t.frameLength);break;case"FRAME_RESULT_BATCH":this._onFrameResultBatch(t.outputBuffers,t.vadScores,t.recycleBuffers);break;case"MODULE_CHANGED":this._onModuleChanged(t.frameLength,t.lookahead);break;case"ERROR":this._logError(`WORKER_ERROR:${t.error}`);break;case"LOG":this._forwardLog(t.level,t.tag,t.text,t.data)}})}_onWorkerInitOk(e){this._frameLength=e,this._framePool.resize(e),this._rebuildForFrameLength(e),this._workerReady=!0,this._logInfo("WORKER_INIT_OK",{frameLength:e})}_sendBatch(){const e=this._batchQueue.splice(0),t=this._pendingRecycles.length>0?this._pendingRecycles.splice(0):void 0;this._workerPort.postMessage({type:"PROCESS_FRAME_BATCH",inputBuffers:e,recycleBuffers:t},function(e,...t){const s=[];for(let t=0;t<e.length;t++)s.push(e[t].buffer);for(let e=0;e<t.length;e++){const r=t[e];if(r)for(let e=0;e<r.length;e++)s.push(r[e].buffer)}return s}(e,t))}_onFrameResultBatch(e,t,s){for(let t=0;t<e.length;t++)this._outputQueue.push(e[t]),this._pendingRecycles.push(e[t]);if(s)for(let e=0;e<s.length;e++)this._framePool.release(s[e]);if(t){const e=t[t.length-1];this._maybeEmitVadLog(e)}}_onModuleChanged(e,t){e!==this._frameLength&&(this._frameLength=e,this._framePool.resize(e),this._rebuildForFrameLength(e)),this._logInfo("MODULE_CHANGED",{frameLength:e})}_rebuildForFrameLength(e){const t=128*Math.max(e,128),r=this._inputQueue,i=this._outputQueue;if(this._inputQueue=new s(t),this._outputQueue=new s(t),r.drainInto(this._inputQueue),i.drainInto(this._outputQueue),!this._prefilled){this._prefilled=!0;const t=128*(Math.ceil(this._batchFrames*e/128)+Math.ceil(2*this._batchFrames));this._outputQueue.push(new Float32Array(t).fill(0)),this._logInfo("PREFILL",{frameLength:e,batchFrames:this._batchFrames,prefill:t})}this._logInfo("REBUILD_QUEUES",{frameLength:e,queueCapacity:t})}_setEnabled(e){this._lastVadLogAtMs=0,this._workerPort?.postMessage({type:"SET_ENABLED",enable:e}),this._logInfo(e?"AUDIO_PIPELINE_ENABLED":"AUDIO_PIPELINE_DISABLED")}_handleSetStageModule(t){if("denoise"!==t.stage)throw new Error(`Unsupported stage: ${t.stage}`);const s=e(t.moduleId);this._logInfo("MODULE_SWITCH_START",{from:this._currentModuleId,to:s}),this._currentModuleId=s,this._workerPort?.postMessage({type:"SET_MODULE",moduleId:s})}_handleSetModuleConfig(e){if("rnnoise"===e.moduleId)return void 0!==e.config.vadLogIntervalMs&&(this._vadLogIntervalMs=e.config.vadLogIntervalMs),void this._workerPort?.postMessage({type:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:e.config});this._workerPort?.postMessage({type:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:e.config})}_destroy(){this._destroyed||(this._destroyed=!0,this._workerReady=!1,this._workerPort?.postMessage({type:"DESTROY"}),this._workerPort?.close(),this._workerPort=void 0,this._inputQueue.clear(),this._outputQueue.clear(),this._logInfo("AUDIO_PIPELINE_WORKLET_DESTROYED"))}_respondOk(e,t){if(void 0===e)return;const s={type:"COMMAND_OK",requestId:e,command:t};this.port.postMessage(s)}_respondError(e,t,s){const r=s instanceof Error?s.message:String(s),i={type:"COMMAND_ERROR",requestId:e,command:t,error:r};this.port.postMessage(i),this._logError(`${t}:${r}`)}_maybeEmitVadLog(e){if(!this._debugLogs||"rnnoise"!==this._currentModuleId||!this._vadLogsEnabled)return;if(!Number.isFinite(e))return;this._lastVadScore=e;const t=this._nowMs();t-this._lastVadLogAtMs<this._vadLogIntervalMs||(this._lastVadLogAtMs=t,this._logInfo("AUDIO_PIPELINE_RNNOISE_VAD",{vadScore:this._lastVadScore,intervalMs:this._vadLogIntervalMs}))}_nowMs(){return"function"==typeof globalThis.performance?.now?globalThis.performance.now():Date.now()}static _LOG_TAG="[AudioPipeline:Worklet]";_postLog(e,t,s,r){const i={type:"LOG",level:e,tag:t,text:s,data:r};try{this.port.postMessage(i)}catch{}}_forwardLog(e,t,s,r){this._postLog(e,t,s,r)}_logInfo(e,t,s=!1){(s||this._debugLogs)&&this._postLog("info",r._LOG_TAG,e,t)}_logError(e,t){this._postLog("error",r._LOG_TAG,e,t)}}registerProcessor("AudioPipelineWorklet",r)})();
Binary file
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";const e=1e4;function t(e){return e.slice(0)}function o(e){if("string"!=typeof e)return;const t=e.trim();return 0!==t.length?t:void 0}function s(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function i(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function r(e){return Number.isFinite(e)?Math.abs(e??100):100}function n(e){return Number.isFinite(e)?Math.max(0,e??0):0}function a(e){return{modelUrl:o(e?.modelUrl),modelBuffer:void 0!==e?.modelBuffer?t(e.modelBuffer):void 0,attenLimDb:r(e?.attenLimDb),postFilterBeta:n(e?.postFilterBeta)}}function d(e){const t=e.lastIndexOf("/");return t>=0?e.substring(0,t+1):"./"}function l(e){const t=d(e);return{rnnoise:`${t}rnnoise.wasm`,deepfilter:`${t}deepfilter.wasm`}}function u(e,t){return t?.trim()?t.trim():`${d(e)}AudioPipelineWorker.js`}function m(e){const t=function(e){const t=e.trim();if(0===t.length)throw new Error("workletUrl is required");return t}(e.workletUrl);return{workletUrl:t,workerUrl:u(t,e.workerUrl),wasmUrls:l(t),debugLogs:Boolean(e.debugLogs),stages:{denoise:s(e.stages?.denoise)},moduleConfigs:{rnnoise:(o=e.moduleConfigs?.rnnoise,{vadLogs:Boolean(o?.vadLogs),bufferOverflowMs:i(o?.bufferOverflowMs)}),deepfilternet:a(e.moduleConfigs?.deepfilternet)}};var o}class c{static _loadedContexts=new WeakSet;static _loadedWorkletUrls=new WeakMap;name="audio-pipeline-filter";processedTrack;_audioOpts;_workletNode;_sourceNode;_worker;_enabled=!0;_options;_nextRequestId=1;_pendingCommands=new Map;_operationQueue=Promise.resolve();constructor(e){this._options=m(e)}static isSupported(){return!0}async init(e){this._debug("init",e),await this._initInternal(e,!1)}async restart(e){e.audioContext=e.audioContext??this._audioOpts?.audioContext,this._debug("restart",e),await this._initInternal(e,!0)}async onPublish(e){this._debug("onPublish",e.name)}async onUnpublish(){this._debug("onUnpublish")}async setEnabled(e){return this._runSerial((async()=>{this._debug("setEnabled",e),this._enabled=e,this._workletNode&&await this._sendCommand({message:"SET_ENABLED",enable:e})}))}async setStageModule(e,t){return this._runSerial((async()=>{if("denoise"!==e)throw new Error(`Unsupported stage: ${e}`);const o=s(t);this._options.stages.denoise!==o&&(this._workletNode&&await this._sendCommand({message:"SET_STAGE_MODULE",stage:"denoise",moduleId:o}),this._options.stages.denoise=o)}))}async setModuleConfig(e,t){return this._runSerial((async()=>{"rnnoise"===e?await this._applyRnnoiseConfig(t):await this._applyDeepFilterConfig(t)}))}async isEnabled(){return Boolean(this._workletNode&&this._enabled)}async destroy(){this._debug("destroy"),this._closeInternal()}async _applyRnnoiseConfig(e){const t=(o=this._options.moduleConfigs.rnnoise,(s=e)?{vadLogs:s.vadLogs??o.vadLogs,bufferOverflowMs:void 0!==s.bufferOverflowMs?i(s.bufferOverflowMs):o.bufferOverflowMs}:{...o});var o,s;this._workletNode&&await this._sendCommand({message:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:{...t}}),this._options.moduleConfigs.rnnoise=t}async _applyDeepFilterConfig(e){const s=function(e,s){if(!s)return{...e,modelBuffer:e.modelBuffer?t(e.modelBuffer):void 0};let i=e.modelUrl,a=e.modelBuffer?t(e.modelBuffer):void 0;return!0===s.clearModel&&(i=void 0,a=void 0),void 0!==s.modelUrl&&(i=o(s.modelUrl),a=void 0),void 0!==s.modelBuffer&&(a=t(s.modelBuffer)),{modelUrl:i,modelBuffer:a,attenLimDb:void 0!==s.attenLimDb?r(s.attenLimDb):e.attenLimDb,postFilterBeta:void 0!==s.postFilterBeta?n(s.postFilterBeta):e.postFilterBeta}}(this._options.moduleConfigs.deepfilternet,e);let i,a=!1;if(void 0!==e.modelBuffer){if(e.modelBuffer.byteLength<=0)throw new Error("DeepFilter modelBuffer is empty");i=t(e.modelBuffer),s.modelBuffer=t(i)}else void 0!==e.modelUrl?s.modelUrl?(i=await this._fetchBinary(s.modelUrl,"DeepFilter model"),s.modelBuffer=t(i)):(a=!0,s.modelBuffer=void 0):!0===e.clearModel&&(a=!0,s.modelBuffer=void 0);if(this._workletNode){const e={attenLimDb:s.attenLimDb,postFilterBeta:s.postFilterBeta,modelBuffer:i,clearModel:a};await this._sendCommand({message:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:e},i?[i]:void 0)}this._options.moduleConfigs.deepfilternet=s}async _initInternal(e,o){if(!e?.audioContext||!e.track)throw new Error("audioContext and track are required");o&&this._closeInternal(),this._audioOpts=e;const s=e.audioContext;await this._ensureWorkletLoaded(s),this._workletNode=new AudioWorkletNode(s,"AudioPipelineWorklet",{processorOptions:{debugLogs:this._options.debugLogs,numberOfChannels:e.track.getSettings().channelCount}}),this._workletNode.port.onmessage=this._handleRuntimeMessage;const i=this._options.stages.denoise,r=this._options.moduleConfigs.deepfilternet,{wasmBinaries:n,wasmTransferables:a}=await this._fetchWasmBinaries(this._options.wasmUrls),d=await this._resolveModelBuffer(r);d&&(this._options.moduleConfigs.deepfilternet.modelBuffer=t(d)),this._worker=new Worker(this._options.workerUrl);const l=new MessageChannel;this._worker.postMessage({type:"CONNECT_PORT",port:l.port1},[l.port1]);const u={type:"INIT",wasmBinaries:n,moduleId:i,moduleConfigs:{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{attenLimDb:r.attenLimDb,postFilterBeta:r.postFilterBeta,modelBuffer:d}},debugLogs:this._options.debugLogs},m=[...a];d&&m.push(d),l.port2.postMessage(u,m);const c=await this._waitForWorkerInit(l.port2);this._debug("worker init complete",c),await this._sendCommand({message:"INIT_PIPELINE",enable:this._enabled,debugLogs:this._options.debugLogs,workerPort:l.port2,frameLength:c.frameLength,stages:{denoise:i},moduleConfigs:{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{attenLimDb:r.attenLimDb,postFilterBeta:r.postFilterBeta}}},[l.port2]),this._sourceNode=s.createMediaStreamSource(new MediaStream([e.track])),this._sourceNode.connect(this._workletNode);const f=s.createMediaStreamDestination();this._workletNode.connect(f),this.processedTrack=f.stream.getAudioTracks()[0],this._debug("init complete",`sourceID: ${e.track.id}, newTrackID: ${this.processedTrack.id}`)}async _ensureWorkletLoaded(e){const t=this._options.workletUrl;if(!t)throw new Error("workletUrl is required. Pass AudioPipelineTrackProcessor({ workletUrl }).");if(!c._loadedContexts.has(e)){this._debug("loading worklet",t);try{await e.audioWorklet.addModule(t),c._loadedContexts.add(e),c._loadedWorkletUrls.set(e,t)}catch(e){throw new Error(`Failed to load audio pipeline worklet module: ${String(e)}. URL: ${t}`)}}}_waitForWorkerInit(t){const o=performance.now();return new Promise(((s,i)=>{const r=setTimeout((()=>{t.onmessage=null,i(new Error("Worker init timeout after 10000ms"))}),e),n=t.onmessage;t.onmessage=e=>{const a=e.data;"INIT_OK"===a?.type?(clearTimeout(r),t.onmessage=n,this._debug("worker INIT_OK",`${(performance.now()-o).toFixed(2)}ms`),s({frameLength:a.frameLength,lookahead:a.lookahead})):"ERROR"===a?.type&&(clearTimeout(r),t.onmessage=n,i(new Error(`Worker init failed: ${a.error}`)))}}))}_closeInternal(){if(this._workletNode){try{this._workletNode.port.postMessage({message:"DESTROY"})}catch{}this._workletNode.port.onmessage=null}if(this._worker){try{this._worker.postMessage({type:"DESTROY"})}catch{}this._worker.terminate(),this._worker=void 0}this._rejectAllPendingCommands("Audio pipeline runtime closed"),this._workletNode?.disconnect(),this._sourceNode?.disconnect(),this._workletNode=void 0,this._sourceNode=void 0,this.processedTrack=void 0}async _fetchWasmBinaries(e){const t={},o=[];this._debug("fetching rnnoise wasm",e.rnnoise);const s=await this._fetchBinary(e.rnnoise,"RNNoise WASM");t.rnnoiseWasm=s,o.push(s),this._debug("fetching deepfilter wasm",e.deepfilter);const i=await this._fetchBinary(e.deepfilter,"DeepFilter WASM");return t.deepfilterWasm=i,o.push(i),{wasmBinaries:t,wasmTransferables:o}}async _resolveModelBuffer(e){return e.modelBuffer?t(e.modelBuffer):e.modelUrl?this._fetchBinary(e.modelUrl,"DeepFilter model"):void 0}async _fetchBinary(e,t){const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status} ${o.statusText} (${e})`);return o.arrayBuffer()}_handleRuntimeMessage=e=>{const t=e.data;t?.message&&("COMMAND_OK"===t.message?this._resolvePending(t.requestId):"COMMAND_ERROR"===t.message?this._rejectPending(t):"LOG"===t.message&&this._handleLog(t))};_handleLog(e){const t=`${e.tag} ${e.text}`;"error"===e.level?void 0!==e.data?console.error(t,e.data):console.error(t):void 0!==e.data?console.log(t,e.data):console.log(t)}_runSerial(e){const t=this._operationQueue.then(e,e);return this._operationQueue=t.then((()=>{}),(()=>{})),t}async _sendCommand(t,o){if(!this._workletNode)throw new Error("Audio pipeline worklet is not initialized");const s=this._nextRequestId++,i=performance.now();await new Promise(((i,r)=>{const n=setTimeout((()=>{this._pendingCommands.delete(s),r(new Error(`Command timeout after 10000ms: ${t.message}`))}),e);this._pendingCommands.set(s,{command:t.message,timeoutId:n,resolve:i,reject:r});try{this._workletNode?.port.postMessage({...t,requestId:s},o??[])}catch(e){clearTimeout(n),this._pendingCommands.delete(s),r(e instanceof Error?e:new Error(String(e)))}})),this._debug(`${t.message} round-trip`,`${(performance.now()-i).toFixed(2)}ms`)}_resolvePending(e){if(void 0===e)return;const t=this._pendingCommands.get(e);t&&(clearTimeout(t.timeoutId),this._pendingCommands.delete(e),t.resolve())}_rejectPending(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`;if(void 0===e.requestId)return void this._debug("COMMAND_ERROR (no requestId)",t);const o=this._pendingCommands.get(e.requestId);o?(clearTimeout(o.timeoutId),this._pendingCommands.delete(e.requestId),o.reject(new Error(t))):this._debug("COMMAND_ERROR (stale)",t)}_rejectAllPendingCommands(e){for(const t of this._pendingCommands.values())clearTimeout(t.timeoutId),t.reject(new Error(e));this._pendingCommands.clear()}static _LOG_TAG="[AudioPipeline:Main]";_debug(e,t){this._options.debugLogs&&(void 0!==t?console.log(`${c._LOG_TAG} ${e}`,t):console.log(`${c._LOG_TAG} ${e}`))}}exports.AudioPipelineTrackProcessor=c;
1
+ "use strict";const e=1e4;class t{_nextRequestId=1;_pendingCommands=new Map;async send(t,o,s){const n=this._nextRequestId++;return await new Promise(((r,i)=>{const a=setTimeout((()=>{this._pendingCommands.delete(n),i(new Error(`Command timeout after 10000ms: ${o.type}`))}),e);this._pendingCommands.set(n,{command:o.type,timeoutId:a,resolve:r,reject:i});try{t.postMessage({...o,requestId:n},s??[])}catch(e){clearTimeout(a),this._pendingCommands.delete(n),i(e instanceof Error?e:new Error(String(e)))}})),n}resolve(e){if(void 0===e)return;const t=this._pendingCommands.get(e);t&&(clearTimeout(t.timeoutId),this._pendingCommands.delete(e),t.resolve())}reject(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`;if(void 0===e.requestId)return;const o=this._pendingCommands.get(e.requestId);o&&(clearTimeout(o.timeoutId),this._pendingCommands.delete(e.requestId),o.reject(new Error(t)))}close(e){for(const t of this._pendingCommands.values())clearTimeout(t.timeoutId),t.reject(new Error(e));this._pendingCommands.clear()}getPendingCommand(e){if(void 0!==e)return this._pendingCommands.get(e)?.command}}function o(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function s(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function n(e){return Number.isFinite(e)?Math.abs(e??100):100}function r(e){return Number.isFinite(e)?Math.max(0,e??0):0}function i(e,t){return Number.isFinite(e)?e:t}function a(e){return{attenLimDb:n(e?.attenLimDb),postFilterBeta:r(e?.postFilterBeta),minDbThresh:i(e?.minDbThresh,-15),maxDbErbThresh:i(e?.maxDbErbThresh,35),maxDbDfThresh:i(e?.maxDbDfThresh,35)}}function d(e){const t=e.lastIndexOf("/");return t>=0?e.substring(0,t+1):"./"}function l(e){const t=d(e);return{rnnoise:`${t}rnnoise.wasm`,deepfilter:`${t}deepfilter.wasm`}}function h(e,t){return t?.trim()?t.trim():`${d(e)}AudioPipelineWorker.js`}function m(e){const t=function(e){const t=e.trim();if(0===t.length)throw new Error("workletUrl is required");return t}(e.workletUrl);return{workletUrl:t,workerUrl:h(t,e.workerUrl),wasmUrls:l(t),debugLogs:Boolean(e.debugLogs),batchFrames:Math.max(1,Math.floor(e.batchFrames??1)),stages:{denoise:o(e.stages?.denoise)},moduleConfigs:{rnnoise:(n=e.moduleConfigs?.rnnoise,{vadLogs:Boolean(n?.vadLogs),vadLogIntervalMs:s(n?.vadLogIntervalMs)}),deepfilternet:a(e.moduleConfigs?.deepfilternet)}};var n}async function u(e,t){const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status} ${o.statusText} (${e})`);return o.arrayBuffer()}class c{static _loadedContexts=new WeakSet;name="audio-pipeline-filter";processedTrack;_audioOpts;_workletNode;_sourceNode;_worker;_enabled=!0;_options;_commandTransport=new t;_operationQueue=Promise.resolve();constructor(e){this._options=m(e)}static isSupported(){return!0}async init(e){this._debug("init",e),await this._initInternal(e,!1)}async restart(e){e.audioContext=e.audioContext??this._audioOpts?.audioContext,this._debug("restart",e),await this._initInternal(e,!0)}async onPublish(e){this._debug("onPublish",e.name)}async onUnpublish(){this._debug("onUnpublish")}async setEnabled(e){return this._runSerial((async()=>{this._debug("setEnabled",e),this._enabled=e,this._workletNode&&await this._sendCommand({type:"SET_ENABLED",enable:e})}))}async setStageModule(e,t){return this._runSerial((async()=>{if("denoise"!==e)throw new Error(`Unsupported stage: ${e}`);const s=o(t);this._options.stages.denoise!==s&&(this._workletNode&&await this._sendCommand({type:"SET_STAGE_MODULE",stage:"denoise",moduleId:s}),this._options.stages.denoise=s)}))}async setModuleConfig(e,t){return this._runSerial((async()=>{"rnnoise"===e?await this._applyRnnoiseConfig(t):await this._applyDeepFilterConfig(t)}))}async isEnabled(){return Boolean(this._workletNode&&this._enabled)}async destroy(){this._debug("destroy"),this._closeInternal()}async _applyRnnoiseConfig(e){const t=(o=this._options.moduleConfigs.rnnoise,(n=e)?{vadLogs:n.vadLogs??o.vadLogs,vadLogIntervalMs:void 0!==n.vadLogIntervalMs?s(n.vadLogIntervalMs):o.vadLogIntervalMs}:{...o});var o,n;this._workletNode&&await this._sendCommand({type:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:{...t}}),this._options.moduleConfigs.rnnoise=t}async _applyDeepFilterConfig(e){const t=(o=this._options.moduleConfigs.deepfilternet,(s=e)?{attenLimDb:void 0!==s.attenLimDb?n(s.attenLimDb):o.attenLimDb,postFilterBeta:void 0!==s.postFilterBeta?r(s.postFilterBeta):o.postFilterBeta,minDbThresh:i(s.minDbThresh,o.minDbThresh),maxDbErbThresh:i(s.maxDbErbThresh,o.maxDbErbThresh),maxDbDfThresh:i(s.maxDbDfThresh,o.maxDbDfThresh)}:{...o});var o,s;this._workletNode&&await this._sendCommand({type:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:{...t}}),this._options.moduleConfigs.deepfilternet=t}async _initInternal(e,t){if(!e?.audioContext||!e.track)throw new Error("audioContext and track are required");t&&this._closeInternal(),this._audioOpts=e;const o=e.audioContext;await this._ensureWorkletLoaded(o),this._workletNode=new AudioWorkletNode(o,"AudioPipelineWorklet",{processorOptions:{debugLogs:this._options.debugLogs,numberOfChannels:e.track.getSettings().channelCount}}),this._workletNode.port.onmessage=this._handleRuntimeMessage;const s=this._options.stages.denoise,n=this._createModuleConfigs(),{wasmBinaries:r,wasmTransferables:i}=await async function(e,t){const o={},s=[];t?.("fetching rnnoise wasm",e.rnnoise);const n=await u(e.rnnoise,"RNNoise WASM");o.rnnoiseWasm=n,s.push(n),t?.("fetching deepfilter wasm",e.deepfilter);const r=await u(e.deepfilter,"DeepFilter WASM");return o.deepfilterWasm=r,s.push(r),{wasmBinaries:o,wasmTransferables:s}}(this._options.wasmUrls,((e,t)=>this._debug(e,t)));this._worker=new Worker(this._options.workerUrl);const a=new MessageChannel;this._worker.postMessage({type:"CONNECT_PORT",port:a.port1},[a.port1]);const d={type:"INIT",wasmBinaries:r,moduleId:s,moduleConfigs:n,debugLogs:this._options.debugLogs};a.port2.postMessage(d,i);const l=await this._waitForWorkerInit(a.port2);this._debug("worker init complete",l),await this._sendCommand({type:"INIT_PIPELINE",enable:this._enabled,debugLogs:this._options.debugLogs,workerPort:a.port2,frameLength:l.frameLength,batchFrames:this._options.batchFrames,stages:{denoise:s},moduleConfigs:n},[a.port2]),this._sourceNode=o.createMediaStreamSource(new MediaStream([e.track])),this._sourceNode.connect(this._workletNode);const h=o.createMediaStreamDestination();this._workletNode.connect(h),this.processedTrack=h.stream.getAudioTracks()[0],this._debug("init complete",`sourceID: ${e.track.id}, newTrackID: ${this.processedTrack.id}`)}async _ensureWorkletLoaded(e){const t=this._options.workletUrl;if(!t)throw new Error("workletUrl is required. Pass AudioPipelineTrackProcessor({ workletUrl }).");if(!c._loadedContexts.has(e)){this._debug("loading worklet",t);try{await e.audioWorklet.addModule(t),c._loadedContexts.add(e)}catch(e){throw new Error(`Failed to load audio pipeline worklet module: ${String(e)}. URL: ${t}`)}}}_waitForWorkerInit(t){const o=performance.now();return new Promise(((s,n)=>{const r=setTimeout((()=>{t.onmessage=null,n(new Error("Worker init timeout after 10000ms"))}),e),i=t.onmessage;t.onmessage=e=>{const a=e.data;"INIT_OK"===a?.type?(clearTimeout(r),t.onmessage=i,this._debug("worker INIT_OK",`${(performance.now()-o).toFixed(2)}ms`),s({frameLength:a.frameLength,lookahead:a.lookahead})):"ERROR"===a?.type&&(clearTimeout(r),t.onmessage=i,n(new Error(`Worker init failed: ${a.error}`)))}}))}_closeInternal(){if(this._workletNode){try{this._workletNode.port.postMessage({type:"DESTROY"})}catch{}this._workletNode.port.onmessage=null}if(this._worker){try{this._worker.postMessage({type:"DESTROY"})}catch{}this._worker.terminate(),this._worker=void 0}this._commandTransport.close("Audio pipeline runtime closed"),this._workletNode?.disconnect(),this._sourceNode?.disconnect(),this._workletNode=void 0,this._sourceNode=void 0,this.processedTrack=void 0}_handleRuntimeMessage=e=>{const t=e.data;t?.type&&("COMMAND_OK"===t.type?this._commandTransport.resolve(t.requestId):"COMMAND_ERROR"===t.type?this._handleCommandError(t):"LOG"===t.type&&this._handleLog(t))};_handleLog(e){const t=`${e.tag} ${e.text}`;"error"===e.level?void 0!==e.data?console.error(t,e.data):console.error(t):void 0!==e.data?console.log(t,e.data):console.log(t)}_handleCommandError(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`,o=this._commandTransport.getPendingCommand(e.requestId);void 0!==e.requestId?o?this._commandTransport.reject(e):this._debug("COMMAND_ERROR (stale)",t):this._debug("COMMAND_ERROR (no requestId)",t)}_runSerial(e){const t=this._operationQueue.then(e,e);return this._operationQueue=t.then((()=>{}),(()=>{})),t}_createModuleConfigs(){return{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{...this._options.moduleConfigs.deepfilternet}}}async _sendCommand(e,t){if(!this._workletNode)throw new Error("Audio pipeline worklet is not initialized");const o=performance.now();await this._commandTransport.send(this._workletNode.port,e,t),this._debug(`${e.type} round-trip`,`${(performance.now()-o).toFixed(2)}ms`)}static _LOG_TAG="[AudioPipeline:Main]";_debug(e,t){this._options.debugLogs&&(void 0!==t?console.log(`${c._LOG_TAG} ${e}`,t):console.log(`${c._LOG_TAG} ${e}`))}}exports.AudioPipelineTrackProcessor=c;
2
2
  //# sourceMappingURL=index.cjs.map
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- const e=1e4;function t(e){return e.slice(0)}function o(e){if("string"!=typeof e)return;const t=e.trim();return 0!==t.length?t:void 0}function s(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function i(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function r(e){return Number.isFinite(e)?Math.abs(e??100):100}function n(e){return Number.isFinite(e)?Math.max(0,e??0):0}function a(e){return{modelUrl:o(e?.modelUrl),modelBuffer:void 0!==e?.modelBuffer?t(e.modelBuffer):void 0,attenLimDb:r(e?.attenLimDb),postFilterBeta:n(e?.postFilterBeta)}}function d(e){const t=e.lastIndexOf("/");return t>=0?e.substring(0,t+1):"./"}function l(e){const t=d(e);return{rnnoise:`${t}rnnoise.wasm`,deepfilter:`${t}deepfilter.wasm`}}function u(e,t){return t?.trim()?t.trim():`${d(e)}AudioPipelineWorker.js`}function m(e){const t=function(e){const t=e.trim();if(0===t.length)throw new Error("workletUrl is required");return t}(e.workletUrl);return{workletUrl:t,workerUrl:u(t,e.workerUrl),wasmUrls:l(t),debugLogs:Boolean(e.debugLogs),stages:{denoise:s(e.stages?.denoise)},moduleConfigs:{rnnoise:(o=e.moduleConfigs?.rnnoise,{vadLogs:Boolean(o?.vadLogs),bufferOverflowMs:i(o?.bufferOverflowMs)}),deepfilternet:a(e.moduleConfigs?.deepfilternet)}};var o}class f{static _loadedContexts=new WeakSet;static _loadedWorkletUrls=new WeakMap;name="audio-pipeline-filter";processedTrack;_audioOpts;_workletNode;_sourceNode;_worker;_enabled=!0;_options;_nextRequestId=1;_pendingCommands=new Map;_operationQueue=Promise.resolve();constructor(e){this._options=m(e)}static isSupported(){return!0}async init(e){this._debug("init",e),await this._initInternal(e,!1)}async restart(e){e.audioContext=e.audioContext??this._audioOpts?.audioContext,this._debug("restart",e),await this._initInternal(e,!0)}async onPublish(e){this._debug("onPublish",e.name)}async onUnpublish(){this._debug("onUnpublish")}async setEnabled(e){return this._runSerial((async()=>{this._debug("setEnabled",e),this._enabled=e,this._workletNode&&await this._sendCommand({message:"SET_ENABLED",enable:e})}))}async setStageModule(e,t){return this._runSerial((async()=>{if("denoise"!==e)throw new Error(`Unsupported stage: ${e}`);const o=s(t);this._options.stages.denoise!==o&&(this._workletNode&&await this._sendCommand({message:"SET_STAGE_MODULE",stage:"denoise",moduleId:o}),this._options.stages.denoise=o)}))}async setModuleConfig(e,t){return this._runSerial((async()=>{"rnnoise"===e?await this._applyRnnoiseConfig(t):await this._applyDeepFilterConfig(t)}))}async isEnabled(){return Boolean(this._workletNode&&this._enabled)}async destroy(){this._debug("destroy"),this._closeInternal()}async _applyRnnoiseConfig(e){const t=(o=this._options.moduleConfigs.rnnoise,(s=e)?{vadLogs:s.vadLogs??o.vadLogs,bufferOverflowMs:void 0!==s.bufferOverflowMs?i(s.bufferOverflowMs):o.bufferOverflowMs}:{...o});var o,s;this._workletNode&&await this._sendCommand({message:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:{...t}}),this._options.moduleConfigs.rnnoise=t}async _applyDeepFilterConfig(e){const s=function(e,s){if(!s)return{...e,modelBuffer:e.modelBuffer?t(e.modelBuffer):void 0};let i=e.modelUrl,a=e.modelBuffer?t(e.modelBuffer):void 0;return!0===s.clearModel&&(i=void 0,a=void 0),void 0!==s.modelUrl&&(i=o(s.modelUrl),a=void 0),void 0!==s.modelBuffer&&(a=t(s.modelBuffer)),{modelUrl:i,modelBuffer:a,attenLimDb:void 0!==s.attenLimDb?r(s.attenLimDb):e.attenLimDb,postFilterBeta:void 0!==s.postFilterBeta?n(s.postFilterBeta):e.postFilterBeta}}(this._options.moduleConfigs.deepfilternet,e);let i,a=!1;if(void 0!==e.modelBuffer){if(e.modelBuffer.byteLength<=0)throw new Error("DeepFilter modelBuffer is empty");i=t(e.modelBuffer),s.modelBuffer=t(i)}else void 0!==e.modelUrl?s.modelUrl?(i=await this._fetchBinary(s.modelUrl,"DeepFilter model"),s.modelBuffer=t(i)):(a=!0,s.modelBuffer=void 0):!0===e.clearModel&&(a=!0,s.modelBuffer=void 0);if(this._workletNode){const e={attenLimDb:s.attenLimDb,postFilterBeta:s.postFilterBeta,modelBuffer:i,clearModel:a};await this._sendCommand({message:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:e},i?[i]:void 0)}this._options.moduleConfigs.deepfilternet=s}async _initInternal(e,o){if(!e?.audioContext||!e.track)throw new Error("audioContext and track are required");o&&this._closeInternal(),this._audioOpts=e;const s=e.audioContext;await this._ensureWorkletLoaded(s),this._workletNode=new AudioWorkletNode(s,"AudioPipelineWorklet",{processorOptions:{debugLogs:this._options.debugLogs,numberOfChannels:e.track.getSettings().channelCount}}),this._workletNode.port.onmessage=this._handleRuntimeMessage;const i=this._options.stages.denoise,r=this._options.moduleConfigs.deepfilternet,{wasmBinaries:n,wasmTransferables:a}=await this._fetchWasmBinaries(this._options.wasmUrls),d=await this._resolveModelBuffer(r);d&&(this._options.moduleConfigs.deepfilternet.modelBuffer=t(d)),this._worker=new Worker(this._options.workerUrl);const l=new MessageChannel;this._worker.postMessage({type:"CONNECT_PORT",port:l.port1},[l.port1]);const u={type:"INIT",wasmBinaries:n,moduleId:i,moduleConfigs:{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{attenLimDb:r.attenLimDb,postFilterBeta:r.postFilterBeta,modelBuffer:d}},debugLogs:this._options.debugLogs},m=[...a];d&&m.push(d),l.port2.postMessage(u,m);const f=await this._waitForWorkerInit(l.port2);this._debug("worker init complete",f),await this._sendCommand({message:"INIT_PIPELINE",enable:this._enabled,debugLogs:this._options.debugLogs,workerPort:l.port2,frameLength:f.frameLength,stages:{denoise:i},moduleConfigs:{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{attenLimDb:r.attenLimDb,postFilterBeta:r.postFilterBeta}}},[l.port2]),this._sourceNode=s.createMediaStreamSource(new MediaStream([e.track])),this._sourceNode.connect(this._workletNode);const c=s.createMediaStreamDestination();this._workletNode.connect(c),this.processedTrack=c.stream.getAudioTracks()[0],this._debug("init complete",`sourceID: ${e.track.id}, newTrackID: ${this.processedTrack.id}`)}async _ensureWorkletLoaded(e){const t=this._options.workletUrl;if(!t)throw new Error("workletUrl is required. Pass AudioPipelineTrackProcessor({ workletUrl }).");if(!f._loadedContexts.has(e)){this._debug("loading worklet",t);try{await e.audioWorklet.addModule(t),f._loadedContexts.add(e),f._loadedWorkletUrls.set(e,t)}catch(e){throw new Error(`Failed to load audio pipeline worklet module: ${String(e)}. URL: ${t}`)}}}_waitForWorkerInit(t){const o=performance.now();return new Promise(((s,i)=>{const r=setTimeout((()=>{t.onmessage=null,i(new Error("Worker init timeout after 10000ms"))}),e),n=t.onmessage;t.onmessage=e=>{const a=e.data;"INIT_OK"===a?.type?(clearTimeout(r),t.onmessage=n,this._debug("worker INIT_OK",`${(performance.now()-o).toFixed(2)}ms`),s({frameLength:a.frameLength,lookahead:a.lookahead})):"ERROR"===a?.type&&(clearTimeout(r),t.onmessage=n,i(new Error(`Worker init failed: ${a.error}`)))}}))}_closeInternal(){if(this._workletNode){try{this._workletNode.port.postMessage({message:"DESTROY"})}catch{}this._workletNode.port.onmessage=null}if(this._worker){try{this._worker.postMessage({type:"DESTROY"})}catch{}this._worker.terminate(),this._worker=void 0}this._rejectAllPendingCommands("Audio pipeline runtime closed"),this._workletNode?.disconnect(),this._sourceNode?.disconnect(),this._workletNode=void 0,this._sourceNode=void 0,this.processedTrack=void 0}async _fetchWasmBinaries(e){const t={},o=[];this._debug("fetching rnnoise wasm",e.rnnoise);const s=await this._fetchBinary(e.rnnoise,"RNNoise WASM");t.rnnoiseWasm=s,o.push(s),this._debug("fetching deepfilter wasm",e.deepfilter);const i=await this._fetchBinary(e.deepfilter,"DeepFilter WASM");return t.deepfilterWasm=i,o.push(i),{wasmBinaries:t,wasmTransferables:o}}async _resolveModelBuffer(e){return e.modelBuffer?t(e.modelBuffer):e.modelUrl?this._fetchBinary(e.modelUrl,"DeepFilter model"):void 0}async _fetchBinary(e,t){const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status} ${o.statusText} (${e})`);return o.arrayBuffer()}_handleRuntimeMessage=e=>{const t=e.data;t?.message&&("COMMAND_OK"===t.message?this._resolvePending(t.requestId):"COMMAND_ERROR"===t.message?this._rejectPending(t):"LOG"===t.message&&this._handleLog(t))};_handleLog(e){const t=`${e.tag} ${e.text}`;"error"===e.level?void 0!==e.data?console.error(t,e.data):console.error(t):void 0!==e.data?console.log(t,e.data):console.log(t)}_runSerial(e){const t=this._operationQueue.then(e,e);return this._operationQueue=t.then((()=>{}),(()=>{})),t}async _sendCommand(t,o){if(!this._workletNode)throw new Error("Audio pipeline worklet is not initialized");const s=this._nextRequestId++,i=performance.now();await new Promise(((i,r)=>{const n=setTimeout((()=>{this._pendingCommands.delete(s),r(new Error(`Command timeout after 10000ms: ${t.message}`))}),e);this._pendingCommands.set(s,{command:t.message,timeoutId:n,resolve:i,reject:r});try{this._workletNode?.port.postMessage({...t,requestId:s},o??[])}catch(e){clearTimeout(n),this._pendingCommands.delete(s),r(e instanceof Error?e:new Error(String(e)))}})),this._debug(`${t.message} round-trip`,`${(performance.now()-i).toFixed(2)}ms`)}_resolvePending(e){if(void 0===e)return;const t=this._pendingCommands.get(e);t&&(clearTimeout(t.timeoutId),this._pendingCommands.delete(e),t.resolve())}_rejectPending(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`;if(void 0===e.requestId)return void this._debug("COMMAND_ERROR (no requestId)",t);const o=this._pendingCommands.get(e.requestId);o?(clearTimeout(o.timeoutId),this._pendingCommands.delete(e.requestId),o.reject(new Error(t))):this._debug("COMMAND_ERROR (stale)",t)}_rejectAllPendingCommands(e){for(const t of this._pendingCommands.values())clearTimeout(t.timeoutId),t.reject(new Error(e));this._pendingCommands.clear()}static _LOG_TAG="[AudioPipeline:Main]";_debug(e,t){this._options.debugLogs&&(void 0!==t?console.log(`${f._LOG_TAG} ${e}`,t):console.log(`${f._LOG_TAG} ${e}`))}}export{f as AudioPipelineTrackProcessor};
1
+ const e=1e4;class t{_nextRequestId=1;_pendingCommands=new Map;async send(t,o,s){const n=this._nextRequestId++;return await new Promise(((r,i)=>{const a=setTimeout((()=>{this._pendingCommands.delete(n),i(new Error(`Command timeout after 10000ms: ${o.type}`))}),e);this._pendingCommands.set(n,{command:o.type,timeoutId:a,resolve:r,reject:i});try{t.postMessage({...o,requestId:n},s??[])}catch(e){clearTimeout(a),this._pendingCommands.delete(n),i(e instanceof Error?e:new Error(String(e)))}})),n}resolve(e){if(void 0===e)return;const t=this._pendingCommands.get(e);t&&(clearTimeout(t.timeoutId),this._pendingCommands.delete(e),t.resolve())}reject(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`;if(void 0===e.requestId)return;const o=this._pendingCommands.get(e.requestId);o&&(clearTimeout(o.timeoutId),this._pendingCommands.delete(e.requestId),o.reject(new Error(t)))}close(e){for(const t of this._pendingCommands.values())clearTimeout(t.timeoutId),t.reject(new Error(e));this._pendingCommands.clear()}getPendingCommand(e){if(void 0!==e)return this._pendingCommands.get(e)?.command}}function o(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function s(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function n(e){return Number.isFinite(e)?Math.abs(e??100):100}function r(e){return Number.isFinite(e)?Math.max(0,e??0):0}function i(e,t){return Number.isFinite(e)?e:t}function a(e){return{attenLimDb:n(e?.attenLimDb),postFilterBeta:r(e?.postFilterBeta),minDbThresh:i(e?.minDbThresh,-15),maxDbErbThresh:i(e?.maxDbErbThresh,35),maxDbDfThresh:i(e?.maxDbDfThresh,35)}}function d(e){const t=e.lastIndexOf("/");return t>=0?e.substring(0,t+1):"./"}function l(e){const t=d(e);return{rnnoise:`${t}rnnoise.wasm`,deepfilter:`${t}deepfilter.wasm`}}function h(e,t){return t?.trim()?t.trim():`${d(e)}AudioPipelineWorker.js`}function m(e){const t=function(e){const t=e.trim();if(0===t.length)throw new Error("workletUrl is required");return t}(e.workletUrl);return{workletUrl:t,workerUrl:h(t,e.workerUrl),wasmUrls:l(t),debugLogs:Boolean(e.debugLogs),batchFrames:Math.max(1,Math.floor(e.batchFrames??1)),stages:{denoise:o(e.stages?.denoise)},moduleConfigs:{rnnoise:(n=e.moduleConfigs?.rnnoise,{vadLogs:Boolean(n?.vadLogs),vadLogIntervalMs:s(n?.vadLogIntervalMs)}),deepfilternet:a(e.moduleConfigs?.deepfilternet)}};var n}async function u(e,t){const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status} ${o.statusText} (${e})`);return o.arrayBuffer()}class c{static _loadedContexts=new WeakSet;name="audio-pipeline-filter";processedTrack;_audioOpts;_workletNode;_sourceNode;_worker;_enabled=!0;_options;_commandTransport=new t;_operationQueue=Promise.resolve();constructor(e){this._options=m(e)}static isSupported(){return!0}async init(e){this._debug("init",e),await this._initInternal(e,!1)}async restart(e){e.audioContext=e.audioContext??this._audioOpts?.audioContext,this._debug("restart",e),await this._initInternal(e,!0)}async onPublish(e){this._debug("onPublish",e.name)}async onUnpublish(){this._debug("onUnpublish")}async setEnabled(e){return this._runSerial((async()=>{this._debug("setEnabled",e),this._enabled=e,this._workletNode&&await this._sendCommand({type:"SET_ENABLED",enable:e})}))}async setStageModule(e,t){return this._runSerial((async()=>{if("denoise"!==e)throw new Error(`Unsupported stage: ${e}`);const s=o(t);this._options.stages.denoise!==s&&(this._workletNode&&await this._sendCommand({type:"SET_STAGE_MODULE",stage:"denoise",moduleId:s}),this._options.stages.denoise=s)}))}async setModuleConfig(e,t){return this._runSerial((async()=>{"rnnoise"===e?await this._applyRnnoiseConfig(t):await this._applyDeepFilterConfig(t)}))}async isEnabled(){return Boolean(this._workletNode&&this._enabled)}async destroy(){this._debug("destroy"),this._closeInternal()}async _applyRnnoiseConfig(e){const t=(o=this._options.moduleConfigs.rnnoise,(n=e)?{vadLogs:n.vadLogs??o.vadLogs,vadLogIntervalMs:void 0!==n.vadLogIntervalMs?s(n.vadLogIntervalMs):o.vadLogIntervalMs}:{...o});var o,n;this._workletNode&&await this._sendCommand({type:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:{...t}}),this._options.moduleConfigs.rnnoise=t}async _applyDeepFilterConfig(e){const t=(o=this._options.moduleConfigs.deepfilternet,(s=e)?{attenLimDb:void 0!==s.attenLimDb?n(s.attenLimDb):o.attenLimDb,postFilterBeta:void 0!==s.postFilterBeta?r(s.postFilterBeta):o.postFilterBeta,minDbThresh:i(s.minDbThresh,o.minDbThresh),maxDbErbThresh:i(s.maxDbErbThresh,o.maxDbErbThresh),maxDbDfThresh:i(s.maxDbDfThresh,o.maxDbDfThresh)}:{...o});var o,s;this._workletNode&&await this._sendCommand({type:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:{...t}}),this._options.moduleConfigs.deepfilternet=t}async _initInternal(e,t){if(!e?.audioContext||!e.track)throw new Error("audioContext and track are required");t&&this._closeInternal(),this._audioOpts=e;const o=e.audioContext;await this._ensureWorkletLoaded(o),this._workletNode=new AudioWorkletNode(o,"AudioPipelineWorklet",{processorOptions:{debugLogs:this._options.debugLogs,numberOfChannels:e.track.getSettings().channelCount}}),this._workletNode.port.onmessage=this._handleRuntimeMessage;const s=this._options.stages.denoise,n=this._createModuleConfigs(),{wasmBinaries:r,wasmTransferables:i}=await async function(e,t){const o={},s=[];t?.("fetching rnnoise wasm",e.rnnoise);const n=await u(e.rnnoise,"RNNoise WASM");o.rnnoiseWasm=n,s.push(n),t?.("fetching deepfilter wasm",e.deepfilter);const r=await u(e.deepfilter,"DeepFilter WASM");return o.deepfilterWasm=r,s.push(r),{wasmBinaries:o,wasmTransferables:s}}(this._options.wasmUrls,((e,t)=>this._debug(e,t)));this._worker=new Worker(this._options.workerUrl);const a=new MessageChannel;this._worker.postMessage({type:"CONNECT_PORT",port:a.port1},[a.port1]);const d={type:"INIT",wasmBinaries:r,moduleId:s,moduleConfigs:n,debugLogs:this._options.debugLogs};a.port2.postMessage(d,i);const l=await this._waitForWorkerInit(a.port2);this._debug("worker init complete",l),await this._sendCommand({type:"INIT_PIPELINE",enable:this._enabled,debugLogs:this._options.debugLogs,workerPort:a.port2,frameLength:l.frameLength,batchFrames:this._options.batchFrames,stages:{denoise:s},moduleConfigs:n},[a.port2]),this._sourceNode=o.createMediaStreamSource(new MediaStream([e.track])),this._sourceNode.connect(this._workletNode);const h=o.createMediaStreamDestination();this._workletNode.connect(h),this.processedTrack=h.stream.getAudioTracks()[0],this._debug("init complete",`sourceID: ${e.track.id}, newTrackID: ${this.processedTrack.id}`)}async _ensureWorkletLoaded(e){const t=this._options.workletUrl;if(!t)throw new Error("workletUrl is required. Pass AudioPipelineTrackProcessor({ workletUrl }).");if(!c._loadedContexts.has(e)){this._debug("loading worklet",t);try{await e.audioWorklet.addModule(t),c._loadedContexts.add(e)}catch(e){throw new Error(`Failed to load audio pipeline worklet module: ${String(e)}. URL: ${t}`)}}}_waitForWorkerInit(t){const o=performance.now();return new Promise(((s,n)=>{const r=setTimeout((()=>{t.onmessage=null,n(new Error("Worker init timeout after 10000ms"))}),e),i=t.onmessage;t.onmessage=e=>{const a=e.data;"INIT_OK"===a?.type?(clearTimeout(r),t.onmessage=i,this._debug("worker INIT_OK",`${(performance.now()-o).toFixed(2)}ms`),s({frameLength:a.frameLength,lookahead:a.lookahead})):"ERROR"===a?.type&&(clearTimeout(r),t.onmessage=i,n(new Error(`Worker init failed: ${a.error}`)))}}))}_closeInternal(){if(this._workletNode){try{this._workletNode.port.postMessage({type:"DESTROY"})}catch{}this._workletNode.port.onmessage=null}if(this._worker){try{this._worker.postMessage({type:"DESTROY"})}catch{}this._worker.terminate(),this._worker=void 0}this._commandTransport.close("Audio pipeline runtime closed"),this._workletNode?.disconnect(),this._sourceNode?.disconnect(),this._workletNode=void 0,this._sourceNode=void 0,this.processedTrack=void 0}_handleRuntimeMessage=e=>{const t=e.data;t?.type&&("COMMAND_OK"===t.type?this._commandTransport.resolve(t.requestId):"COMMAND_ERROR"===t.type?this._handleCommandError(t):"LOG"===t.type&&this._handleLog(t))};_handleLog(e){const t=`${e.tag} ${e.text}`;"error"===e.level?void 0!==e.data?console.error(t,e.data):console.error(t):void 0!==e.data?console.log(t,e.data):console.log(t)}_handleCommandError(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`,o=this._commandTransport.getPendingCommand(e.requestId);void 0!==e.requestId?o?this._commandTransport.reject(e):this._debug("COMMAND_ERROR (stale)",t):this._debug("COMMAND_ERROR (no requestId)",t)}_runSerial(e){const t=this._operationQueue.then(e,e);return this._operationQueue=t.then((()=>{}),(()=>{})),t}_createModuleConfigs(){return{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{...this._options.moduleConfigs.deepfilternet}}}async _sendCommand(e,t){if(!this._workletNode)throw new Error("Audio pipeline worklet is not initialized");const o=performance.now();await this._commandTransport.send(this._workletNode.port,e,t),this._debug(`${e.type} round-trip`,`${(performance.now()-o).toFixed(2)}ms`)}static _LOG_TAG="[AudioPipeline:Main]";_debug(e,t){this._options.debugLogs&&(void 0!==t?console.log(`${c._LOG_TAG} ${e}`,t):console.log(`${c._LOG_TAG} ${e}`))}}export{c as AudioPipelineTrackProcessor};
2
2
  //# sourceMappingURL=index.js.map
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AudioPipelinePlugin={})}(this,(function(e){"use strict";const t=1e4;function o(e){return e.slice(0)}function s(e){if("string"!=typeof e)return;const t=e.trim();return 0!==t.length?t:void 0}function i(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function r(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function n(e){return Number.isFinite(e)?Math.abs(e??100):100}function a(e){return Number.isFinite(e)?Math.max(0,e??0):0}function d(e){return{modelUrl:s(e?.modelUrl),modelBuffer:void 0!==e?.modelBuffer?o(e.modelBuffer):void 0,attenLimDb:n(e?.attenLimDb),postFilterBeta:a(e?.postFilterBeta)}}function l(e){const t=e.lastIndexOf("/");return t>=0?e.substring(0,t+1):"./"}function u(e){const t=l(e);return{rnnoise:`${t}rnnoise.wasm`,deepfilter:`${t}deepfilter.wasm`}}function m(e,t){return t?.trim()?t.trim():`${l(e)}AudioPipelineWorker.js`}function f(e){const t=function(e){const t=e.trim();if(0===t.length)throw new Error("workletUrl is required");return t}(e.workletUrl);return{workletUrl:t,workerUrl:m(t,e.workerUrl),wasmUrls:u(t),debugLogs:Boolean(e.debugLogs),stages:{denoise:i(e.stages?.denoise)},moduleConfigs:{rnnoise:(o=e.moduleConfigs?.rnnoise,{vadLogs:Boolean(o?.vadLogs),bufferOverflowMs:r(o?.bufferOverflowMs)}),deepfilternet:d(e.moduleConfigs?.deepfilternet)}};var o}class c{static _loadedContexts=new WeakSet;static _loadedWorkletUrls=new WeakMap;name="audio-pipeline-filter";processedTrack;_audioOpts;_workletNode;_sourceNode;_worker;_enabled=!0;_options;_nextRequestId=1;_pendingCommands=new Map;_operationQueue=Promise.resolve();constructor(e){this._options=f(e)}static isSupported(){return!0}async init(e){this._debug("init",e),await this._initInternal(e,!1)}async restart(e){e.audioContext=e.audioContext??this._audioOpts?.audioContext,this._debug("restart",e),await this._initInternal(e,!0)}async onPublish(e){this._debug("onPublish",e.name)}async onUnpublish(){this._debug("onUnpublish")}async setEnabled(e){return this._runSerial((async()=>{this._debug("setEnabled",e),this._enabled=e,this._workletNode&&await this._sendCommand({message:"SET_ENABLED",enable:e})}))}async setStageModule(e,t){return this._runSerial((async()=>{if("denoise"!==e)throw new Error(`Unsupported stage: ${e}`);const o=i(t);this._options.stages.denoise!==o&&(this._workletNode&&await this._sendCommand({message:"SET_STAGE_MODULE",stage:"denoise",moduleId:o}),this._options.stages.denoise=o)}))}async setModuleConfig(e,t){return this._runSerial((async()=>{"rnnoise"===e?await this._applyRnnoiseConfig(t):await this._applyDeepFilterConfig(t)}))}async isEnabled(){return Boolean(this._workletNode&&this._enabled)}async destroy(){this._debug("destroy"),this._closeInternal()}async _applyRnnoiseConfig(e){const t=(o=this._options.moduleConfigs.rnnoise,(s=e)?{vadLogs:s.vadLogs??o.vadLogs,bufferOverflowMs:void 0!==s.bufferOverflowMs?r(s.bufferOverflowMs):o.bufferOverflowMs}:{...o});var o,s;this._workletNode&&await this._sendCommand({message:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:{...t}}),this._options.moduleConfigs.rnnoise=t}async _applyDeepFilterConfig(e){const t=function(e,t){if(!t)return{...e,modelBuffer:e.modelBuffer?o(e.modelBuffer):void 0};let i=e.modelUrl,r=e.modelBuffer?o(e.modelBuffer):void 0;return!0===t.clearModel&&(i=void 0,r=void 0),void 0!==t.modelUrl&&(i=s(t.modelUrl),r=void 0),void 0!==t.modelBuffer&&(r=o(t.modelBuffer)),{modelUrl:i,modelBuffer:r,attenLimDb:void 0!==t.attenLimDb?n(t.attenLimDb):e.attenLimDb,postFilterBeta:void 0!==t.postFilterBeta?a(t.postFilterBeta):e.postFilterBeta}}(this._options.moduleConfigs.deepfilternet,e);let i,r=!1;if(void 0!==e.modelBuffer){if(e.modelBuffer.byteLength<=0)throw new Error("DeepFilter modelBuffer is empty");i=o(e.modelBuffer),t.modelBuffer=o(i)}else void 0!==e.modelUrl?t.modelUrl?(i=await this._fetchBinary(t.modelUrl,"DeepFilter model"),t.modelBuffer=o(i)):(r=!0,t.modelBuffer=void 0):!0===e.clearModel&&(r=!0,t.modelBuffer=void 0);if(this._workletNode){const e={attenLimDb:t.attenLimDb,postFilterBeta:t.postFilterBeta,modelBuffer:i,clearModel:r};await this._sendCommand({message:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:e},i?[i]:void 0)}this._options.moduleConfigs.deepfilternet=t}async _initInternal(e,t){if(!e?.audioContext||!e.track)throw new Error("audioContext and track are required");t&&this._closeInternal(),this._audioOpts=e;const s=e.audioContext;await this._ensureWorkletLoaded(s),this._workletNode=new AudioWorkletNode(s,"AudioPipelineWorklet",{processorOptions:{debugLogs:this._options.debugLogs,numberOfChannels:e.track.getSettings().channelCount}}),this._workletNode.port.onmessage=this._handleRuntimeMessage;const i=this._options.stages.denoise,r=this._options.moduleConfigs.deepfilternet,{wasmBinaries:n,wasmTransferables:a}=await this._fetchWasmBinaries(this._options.wasmUrls),d=await this._resolveModelBuffer(r);d&&(this._options.moduleConfigs.deepfilternet.modelBuffer=o(d)),this._worker=new Worker(this._options.workerUrl);const l=new MessageChannel;this._worker.postMessage({type:"CONNECT_PORT",port:l.port1},[l.port1]);const u={type:"INIT",wasmBinaries:n,moduleId:i,moduleConfigs:{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{attenLimDb:r.attenLimDb,postFilterBeta:r.postFilterBeta,modelBuffer:d}},debugLogs:this._options.debugLogs},m=[...a];d&&m.push(d),l.port2.postMessage(u,m);const f=await this._waitForWorkerInit(l.port2);this._debug("worker init complete",f),await this._sendCommand({message:"INIT_PIPELINE",enable:this._enabled,debugLogs:this._options.debugLogs,workerPort:l.port2,frameLength:f.frameLength,stages:{denoise:i},moduleConfigs:{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{attenLimDb:r.attenLimDb,postFilterBeta:r.postFilterBeta}}},[l.port2]),this._sourceNode=s.createMediaStreamSource(new MediaStream([e.track])),this._sourceNode.connect(this._workletNode);const c=s.createMediaStreamDestination();this._workletNode.connect(c),this.processedTrack=c.stream.getAudioTracks()[0],this._debug("init complete",`sourceID: ${e.track.id}, newTrackID: ${this.processedTrack.id}`)}async _ensureWorkletLoaded(e){const t=this._options.workletUrl;if(!t)throw new Error("workletUrl is required. Pass AudioPipelineTrackProcessor({ workletUrl }).");if(!c._loadedContexts.has(e)){this._debug("loading worklet",t);try{await e.audioWorklet.addModule(t),c._loadedContexts.add(e),c._loadedWorkletUrls.set(e,t)}catch(e){throw new Error(`Failed to load audio pipeline worklet module: ${String(e)}. URL: ${t}`)}}}_waitForWorkerInit(e){const o=performance.now();return new Promise(((s,i)=>{const r=setTimeout((()=>{e.onmessage=null,i(new Error("Worker init timeout after 10000ms"))}),t),n=e.onmessage;e.onmessage=t=>{const a=t.data;"INIT_OK"===a?.type?(clearTimeout(r),e.onmessage=n,this._debug("worker INIT_OK",`${(performance.now()-o).toFixed(2)}ms`),s({frameLength:a.frameLength,lookahead:a.lookahead})):"ERROR"===a?.type&&(clearTimeout(r),e.onmessage=n,i(new Error(`Worker init failed: ${a.error}`)))}}))}_closeInternal(){if(this._workletNode){try{this._workletNode.port.postMessage({message:"DESTROY"})}catch{}this._workletNode.port.onmessage=null}if(this._worker){try{this._worker.postMessage({type:"DESTROY"})}catch{}this._worker.terminate(),this._worker=void 0}this._rejectAllPendingCommands("Audio pipeline runtime closed"),this._workletNode?.disconnect(),this._sourceNode?.disconnect(),this._workletNode=void 0,this._sourceNode=void 0,this.processedTrack=void 0}async _fetchWasmBinaries(e){const t={},o=[];this._debug("fetching rnnoise wasm",e.rnnoise);const s=await this._fetchBinary(e.rnnoise,"RNNoise WASM");t.rnnoiseWasm=s,o.push(s),this._debug("fetching deepfilter wasm",e.deepfilter);const i=await this._fetchBinary(e.deepfilter,"DeepFilter WASM");return t.deepfilterWasm=i,o.push(i),{wasmBinaries:t,wasmTransferables:o}}async _resolveModelBuffer(e){return e.modelBuffer?o(e.modelBuffer):e.modelUrl?this._fetchBinary(e.modelUrl,"DeepFilter model"):void 0}async _fetchBinary(e,t){const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status} ${o.statusText} (${e})`);return o.arrayBuffer()}_handleRuntimeMessage=e=>{const t=e.data;t?.message&&("COMMAND_OK"===t.message?this._resolvePending(t.requestId):"COMMAND_ERROR"===t.message?this._rejectPending(t):"LOG"===t.message&&this._handleLog(t))};_handleLog(e){const t=`${e.tag} ${e.text}`;"error"===e.level?void 0!==e.data?console.error(t,e.data):console.error(t):void 0!==e.data?console.log(t,e.data):console.log(t)}_runSerial(e){const t=this._operationQueue.then(e,e);return this._operationQueue=t.then((()=>{}),(()=>{})),t}async _sendCommand(e,o){if(!this._workletNode)throw new Error("Audio pipeline worklet is not initialized");const s=this._nextRequestId++,i=performance.now();await new Promise(((i,r)=>{const n=setTimeout((()=>{this._pendingCommands.delete(s),r(new Error(`Command timeout after 10000ms: ${e.message}`))}),t);this._pendingCommands.set(s,{command:e.message,timeoutId:n,resolve:i,reject:r});try{this._workletNode?.port.postMessage({...e,requestId:s},o??[])}catch(e){clearTimeout(n),this._pendingCommands.delete(s),r(e instanceof Error?e:new Error(String(e)))}})),this._debug(`${e.message} round-trip`,`${(performance.now()-i).toFixed(2)}ms`)}_resolvePending(e){if(void 0===e)return;const t=this._pendingCommands.get(e);t&&(clearTimeout(t.timeoutId),this._pendingCommands.delete(e),t.resolve())}_rejectPending(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`;if(void 0===e.requestId)return void this._debug("COMMAND_ERROR (no requestId)",t);const o=this._pendingCommands.get(e.requestId);o?(clearTimeout(o.timeoutId),this._pendingCommands.delete(e.requestId),o.reject(new Error(t))):this._debug("COMMAND_ERROR (stale)",t)}_rejectAllPendingCommands(e){for(const t of this._pendingCommands.values())clearTimeout(t.timeoutId),t.reject(new Error(e));this._pendingCommands.clear()}static _LOG_TAG="[AudioPipeline:Main]";_debug(e,t){this._options.debugLogs&&(void 0!==t?console.log(`${c._LOG_TAG} ${e}`,t):console.log(`${c._LOG_TAG} ${e}`))}}e.AudioPipelineTrackProcessor=c}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).AudioPipelinePlugin={})}(this,(function(e){"use strict";const t=1e4;class o{_nextRequestId=1;_pendingCommands=new Map;async send(e,o,n){const s=this._nextRequestId++;return await new Promise(((r,i)=>{const a=setTimeout((()=>{this._pendingCommands.delete(s),i(new Error(`Command timeout after 10000ms: ${o.type}`))}),t);this._pendingCommands.set(s,{command:o.type,timeoutId:a,resolve:r,reject:i});try{e.postMessage({...o,requestId:s},n??[])}catch(e){clearTimeout(a),this._pendingCommands.delete(s),i(e instanceof Error?e:new Error(String(e)))}})),s}resolve(e){if(void 0===e)return;const t=this._pendingCommands.get(e);t&&(clearTimeout(t.timeoutId),this._pendingCommands.delete(e),t.resolve())}reject(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`;if(void 0===e.requestId)return;const o=this._pendingCommands.get(e.requestId);o&&(clearTimeout(o.timeoutId),this._pendingCommands.delete(e.requestId),o.reject(new Error(t)))}close(e){for(const t of this._pendingCommands.values())clearTimeout(t.timeoutId),t.reject(new Error(e));this._pendingCommands.clear()}getPendingCommand(e){if(void 0!==e)return this._pendingCommands.get(e)?.command}}function n(e){return"deepfilternet"===e?"deepfilternet":"rnnoise"}function s(e){return!Number.isFinite(e)||(e??0)<=0?1e3:e??1e3}function r(e){return Number.isFinite(e)?Math.abs(e??100):100}function i(e){return Number.isFinite(e)?Math.max(0,e??0):0}function a(e,t){return Number.isFinite(e)?e:t}function d(e){return{attenLimDb:r(e?.attenLimDb),postFilterBeta:i(e?.postFilterBeta),minDbThresh:a(e?.minDbThresh,-15),maxDbErbThresh:a(e?.maxDbErbThresh,35),maxDbDfThresh:a(e?.maxDbDfThresh,35)}}function l(e){const t=e.lastIndexOf("/");return t>=0?e.substring(0,t+1):"./"}function u(e){const t=l(e);return{rnnoise:`${t}rnnoise.wasm`,deepfilter:`${t}deepfilter.wasm`}}function h(e,t){return t?.trim()?t.trim():`${l(e)}AudioPipelineWorker.js`}function m(e){const t=function(e){const t=e.trim();if(0===t.length)throw new Error("workletUrl is required");return t}(e.workletUrl);return{workletUrl:t,workerUrl:h(t,e.workerUrl),wasmUrls:u(t),debugLogs:Boolean(e.debugLogs),batchFrames:Math.max(1,Math.floor(e.batchFrames??1)),stages:{denoise:n(e.stages?.denoise)},moduleConfigs:{rnnoise:(o=e.moduleConfigs?.rnnoise,{vadLogs:Boolean(o?.vadLogs),vadLogIntervalMs:s(o?.vadLogIntervalMs)}),deepfilternet:d(e.moduleConfigs?.deepfilternet)}};var o}async function c(e,t){const o=await fetch(e);if(!o.ok)throw new Error(`Failed to fetch ${t}: ${o.status} ${o.statusText} (${e})`);return o.arrayBuffer()}class p{static _loadedContexts=new WeakSet;name="audio-pipeline-filter";processedTrack;_audioOpts;_workletNode;_sourceNode;_worker;_enabled=!0;_options;_commandTransport=new o;_operationQueue=Promise.resolve();constructor(e){this._options=m(e)}static isSupported(){return!0}async init(e){this._debug("init",e),await this._initInternal(e,!1)}async restart(e){e.audioContext=e.audioContext??this._audioOpts?.audioContext,this._debug("restart",e),await this._initInternal(e,!0)}async onPublish(e){this._debug("onPublish",e.name)}async onUnpublish(){this._debug("onUnpublish")}async setEnabled(e){return this._runSerial((async()=>{this._debug("setEnabled",e),this._enabled=e,this._workletNode&&await this._sendCommand({type:"SET_ENABLED",enable:e})}))}async setStageModule(e,t){return this._runSerial((async()=>{if("denoise"!==e)throw new Error(`Unsupported stage: ${e}`);const o=n(t);this._options.stages.denoise!==o&&(this._workletNode&&await this._sendCommand({type:"SET_STAGE_MODULE",stage:"denoise",moduleId:o}),this._options.stages.denoise=o)}))}async setModuleConfig(e,t){return this._runSerial((async()=>{"rnnoise"===e?await this._applyRnnoiseConfig(t):await this._applyDeepFilterConfig(t)}))}async isEnabled(){return Boolean(this._workletNode&&this._enabled)}async destroy(){this._debug("destroy"),this._closeInternal()}async _applyRnnoiseConfig(e){const t=(o=this._options.moduleConfigs.rnnoise,(n=e)?{vadLogs:n.vadLogs??o.vadLogs,vadLogIntervalMs:void 0!==n.vadLogIntervalMs?s(n.vadLogIntervalMs):o.vadLogIntervalMs}:{...o});var o,n;this._workletNode&&await this._sendCommand({type:"SET_MODULE_CONFIG",moduleId:"rnnoise",config:{...t}}),this._options.moduleConfigs.rnnoise=t}async _applyDeepFilterConfig(e){const t=(o=this._options.moduleConfigs.deepfilternet,(n=e)?{attenLimDb:void 0!==n.attenLimDb?r(n.attenLimDb):o.attenLimDb,postFilterBeta:void 0!==n.postFilterBeta?i(n.postFilterBeta):o.postFilterBeta,minDbThresh:a(n.minDbThresh,o.minDbThresh),maxDbErbThresh:a(n.maxDbErbThresh,o.maxDbErbThresh),maxDbDfThresh:a(n.maxDbDfThresh,o.maxDbDfThresh)}:{...o});var o,n;this._workletNode&&await this._sendCommand({type:"SET_MODULE_CONFIG",moduleId:"deepfilternet",config:{...t}}),this._options.moduleConfigs.deepfilternet=t}async _initInternal(e,t){if(!e?.audioContext||!e.track)throw new Error("audioContext and track are required");t&&this._closeInternal(),this._audioOpts=e;const o=e.audioContext;await this._ensureWorkletLoaded(o),this._workletNode=new AudioWorkletNode(o,"AudioPipelineWorklet",{processorOptions:{debugLogs:this._options.debugLogs,numberOfChannels:e.track.getSettings().channelCount}}),this._workletNode.port.onmessage=this._handleRuntimeMessage;const n=this._options.stages.denoise,s=this._createModuleConfigs(),{wasmBinaries:r,wasmTransferables:i}=await async function(e,t){const o={},n=[];t?.("fetching rnnoise wasm",e.rnnoise);const s=await c(e.rnnoise,"RNNoise WASM");o.rnnoiseWasm=s,n.push(s),t?.("fetching deepfilter wasm",e.deepfilter);const r=await c(e.deepfilter,"DeepFilter WASM");return o.deepfilterWasm=r,n.push(r),{wasmBinaries:o,wasmTransferables:n}}(this._options.wasmUrls,((e,t)=>this._debug(e,t)));this._worker=new Worker(this._options.workerUrl);const a=new MessageChannel;this._worker.postMessage({type:"CONNECT_PORT",port:a.port1},[a.port1]);const d={type:"INIT",wasmBinaries:r,moduleId:n,moduleConfigs:s,debugLogs:this._options.debugLogs};a.port2.postMessage(d,i);const l=await this._waitForWorkerInit(a.port2);this._debug("worker init complete",l),await this._sendCommand({type:"INIT_PIPELINE",enable:this._enabled,debugLogs:this._options.debugLogs,workerPort:a.port2,frameLength:l.frameLength,batchFrames:this._options.batchFrames,stages:{denoise:n},moduleConfigs:s},[a.port2]),this._sourceNode=o.createMediaStreamSource(new MediaStream([e.track])),this._sourceNode.connect(this._workletNode);const u=o.createMediaStreamDestination();this._workletNode.connect(u),this.processedTrack=u.stream.getAudioTracks()[0],this._debug("init complete",`sourceID: ${e.track.id}, newTrackID: ${this.processedTrack.id}`)}async _ensureWorkletLoaded(e){const t=this._options.workletUrl;if(!t)throw new Error("workletUrl is required. Pass AudioPipelineTrackProcessor({ workletUrl }).");if(!p._loadedContexts.has(e)){this._debug("loading worklet",t);try{await e.audioWorklet.addModule(t),p._loadedContexts.add(e)}catch(e){throw new Error(`Failed to load audio pipeline worklet module: ${String(e)}. URL: ${t}`)}}}_waitForWorkerInit(e){const o=performance.now();return new Promise(((n,s)=>{const r=setTimeout((()=>{e.onmessage=null,s(new Error("Worker init timeout after 10000ms"))}),t),i=e.onmessage;e.onmessage=t=>{const a=t.data;"INIT_OK"===a?.type?(clearTimeout(r),e.onmessage=i,this._debug("worker INIT_OK",`${(performance.now()-o).toFixed(2)}ms`),n({frameLength:a.frameLength,lookahead:a.lookahead})):"ERROR"===a?.type&&(clearTimeout(r),e.onmessage=i,s(new Error(`Worker init failed: ${a.error}`)))}}))}_closeInternal(){if(this._workletNode){try{this._workletNode.port.postMessage({type:"DESTROY"})}catch{}this._workletNode.port.onmessage=null}if(this._worker){try{this._worker.postMessage({type:"DESTROY"})}catch{}this._worker.terminate(),this._worker=void 0}this._commandTransport.close("Audio pipeline runtime closed"),this._workletNode?.disconnect(),this._sourceNode?.disconnect(),this._workletNode=void 0,this._sourceNode=void 0,this.processedTrack=void 0}_handleRuntimeMessage=e=>{const t=e.data;t?.type&&("COMMAND_OK"===t.type?this._commandTransport.resolve(t.requestId):"COMMAND_ERROR"===t.type?this._handleCommandError(t):"LOG"===t.type&&this._handleLog(t))};_handleLog(e){const t=`${e.tag} ${e.text}`;"error"===e.level?void 0!==e.data?console.error(t,e.data):console.error(t):void 0!==e.data?console.log(t,e.data):console.log(t)}_handleCommandError(e){const t=e.error??`Runtime command failed: ${e.command??"unknown"}`,o=this._commandTransport.getPendingCommand(e.requestId);void 0!==e.requestId?o?this._commandTransport.reject(e):this._debug("COMMAND_ERROR (stale)",t):this._debug("COMMAND_ERROR (no requestId)",t)}_runSerial(e){const t=this._operationQueue.then(e,e);return this._operationQueue=t.then((()=>{}),(()=>{})),t}_createModuleConfigs(){return{rnnoise:{...this._options.moduleConfigs.rnnoise},deepfilternet:{...this._options.moduleConfigs.deepfilternet}}}async _sendCommand(e,t){if(!this._workletNode)throw new Error("Audio pipeline worklet is not initialized");const o=performance.now();await this._commandTransport.send(this._workletNode.port,e,t),this._debug(`${e.type} round-trip`,`${(performance.now()-o).toFixed(2)}ms`)}static _LOG_TAG="[AudioPipeline:Main]";_debug(e,t){this._options.debugLogs&&(void 0!==t?console.log(`${p._LOG_TAG} ${e}`,t):console.log(`${p._LOG_TAG} ${e}`))}}e.AudioPipelineTrackProcessor=p}));
2
2
  //# sourceMappingURL=index.umd.js.map
package/dist/options.d.ts CHANGED
@@ -2,19 +2,23 @@ export type PipelineStage = "denoise";
2
2
  export type DenoiseModuleId = "rnnoise" | "deepfilternet";
3
3
  export interface RnnoiseModuleConfig {
4
4
  vadLogs?: boolean;
5
- bufferOverflowMs?: number;
5
+ vadLogIntervalMs?: number;
6
6
  }
7
7
  export interface DeepFilterModuleConfig {
8
- modelUrl?: string;
9
- modelBuffer?: ArrayBuffer;
10
- clearModel?: boolean;
11
8
  attenLimDb?: number;
12
9
  postFilterBeta?: number;
10
+ /** Minimum dB threshold (default -15). Below this, treat as noise only. */
11
+ minDbThresh?: number;
12
+ /** Max dB threshold for ERB stage (default 35). Above this, skip processing. */
13
+ maxDbErbThresh?: number;
14
+ /** Max dB threshold for DF stage (default 35). Above this, skip DF stage. */
15
+ maxDbDfThresh?: number;
13
16
  }
14
17
  export interface AudioPipelineOptions {
15
18
  workletUrl: string;
16
19
  workerUrl?: string;
17
20
  debugLogs?: boolean;
21
+ batchFrames?: number;
18
22
  stages?: {
19
23
  denoise?: DenoiseModuleId;
20
24
  };
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@cc-livekit/audio-pipeline-plugin",
3
3
  "description": "A WebAssembly audio pipeline module for RNNoise and DeepFilterNet on web frontends.",
4
- "version": "1.1.5",
4
+ "version": "1.1.7",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/difftim/denoise-plugin.git"
10
+ "url": "git+https://github.com/TempTalkOrg/audio-pipeline-plugin.git"
11
11
  },
12
12
  "scripts": {
13
13
  "build": "npm run build:rnnoise:wasm && npm run build:deepfilter:wasm && npm run build:js",