longpipe 0.0.15 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { D as Dtype, F as FaceTouchupStyle } from './index-BctoEDhZ.cjs';
2
2
  export { A as Activation, B as Backend, C as Conv2dParams, a as DepthwiseParams, O as Op, T as Tensor, W as WebGPUBackend } from './index-BctoEDhZ.cjs';
3
+ import { D as DenoiseModelOption, A as AudioStats } from './messages-DjW-szBq.cjs';
4
+ export { a as DenoiseModel, b as DenoiseTier } from './messages-DjW-szBq.cjs';
3
5
 
4
6
  type ModelName = 'xs' | 'small' | 'medium' | 'large' | 'xl';
5
7
  type PresetName = 'fast' | 'balanced' | 'quality' | 'auto';
@@ -72,10 +74,6 @@ interface PipelineError {
72
74
  cause?: unknown;
73
75
  }
74
76
 
75
- type DenoiseModel = 'rnnoise' | 'dfn' | 'dfnint8';
76
- type DenoiseTier = 'high' | 'mid' | 'low';
77
- type DenoiseModelOption = 'auto' | DenoiseTier | DenoiseModel;
78
-
79
77
  interface DenoiseOptions {
80
78
  model?: DenoiseModelOption;
81
79
  postFilterBeta?: number;
@@ -87,15 +85,6 @@ type AudioInput = 'passthrough' | 'drop' | 'denoise' | {
87
85
  };
88
86
  type AudioMode = 'passthrough' | 'drop';
89
87
 
90
- interface AudioStats {
91
- model: DenoiseModel;
92
- p50Ms: number | null;
93
- p95Ms: number | null;
94
- latencyMs: number;
95
- active: boolean;
96
- sampleRate: number;
97
- }
98
-
99
88
  interface PipelineOptions {
100
89
  background?: BackgroundInput;
101
90
  preset?: PresetName | ManualPreset;
@@ -166,4 +155,4 @@ declare class Pipeline implements PromiseLike<Pipeline> {
166
155
  destroy(): void;
167
156
  }
168
157
 
169
- export { type AudioInput, type AudioMode, type AudioStats, type Background, type BackgroundInput, type BlurInput, type ColorInput, type DenoiseModel, type DenoiseModelOption, type DenoiseOptions, type DenoiseTier, Pipeline as EffectsPipeline, type ErrorSource, FaceTouchupStyle, type ImageInput, type ManualPreset, type ModelName, type PipelineError, type PipelineOptions, type PresetName, type TouchupOptions, type VideoInput };
158
+ export { type AudioInput, type AudioMode, AudioStats, type Background, type BackgroundInput, type BlurInput, type ColorInput, DenoiseModelOption, type DenoiseOptions, Pipeline as EffectsPipeline, type ErrorSource, FaceTouchupStyle, type ImageInput, type ManualPreset, type ModelName, type PipelineError, type PipelineOptions, type PresetName, type TouchupOptions, type VideoInput };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { D as Dtype, F as FaceTouchupStyle } from './index-BctoEDhZ.js';
2
2
  export { A as Activation, B as Backend, C as Conv2dParams, a as DepthwiseParams, O as Op, T as Tensor, W as WebGPUBackend } from './index-BctoEDhZ.js';
3
+ import { D as DenoiseModelOption, A as AudioStats } from './messages-DjW-szBq.js';
4
+ export { a as DenoiseModel, b as DenoiseTier } from './messages-DjW-szBq.js';
3
5
 
4
6
  type ModelName = 'xs' | 'small' | 'medium' | 'large' | 'xl';
5
7
  type PresetName = 'fast' | 'balanced' | 'quality' | 'auto';
@@ -72,10 +74,6 @@ interface PipelineError {
72
74
  cause?: unknown;
73
75
  }
74
76
 
75
- type DenoiseModel = 'rnnoise' | 'dfn' | 'dfnint8';
76
- type DenoiseTier = 'high' | 'mid' | 'low';
77
- type DenoiseModelOption = 'auto' | DenoiseTier | DenoiseModel;
78
-
79
77
  interface DenoiseOptions {
80
78
  model?: DenoiseModelOption;
81
79
  postFilterBeta?: number;
@@ -87,15 +85,6 @@ type AudioInput = 'passthrough' | 'drop' | 'denoise' | {
87
85
  };
88
86
  type AudioMode = 'passthrough' | 'drop';
89
87
 
90
- interface AudioStats {
91
- model: DenoiseModel;
92
- p50Ms: number | null;
93
- p95Ms: number | null;
94
- latencyMs: number;
95
- active: boolean;
96
- sampleRate: number;
97
- }
98
-
99
88
  interface PipelineOptions {
100
89
  background?: BackgroundInput;
101
90
  preset?: PresetName | ManualPreset;
@@ -166,4 +155,4 @@ declare class Pipeline implements PromiseLike<Pipeline> {
166
155
  destroy(): void;
167
156
  }
168
157
 
169
- export { type AudioInput, type AudioMode, type AudioStats, type Background, type BackgroundInput, type BlurInput, type ColorInput, type DenoiseModel, type DenoiseModelOption, type DenoiseOptions, type DenoiseTier, Pipeline as EffectsPipeline, type ErrorSource, FaceTouchupStyle, type ImageInput, type ManualPreset, type ModelName, type PipelineError, type PipelineOptions, type PresetName, type TouchupOptions, type VideoInput };
158
+ export { type AudioInput, type AudioMode, AudioStats, type Background, type BackgroundInput, type BlurInput, type ColorInput, DenoiseModelOption, type DenoiseOptions, Pipeline as EffectsPipeline, type ErrorSource, FaceTouchupStyle, type ImageInput, type ManualPreset, type ModelName, type PipelineError, type PipelineOptions, type PresetName, type TouchupOptions, type VideoInput };
package/dist/index.js CHANGED
@@ -1,35 +1,4 @@
1
- export{h as WebGPUBackend}from'./chunk-NYCCJS3G.js';var _=[{model:"xs",dtype:"f16",resolution:{w:384,h:240},skipFrames:2},{model:"small",dtype:"f16",resolution:{w:384,h:224},skipFrames:1},{model:"medium",dtype:"f16",resolution:{w:512,h:320},skipFrames:1},{model:"large",dtype:"f32",resolution:{w:640,h:400},skipFrames:0},{model:"xl",dtype:"f32",resolution:{w:1280,h:768},skipFrames:0}];var B=false;function z(t){B=t;}function g(t){let e=`[longpipe/${t}]`,n=((...r)=>{B&&console.log(e,...r);});return n.warn=(...r)=>{B&&console.warn(e,...r);},n}var w=g("adaptive"),he=2e3,fe=1e4,de=30,me=20,ge=5e3,_e=.3,ve=15e3,P=class{constructor(e){this.opts=e;this.currentPresetIdx=_.findIndex(n=>n.model===e.initialModel),this.lastSwapAt=performance.now();}opts;timer=null;currentPresetIdx;lastSwapAt=0;overshootStart=0;headroomStart=0;start(){w(`started; backend=${this.opts.backendKind} initial=${this.opts.initialModel} idx=${this.currentPresetIdx}`),this.timer=setInterval(()=>{this.tick().catch(e=>w("tick failed:",e));},he);}stop(){this.timer&&clearInterval(this.timer),this.timer=null;}async tick(){if(typeof document<"u"&&document.hidden)return;let e=performance.now();if(e-this.lastSwapAt<fe)return;let n=await this.opts.getStats();if(n.fps<me?(this.overshootStart===0&&(this.overshootStart=e),e-this.overshootStart>=ge&&this.tryDowngrade(n.fps)):this.overshootStart=0,this.opts.backendKind==="webgpu"&&n.modelMs>0){let r=1e3/de*_e;n.modelMs<r?(this.headroomStart===0&&(this.headroomStart=e),e-this.headroomStart>=ve&&this.tryUpgrade(n.modelMs,r)):this.headroomStart=0;}}tryDowngrade(e){if(this.currentPresetIdx<=0)return;let n=this.currentPresetIdx-1;w(`downgrade ${_[this.currentPresetIdx].model} \u2192 ${_[n].model} (fps=${e})`),this.swap(n);}tryUpgrade(e,n){if(_[this.currentPresetIdx+1]?.model==="xl"||this.currentPresetIdx>=_.length-1)return;let r=this.currentPresetIdx+1;w(`upgrade ${_[this.currentPresetIdx].model} \u2192 ${_[r].model} (modelMs=${e.toFixed(1)} < ${n.toFixed(1)})`),this.swap(r);}async swap(e){let n=_[e];this.lastSwapAt=performance.now(),this.overshootStart=0,this.headroomStart=0;try{let r=await this.opts.fetchWeights(n.model);await this.opts.swapPreset(n,r),this.currentPresetIdx=e,w(`swap to ${n.model} done`);}catch(r){w("swap failed:",r),this.opts.onError?.({message:`adaptive preset swap failed: ${r.message??String(r)}`,source:"adaptive",recoverable:true,cause:r});}}};async function H(t){let e,n=false;if(t instanceof HTMLVideoElement){if(e=t.currentSrc||t.src,!e)throw new Error("background video: HTMLVideoElement has no src")}else if(t instanceof Blob)e=URL.createObjectURL(t),n=true;else if(typeof t=="string")e=t;else throw new Error("background video: unsupported input shape");let r=document.createElement("video");r.crossOrigin="anonymous",r.muted=true,r.loop=true,r.playsInline=true,r.src=e,await new Promise((l,c)=>{r.addEventListener("loadeddata",()=>l(),{once:true}),r.addEventListener("error",()=>c(new Error(`background video: failed to load ${e}`)),{once:true});});try{await r.play();}catch(l){throw new Error(`background video: play() rejected \u2014 ${l.message}`)}let a=new MessageChannel,i=a.port1,s=a.port2,u=false,p=r.requestVideoFrameCallback?.bind(r);if(p){let l=(c,h)=>{if(!u){try{let d=new VideoFrame(r,{timestamp:h.mediaTime*1e6});i.postMessage({frame:d},[d]);}catch{}p(l);}};p(l);}else {let l=()=>{if(!u){try{let c=new VideoFrame(r,{timestamp:performance.now()*1e3});i.postMessage({frame:c},[c]);}catch{}requestAnimationFrame(l);}};requestAnimationFrame(l);}return {port:s,transferList:[s],cleanup:()=>{u=true,i.close(),r.pause(),r.removeAttribute("src"),r.load(),n&&URL.revokeObjectURL(e);}}}var xe=4,M=8,N=16;async function E(t){if(typeof t=="string")return t==="none"?{background:{kind:"none"}}:t==="blur"?{background:{kind:"blur",sigma:M}}:{background:{kind:"image",bitmap:await V(t)}};if(t instanceof ImageBitmap)return {background:{kind:"image",bitmap:t}};if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return {background:{kind:"image",bitmap:await createImageBitmap(t)}};if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)return await G(t);let e=t;if(e.color!==void 0)return {background:{kind:"color",rgb:be(e.color)}};if(e.blur!==void 0)return {background:{kind:"blur",sigma:we(e.blur)}};if(e.image!==void 0)return {background:{kind:"image",bitmap:await ye(e.image)}};if(e.video!==void 0)return await G(e.video);throw new Error(`background: unrecognized input shape \u2014 ${x(t)}`)}async function G(t){let e;if(typeof t=="string")e=t;else if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)e=t;else if(t&&typeof t=="object"&&"data"in t&&"type"in t)e=t.data instanceof Blob?t.data:new Blob([t.data],{type:t.type});else throw new Error(`background.video: unrecognized shape \u2014 ${x(t)}`);let n=await H(e);return {background:{kind:"video",port:n.port},transferList:n.transferList,cleanup:n.cleanup}}function be(t){if(typeof t=="string"){let e=t.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(e))return [parseInt(e.slice(0,2),16)/255,parseInt(e.slice(2,4),16)/255,parseInt(e.slice(4,6),16)/255];if(/^[0-9a-fA-F]{3}$/.test(e))return [parseInt(e[0]+e[0],16)/255,parseInt(e[1]+e[1],16)/255,parseInt(e[2]+e[2],16)/255];throw new Error(`background.color: hex must be #rgb or #rrggbb, got ${x(t)}`)}if(!Array.isArray(t)||t.length!==3||!t.every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1))throw new Error(`background.color: expected hex string or [r, g, b] floats in [0, 1], got ${x(t)}`);return [t[0],t[1],t[2]]}function we(t){if(t===true)return M;if("sigma"in t){if(typeof t.sigma!="number"||!Number.isFinite(t.sigma)||t.sigma<0)throw new Error(`background.blur.sigma must be a non-negative number, got ${t.sigma}`);return t.sigma}if("strength"in t){let e=t.strength;if(typeof e=="number"){let n=Math.max(0,Math.min(1,e));return N*n}if(e==="low")return xe;if(e==="medium")return M;if(e==="high")return N;throw new Error(`background.blur.strength must be 'low' | 'medium' | 'high' | number, got ${x(e)}`)}throw new Error(`background.blur: must be true, { strength }, or { sigma } \u2014 got ${x(t)}`)}async function ye(t){if(t instanceof ImageBitmap)return t;if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return createImageBitmap(t);if(typeof t=="string")return V(t);if(t&&typeof t=="object"&&"data"in t&&"type"in t){let e=t.data instanceof Blob?t.data:new Blob([t.data],{type:t.type});return createImageBitmap(e)}throw new Error(`background.image: unrecognized shape \u2014 ${x(t)}`)}async function V(t){let e=await fetch(t);if(!e.ok)throw new Error(`background: failed to load image from ${t} (HTTP ${e.status})`);let n=await e.blob();return createImageBitmap(n)}function x(t){return t===null?"null":typeof t!="object"?typeof t+"("+String(t)+")":`${t.constructor?.name??"Object"} ${JSON.stringify(t).slice(0,80)}`}function $(){return {input:"MediaStreamTrackProcessor"in self?"mstp":"rvfc-postmessage",output:"MediaStreamTrackGenerator"in self?"mstg":ke()?"transfer-capture":"bitmap-shuttle"}}var A=null;function ke(){return A!==null||(A=!/Firefox/.test(navigator.userAgent)),A}function j(t){return t==="denoise"?{mode:"denoise",denoise:{}}:typeof t=="object"?{mode:"denoise",denoise:t.denoise}:{mode:t}}function X(t,e,n,r){let a=[t];return n.mode==="passthrough"?a.push(...e.getAudioTracks()):n.mode==="denoise"&&r&&a.push(r),new MediaStream(a)}var y={rnnoise:{wasm:"rnnoise.wasm",weights:null,scaleIn:32768,scaleOut:30517578125e-15,needsSimd:false,exports:{malloc:"malloc",create:"rn_create",process:"rn_process"}},dfn:{wasm:"dfn.wasm",weights:"dfn_weights.pack",scaleIn:1,scaleOut:1,needsSimd:true,exports:{malloc:"df_lite_malloc",create:"df_lite_create",process:"df_lite_process",setBeta:"df_lite_set_beta",setGruLeak:"df_lite_set_gru_leak"}},dfnint8:{wasm:"dfn.wasm",weights:"dfn_weights_int8.pack",scaleIn:1,scaleOut:1,needsSimd:true,exports:{malloc:"df_lite_malloc",create:"df_lite_create_i8",process:"df_lite_process",setBeta:"df_lite_set_beta",setGruLeak:"df_lite_set_gru_leak"}}},Ce={high:"dfn",mid:"dfnint8",low:"rnnoise"},Te=["high","mid","low"];function Pe(t){return Te.includes(t)}function q(t){return Pe(t)?Ce[t]:t}function K(t,e){return `${t.replace(/\/$/,"")}/${e}`}async function Y(t){let e=await fetch(t);if(!e.ok)throw new Error(`audio asset fetch failed: ${e.status} ${t}`);return e.arrayBuffer()}async function Q(t,e){let n=y[t],[r,a]=await Promise.all([Y(K(e,n.wasm)),n.weights?Y(K(e,n.weights)):Promise.resolve(null)]);return {wasmBytes:r,weights:a}}function S(){try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,22,1,20,0,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11]))}catch{return false}}var Ee=1.3,Ae=64,Se=3,Fe=`
2
- self.onmessage = async (e) => {
3
- const { wasmUrl, iters, rounds, budget } = e.data
4
- try {
5
- const res = await fetch(wasmUrl)
6
- if (!res.ok) throw new Error(res.status + ' ' + wasmUrl)
7
- const module = await WebAssembly.compile(await res.arrayBuffer())
8
- const imports = {}
9
- for (const im of WebAssembly.Module.imports(module)) {
10
- ;(imports[im.module] = imports[im.module] || {})
11
- if (im.kind === 'function') imports[im.module][im.name] = () => 0
12
- }
13
- const ex = new WebAssembly.Instance(module, imports).exports
14
- const best = (fn) => {
15
- fn(iters) // warm up
16
- let b = Infinity
17
- for (let r = 0; r < rounds; r++) {
18
- const t = performance.now()
19
- fn(iters)
20
- b = Math.min(b, (performance.now() - t) / iters)
21
- }
22
- return b
23
- }
24
- const dfnMs = best(ex.calibrate_f32)
25
- const int8Ms = ex.calibrate_i8 ? best(ex.calibrate_i8) : Infinity
26
- const model = dfnMs <= budget ? 'dfn' : int8Ms <= budget ? 'dfnint8' : 'rnnoise'
27
- self.postMessage({ model, dfnMs, int8Ms })
28
- } catch (err) {
29
- self.postMessage({ error: (err && err.message) || String(err) })
30
- }
31
- }
32
- `;async function J(t,e){if(!S())return "rnnoise";let n=`${t.replace(/\/$/,"")}/${y.dfn.wasm}`,r=null,a=null;try{r=URL.createObjectURL(new Blob([Fe],{type:"application/javascript"})),a=new Worker(r);let i=await new Promise((s,u)=>{a.onmessage=p=>s(p.data),a.onerror=p=>u(new Error(p.message||"probe worker error")),a.postMessage({wasmUrl:n,iters:Ae,rounds:Se,budget:Ee});});if(i.error)throw new Error(i.error);return i.model??"rnnoise"}catch(i){return e?.(`audio tier probe failed (${i.message??String(i)}); using rnnoise`),"rnnoise"}finally{a?.terminate(),r&&URL.revokeObjectURL(r);}}var O='var b=Object.defineProperty;var y=(u,a,i)=>a in u?b(u,a,{enumerable:!0,configurable:!0,writable:!0,value:i}):u[a]=i;var r=(u,a,i)=>y(u,typeof a!="symbol"?a+"":a,i);var f={rnnoise:{wasm:"rnnoise.wasm",weights:null,scaleIn:32768,scaleOut:30517578125e-15,needsSimd:!1,exports:{malloc:"malloc",create:"rn_create",process:"rn_process"}},dfn:{wasm:"dfn.wasm",weights:"dfn_weights.pack",scaleIn:1,scaleOut:1,needsSimd:!0,exports:{malloc:"df_lite_malloc",create:"df_lite_create",process:"df_lite_process",setBeta:"df_lite_set_beta",setGruLeak:"df_lite_set_gru_leak"}},dfnint8:{wasm:"dfn.wasm",weights:"dfn_weights_int8.pack",scaleIn:1,scaleOut:1,needsSimd:!0,exports:{malloc:"df_lite_malloc",create:"df_lite_create_i8",process:"df_lite_process",setBeta:"df_lite_set_beta",setGruLeak:"df_lite_set_gru_leak"}}};var c=4096,m=class extends AudioWorkletProcessor{constructor(i){super();r(this,"cfg");r(this,"mem");r(this,"run");r(this,"state",0);r(this,"inPtr",0);r(this,"outPtr",0);r(this,"setBeta",null);r(this,"setGruLeak",null);r(this,"resample",!1);r(this,"rsPush",null);r(this,"inRs",0);r(this,"outRs",0);r(this,"rsDevInPtr",0);r(this,"rsOutPtr",0);r(this,"enabled");r(this,"model");r(this,"inAcc",new Float32Array(480));r(this,"inFill",0);r(this,"outRing",new Float32Array(4096));r(this,"outRead",0);r(this,"outWrite",0);r(this,"outCount",0);r(this,"primed",!1);r(this,"now");r(this,"times",new Float32Array(256));r(this,"tIdx",0);r(this,"hops",0);r(this,"_f32",null);let o=i.processorOptions;this.model=o.model,this.enabled=o.enabled,this.cfg=f[o.model];try{let t=this.instantiate(o.wasmBytes),e=n=>n?t[n]:void 0;this.mem=t.memory;let s=t[this.cfg.exports.malloc];if(this.run=t[this.cfg.exports.process],this.inPtr=s(480*4),this.outPtr=s(480*4),o.weights?this.state=t[this.cfg.exports.create](this.upload(s,o.weights),o.weights.byteLength):this.state=t[this.cfg.exports.create](),this.setBeta=e(this.cfg.exports.setBeta)??null,this.setGruLeak=e(this.cfg.exports.setGruLeak)??null,this.setBeta&&(o.postFilterBeta??0)>0&&this.setBeta(this.state,o.postFilterBeta),this.setGruLeak&&(o.gruLeak??1)<1&&this.setGruLeak(this.state,o.gruLeak),sampleRate!==48e3){let n=t.df_resampler_create;this.rsPush=t.df_resampler_push??null,n&&this.rsPush?(this.resample=!0,this.inRs=n(sampleRate,48e3),this.outRs=n(48e3,sampleRate),this.rsDevInPtr=s(256*4),this.rsOutPtr=s(c*4)):this.post({type:"error",message:`${o.model} can\'t resample ${sampleRate}\\u219248000 Hz; needs a 48 kHz AudioContext`})}}catch(t){let e=t;this.post({type:"error",message:`denoise init failed: ${e.message??String(t)}${e.stack?`\n`+e.stack:""}`})}this.now=typeof performance<"u"&&performance.now?()=>performance.now():null,this.port.onmessage=t=>{let e=t.data;e.type==="enabled"?this.enabled=e.value:e.type==="config"&&(this.setBeta&&e.postFilterBeta!=null&&this.setBeta(this.state,e.postFilterBeta),this.setGruLeak&&e.gruLeak!=null&&this.setGruLeak(this.state,e.gruLeak))},this.post({type:"ready"})}instantiate(i){var e;let o=new WebAssembly.Module(i),t={};for(let s of WebAssembly.Module.imports(o))t[e=s.module]??(t[e]={}),s.kind==="function"?t[s.module][s.name]=()=>0:s.kind==="memory"?t[s.module][s.name]=new WebAssembly.Memory({initial:256}):s.kind==="table"?t[s.module][s.name]=new WebAssembly.Table({initial:0,element:"anyfunc"}):s.kind==="global"&&(t[s.module][s.name]=new WebAssembly.Global({value:"i32",mutable:!1},0));return new WebAssembly.Instance(o,t).exports}upload(i,o){let t=new Uint8Array(o),e=i(t.length);return new Uint8Array(this.mem.buffer).set(t,e),e}heap(){return(!this._f32||this._f32.buffer!==this.mem.buffer)&&(this._f32=new Float32Array(this.mem.buffer)),this._f32}post(i){this.port.postMessage(i)}pushOut(i){this.outRing[this.outWrite]=i,this.outWrite=(this.outWrite+1)%this.outRing.length,this.outCount++}feed48k(i,o){for(let t=0;t<o;t++)this.inAcc[this.inFill++]=i[t],this.inFill===480&&(this.runHop(),this.inFill=0)}runHop(){let i=this.heap(),o=this.inPtr>>2;for(let e=0;e<480;e++)i[o+e]=this.inAcc[e]*this.cfg.scaleIn;let t=this.now?this.now():0;if(this.run(this.state,this.inPtr,this.outPtr),this.now&&(this.times[this.tIdx=this.tIdx+1&255]=this.now()-t),this.resample&&this.rsPush){let e=this.rsPush(this.outRs,this.outPtr,480,this.rsOutPtr,c);i=this.heap();let s=this.rsOutPtr>>2;for(let n=0;n<e;n++)this.pushOut(i[s+n])}else{let e=this.outPtr>>2;for(let s=0;s<480;s++)this.pushOut(i[e+s]*this.cfg.scaleOut)}++this.hops>=50&&(this.reportStats(),this.hops=0)}reportStats(){let i=Array.from(this.times).filter(e=>e>0).sort((e,s)=>e-s),o=e=>i.length?i[Math.min(i.length-1,Math.floor(e*i.length))]:null,t={model:this.model,p50Ms:this.now?o(.5):null,p95Ms:this.now?o(.95):null,latencyMs:this.outCount/sampleRate*1e3,active:this.enabled&&this.state!==0,sampleRate};this.post({type:"stats",stats:t})}process(i,o){let t=i[0]?.[0],e=o[0]?.[0];if(!e)return!0;let s=e.length;if(!t||!this.enabled||this.state===0)return t&&!this.enabled?e.set(t):e.fill(0),!0;if(this.resample&&this.rsPush){let n=this.heap(),g=this.rsDevInPtr>>2;for(let h=0;h<s;h++)n[g+h]=t[h];let d=this.rsPush(this.inRs,this.rsDevInPtr,s,this.rsOutPtr,c);n=this.heap(),this.feed48k(n.subarray(this.rsOutPtr>>2,(this.rsOutPtr>>2)+d),d)}else this.feed48k(t,s);if(!this.primed)if(this.outCount>=480)this.primed=!0;else return e.fill(0),!0;if(this.outCount>=s)for(let n=0;n<s;n++)e[n]=this.outRing[this.outRead],this.outRead=(this.outRead+1)%this.outRing.length,this.outCount--;else e.fill(0);return!0}};registerProcessor("denoise",m);\n';var De=.03,Ue=.995,F=class{constructor(e,n){this.opts=n;this.ctx=new AudioContext({sampleRate:48e3}),this.source=this.ctx.createMediaStreamSource(new MediaStream([e])),this.dest=this.ctx.createMediaStreamDestination(),this.outputTrack=this.dest.stream.getAudioTracks()[0],this.source.connect(this.dest),this.ready=this.init().catch(r=>{this.opts.onError?.(`audio denoise init failed: ${r.message??String(r)}`);});}opts;outputTrack;ready;ctx;source;dest;node=null;model=null;latestStats=null;destroyed=false;resolveExplicit(){let e=q(this.opts.model);return y[e].needsSimd&&!S()?(this.opts.onError?.(`${e} needs wasm SIMD; falling back to rnnoise`),"rnnoise"):e}async init(){let e=this.opts.model==="auto"?await J(this.opts.weightsBaseUrl,this.opts.onError):this.resolveExplicit();this.model=e;let n=await Q(e,this.opts.weightsBaseUrl);if(await this.ctx.audioWorklet.addModule(Re()),this.destroyed)return;let r={model:e,wasmBytes:n.wasmBytes,weights:n.weights,enabled:this.opts.enabled??true,postFilterBeta:this.opts.postFilterBeta??De,gruLeak:this.opts.gruLeak??Ue},a=new AudioWorkletNode(this.ctx,"denoise",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:r});a.port.onmessage=i=>{let s=i.data;s.type==="stats"?this.latestStats=s.stats:s.type==="error"?this.opts.onError?.(s.message):s.type==="ready"&&this.opts.onReady?.();},this.node=a,this.source.disconnect(this.dest),this.source.connect(a).connect(this.dest);}setEnabled(e){this.node?.port.postMessage({type:"enabled",value:e});}setConfig(e){this.node?.port.postMessage({type:"config",...e});}getStats(){return this.latestStats}destroy(){this.destroyed=true;try{this.node?.disconnect();}catch{}try{this.source.disconnect();}catch{}this.ctx.close();}};function Re(){return URL.createObjectURL(new Blob([O],{type:"application/javascript"}))}var I=g("worker_controller"),D=class{worker;listeners=new Map;persistentEvents=new Set;constructor(e){this.worker=e,this.worker.addEventListener("message",this.handleMessage.bind(this)),I("constructed; message listener attached");}handleMessage(e){let{request_id:n,res:r}=e.data,a=this.listeners.get(n);I("msg received: request_id=",n,"handler?",!!a,"persistent?",this.persistentEvents.has(n)),a&&(a(r),this.persistentEvents.has(n)||this.listeners.delete(n));}addPersistentListener(e,n){this.persistentEvents.add(e),this.listeners.set(e,n),I("addPersistentListener:",e);}removePersistentListener(e){this.persistentEvents.delete(e),this.listeners.delete(e);}sendMessage(e,n,r=[]){let a=crypto.randomUUID();return I("sendMessage:",e,"request_id=",a,"transferables=",r.length),new Promise(i=>{this.listeners.set(a,u=>i(u));let s={cmd:e,data:n,request_id:a};this.worker.postMessage(s,r);})}terminate(){this.worker.terminate(),this.listeners.clear(),this.persistentEvents.clear();}};var Z=g("input-postmessage/main");function ee(t){let e=document.createElement("video");e.srcObject=t,e.muted=true,e.autoplay=true,e.playsInline=true,e.play().catch(o=>{Z.warn("video.play() rejected:",o);});let n=e.requestVideoFrameCallback?.bind(e);if(!n)throw new Error("setupPostMessageInput: requestVideoFrameCallback not supported on this browser");let r=new MessageChannel,a=r.port1,i=r.port2,s=false,u=(o,l)=>{if(!s){try{let c=new VideoFrame(e,{timestamp:l.mediaTime*1e6});a.postMessage({frame:c},[c]);}catch(c){Z.warn("VideoFrame() failed; skipping frame:",c);}n(u);}};return n(u),{port:i,transferList:[i],cleanup:()=>{s=true,a.close(),e.srcObject=null,e.pause();}}}function te(t){let e=t.getVideoTracks();if(e.length===0)throw new Error("setupMstpInput: input MediaStream has no video tracks");let n=e[0],r=self.MediaStreamTrackProcessor;if(!r)throw new Error("setupMstpInput: MediaStreamTrackProcessor not supported on this browser");let i=new r({track:n}).readable;return {readable:i,transferList:[i],cleanup:()=>{i.cancel().catch(()=>{});}}}function ne(t,e){switch(t){case "mstp":{let n=te(e);return {initFields:{inputReadable:n.readable},transferList:n.transferList,cleanup:n.cleanup}}case "rvfc-postmessage":{let n=ee(e);return {initFields:{inputPort:n.port},transferList:n.transferList,cleanup:n.cleanup}}}}var Be=g("bitmap-shuttle/main"),Me=30;function re(t,e=Me){let n=document.createElement("canvas");n.width=t.w,n.height=t.h;let r=n.getContext("bitmaprenderer");if(!r)throw new Error("setupBitmapShuttleOutput: bitmaprenderer context not available");let i=n.captureStream(e).getVideoTracks();if(i.length===0)throw new Error("setupBitmapShuttleOutput: captureStream produced no video tracks");let s=i[0],u=new MessageChannel,p=u.port1,o=u.port2,l=false,c=null,h=()=>{},d=3,f=0;return p.onmessage=k=>{if(l){if(f++,f<d){k.data.bmp.close();return}h();}try{r.transferFromImageBitmap(k.data.bmp);}catch(m){Be.warn("transferFromImageBitmap failed:",m);}},p.start(),{videoTrack:s,port:o,transferList:[o],startPassthrough:k=>{if(l)return;l=true;let m=document.createElement("video");m.srcObject=k,m.muted=true,m.playsInline=true,m.play().catch(()=>{}),c=m;let C="requestVideoFrameCallback"in m?b=>{m.requestVideoFrameCallback(b);}:b=>{requestAnimationFrame(b);},T=()=>{if(l){if(m.videoWidth===0){C(T);return}createImageBitmap(m,{resizeWidth:n.width,resizeHeight:n.height,resizeQuality:"medium"}).then(b=>{if(!l){b.close();return}try{r.transferFromImageBitmap(b);}catch{}C(T);}).catch(()=>{C(T);});}};C(T),h=()=>{l=false,c&&(c.srcObject=null,c.pause(),c=null);};},cleanup:()=>{h(),p.onmessage=null,p.close(),s.stop();}}}function ae(){let t=self.MediaStreamTrackGenerator;if(!t)throw new Error("setupMstgOutput: MediaStreamTrackGenerator not supported on this browser");let e=new t({kind:"video"}),n=e.writable;return {videoTrack:e,writable:n,transferList:[n],cleanup:()=>{n.abort().catch(()=>{}),e.stop();}}}function ie(t,e=30){let n=document.createElement("canvas");n.width=t.w,n.height=t.h;let a=n.captureStream(e).getVideoTracks();if(a.length===0)throw new Error("setupTransferCaptureOutput: captureStream produced no video tracks");let i=a[0],s=n.transferControlToOffscreen();return {videoTrack:i,canvas:s,transferList:[s],cleanup:()=>{i.stop();}}}function se(t,e){switch(t){case "mstg":{let n=ae();return {videoTrack:n.videoTrack,initFields:{outputWritable:n.writable},transferList:n.transferList,cleanup:n.cleanup}}case "transfer-capture":{let n=ie(e);return {videoTrack:n.videoTrack,initFields:{outputCanvas:n.canvas},transferList:n.transferList,cleanup:n.cleanup}}case "bitmap-shuttle":{let n=re(e);return {videoTrack:n.videoTrack,initFields:{outputPort:n.port},transferList:n.transferList,startPassthrough:n.startPassthrough,cleanup:n.cleanup}}}}var W=`var Ya=Object.defineProperty;var Qa=(u,e,r)=>e in u?Ya(u,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):u[e]=r;var i=(u,e,r)=>Qa(u,typeof e!="symbol"?e+"":e,r);var sr=!1;function gr(u){sr=u}function Y(u){let e=\`[longpipe/\${u}]\`,r=((...t)=>{sr&&console.log(e,...t)});return r.warn=(...t)=>{sr&&console.warn(e,...t)},r}var nr=[{model:"xs",dtype:"f16",resolution:{w:384,h:240},skipFrames:2},{model:"small",dtype:"f16",resolution:{w:384,h:224},skipFrames:1},{model:"medium",dtype:"f16",resolution:{w:512,h:320},skipFrames:1},{model:"large",dtype:"f32",resolution:{w:640,h:400},skipFrames:0},{model:"xl",dtype:"f32",resolution:{w:1280,h:768},skipFrames:0}],Ja={fast:0,balanced:2,quality:4};function ge(u){return u==="auto"?null:nr[Ja[u]]}var _e=class{constructor(e,r,t,a){i(this,"op");this.op=e.ops.BilinearUpsample(r,{outH:t,outW:a})}get output(){return this.op.output}run(){this.op.run()}};var be=class{constructor(e,r,t,a){i(this,"op");this.op=e.ops.BicubicUpsample(r,{outH:t,outW:a})}get output(){return this.op.output}run(){this.op.run()}};var ve=class{constructor(e,r,t,a,o="main"){i(this,"presenter");this.presenter=e.presenters.CompositeSolid(r,t,a,o)}run(){this.presenter.run()}};var xe=class{constructor(e,r,t,a,o="main"){i(this,"presenter");this.presenter=e.presenters.CompositeImage(r,t,a,o)}run(){this.presenter.run()}};var ye=class{constructor(e,r,t){i(this,"downs",[]);i(this,"ups",[]);let a=Za(t),o=r;for(let n=0;n<a;n++){let s=e.ops.BilinearUpsample(o,{outH:Math.max(1,Math.floor(o.h/2)),outW:Math.max(1,Math.floor(o.w/2))});this.downs.push(s),o=s.output}for(let n=a-1;n>=1;n--){let s=this.downs[n-1].output,p=e.ops.BilinearUpsample(o,{outH:s.h,outW:s.w});this.ups.push(p),o=p.output}}get output(){return this.ups.length>0?this.ups[this.ups.length-1].output:this.downs[0].output}run(){for(let e of this.downs)e.run();for(let e of this.ups)e.run()}};function Za(u){let e=Math.max(1,3*u);return Math.max(2,Math.min(6,Math.round(Math.log2(e))))}var ei=.05,we=class{constructor(e,r,t,a,o="main"){i(this,"blur");i(this,"presenter");a<=ei?(this.blur=null,this.presenter=e.presenters.CompositeImage(r,t,r,o)):(this.blur=new ye(e,r,a),this.presenter=e.presenters.CompositeImageBilinear(r,t,this.blur.output,o))}run(){this.blur?.run(),this.presenter.run()}};var ke=class{constructor(e){i(this,"backend",e);i(this,"displayInput");i(this,"image");i(this,"network",null);i(this,"networkInput",null);i(this,"upscaler",null);i(this,"upscalerMode","bilinear");i(this,"bgConfig",{mode:"solid",color:[0,0,0]});i(this,"effectChain",[]);i(this,"viewRect",null);i(this,"viewFg",null);i(this,"viewAlpha",null);i(this,"displayDirty",!1);i(this,"compositors",new Map);let r=e.canvas;this.displayInput=e.ops.Input(r.height,r.width),this.image=this.displayInput.output}attachNetwork(e,r,t){this.network=e,this.networkInput=r,this.upscalerMode=t.upscaler,this.bgConfig=t.background,this.upscaler=this.makeUpscaler(),this.rebuildView(),this.compositors.clear()}hasNetwork(){return this.network!==null}setSource(e){this.networkInput?.setSource(e),this.displayInput.setSource(e),this.displayDirty=!0}setUpscaler(e){e!==this.upscalerMode&&(this.upscalerMode=e,this.network&&(this.upscaler=this.makeUpscaler(),this.rebuildView(),this.compositors.clear()))}setBackground(e){this.bgConfig=e}get displayImage(){return this.image}fgImage(){return this.viewFg?this.viewFg.output:this.chainTail()}chainTail(){return this.effectChain.length?this.effectChain[this.effectChain.length-1].output:this.image}alphaImage(){if(!this.upscaler)throw new Error("RenderOp.alphaImage called before attachNetwork");return this.viewAlpha?this.viewAlpha.output:this.upscaler.output}setViewTransform(e){this.viewRect=e,this.rebuildView(),this.compositors.clear()}rebuildView(){this.viewFg=null,this.viewAlpha=null,this.viewRect&&(this.viewFg=this.backend.ops.Reframe(this.chainTail(),this.viewRect),this.upscaler&&(this.viewAlpha=this.backend.ops.Reframe(this.upscaler.output,this.viewRect)))}setEffectChain(e){this.effectChain=e,this.rebuildView(),this.compositors.clear()}runEffects(){for(let e of this.effectChain)e.run();this.viewFg?.run(),this.viewAlpha?.run()}run(){this.runModel(),this.runDisplay()}runDisplay(){this.refreshDisplayInput(),this.runEffects(),this.compositeMain("effect")}runFgPassthrough(){this.refreshDisplayInput(),this.runEffects(),this.compositeMain("fg")}runPassthrough(){this.refreshDisplayInput(),this.compositeMain("raw")}compositeMain(e){let r=e==="effect"?this.bgConfig:e==="fg"?{mode:"fg-passthrough"}:{mode:"passthrough"};this.compositeTo("main",r)}refreshDisplayInput(){this.displayDirty&&(this.displayInput.run(),this.displayDirty=!1)}compositeTo(e,r){let t=this.compositors.get(e);if(t&&ti(t.spec,r)){t.handle.run();return}let a=this.buildCompositor(e,r);this.compositors.set(e,{spec:r,handle:a}),a.run()}applyAlpha(e){if(!this.network||!this.upscaler)throw new Error("RenderOp.applyAlpha called before attachNetwork");this.backend.copyTensor(e,this.network.output),this.upscaler.run()}runModel(){if(!this.network||!this.networkInput||!this.upscaler)throw new Error("RenderOp.runModel called before attachNetwork");this.networkInput.run(),this.network.run(),this.upscaler.run()}makeUpscaler(){if(!this.network)throw new Error("makeUpscaler called with no network");let{backend:e,network:r,image:t}=this;return this.upscalerMode==="bicubic"?new be(e,r.output,t.h,t.w):new _e(e,r.output,t.h,t.w)}buildCompositor(e,r){let{backend:t,image:a}=this;if(r.mode==="passthrough")return t.presenters.CompositePassthrough(a,e);let o=this.fgImage();if(r.mode==="fg-passthrough")return t.presenters.CompositePassthrough(o,e);if(!this.upscaler)throw new Error("RenderOp.compositeTo (effect spec) called before attachNetwork");let n=this.alphaImage();switch(r.mode){case"solid":return new ve(t,o,n,r.color,e);case"image":return new xe(t,o,n,r.image,e);case"blur":return new we(t,o,n,r.sigma,e)}}};function ti(u,e){if(u.mode!==e.mode)return!1;switch(e.mode){case"passthrough":return!0;case"fg-passthrough":return!0;case"solid":{let r=u.color;return r[0]===e.color[0]&&r[1]===e.color[1]&&r[2]===e.color[2]}case"blur":return u.sigma===e.sigma;case"image":return u.image===e.image}}var ri=u=>typeof u=="object"&&u!==null&&typeof u.offset=="number"&&typeof u.length=="number";function ur(u){if(u.byteLength<4)throw new Error("weights buffer too small");let e=new DataView(u,0,4).getUint32(0,!0),r=4+e;if(u.byteLength<r)throw new Error("weights buffer truncated (header)");let t=new Uint8Array(u,4,e),a=JSON.parse(new TextDecoder().decode(t)),o=a.__dtype__??"f32",n=o==="f16"?2:4;if(r%n!==0)throw new Error(\`payload not \${n}-byte aligned (header=\${e})\`);let s=(u.byteLength-r)/n,p=c=>{if(ri(c)){let{offset:l,length:f}=c;if(l+f>s)throw new Error(\`array ref out of range: offset=\${l} length=\${f}\`);let d=r+l*n;return o==="f16"?new Uint16Array(u,d,f):new Float32Array(u,d,f)}if(Array.isArray(c))return c.map(p);if(typeof c=="object"&&c!==null){let l={};for(let f of Object.keys(c))f!=="__dtype__"&&(l[f]=p(c[f]));return l}return c};return p(a)}function _r(u,e,r,t){let a=t.variant,o=a==="E"||a==="D",n=a==="D",s=e.h,p=e.w,c=[],l=null,f=null,d=0,_=0,b;if(o)if(n){if(!r.down2)throw new Error("variant D requires w.down2");d=Math.round(s/1.25),_=Math.round(p/1.25);let x=u.ops.Conv2d(e,r.down1,{outChannels:t.cHigh,kernel:3,stride:1,padding:1,activation:"relu"});c.push(x),f=x.output;let v=u.ops.BilinearUpsample(f,{outH:d,outW:_});c.push(v),l=v.output;let y=u.ops.DownAdapter(l,r.down2,r.adapter,{stride:2});c.push(y),b=y.output}else{if(!r.down2)throw new Error("variant E requires w.down2");let x=u.ops.Conv2d(e,r.down1,{outChannels:t.cHigh,kernel:3,stride:2,padding:1,activation:"relu"});c.push(x),l=x.output,d=l.h,_=l.w;let v=u.ops.DownAdapter(l,r.down2,r.adapter,{stride:2});c.push(v),b=v.output}else{let x=a==="A"?2:3,v=u.ops.DownAdapter(e,r.down1,r.adapter,{stride:x});c.push(v),b=v.output}return{steps:c,adapted:b,d1:l,dFull:f,midH:d,midW:_}}function br(u,e,r,t,a,o,n,s,p){let c=p.variant,l=c==="E"||c==="D",f=c==="D",d=[],_=u.ops.ConvExpand(r,s.expandFeat);d.push(_);let b=_.output,x;if(l){if(!s.up1Combine)throw new Error("two-stage variant requires w.up1Combine");let y=u.ops.BilinearUpsample(b,{outH:o,outW:n});d.push(y);let W=u.ops.CatConv6to2(y.output,t,s.up1Combine);d.push(W);let B=u.ops.BilinearUpsample(W.output,{outH:e.h,outW:e.w});d.push(B),x=B.output}else{let y=u.ops.BilinearUpsample(b,{outH:e.h,outW:e.w});d.push(y),x=y.output}let v=f?u.ops.UpFinalSkip(x,a,e,s.upCombine):u.ops.UpFinal(x,e,s.upCombine);return d.push(v),{steps:d,alpha:v.output}}var Te=class{constructor(e,r,t,a,o,n){i(this,"inputs");i(this,"output");i(this,"encoderTaps");i(this,"halfTap");i(this,"steps");this.inputs=[r];let s=_r(e,r,a,o),p=new n(e,s.adapted,t),c=e.ops.BilinearUpsample(p.featLowRes,{outH:s.adapted.h,outW:s.adapted.w}),l=br(e,r,c.output,s.d1,s.dFull,s.midH,s.midW,a,o);this.steps=[...s.steps,p,c,...l.steps],this.output=l.alpha,this.encoderTaps=p.encoderTaps,this.halfTap=p.halfTap}run(){for(let e of this.steps)e.run()}};var oi=[5,5,3,3],ai=[2,2,1,1];function Pe(u,e,r,t){if(e.h===r.h&&e.w===r.w)return e;let a=u.ops.Crop(e,{outH:r.h,outW:r.w});return t.push(a),a.output}var Ce=class{constructor(e,r,t,a,o,n=16,s={}){i(this,"inputs");i(this,"output");i(this,"steps");this.inputs=[r,t,...a,...s.halfTap?[s.halfTap]:[]];let p=[],c=e.ops.ChannelConcat(r,t);p.push(c);let l=e.ops.Conv2d(c.output,o.stem,{outChannels:n,kernel:7,stride:2,padding:3,activation:"relu6"});p.push(l);let f=[],d=l.output;if(s.fuseStem&&s.halfTap){let v=Pe(e,s.halfTap,l.output,p),y=e.ops.ChannelConcat(l.output,v);p.push(y),f.push(y.output),d=y.output}for(let v=0;v<a.length;v++){let y=e.ops.Conv2d(d,o.stages[v],{outChannels:n,kernel:oi[v],stride:2,padding:ai[v],activation:"relu6"});p.push(y);let W=Pe(e,a[v],y.output,p),B=e.ops.ChannelConcat(y.output,W);p.push(B),f.push(B.output),d=B.output}let _=e.ops.Conv2d(f[f.length-1],o.predictBot,{outChannels:4,kernel:3,stride:1,padding:1,activation:"none"});p.push(_);let b=_.output,x=f[f.length-1];for(let v=0;v<f.length-1;v++){let y=f.length-2-v,W=e.ops.BilinearUpsample(x,{outH:x.h*2,outW:x.w*2}),B=e.ops.Conv2d(W.output,o.deconv[v],{outChannels:n,kernel:3,stride:1,padding:1,activation:"relu6"}),M=e.ops.BilinearUpsample(b,{outH:b.h*2,outW:b.w*2});p.push(W,B,M);let T=Pe(e,B.output,f[y],p),F=Pe(e,M.output,f[y],p),D=e.ops.ChannelConcat(f[y],T),E=e.ops.ChannelConcat(D.output,F);p.push(D,E);let R=e.ops.Conv2d(E.output,o.predict[v],{outChannels:4,kernel:3,stride:1,padding:1,activation:"none"});p.push(R),b=R.output,x=E.output}this.output=b,this.steps=p}run(){for(let e of this.steps)e.run()}};var I=class{constructor(e,r,t,a,o){i(this,"inputs");i(this,"output");i(this,"upOp");i(this,"concatConvOp");i(this,"conv2Op");this.inputs=[r,t],this.upOp=e.ops.BilinearUpsample(r,{outH:t.h,outW:t.w}),this.concatConvOp=e.ops.ConcatConv2d(this.upOp.output,t,a.conv1,{outChannels:o.outChannels}),this.conv2Op=e.ops.Conv2d(this.concatConvOp.output,a.conv2,{outChannels:o.outChannels,kernel:3,stride:1,padding:1,activation:"relu6"}),this.output=this.conv2Op.output}run(){this.upOp.run(),this.concatConvOp.run(),this.conv2Op.run()}};var ii=64,si=48,ni=32,ui=8,We=class{constructor(e,r,t){i(this,"inputs");i(this,"output");i(this,"steps");if(r.length<3)throw new Error(\`FaceHeatmapNet: needs \\u22653 encoder taps, got \${r.length}\`);let a=r[r.length-1],o=r[r.length-2],n=r[r.length-3];this.inputs=[a,o,n];let s=[],p=e.ops.Conv2d(a,t.proj,{outChannels:ii,kernel:1,stride:1,padding:0,activation:"relu6"});s.push(p);let c=new I(e,p.output,o,t.block1,{outChannels:si}),l=new I(e,c.output,n,t.block2,{outChannels:ni});s.push(c,l);let f=e.ops.Conv2d(l.output,t.out,{outChannels:ui,kernel:1,stride:1,padding:0,activation:"none"}),d=e.ops.Sigmoid(f.output);s.push(f,d),this.output=d.output,this.steps=s}run(){for(let e of this.steps)e.run()}};var le=[{c:12,stride:2},{c:12,stride:1},{c:24,stride:2},{c:24,stride:1},{c:48,stride:2},{c:48,stride:1},{c:48,stride:1},{c:64,stride:2},{c:64,stride:1},{c:96,stride:2}],pi=32,ci=478,li=ci*2,Ge=class{constructor(e,r,t){i(this,"inputs");i(this,"output");i(this,"steps");if(t.blocks.length!==le.length)throw new Error(\`LandmarkNet: expected \${le.length} block weights, got \${t.blocks.length}\`);this.inputs=[r];let a=[],o=e.ops.Conv2d(r,t.stem,{outChannels:8,kernel:3,stride:2,padding:1,activation:"relu6"});a.push(o);let n=o.output;for(let c=0;c<le.length;c++){let l=e.ops.Conv2d(n,t.blocks[c],{outChannels:le[c].c,kernel:3,stride:le[c].stride,padding:1,activation:"relu6"});a.push(l),n=l.output}let s=e.ops.Conv2d(n,t.headConv,{outChannels:pi,kernel:1,stride:1,padding:0,activation:"relu6"});a.push(s);let p=e.ops.Conv2d(s.output,t.fc,{outChannels:li,kernel:s.output.h,stride:1,padding:0,activation:"none"});a.push(p),this.output=p.output,this.steps=a}run(){for(let e of this.steps)e.run()}};var Q=class{constructor(e,r,t,a){i(this,"inputs");i(this,"output");i(this,"dwOp");i(this,"pwOp");this.inputs=[r],this.dwOp=e.ops.DepthwiseConv2d(r,t.dw,{kernel:a.kernel,stride:a.stride,padding:a.padding,activation:"relu6"}),this.pwOp=e.ops.Conv2d(this.dwOp.output,t.pw,{outChannels:a.outChannels,kernel:1,stride:1,padding:0,activation:"none"}),this.output=this.pwOp.output}run(){this.dwOp.run(),this.pwOp.run()}};var k=class{constructor(e,r,t,a){i(this,"inputs");i(this,"output");i(this,"expandOp");i(this,"dwOp");i(this,"projOp");this.inputs=[r];let o=a.midChannels!==a.inChannels,n=a.stride===1&&a.inChannels===a.outChannels;this.expandOp=o?e.ops.Conv2d(r,t.expand,{outChannels:a.midChannels,kernel:1,stride:1,padding:0,activation:"relu6"}):null;let s=this.expandOp?this.expandOp.output:r;this.dwOp=e.ops.DepthwiseConv2d(s,t.dw,{kernel:a.kernel,stride:a.stride,padding:a.padding,activation:"relu6"}),this.projOp=n?e.ops.ProjResidual(this.dwOp.output,r,t.proj,{outChannels:a.outChannels}):e.ops.Conv2d(this.dwOp.output,t.proj,{outChannels:a.outChannels,kernel:1,stride:1,padding:0,activation:"none"}),this.output=this.projOp.output}run(){this.expandOp?.run(),this.dwOp.run(),this.projOp.run()}};var Ue=class{constructor(e,r,t){i(this,"output");i(this,"featLowRes");i(this,"encoderTaps");i(this,"halfTap");i(this,"stem");i(this,"s0");i(this,"s1b0");i(this,"s1b1");i(this,"s2b0");i(this,"s2b1");i(this,"s3b0");i(this,"s3b1");i(this,"s3b2");i(this,"s4b0");i(this,"s4b1");i(this,"s4b2");i(this,"bottleneck");i(this,"dec0");i(this,"dec1");i(this,"finalUp");i(this,"outConv");i(this,"alpha");this.stem=e.ops.Conv2d(r,t.encoder.stem,{outChannels:32,kernel:3,stride:2,padding:"same",activation:"relu6"}),this.s0=new Q(e,this.stem.output,t.encoder.s0,{outChannels:16,kernel:3,stride:1,padding:1}),this.s1b0=new k(e,this.s0.output,t.encoder.s1[0],{inChannels:16,midChannels:96,outChannels:24,kernel:3,stride:2,padding:"same"}),this.s1b1=new k(e,this.s1b0.output,t.encoder.s1[1],{inChannels:24,midChannels:144,outChannels:24,kernel:3,stride:1,padding:1}),this.s2b0=new k(e,this.s1b1.output,t.encoder.s2[0],{inChannels:24,midChannels:144,outChannels:40,kernel:5,stride:2,padding:"same"}),this.s2b1=new k(e,this.s2b0.output,t.encoder.s2[1],{inChannels:40,midChannels:240,outChannels:40,kernel:5,stride:1,padding:2}),this.s3b0=new k(e,this.s2b1.output,t.encoder.s3[0],{inChannels:40,midChannels:240,outChannels:80,kernel:3,stride:2,padding:"same"}),this.s3b1=new k(e,this.s3b0.output,t.encoder.s3[1],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s3b2=new k(e,this.s3b1.output,t.encoder.s3[2],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s4b0=new k(e,this.s3b2.output,t.encoder.s4[0],{inChannels:80,midChannels:480,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b1=new k(e,this.s4b0.output,t.encoder.s4[1],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b2=new k(e,this.s4b1.output,t.encoder.s4[2],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.bottleneck=e.ops.Conv2d(this.s4b2.output,t.bottleneck,{outChannels:128,kernel:1,stride:1,padding:0,activation:"relu6"}),this.dec0=new I(e,this.bottleneck.output,this.s2b1.output,t.decoder.blocks[0],{outChannels:64}),this.dec1=new I(e,this.dec0.output,this.s1b1.output,t.decoder.blocks[1],{outChannels:32}),this.finalUp=e.ops.UpsampleConv1x1(this.dec1.output,t.decoder.finalUpsample,{outH:this.dec1.output.h*2,outW:this.dec1.output.w*2,outChannels:32,activation:"relu6"}),this.featLowRes=this.finalUp.output,this.encoderTaps=[this.s1b1.output,this.s2b1.output,this.s4b2.output],this.halfTap=this.s0.output,this.outConv=e.ops.Conv2d(this.finalUp.output,t.decoder.outputConv,{outChannels:4,kernel:1,stride:1,padding:0,activation:"none"}),this.alpha=e.ops.UpsampleSigmoid(this.outConv.output,{outH:this.outConv.output.h*2,outW:this.outConv.output.w*2}),this.output=this.alpha.output}run(){this.stem.run(),this.s0.run(),this.s1b0.run(),this.s1b1.run(),this.s2b0.run(),this.s2b1.run(),this.s3b0.run(),this.s3b1.run(),this.s3b2.run(),this.s4b0.run(),this.s4b1.run(),this.s4b2.run(),this.bottleneck.run(),this.dec0.run(),this.dec1.run(),this.finalUp.run(),this.outConv.run(),this.alpha.run()}};var Be=class{constructor(e,r,t){i(this,"output");i(this,"featLowRes");i(this,"encoderTaps");i(this,"stem");i(this,"s0");i(this,"s1b0");i(this,"s1b1");i(this,"s2b0");i(this,"s2b1");i(this,"s3b0");i(this,"s3b1");i(this,"s3b2");i(this,"s4b0");i(this,"s4b1");i(this,"s4b2");i(this,"s5b0");i(this,"s5b1");i(this,"s5b2");i(this,"s5b3");i(this,"s6b0");i(this,"bottleneck");i(this,"dec0");i(this,"dec1");i(this,"dec2");i(this,"finalUp");i(this,"outConv");i(this,"alpha");this.stem=e.ops.Conv2d(r,t.encoder.stem,{outChannels:32,kernel:3,stride:2,padding:"same",activation:"relu6"}),this.s0=new Q(e,this.stem.output,t.encoder.s0,{outChannels:16,kernel:3,stride:1,padding:1}),this.s1b0=new k(e,this.s0.output,t.encoder.s1[0],{inChannels:16,midChannels:96,outChannels:24,kernel:3,stride:2,padding:"same"}),this.s1b1=new k(e,this.s1b0.output,t.encoder.s1[1],{inChannels:24,midChannels:144,outChannels:24,kernel:3,stride:1,padding:1}),this.s2b0=new k(e,this.s1b1.output,t.encoder.s2[0],{inChannels:24,midChannels:144,outChannels:40,kernel:5,stride:2,padding:"same"}),this.s2b1=new k(e,this.s2b0.output,t.encoder.s2[1],{inChannels:40,midChannels:240,outChannels:40,kernel:5,stride:1,padding:2}),this.s3b0=new k(e,this.s2b1.output,t.encoder.s3[0],{inChannels:40,midChannels:240,outChannels:80,kernel:3,stride:2,padding:"same"}),this.s3b1=new k(e,this.s3b0.output,t.encoder.s3[1],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s3b2=new k(e,this.s3b1.output,t.encoder.s3[2],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s4b0=new k(e,this.s3b2.output,t.encoder.s4[0],{inChannels:80,midChannels:480,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b1=new k(e,this.s4b0.output,t.encoder.s4[1],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b2=new k(e,this.s4b1.output,t.encoder.s4[2],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.s5b0=new k(e,this.s4b2.output,t.encoder.s5[0],{inChannels:112,midChannels:672,outChannels:192,kernel:5,stride:2,padding:"same"}),this.s5b1=new k(e,this.s5b0.output,t.encoder.s5[1],{inChannels:192,midChannels:1152,outChannels:192,kernel:5,stride:1,padding:2}),this.s5b2=new k(e,this.s5b1.output,t.encoder.s5[2],{inChannels:192,midChannels:1152,outChannels:192,kernel:5,stride:1,padding:2}),this.s5b3=new k(e,this.s5b2.output,t.encoder.s5[3],{inChannels:192,midChannels:1152,outChannels:192,kernel:5,stride:1,padding:2}),this.s6b0=new k(e,this.s5b3.output,t.encoder.s6[0],{inChannels:192,midChannels:1152,outChannels:320,kernel:3,stride:1,padding:1}),this.bottleneck=e.ops.Conv2d(this.s6b0.output,t.bottleneck,{outChannels:128,kernel:1,stride:1,padding:0,activation:"relu6"}),this.dec0=new I(e,this.bottleneck.output,this.s4b2.output,t.decoder.blocks[0],{outChannels:64}),this.dec1=new I(e,this.dec0.output,this.s2b1.output,t.decoder.blocks[1],{outChannels:32}),this.dec2=new I(e,this.dec1.output,this.s1b1.output,t.decoder.blocks[2],{outChannels:16}),this.finalUp=e.ops.UpsampleConv1x1(this.dec2.output,t.decoder.finalUpsample,{outH:this.dec2.output.h*2,outW:this.dec2.output.w*2,outChannels:16,activation:"relu6"}),this.featLowRes=this.finalUp.output,this.encoderTaps=[this.s1b1.output,this.s2b1.output,this.s4b2.output,this.s6b0.output],this.outConv=e.ops.Conv2d(this.finalUp.output,t.decoder.outputConv,{outChannels:4,kernel:1,stride:1,padding:0,activation:"none"}),this.alpha=e.ops.UpsampleSigmoid(this.outConv.output,{outH:this.outConv.output.h*2,outW:this.outConv.output.w*2}),this.output=this.alpha.output}run(){this.stem.run(),this.s0.run(),this.s1b0.run(),this.s1b1.run(),this.s2b0.run(),this.s2b1.run(),this.s3b0.run(),this.s3b1.run(),this.s3b2.run(),this.s4b0.run(),this.s4b1.run(),this.s4b2.run(),this.s5b0.run(),this.s5b1.run(),this.s5b2.run(),this.s5b3.run(),this.s6b0.run(),this.bottleneck.run(),this.dec0.run(),this.dec1.run(),this.dec2.run(),this.finalUp.run(),this.outConv.run(),this.alpha.run()}};var pr=[[{in:24,mid:144,out:32,k:3,s:2},{in:32,mid:192,out:32,k:3,s:1},{in:32,mid:192,out:32,k:3,s:1}],[{in:32,mid:192,out:48,k:5,s:2},{in:48,mid:288,out:48,k:5,s:1},{in:48,mid:288,out:48,k:5,s:1}],[{in:48,mid:288,out:96,k:3,s:2},{in:96,mid:576,out:96,k:3,s:1},{in:96,mid:576,out:96,k:3,s:1},{in:96,mid:576,out:96,k:3,s:1},{in:96,mid:576,out:96,k:3,s:1}],[{in:96,mid:576,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1}],[{in:136,mid:816,out:232,k:5,s:2},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1}],[{in:232,mid:1392,out:384,k:3,s:1}]],Se=class{constructor(e,r,t){i(this,"output");i(this,"featLowRes");i(this,"encoderTaps");i(this,"stem");i(this,"s0");i(this,"stages");i(this,"bottleneck");i(this,"dec0");i(this,"dec1");i(this,"dec2");i(this,"finalUp");i(this,"outConv");i(this,"alpha");this.stem=e.ops.Conv2d(r,t.encoder.stem,{outChannels:32,kernel:3,stride:2,padding:"same",activation:"relu6"}),this.s0=new Q(e,this.stem.output,t.encoder.s0,{outChannels:24,kernel:3,stride:1,padding:1});let a=[t.encoder.s1,t.encoder.s2,t.encoder.s3,t.encoder.s4,t.encoder.s5,t.encoder.s6];this.stages=[];let o=this.s0.output;for(let f=0;f<pr.length;f++){let d=[];for(let _=0;_<pr[f].length;_++){let b=pr[f][_],x=new k(e,o,a[f][_],{inChannels:b.in,midChannels:b.mid,outChannels:b.out,kernel:b.k,stride:b.s,padding:b.s===2?"same":(b.k-1)/2});d.push(x),o=x.output}this.stages.push(d)}let n=f=>this.stages[f][this.stages[f].length-1].output,s=n(0),p=n(1),c=n(3),l=n(5);this.bottleneck=e.ops.Conv2d(l,t.bottleneck,{outChannels:256,kernel:1,stride:1,padding:0,activation:"relu6"}),this.dec0=new I(e,this.bottleneck.output,c,t.decoder.blocks[0],{outChannels:128}),this.dec1=new I(e,this.dec0.output,p,t.decoder.blocks[1],{outChannels:64}),this.dec2=new I(e,this.dec1.output,s,t.decoder.blocks[2],{outChannels:32}),this.finalUp=e.ops.UpsampleConv1x1(this.dec2.output,t.decoder.finalUpsample,{outH:this.dec2.output.h*2,outW:this.dec2.output.w*2,outChannels:32,activation:"relu6"}),this.featLowRes=this.finalUp.output,this.encoderTaps=[s,p,c,l],this.outConv=e.ops.Conv2d(this.finalUp.output,t.decoder.outputConv,{outChannels:4,kernel:1,stride:1,padding:0,activation:"none"}),this.alpha=e.ops.UpsampleSigmoid(this.outConv.output,{outH:this.outConv.output.h*2,outW:this.outConv.output.w*2}),this.output=this.alpha.output}run(){this.stem.run(),this.s0.run();for(let e of this.stages)for(let r of e)r.run();this.bottleneck.run(),this.dec0.run(),this.dec1.run(),this.dec2.run(),this.finalUp.run(),this.outConv.run(),this.alpha.run()}};var vr=Ue,xr=Be,fi=Se,J={xs:{base:vr,wrapper:{variant:"B",cHigh:4,cLow:4,cUp:2},canvasRes:{w:384,h:240},baseRes:{w:128,h:80},flowFuseStem:!0},small:{base:vr,wrapper:{variant:"A",cHigh:4,cLow:4,cUp:2},canvasRes:{w:384,h:224},baseRes:{w:192,h:112}},medium:{base:xr,wrapper:{variant:"A",cHigh:4,cLow:4,cUp:2},canvasRes:{w:512,h:320},baseRes:{w:256,h:160}},large:{base:xr,wrapper:{variant:"D",cHigh:4,cLow:4,cUp:2},canvasRes:{w:640,h:400},baseRes:{w:256,h:160}},xl:{base:fi,wrapper:{variant:"E",cHigh:4,cLow:4,cUp:2},canvasRes:{w:1280,h:768},baseRes:{w:320,h:192}}};var cr={zoom:1.35,gravity:.5,margin:.04},di={deadband:.09,ease:.07},yr=0,wr=1,mi=2,hi=16,gi={tLo:.15,tHi:2.5,leak:.15,release:.9,tDiv:1,divScale:2},kr=256,_i=[.485,.456,.406],bi=[.229,.224,.225],vi={win:3,thresh:.15,boxScale:2.4},xi=new Set(["medium","large","xl"]),yi=4,wi=.6,ki={webgpu:6,webgl:30},Ti=15,Pi=5,Tr=1e3,Ae=class{constructor(e){i(this,"canvas");i(this,"backend");i(this,"backendKind");i(this,"topology");i(this,"preset",null);i(this,"enabled");i(this,"currentBackground");i(this,"modelTimingCounter",0);i(this,"renderOp");i(this,"flow",null);i(this,"faceChain",null);i(this,"faceCfg",null);i(this,"reframe",null);i(this,"reframeCfg",null);i(this,"reframeSolveOnce",!1);i(this,"faceLive",0);i(this,"faceProbePending",!1);i(this,"faceProbeCounter",0);i(this,"tier",null);i(this,"tierInput",null);i(this,"lastTierWeights",null);i(this,"bgImageInputs",new Map);i(this,"bgVideoInputs",new Map);i(this,"bgVideoPorts",new Map);i(this,"previewCanvas",null);i(this,"previewCtx",null);i(this,"previewBg",null);i(this,"previewEffectSpec",null);i(this,"previewIntervalMs",1e3/Ti);i(this,"lastPreviewAt",0);i(this,"skipCounter",0);i(this,"framesRenderedAt",[]);i(this,"modelRunSamples",[]);i(this,"displayRunSamples",[]);i(this,"skippedCount",0);this.backend=e.backend,this.backendKind=e.backendKind,this.canvas=e.canvas,this.enabled=e.enabled,this.currentBackground=e.background,this.topology=e.topology,this.renderOp=new ke(this.backend)}process(e){this.renderOp.setSource(e);let r=performance.now(),t=this.renderOp.hasNetwork(),a=this.enabled&&t&&this.faceChain!==null,o=this.enabled&&t&&this.currentBackground.kind!=="none",n=o||a,s=this.isPreviewTick(r),p=s&&t&&this.previewBg!==null&&this.previewBg.kind!=="none",c=!1;n&&this.flow?c=this.stepFlow():n&&(this.shouldRunModel()?(this.runModelOnce(),c=!0):this.skippedCount++),!c&&p&&(this.runModelOnce(),c=!0),a&&this.stepFace(c);let l=performance.now();s&&this.previewCanvas?(this.backendKind==="webgl"?this.compositePreviewWebGL(o,p,a):(this.compositeMain(o,a),this.renderOp.compositeTo("preview",this.previewSpec(p))),this.lastPreviewAt=r):this.compositeMain(o,a),this.displayRunSamples.push({ts:performance.now(),ms:performance.now()-l}),this.trimSamples(this.displayRunSamples),this.framesRenderedAt.push(performance.now()),this.trim(this.framesRenderedAt)}compositeMain(e,r){e?this.renderOp.runDisplay():r?this.renderOp.runFgPassthrough():this.renderOp.runPassthrough()}compositePreviewWebGL(e,r,t){this.renderOp.refreshDisplayInput(),this.renderOp.runEffects(),this.renderOp.compositeTo("preview",this.previewSpec(r));let a=this.canvas.transferToImageBitmap();this.previewCtx.transferFromImageBitmap(a),this.renderOp.compositeMain(e?"effect":t?"fg":"raw")}previewSpec(e){return e&&this.previewEffectSpec?this.previewEffectSpec:{mode:"passthrough"}}runModelOnce(){let e=performance.now();this.renderOp.runModel(),this.backendKind==="webgpu"&&this.modelTimingCounter%Pi===0&&this.backend.sync().then(()=>{this.modelRunSamples.push({ts:performance.now(),ms:performance.now()-e}),this.trimSamples(this.modelRunSamples)}).catch(()=>{}),this.modelTimingCounter++}stepFlow(){let e=this.flow,r=!1;return e.networkInput.run(),e.curBaseDown.run(),e.everyFrame?(e.net.run(),e.up.run(),this.runModelOnce(),r=!0,this.backend.copyTensor(e.curBaseDown.output,e.frameAHeld),this.backend.copyTensor(e.tier.output,e.predBuf)):this.shouldRunModel()?(this.runModelOnce(),r=!0,this.backend.copyTensor(e.curBaseDown.output,e.frameAHeld),this.backend.copyTensor(e.tier.output,e.alphaHeld),this.backend.copyTensor(e.tier.output,e.predBuf)):(this.skippedCount++,e.net.run(),e.up.run(),e.predWarp.run(),this.backend.copyTensor(e.predWarp.output,e.predBuf)),e.warm?(e.refWarp.run(),e.stab.run(),this.backend.copyTensor(e.stab.output,e.stabPrev),this.renderOp.applyAlpha(e.stab.output),r):(this.backend.copyTensor(e.tier.output,e.stabPrev),e.warm=r,r)}stepFace(e){let r=this.faceChain;if(e?(r.face.run(),this.backend.copyTensor(r.face.output,r.hmBuf),r.hmHeld&&this.backend.copyTensor(r.face.output,r.hmHeld)):r.hmWarp&&this.flow&&(r.hmFlowDown.run(),r.hmWarp.run(),this.backend.copyTensor(r.hmWarp.output,r.hmBuf)),r.boxOp.run(),this.backend.copyTensor(r.boxOp.output,r.boxStable),r.stage){this.probeFaceOccupancy(r);let t=r.crops.length===1?1:this.faceLive;for(let a=0;a<t;a++)r.crops[a].run(),r.lms[a].run();if(t>0)for(let a of r.packLm)a.run();r.stage.setActiveSlots(t)}if(this.reframe){let t=this.reframe,a=t.auto?t.cmdAuto:this.reframeSolveOnce?t.cmdSolve:t.cmdHold;this.backend.copyTensor(a,t.cmd),this.reframeSolveOnce=!1,t.stateOp.run(),this.backend.copyTensor(t.stateOp.output,t.state)}}buildReframe(){this.reframe=null,this.renderOp.setViewTransform(null);let e=this.faceChain,r=this.reframeCfg;if(!r||!e||!this.preset)return;let t=J[this.preset.model].canvasRes,a=r.auto??!0,o=a!==!1,n={...di,...typeof a=="object"?a:{}},s=f=>this.backend.tensor(1,1,4,new Float32Array(f)),p=this.backend.tensor(1,1,8,new Float32Array(8)),c=s([o?yr:wr,0,0,0]),l=this.backend.ops.ReframeState(e.boxStable,p,c,{zoom:r.zoom??cr.zoom,gravity:r.gravity??cr.gravity,margin:r.margin??cr.margin,deadband:n.deadband,ease:n.ease,aspect:t.w/t.h});this.reframe={stateOp:l,state:p,cmd:c,auto:o,cmdAuto:s([yr,0,0,0]),cmdHold:s([wr,0,0,0]),cmdSolve:s([mi,0,0,0])},this.renderOp.setViewTransform(p)}probeFaceOccupancy(e){let r=e.crops.length;if(r===1)return;let t=ki[this.backendKind];this.faceProbePending||this.faceProbeCounter++%t!==0||(this.faceProbePending=!0,this.backend.readback(e.boxStable).then(a=>{let o=0;for(;o<r&&a[o*4+3]>0;)o++;this.faceLive=o,this.faceProbePending=!1}).catch(()=>{this.faceProbePending=!1}))}isPreviewTick(e){return!this.previewCanvas||this.previewBg===null||!this.enabled?!1:e-this.lastPreviewAt>=this.previewIntervalMs}shouldRunModel(){return this.skipCounter===0?(this.skipCounter=this.preset?.skipFrames??0,!0):(this.skipCounter--,!1)}setBackground(e){this.currentBackground=e,this.renderOp.setBackground(this.translateBackgroundFor("main",e))}setEnabled(e){this.enabled=e}attachPreview(e){if(e.width=this.canvas.width,e.height=this.canvas.height,this.previewCanvas=e,this.backendKind==="webgpu")this.backend.attachCanvas("preview",e);else{let r=e.getContext("bitmaprenderer");if(!r)throw new Error("renderer: failed to get bitmaprenderer context for preview canvas");this.previewCtx=r}}setPreview(e,r){this.previewBg=e,this.previewEffectSpec=e.kind==="none"?null:this.translateBackgroundFor("preview",e),r?.fps&&r.fps>0&&(this.previewIntervalMs=1e3/r.fps),this.lastPreviewAt=0}clearPreview(){this.previewBg=null,this.previewEffectSpec=null;let e=this.bgVideoPorts.get("preview");e&&(e.close(),this.bgVideoPorts.delete("preview"))}setPreset(e,r){let t=J[e.model];if(!t)throw new Error(\`renderer: no TIER_CONFIG entry for model '\${e.model}'\`);let a=ur(r),o=this.backend.ops.Input(t.canvasRes.h,t.canvasRes.w),n=new Te(this.backend,o.output,a.base,a.wrapper,t.wrapper,t.base);if(this.renderOp.attachNetwork(n,o,{upscaler:"bilinear",background:this.translateBackgroundFor("main",this.currentBackground)}),this.flow=null,a.flow){let s=t.baseRes,p=t.canvasRes,c=e.skipFrames===0,l=(E,R)=>this.backend.tensor(E,R,4,new Float32Array(E*R*4)),f=this.backend.ops.BilinearUpsample(o.output,{outH:s.h,outW:s.w}),d=l(s.h,s.w),_=new Ce(this.backend,d,f.output,n.encoderTaps,a.flow,hi,t.flowFuseStem?{fuseStem:!0,halfTap:n.halfTap}:{}),b=this.backend.ops.BilinearUpsample(_.output,{outH:p.h,outW:p.w}),x=p.w/s.w,v=l(p.h,p.w),y=l(p.h,p.w),W=this.backend.ops.Warp(y,b.output,{flowScale:x}),B=Math.max(1,Math.round(p.w/_.output.w)),M=Math.max(1,Math.round(p.h/_.output.h)),T=this.backend.ops.Stabilize(b.output,v,W.output,y,{...gi,stepX:B,stepY:M}),F=c?null:l(p.h,p.w),D=F?this.backend.ops.Warp(F,b.output,{flowScale:x}):null;this.flow={tier:n,everyFrame:c,warm:!1,networkInput:o,curBaseDown:f,frameAHeld:d,net:_,up:b,predBuf:v,stabPrev:y,refWarp:W,stab:T,alphaHeld:F,predWarp:D}}this.preset=e,this.skipCounter=0,this.tier=n,this.tierInput=o,this.lastTierWeights=a,this.buildFaceChain()}setFaceEffects(e){this.faceCfg=e,this.preset&&this.buildFaceChain()}setReframe(e){this.reframeCfg=e,this.preset&&this.buildFaceChain()}reframeNow(){this.reframeSolveOnce=!0}buildFaceChain(){this.faceChain=null,this.reframe=null,this.renderOp.setEffectChain([]),this.renderOp.setViewTransform(null);let e=this.faceCfg,r=this.lastTierWeights;if(!e&&!this.reframeCfg||!this.tier||!this.tierInput||!this.preset)return;if(!r?.face){console.warn(\`[longpipe/renderer] face effects configured but the '\${this.preset.model}' weights have no face blob \\u2014 disabled. Re-export the tier with a face-trained checkpoint.\`);return}let t=new We(this.backend,this.tier.encoderTaps,r.face),a=t.output,o=(T,F,D)=>this.backend.tensor(T,F,D,new Float32Array(T*F*D)),n=o(a.h,a.w,a.c),s=null,p=null,c=null;if(this.flow&&(this.preset.skipFrames??0)>0){let T=J[this.preset.model].baseRes.w;s=o(a.h,a.w,a.c),p=this.backend.ops.BilinearUpsample(this.flow.net.output,{outH:a.h,outW:a.w}),c=this.backend.ops.Warp(s,p.output,{flowScale:a.w/T})}let l=xi.has(this.preset.model)?yi:1,f={...vi,...e?.box??{}},d=l>1?this.backend.ops.FaceBoxesFromHeatmaps(n,{...f,maxFaces:l,tol:wi}):this.backend.ops.FaceBoxFromHeatmaps(n,f),_=o(1,l,4);if(!e){this.faceChain={face:t,hmBuf:n,hmHeld:s,hmFlowDown:p,hmWarp:c,boxOp:d,boxStable:_,crops:[],lms:[],packLm:[],stage:null},this.buildReframe();return}let b=ur(e.landmarkWeights),x=this.tierInput.output,v=Array.from({length:l},(T,F)=>this.backend.ops.CropResample(x,_,{outH:kr,outW:kr,mean:_i,std:bi,slot:F})),y=v.map(T=>new Ge(this.backend,T.output,b)),W=[],B=y[0].output;if(l>1){let T=y.map(F=>F.output);for(;T.length>1;){let F=[];for(let D=0;D<T.length;D+=2){let E=this.backend.ops.ChannelConcat(T[D],T[D+1]);W.push(E),F.push(E.output)}T=F}B=T[0]}let M=this.backend.ops.FaceTouchupStage(this.renderOp.displayImage,B,_,e.topology,{...e.touchup,slots:l});this.renderOp.setEffectChain([M]),this.faceLive=l,this.faceProbeCounter=0,this.faceChain={face:t,hmBuf:n,hmHeld:s,hmFlowDown:p,hmWarp:c,boxOp:d,boxStable:_,crops:v,lms:y,packLm:W,stage:M},this.buildReframe()}destroy(){for(let e of this.bgVideoPorts.values())e.close();this.bgVideoPorts.clear(),this.backend.destroy()}getStats(){let e=performance.now();return this.trimRecent(this.framesRenderedAt,e),this.trimSamplesAt(this.modelRunSamples,e),this.trimSamplesAt(this.displayRunSamples,e),{fps:this.framesRenderedAt.length,modelFps:this.modelRunSamples.length,modelMs:Pr(this.modelRunSamples.map(r=>r.ms)),displayMs:Pr(this.displayRunSamples.map(r=>r.ms)),skipped:this.skippedCount,preset:this.preset?.model??"boot",skipFrames:this.preset?.skipFrames??0,enabled:this.enabled,inputPath:this.topology.input,outputPath:this.topology.output}}translateBackgroundFor(e,r){let t=this.bgVideoPorts.get(e);switch(r.kind!=="video"&&t&&(t.close(),this.bgVideoPorts.delete(e)),r.kind){case"none":return{mode:"solid",color:[0,0,0]};case"color":return{mode:"solid",color:r.rgb};case"blur":return{mode:"blur",sigma:r.sigma};case"image":{let a=this.bgInputFor(this.bgImageInputs,e);return a.setSource(r.bitmap),a.run(),{mode:"image",image:a.output}}case"video":{let a=this.bgInputFor(this.bgVideoInputs,e);return t&&t.close(),this.bgVideoPorts.set(e,r.port),r.port.onmessage=o=>{let n=o.data.frame;try{a.setSource(n),a.run()}finally{n.close()}},r.port.start?.(),{mode:"image",image:a.output}}}}bgInputFor(e,r){let t=e.get(r);return t||(t=this.backend.ops.Input(this.canvas.height,this.canvas.width),e.set(r,t)),t}trim(e){e.length>240&&e.splice(0,e.length-240)}trimSamples(e){e.length>240&&e.splice(0,e.length-240)}trimRecent(e,r){let t=r-Tr,a=0;for(;a<e.length&&e[a]<t;)a++;a>0&&e.splice(0,a)}trimSamplesAt(e,r){let t=r-Tr,a=0;for(;a<e.length&&e[a].ts<t;)a++;a>0&&e.splice(0,a)}};function Pr(u){if(u.length===0)return 0;let e=u.slice().sort((t,a)=>t-a),r=e.length>>1;return e.length%2?e[r]:(e[r-1]+e[r])/2}var oe=new Float32Array(1),fe=new Uint32Array(oe.buffer);function Ci(u){oe[0]=u;let e=fe[0],r=e>>>16&32768,t=e&2147483647,a=(t>>>23)-127+15;if((e&2139095040)===2139095040)return(e&8388607)!==0?r|32256:r|31744;if(a>=31)return r|31744;if(a<=0){if(a<-10)return r;let c=t&8388607|8388608,l=14-a,f=c>>>l,d=c>>>l-1&1,_=(c&(1<<l-1)-1)!==0?1:0;return d&&(_||f&1)&&(f+=1),r|f}let o=t>>>13&1023,n=t>>>12&1,s=(t&4095)!==0?1:0,p=a<<10|o;return n&&(s||o&1)&&(p+=1,(p>>>10&31)===31)?r|31744:r|p}function lr(u){let e=(u&32768)<<16,r=(u&31744)>>>10,t=u&1023;if(r===0){if(t===0)return fe[0]=e,oe[0];let a=t,o=1;for(;(a&1024)===0;)a<<=1,o-=1;return a&=1023,fe[0]=e|o+127-15<<23|a<<13,oe[0]}return r===31?(fe[0]=e|2139095040|t<<13,oe[0]):(fe[0]=e|r+127-15<<23|t<<13,oe[0])}function Le(u){let e=new Uint16Array(u.length);for(let r=0;r<u.length;r++)e[r]=Ci(u[r]);return e}function ae(u){let e=new Float32Array(u.length);for(let r=0;r<u.length;r++)e[r]=lr(u[r]);return e}var h=class{constructor(e){i(this,"backend",e);i(this,"shader","");i(this,"pipeline");i(this,"bindGroup");i(this,"uniformDefs",[]);i(this,"uniformBuffers",{})}createUniform(e,r){this.uniformDefs.push({name:e,type:r})}setUniform(e,r){let t=this.backend.device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:!0});r instanceof Uint32Array?new Uint32Array(t.getMappedRange()).set(r):new Float32Array(t.getMappedRange()).set(r),t.unmap(),this.uniformBuffers[e]=t}defaultBindGroup(){let e=[],r=0;for(let t of this.inputs)e.push({binding:r++,resource:{buffer:t.buffer}});for(let t of this.weights)e.push({binding:r++,resource:{buffer:t.buffer}});for(let t of this.uniformDefs)e.push({binding:r++,resource:{buffer:this.uniformBuffers[t.name]}});return e.push({binding:r,resource:{buffer:this.output.buffer}}),this.backend.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:e})}defaultSetup(){let e=this.backend.device.createShaderModule({code:this.shader});this.pipeline=this.backend.device.createComputePipeline({layout:"auto",compute:{module:e,entryPoint:"main"}}),this.bindGroup=this.defaultBindGroup()}run(){let e=this.backend.device.createCommandEncoder(),r=e.beginComputePass();r.setPipeline(this.pipeline),r.setBindGroup(0,this.bindGroup),r.dispatchWorkgroups(...this.dispatch),r.end(),this.backend.device.queue.submit([e.finish()])}};var Cr=\`// Conv2d, output-channel-blocked (K=2) \\u2014 drop-in replacement for conv2d.wgsl.
1
+ import {a,b}from'./chunk-O4OF2WRO.js';export{h as WebGPUBackend}from'./chunk-NYCCJS3G.js';var _=[{model:"xs",dtype:"f16",resolution:{w:384,h:240},skipFrames:2},{model:"small",dtype:"f16",resolution:{w:384,h:224},skipFrames:1},{model:"medium",dtype:"f16",resolution:{w:512,h:320},skipFrames:1},{model:"large",dtype:"f32",resolution:{w:640,h:400},skipFrames:0},{model:"xl",dtype:"f32",resolution:{w:1280,h:768},skipFrames:0}];var U=false;function W(t){U=t;}function g(t){let e=`[longpipe/${t}]`,n=((...r)=>{U&&console.log(e,...r);});return n.warn=(...r)=>{U&&console.warn(e,...r);},n}var w=g("adaptive"),ae=2e3,ie=1e4,se=30,oe=20,ue=5e3,le=.3,pe=15e3,T=class{constructor(e){this.opts=e;this.currentPresetIdx=_.findIndex(n=>n.model===e.initialModel),this.lastSwapAt=performance.now();}opts;timer=null;currentPresetIdx;lastSwapAt=0;overshootStart=0;headroomStart=0;start(){w(`started; backend=${this.opts.backendKind} initial=${this.opts.initialModel} idx=${this.currentPresetIdx}`),this.timer=setInterval(()=>{this.tick().catch(e=>w("tick failed:",e));},ae);}stop(){this.timer&&clearInterval(this.timer),this.timer=null;}async tick(){if(typeof document<"u"&&document.hidden)return;let e=performance.now();if(e-this.lastSwapAt<ie)return;let n=await this.opts.getStats();if(n.fps<oe?(this.overshootStart===0&&(this.overshootStart=e),e-this.overshootStart>=ue&&this.tryDowngrade(n.fps)):this.overshootStart=0,this.opts.backendKind==="webgpu"&&n.modelMs>0){let r=1e3/se*le;n.modelMs<r?(this.headroomStart===0&&(this.headroomStart=e),e-this.headroomStart>=pe&&this.tryUpgrade(n.modelMs,r)):this.headroomStart=0;}}tryDowngrade(e){if(this.currentPresetIdx<=0)return;let n=this.currentPresetIdx-1;w(`downgrade ${_[this.currentPresetIdx].model} \u2192 ${_[n].model} (fps=${e})`),this.swap(n);}tryUpgrade(e,n){if(_[this.currentPresetIdx+1]?.model==="xl"||this.currentPresetIdx>=_.length-1)return;let r=this.currentPresetIdx+1;w(`upgrade ${_[this.currentPresetIdx].model} \u2192 ${_[r].model} (modelMs=${e.toFixed(1)} < ${n.toFixed(1)})`),this.swap(r);}async swap(e){let n=_[e];this.lastSwapAt=performance.now(),this.overshootStart=0,this.headroomStart=0;try{let r=await this.opts.fetchWeights(n.model);await this.opts.swapPreset(n,r),this.currentPresetIdx=e,w(`swap to ${n.model} done`);}catch(r){w("swap failed:",r),this.opts.onError?.({message:`adaptive preset swap failed: ${r.message??String(r)}`,source:"adaptive",recoverable:true,cause:r});}}};async function z(t){let e,n=false;if(t instanceof HTMLVideoElement){if(e=t.currentSrc||t.src,!e)throw new Error("background video: HTMLVideoElement has no src")}else if(t instanceof Blob)e=URL.createObjectURL(t),n=true;else if(typeof t=="string")e=t;else throw new Error("background video: unsupported input shape");let r=document.createElement("video");r.crossOrigin="anonymous",r.muted=true,r.loop=true,r.playsInline=true,r.src=e,await new Promise((o,p)=>{r.addEventListener("loadeddata",()=>o(),{once:true}),r.addEventListener("error",()=>p(new Error(`background video: failed to load ${e}`)),{once:true});});try{await r.play();}catch(o){throw new Error(`background video: play() rejected \u2014 ${o.message}`)}let a=new MessageChannel,i=a.port1,l=a.port2,u=false,c=r.requestVideoFrameCallback?.bind(r);if(c){let o=(p,h)=>{if(!u){try{let d=new VideoFrame(r,{timestamp:h.mediaTime*1e6});i.postMessage({frame:d},[d]);}catch{}c(o);}};c(o);}else {let o=()=>{if(!u){try{let p=new VideoFrame(r,{timestamp:performance.now()*1e3});i.postMessage({frame:p},[p]);}catch{}requestAnimationFrame(o);}};requestAnimationFrame(o);}return {port:l,transferList:[l],cleanup:()=>{u=true,i.close(),r.pause(),r.removeAttribute("src"),r.load(),n&&URL.revokeObjectURL(e);}}}var ce=4,R=8,L=16;async function P(t){if(typeof t=="string")return t==="none"?{background:{kind:"none"}}:t==="blur"?{background:{kind:"blur",sigma:R}}:{background:{kind:"image",bitmap:await N(t)}};if(t instanceof ImageBitmap)return {background:{kind:"image",bitmap:t}};if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return {background:{kind:"image",bitmap:await createImageBitmap(t)}};if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)return await H(t);let e=t;if(e.color!==void 0)return {background:{kind:"color",rgb:he(e.color)}};if(e.blur!==void 0)return {background:{kind:"blur",sigma:fe(e.blur)}};if(e.image!==void 0)return {background:{kind:"image",bitmap:await de(e.image)}};if(e.video!==void 0)return await H(e.video);throw new Error(`background: unrecognized input shape \u2014 ${x(t)}`)}async function H(t){let e;if(typeof t=="string")e=t;else if(typeof HTMLVideoElement<"u"&&t instanceof HTMLVideoElement)e=t;else if(t&&typeof t=="object"&&"data"in t&&"type"in t)e=t.data instanceof Blob?t.data:new Blob([t.data],{type:t.type});else throw new Error(`background.video: unrecognized shape \u2014 ${x(t)}`);let n=await z(e);return {background:{kind:"video",port:n.port},transferList:n.transferList,cleanup:n.cleanup}}function he(t){if(typeof t=="string"){let e=t.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(e))return [parseInt(e.slice(0,2),16)/255,parseInt(e.slice(2,4),16)/255,parseInt(e.slice(4,6),16)/255];if(/^[0-9a-fA-F]{3}$/.test(e))return [parseInt(e[0]+e[0],16)/255,parseInt(e[1]+e[1],16)/255,parseInt(e[2]+e[2],16)/255];throw new Error(`background.color: hex must be #rgb or #rrggbb, got ${x(t)}`)}if(!Array.isArray(t)||t.length!==3||!t.every(e=>typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1))throw new Error(`background.color: expected hex string or [r, g, b] floats in [0, 1], got ${x(t)}`);return [t[0],t[1],t[2]]}function fe(t){if(t===true)return R;if("sigma"in t){if(typeof t.sigma!="number"||!Number.isFinite(t.sigma)||t.sigma<0)throw new Error(`background.blur.sigma must be a non-negative number, got ${t.sigma}`);return t.sigma}if("strength"in t){let e=t.strength;if(typeof e=="number"){let n=Math.max(0,Math.min(1,e));return L*n}if(e==="low")return ce;if(e==="medium")return R;if(e==="high")return L;throw new Error(`background.blur.strength must be 'low' | 'medium' | 'high' | number, got ${x(e)}`)}throw new Error(`background.blur: must be true, { strength }, or { sigma } \u2014 got ${x(t)}`)}async function de(t){if(t instanceof ImageBitmap)return t;if(typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement)return createImageBitmap(t);if(typeof t=="string")return N(t);if(t&&typeof t=="object"&&"data"in t&&"type"in t){let e=t.data instanceof Blob?t.data:new Blob([t.data],{type:t.type});return createImageBitmap(e)}throw new Error(`background.image: unrecognized shape \u2014 ${x(t)}`)}async function N(t){let e=await fetch(t);if(!e.ok)throw new Error(`background: failed to load image from ${t} (HTTP ${e.status})`);let n=await e.blob();return createImageBitmap(n)}function x(t){return t===null?"null":typeof t!="object"?typeof t+"("+String(t)+")":`${t.constructor?.name??"Object"} ${JSON.stringify(t).slice(0,80)}`}function G(){return {input:"MediaStreamTrackProcessor"in self?"mstp":"rvfc-postmessage",output:"MediaStreamTrackGenerator"in self?"mstg":me()?"transfer-capture":"bitmap-shuttle"}}var E=null;function me(){return E!==null||(E=!/Firefox/.test(navigator.userAgent)),E}function V(t){return t==="denoise"?{mode:"denoise",denoise:{}}:typeof t=="object"?{mode:"denoise",denoise:t.denoise}:{mode:t}}function X(t,e,n,r){let a=[t];return n.mode==="passthrough"?a.push(...e.getAudioTracks()):n.mode==="denoise"&&r&&a.push(r),new MediaStream(a)}var A=g("worker_controller"),S=class{worker;listeners=new Map;persistentEvents=new Set;constructor(e){this.worker=e,this.worker.addEventListener("message",this.handleMessage.bind(this)),A("constructed; message listener attached");}handleMessage(e){let{request_id:n,res:r}=e.data,a=this.listeners.get(n);A("msg received: request_id=",n,"handler?",!!a,"persistent?",this.persistentEvents.has(n)),a&&(a(r),this.persistentEvents.has(n)||this.listeners.delete(n));}addPersistentListener(e,n){this.persistentEvents.add(e),this.listeners.set(e,n),A("addPersistentListener:",e);}removePersistentListener(e){this.persistentEvents.delete(e),this.listeners.delete(e);}sendMessage(e,n,r=[]){let a=crypto.randomUUID();return A("sendMessage:",e,"request_id=",a,"transferables=",r.length),new Promise(i=>{this.listeners.set(a,u=>i(u));let l={cmd:e,data:n,request_id:a};this.worker.postMessage(l,r);})}terminate(){this.worker.terminate(),this.listeners.clear(),this.persistentEvents.clear();}};var $=g("input-postmessage/main");function j(t){let e=document.createElement("video");e.srcObject=t,e.muted=true,e.autoplay=true,e.playsInline=true,e.play().catch(s=>{$.warn("video.play() rejected:",s);});let n=e.requestVideoFrameCallback?.bind(e);if(!n)throw new Error("setupPostMessageInput: requestVideoFrameCallback not supported on this browser");let r=new MessageChannel,a=r.port1,i=r.port2,l=false,u=(s,o)=>{if(!l){try{let p=new VideoFrame(e,{timestamp:o.mediaTime*1e6});a.postMessage({frame:p},[p]);}catch(p){$.warn("VideoFrame() failed; skipping frame:",p);}n(u);}};return n(u),{port:i,transferList:[i],cleanup:()=>{l=true,a.close(),e.srcObject=null,e.pause();}}}function q(t){let e=t.getVideoTracks();if(e.length===0)throw new Error("setupMstpInput: input MediaStream has no video tracks");let n=e[0],r=self.MediaStreamTrackProcessor;if(!r)throw new Error("setupMstpInput: MediaStreamTrackProcessor not supported on this browser");let i=new r({track:n}).readable;return {readable:i,transferList:[i],cleanup:()=>{i.cancel().catch(()=>{});}}}function K(t,e){switch(t){case "mstp":{let n=q(e);return {initFields:{inputReadable:n.readable},transferList:n.transferList,cleanup:n.cleanup}}case "rvfc-postmessage":{let n=j(e);return {initFields:{inputPort:n.port},transferList:n.transferList,cleanup:n.cleanup}}}}var ge=g("bitmap-shuttle/main"),_e=30;function Y(t,e=_e){let n=document.createElement("canvas");n.width=t.w,n.height=t.h;let r=n.getContext("bitmaprenderer");if(!r)throw new Error("setupBitmapShuttleOutput: bitmaprenderer context not available");let i=n.captureStream(e).getVideoTracks();if(i.length===0)throw new Error("setupBitmapShuttleOutput: captureStream produced no video tracks");let l=i[0],u=new MessageChannel,c=u.port1,s=u.port2,o=false,p=null,h=()=>{},d=3,f=0;return c.onmessage=y=>{if(o){if(f++,f<d){y.data.bmp.close();return}h();}try{r.transferFromImageBitmap(y.data.bmp);}catch(m){ge.warn("transferFromImageBitmap failed:",m);}},c.start(),{videoTrack:l,port:s,transferList:[s],startPassthrough:y=>{if(o)return;o=true;let m=document.createElement("video");m.srcObject=y,m.muted=true,m.playsInline=true,m.play().catch(()=>{}),p=m;let k="requestVideoFrameCallback"in m?b=>{m.requestVideoFrameCallback(b);}:b=>{requestAnimationFrame(b);},C=()=>{if(o){if(m.videoWidth===0){k(C);return}createImageBitmap(m,{resizeWidth:n.width,resizeHeight:n.height,resizeQuality:"medium"}).then(b=>{if(!o){b.close();return}try{r.transferFromImageBitmap(b);}catch{}k(C);}).catch(()=>{k(C);});}};k(C),h=()=>{o=false,p&&(p.srcObject=null,p.pause(),p=null);};},cleanup:()=>{h(),c.onmessage=null,c.close(),l.stop();}}}function Q(){let t=self.MediaStreamTrackGenerator;if(!t)throw new Error("setupMstgOutput: MediaStreamTrackGenerator not supported on this browser");let e=new t({kind:"video"}),n=e.writable;return {videoTrack:e,writable:n,transferList:[n],cleanup:()=>{n.abort().catch(()=>{}),e.stop();}}}function J(t,e=30){let n=document.createElement("canvas");n.width=t.w,n.height=t.h;let a=n.captureStream(e).getVideoTracks();if(a.length===0)throw new Error("setupTransferCaptureOutput: captureStream produced no video tracks");let i=a[0],l=n.transferControlToOffscreen();return {videoTrack:i,canvas:l,transferList:[l],cleanup:()=>{i.stop();}}}function Z(t,e){switch(t){case "mstg":{let n=Q();return {videoTrack:n.videoTrack,initFields:{outputWritable:n.writable},transferList:n.transferList,cleanup:n.cleanup}}case "transfer-capture":{let n=J(e);return {videoTrack:n.videoTrack,initFields:{outputCanvas:n.canvas},transferList:n.transferList,cleanup:n.cleanup}}case "bitmap-shuttle":{let n=Y(e);return {videoTrack:n.videoTrack,initFields:{outputPort:n.port},transferList:n.transferList,startPassthrough:n.startPassthrough,cleanup:n.cleanup}}}}var B=`var Ya=Object.defineProperty;var Qa=(u,e,r)=>e in u?Ya(u,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):u[e]=r;var i=(u,e,r)=>Qa(u,typeof e!="symbol"?e+"":e,r);var sr=!1;function gr(u){sr=u}function Y(u){let e=\`[longpipe/\${u}]\`,r=((...t)=>{sr&&console.log(e,...t)});return r.warn=(...t)=>{sr&&console.warn(e,...t)},r}var nr=[{model:"xs",dtype:"f16",resolution:{w:384,h:240},skipFrames:2},{model:"small",dtype:"f16",resolution:{w:384,h:224},skipFrames:1},{model:"medium",dtype:"f16",resolution:{w:512,h:320},skipFrames:1},{model:"large",dtype:"f32",resolution:{w:640,h:400},skipFrames:0},{model:"xl",dtype:"f32",resolution:{w:1280,h:768},skipFrames:0}],Ja={fast:0,balanced:2,quality:4};function ge(u){return u==="auto"?null:nr[Ja[u]]}var _e=class{constructor(e,r,t,a){i(this,"op");this.op=e.ops.BilinearUpsample(r,{outH:t,outW:a})}get output(){return this.op.output}run(){this.op.run()}};var be=class{constructor(e,r,t,a){i(this,"op");this.op=e.ops.BicubicUpsample(r,{outH:t,outW:a})}get output(){return this.op.output}run(){this.op.run()}};var ve=class{constructor(e,r,t,a,o="main"){i(this,"presenter");this.presenter=e.presenters.CompositeSolid(r,t,a,o)}run(){this.presenter.run()}};var xe=class{constructor(e,r,t,a,o="main"){i(this,"presenter");this.presenter=e.presenters.CompositeImage(r,t,a,o)}run(){this.presenter.run()}};var ye=class{constructor(e,r,t){i(this,"downs",[]);i(this,"ups",[]);let a=Za(t),o=r;for(let n=0;n<a;n++){let s=e.ops.BilinearUpsample(o,{outH:Math.max(1,Math.floor(o.h/2)),outW:Math.max(1,Math.floor(o.w/2))});this.downs.push(s),o=s.output}for(let n=a-1;n>=1;n--){let s=this.downs[n-1].output,p=e.ops.BilinearUpsample(o,{outH:s.h,outW:s.w});this.ups.push(p),o=p.output}}get output(){return this.ups.length>0?this.ups[this.ups.length-1].output:this.downs[0].output}run(){for(let e of this.downs)e.run();for(let e of this.ups)e.run()}};function Za(u){let e=Math.max(1,3*u);return Math.max(2,Math.min(6,Math.round(Math.log2(e))))}var ei=.05,we=class{constructor(e,r,t,a,o="main"){i(this,"blur");i(this,"presenter");a<=ei?(this.blur=null,this.presenter=e.presenters.CompositeImage(r,t,r,o)):(this.blur=new ye(e,r,a),this.presenter=e.presenters.CompositeImageBilinear(r,t,this.blur.output,o))}run(){this.blur?.run(),this.presenter.run()}};var ke=class{constructor(e){i(this,"backend",e);i(this,"displayInput");i(this,"image");i(this,"network",null);i(this,"networkInput",null);i(this,"upscaler",null);i(this,"upscalerMode","bilinear");i(this,"bgConfig",{mode:"solid",color:[0,0,0]});i(this,"effectChain",[]);i(this,"viewRect",null);i(this,"viewFg",null);i(this,"viewAlpha",null);i(this,"displayDirty",!1);i(this,"compositors",new Map);let r=e.canvas;this.displayInput=e.ops.Input(r.height,r.width),this.image=this.displayInput.output}attachNetwork(e,r,t){this.network=e,this.networkInput=r,this.upscalerMode=t.upscaler,this.bgConfig=t.background,this.upscaler=this.makeUpscaler(),this.rebuildView(),this.compositors.clear()}hasNetwork(){return this.network!==null}setSource(e){this.networkInput?.setSource(e),this.displayInput.setSource(e),this.displayDirty=!0}setUpscaler(e){e!==this.upscalerMode&&(this.upscalerMode=e,this.network&&(this.upscaler=this.makeUpscaler(),this.rebuildView(),this.compositors.clear()))}setBackground(e){this.bgConfig=e}get displayImage(){return this.image}fgImage(){return this.viewFg?this.viewFg.output:this.chainTail()}chainTail(){return this.effectChain.length?this.effectChain[this.effectChain.length-1].output:this.image}alphaImage(){if(!this.upscaler)throw new Error("RenderOp.alphaImage called before attachNetwork");return this.viewAlpha?this.viewAlpha.output:this.upscaler.output}setViewTransform(e){this.viewRect=e,this.rebuildView(),this.compositors.clear()}rebuildView(){this.viewFg=null,this.viewAlpha=null,this.viewRect&&(this.viewFg=this.backend.ops.Reframe(this.chainTail(),this.viewRect),this.upscaler&&(this.viewAlpha=this.backend.ops.Reframe(this.upscaler.output,this.viewRect)))}setEffectChain(e){this.effectChain=e,this.rebuildView(),this.compositors.clear()}runEffects(){for(let e of this.effectChain)e.run();this.viewFg?.run(),this.viewAlpha?.run()}run(){this.runModel(),this.runDisplay()}runDisplay(){this.refreshDisplayInput(),this.runEffects(),this.compositeMain("effect")}runFgPassthrough(){this.refreshDisplayInput(),this.runEffects(),this.compositeMain("fg")}runPassthrough(){this.refreshDisplayInput(),this.compositeMain("raw")}compositeMain(e){let r=e==="effect"?this.bgConfig:e==="fg"?{mode:"fg-passthrough"}:{mode:"passthrough"};this.compositeTo("main",r)}refreshDisplayInput(){this.displayDirty&&(this.displayInput.run(),this.displayDirty=!1)}compositeTo(e,r){let t=this.compositors.get(e);if(t&&ti(t.spec,r)){t.handle.run();return}let a=this.buildCompositor(e,r);this.compositors.set(e,{spec:r,handle:a}),a.run()}applyAlpha(e){if(!this.network||!this.upscaler)throw new Error("RenderOp.applyAlpha called before attachNetwork");this.backend.copyTensor(e,this.network.output),this.upscaler.run()}runModel(){if(!this.network||!this.networkInput||!this.upscaler)throw new Error("RenderOp.runModel called before attachNetwork");this.networkInput.run(),this.network.run(),this.upscaler.run()}makeUpscaler(){if(!this.network)throw new Error("makeUpscaler called with no network");let{backend:e,network:r,image:t}=this;return this.upscalerMode==="bicubic"?new be(e,r.output,t.h,t.w):new _e(e,r.output,t.h,t.w)}buildCompositor(e,r){let{backend:t,image:a}=this;if(r.mode==="passthrough")return t.presenters.CompositePassthrough(a,e);let o=this.fgImage();if(r.mode==="fg-passthrough")return t.presenters.CompositePassthrough(o,e);if(!this.upscaler)throw new Error("RenderOp.compositeTo (effect spec) called before attachNetwork");let n=this.alphaImage();switch(r.mode){case"solid":return new ve(t,o,n,r.color,e);case"image":return new xe(t,o,n,r.image,e);case"blur":return new we(t,o,n,r.sigma,e)}}};function ti(u,e){if(u.mode!==e.mode)return!1;switch(e.mode){case"passthrough":return!0;case"fg-passthrough":return!0;case"solid":{let r=u.color;return r[0]===e.color[0]&&r[1]===e.color[1]&&r[2]===e.color[2]}case"blur":return u.sigma===e.sigma;case"image":return u.image===e.image}}var ri=u=>typeof u=="object"&&u!==null&&typeof u.offset=="number"&&typeof u.length=="number";function ur(u){if(u.byteLength<4)throw new Error("weights buffer too small");let e=new DataView(u,0,4).getUint32(0,!0),r=4+e;if(u.byteLength<r)throw new Error("weights buffer truncated (header)");let t=new Uint8Array(u,4,e),a=JSON.parse(new TextDecoder().decode(t)),o=a.__dtype__??"f32",n=o==="f16"?2:4;if(r%n!==0)throw new Error(\`payload not \${n}-byte aligned (header=\${e})\`);let s=(u.byteLength-r)/n,p=c=>{if(ri(c)){let{offset:l,length:f}=c;if(l+f>s)throw new Error(\`array ref out of range: offset=\${l} length=\${f}\`);let d=r+l*n;return o==="f16"?new Uint16Array(u,d,f):new Float32Array(u,d,f)}if(Array.isArray(c))return c.map(p);if(typeof c=="object"&&c!==null){let l={};for(let f of Object.keys(c))f!=="__dtype__"&&(l[f]=p(c[f]));return l}return c};return p(a)}function _r(u,e,r,t){let a=t.variant,o=a==="E"||a==="D",n=a==="D",s=e.h,p=e.w,c=[],l=null,f=null,d=0,_=0,b;if(o)if(n){if(!r.down2)throw new Error("variant D requires w.down2");d=Math.round(s/1.25),_=Math.round(p/1.25);let x=u.ops.Conv2d(e,r.down1,{outChannels:t.cHigh,kernel:3,stride:1,padding:1,activation:"relu"});c.push(x),f=x.output;let v=u.ops.BilinearUpsample(f,{outH:d,outW:_});c.push(v),l=v.output;let y=u.ops.DownAdapter(l,r.down2,r.adapter,{stride:2});c.push(y),b=y.output}else{if(!r.down2)throw new Error("variant E requires w.down2");let x=u.ops.Conv2d(e,r.down1,{outChannels:t.cHigh,kernel:3,stride:2,padding:1,activation:"relu"});c.push(x),l=x.output,d=l.h,_=l.w;let v=u.ops.DownAdapter(l,r.down2,r.adapter,{stride:2});c.push(v),b=v.output}else{let x=a==="A"?2:3,v=u.ops.DownAdapter(e,r.down1,r.adapter,{stride:x});c.push(v),b=v.output}return{steps:c,adapted:b,d1:l,dFull:f,midH:d,midW:_}}function br(u,e,r,t,a,o,n,s,p){let c=p.variant,l=c==="E"||c==="D",f=c==="D",d=[],_=u.ops.ConvExpand(r,s.expandFeat);d.push(_);let b=_.output,x;if(l){if(!s.up1Combine)throw new Error("two-stage variant requires w.up1Combine");let y=u.ops.BilinearUpsample(b,{outH:o,outW:n});d.push(y);let W=u.ops.CatConv6to2(y.output,t,s.up1Combine);d.push(W);let B=u.ops.BilinearUpsample(W.output,{outH:e.h,outW:e.w});d.push(B),x=B.output}else{let y=u.ops.BilinearUpsample(b,{outH:e.h,outW:e.w});d.push(y),x=y.output}let v=f?u.ops.UpFinalSkip(x,a,e,s.upCombine):u.ops.UpFinal(x,e,s.upCombine);return d.push(v),{steps:d,alpha:v.output}}var Te=class{constructor(e,r,t,a,o,n){i(this,"inputs");i(this,"output");i(this,"encoderTaps");i(this,"halfTap");i(this,"steps");this.inputs=[r];let s=_r(e,r,a,o),p=new n(e,s.adapted,t),c=e.ops.BilinearUpsample(p.featLowRes,{outH:s.adapted.h,outW:s.adapted.w}),l=br(e,r,c.output,s.d1,s.dFull,s.midH,s.midW,a,o);this.steps=[...s.steps,p,c,...l.steps],this.output=l.alpha,this.encoderTaps=p.encoderTaps,this.halfTap=p.halfTap}run(){for(let e of this.steps)e.run()}};var oi=[5,5,3,3],ai=[2,2,1,1];function Pe(u,e,r,t){if(e.h===r.h&&e.w===r.w)return e;let a=u.ops.Crop(e,{outH:r.h,outW:r.w});return t.push(a),a.output}var Ce=class{constructor(e,r,t,a,o,n=16,s={}){i(this,"inputs");i(this,"output");i(this,"steps");this.inputs=[r,t,...a,...s.halfTap?[s.halfTap]:[]];let p=[],c=e.ops.ChannelConcat(r,t);p.push(c);let l=e.ops.Conv2d(c.output,o.stem,{outChannels:n,kernel:7,stride:2,padding:3,activation:"relu6"});p.push(l);let f=[],d=l.output;if(s.fuseStem&&s.halfTap){let v=Pe(e,s.halfTap,l.output,p),y=e.ops.ChannelConcat(l.output,v);p.push(y),f.push(y.output),d=y.output}for(let v=0;v<a.length;v++){let y=e.ops.Conv2d(d,o.stages[v],{outChannels:n,kernel:oi[v],stride:2,padding:ai[v],activation:"relu6"});p.push(y);let W=Pe(e,a[v],y.output,p),B=e.ops.ChannelConcat(y.output,W);p.push(B),f.push(B.output),d=B.output}let _=e.ops.Conv2d(f[f.length-1],o.predictBot,{outChannels:4,kernel:3,stride:1,padding:1,activation:"none"});p.push(_);let b=_.output,x=f[f.length-1];for(let v=0;v<f.length-1;v++){let y=f.length-2-v,W=e.ops.BilinearUpsample(x,{outH:x.h*2,outW:x.w*2}),B=e.ops.Conv2d(W.output,o.deconv[v],{outChannels:n,kernel:3,stride:1,padding:1,activation:"relu6"}),M=e.ops.BilinearUpsample(b,{outH:b.h*2,outW:b.w*2});p.push(W,B,M);let T=Pe(e,B.output,f[y],p),F=Pe(e,M.output,f[y],p),D=e.ops.ChannelConcat(f[y],T),E=e.ops.ChannelConcat(D.output,F);p.push(D,E);let R=e.ops.Conv2d(E.output,o.predict[v],{outChannels:4,kernel:3,stride:1,padding:1,activation:"none"});p.push(R),b=R.output,x=E.output}this.output=b,this.steps=p}run(){for(let e of this.steps)e.run()}};var I=class{constructor(e,r,t,a,o){i(this,"inputs");i(this,"output");i(this,"upOp");i(this,"concatConvOp");i(this,"conv2Op");this.inputs=[r,t],this.upOp=e.ops.BilinearUpsample(r,{outH:t.h,outW:t.w}),this.concatConvOp=e.ops.ConcatConv2d(this.upOp.output,t,a.conv1,{outChannels:o.outChannels}),this.conv2Op=e.ops.Conv2d(this.concatConvOp.output,a.conv2,{outChannels:o.outChannels,kernel:3,stride:1,padding:1,activation:"relu6"}),this.output=this.conv2Op.output}run(){this.upOp.run(),this.concatConvOp.run(),this.conv2Op.run()}};var ii=64,si=48,ni=32,ui=8,We=class{constructor(e,r,t){i(this,"inputs");i(this,"output");i(this,"steps");if(r.length<3)throw new Error(\`FaceHeatmapNet: needs \\u22653 encoder taps, got \${r.length}\`);let a=r[r.length-1],o=r[r.length-2],n=r[r.length-3];this.inputs=[a,o,n];let s=[],p=e.ops.Conv2d(a,t.proj,{outChannels:ii,kernel:1,stride:1,padding:0,activation:"relu6"});s.push(p);let c=new I(e,p.output,o,t.block1,{outChannels:si}),l=new I(e,c.output,n,t.block2,{outChannels:ni});s.push(c,l);let f=e.ops.Conv2d(l.output,t.out,{outChannels:ui,kernel:1,stride:1,padding:0,activation:"none"}),d=e.ops.Sigmoid(f.output);s.push(f,d),this.output=d.output,this.steps=s}run(){for(let e of this.steps)e.run()}};var le=[{c:12,stride:2},{c:12,stride:1},{c:24,stride:2},{c:24,stride:1},{c:48,stride:2},{c:48,stride:1},{c:48,stride:1},{c:64,stride:2},{c:64,stride:1},{c:96,stride:2}],pi=32,ci=478,li=ci*2,Ge=class{constructor(e,r,t){i(this,"inputs");i(this,"output");i(this,"steps");if(t.blocks.length!==le.length)throw new Error(\`LandmarkNet: expected \${le.length} block weights, got \${t.blocks.length}\`);this.inputs=[r];let a=[],o=e.ops.Conv2d(r,t.stem,{outChannels:8,kernel:3,stride:2,padding:1,activation:"relu6"});a.push(o);let n=o.output;for(let c=0;c<le.length;c++){let l=e.ops.Conv2d(n,t.blocks[c],{outChannels:le[c].c,kernel:3,stride:le[c].stride,padding:1,activation:"relu6"});a.push(l),n=l.output}let s=e.ops.Conv2d(n,t.headConv,{outChannels:pi,kernel:1,stride:1,padding:0,activation:"relu6"});a.push(s);let p=e.ops.Conv2d(s.output,t.fc,{outChannels:li,kernel:s.output.h,stride:1,padding:0,activation:"none"});a.push(p),this.output=p.output,this.steps=a}run(){for(let e of this.steps)e.run()}};var Q=class{constructor(e,r,t,a){i(this,"inputs");i(this,"output");i(this,"dwOp");i(this,"pwOp");this.inputs=[r],this.dwOp=e.ops.DepthwiseConv2d(r,t.dw,{kernel:a.kernel,stride:a.stride,padding:a.padding,activation:"relu6"}),this.pwOp=e.ops.Conv2d(this.dwOp.output,t.pw,{outChannels:a.outChannels,kernel:1,stride:1,padding:0,activation:"none"}),this.output=this.pwOp.output}run(){this.dwOp.run(),this.pwOp.run()}};var k=class{constructor(e,r,t,a){i(this,"inputs");i(this,"output");i(this,"expandOp");i(this,"dwOp");i(this,"projOp");this.inputs=[r];let o=a.midChannels!==a.inChannels,n=a.stride===1&&a.inChannels===a.outChannels;this.expandOp=o?e.ops.Conv2d(r,t.expand,{outChannels:a.midChannels,kernel:1,stride:1,padding:0,activation:"relu6"}):null;let s=this.expandOp?this.expandOp.output:r;this.dwOp=e.ops.DepthwiseConv2d(s,t.dw,{kernel:a.kernel,stride:a.stride,padding:a.padding,activation:"relu6"}),this.projOp=n?e.ops.ProjResidual(this.dwOp.output,r,t.proj,{outChannels:a.outChannels}):e.ops.Conv2d(this.dwOp.output,t.proj,{outChannels:a.outChannels,kernel:1,stride:1,padding:0,activation:"none"}),this.output=this.projOp.output}run(){this.expandOp?.run(),this.dwOp.run(),this.projOp.run()}};var Ue=class{constructor(e,r,t){i(this,"output");i(this,"featLowRes");i(this,"encoderTaps");i(this,"halfTap");i(this,"stem");i(this,"s0");i(this,"s1b0");i(this,"s1b1");i(this,"s2b0");i(this,"s2b1");i(this,"s3b0");i(this,"s3b1");i(this,"s3b2");i(this,"s4b0");i(this,"s4b1");i(this,"s4b2");i(this,"bottleneck");i(this,"dec0");i(this,"dec1");i(this,"finalUp");i(this,"outConv");i(this,"alpha");this.stem=e.ops.Conv2d(r,t.encoder.stem,{outChannels:32,kernel:3,stride:2,padding:"same",activation:"relu6"}),this.s0=new Q(e,this.stem.output,t.encoder.s0,{outChannels:16,kernel:3,stride:1,padding:1}),this.s1b0=new k(e,this.s0.output,t.encoder.s1[0],{inChannels:16,midChannels:96,outChannels:24,kernel:3,stride:2,padding:"same"}),this.s1b1=new k(e,this.s1b0.output,t.encoder.s1[1],{inChannels:24,midChannels:144,outChannels:24,kernel:3,stride:1,padding:1}),this.s2b0=new k(e,this.s1b1.output,t.encoder.s2[0],{inChannels:24,midChannels:144,outChannels:40,kernel:5,stride:2,padding:"same"}),this.s2b1=new k(e,this.s2b0.output,t.encoder.s2[1],{inChannels:40,midChannels:240,outChannels:40,kernel:5,stride:1,padding:2}),this.s3b0=new k(e,this.s2b1.output,t.encoder.s3[0],{inChannels:40,midChannels:240,outChannels:80,kernel:3,stride:2,padding:"same"}),this.s3b1=new k(e,this.s3b0.output,t.encoder.s3[1],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s3b2=new k(e,this.s3b1.output,t.encoder.s3[2],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s4b0=new k(e,this.s3b2.output,t.encoder.s4[0],{inChannels:80,midChannels:480,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b1=new k(e,this.s4b0.output,t.encoder.s4[1],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b2=new k(e,this.s4b1.output,t.encoder.s4[2],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.bottleneck=e.ops.Conv2d(this.s4b2.output,t.bottleneck,{outChannels:128,kernel:1,stride:1,padding:0,activation:"relu6"}),this.dec0=new I(e,this.bottleneck.output,this.s2b1.output,t.decoder.blocks[0],{outChannels:64}),this.dec1=new I(e,this.dec0.output,this.s1b1.output,t.decoder.blocks[1],{outChannels:32}),this.finalUp=e.ops.UpsampleConv1x1(this.dec1.output,t.decoder.finalUpsample,{outH:this.dec1.output.h*2,outW:this.dec1.output.w*2,outChannels:32,activation:"relu6"}),this.featLowRes=this.finalUp.output,this.encoderTaps=[this.s1b1.output,this.s2b1.output,this.s4b2.output],this.halfTap=this.s0.output,this.outConv=e.ops.Conv2d(this.finalUp.output,t.decoder.outputConv,{outChannels:4,kernel:1,stride:1,padding:0,activation:"none"}),this.alpha=e.ops.UpsampleSigmoid(this.outConv.output,{outH:this.outConv.output.h*2,outW:this.outConv.output.w*2}),this.output=this.alpha.output}run(){this.stem.run(),this.s0.run(),this.s1b0.run(),this.s1b1.run(),this.s2b0.run(),this.s2b1.run(),this.s3b0.run(),this.s3b1.run(),this.s3b2.run(),this.s4b0.run(),this.s4b1.run(),this.s4b2.run(),this.bottleneck.run(),this.dec0.run(),this.dec1.run(),this.finalUp.run(),this.outConv.run(),this.alpha.run()}};var Be=class{constructor(e,r,t){i(this,"output");i(this,"featLowRes");i(this,"encoderTaps");i(this,"stem");i(this,"s0");i(this,"s1b0");i(this,"s1b1");i(this,"s2b0");i(this,"s2b1");i(this,"s3b0");i(this,"s3b1");i(this,"s3b2");i(this,"s4b0");i(this,"s4b1");i(this,"s4b2");i(this,"s5b0");i(this,"s5b1");i(this,"s5b2");i(this,"s5b3");i(this,"s6b0");i(this,"bottleneck");i(this,"dec0");i(this,"dec1");i(this,"dec2");i(this,"finalUp");i(this,"outConv");i(this,"alpha");this.stem=e.ops.Conv2d(r,t.encoder.stem,{outChannels:32,kernel:3,stride:2,padding:"same",activation:"relu6"}),this.s0=new Q(e,this.stem.output,t.encoder.s0,{outChannels:16,kernel:3,stride:1,padding:1}),this.s1b0=new k(e,this.s0.output,t.encoder.s1[0],{inChannels:16,midChannels:96,outChannels:24,kernel:3,stride:2,padding:"same"}),this.s1b1=new k(e,this.s1b0.output,t.encoder.s1[1],{inChannels:24,midChannels:144,outChannels:24,kernel:3,stride:1,padding:1}),this.s2b0=new k(e,this.s1b1.output,t.encoder.s2[0],{inChannels:24,midChannels:144,outChannels:40,kernel:5,stride:2,padding:"same"}),this.s2b1=new k(e,this.s2b0.output,t.encoder.s2[1],{inChannels:40,midChannels:240,outChannels:40,kernel:5,stride:1,padding:2}),this.s3b0=new k(e,this.s2b1.output,t.encoder.s3[0],{inChannels:40,midChannels:240,outChannels:80,kernel:3,stride:2,padding:"same"}),this.s3b1=new k(e,this.s3b0.output,t.encoder.s3[1],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s3b2=new k(e,this.s3b1.output,t.encoder.s3[2],{inChannels:80,midChannels:480,outChannels:80,kernel:3,stride:1,padding:1}),this.s4b0=new k(e,this.s3b2.output,t.encoder.s4[0],{inChannels:80,midChannels:480,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b1=new k(e,this.s4b0.output,t.encoder.s4[1],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.s4b2=new k(e,this.s4b1.output,t.encoder.s4[2],{inChannels:112,midChannels:672,outChannels:112,kernel:5,stride:1,padding:2}),this.s5b0=new k(e,this.s4b2.output,t.encoder.s5[0],{inChannels:112,midChannels:672,outChannels:192,kernel:5,stride:2,padding:"same"}),this.s5b1=new k(e,this.s5b0.output,t.encoder.s5[1],{inChannels:192,midChannels:1152,outChannels:192,kernel:5,stride:1,padding:2}),this.s5b2=new k(e,this.s5b1.output,t.encoder.s5[2],{inChannels:192,midChannels:1152,outChannels:192,kernel:5,stride:1,padding:2}),this.s5b3=new k(e,this.s5b2.output,t.encoder.s5[3],{inChannels:192,midChannels:1152,outChannels:192,kernel:5,stride:1,padding:2}),this.s6b0=new k(e,this.s5b3.output,t.encoder.s6[0],{inChannels:192,midChannels:1152,outChannels:320,kernel:3,stride:1,padding:1}),this.bottleneck=e.ops.Conv2d(this.s6b0.output,t.bottleneck,{outChannels:128,kernel:1,stride:1,padding:0,activation:"relu6"}),this.dec0=new I(e,this.bottleneck.output,this.s4b2.output,t.decoder.blocks[0],{outChannels:64}),this.dec1=new I(e,this.dec0.output,this.s2b1.output,t.decoder.blocks[1],{outChannels:32}),this.dec2=new I(e,this.dec1.output,this.s1b1.output,t.decoder.blocks[2],{outChannels:16}),this.finalUp=e.ops.UpsampleConv1x1(this.dec2.output,t.decoder.finalUpsample,{outH:this.dec2.output.h*2,outW:this.dec2.output.w*2,outChannels:16,activation:"relu6"}),this.featLowRes=this.finalUp.output,this.encoderTaps=[this.s1b1.output,this.s2b1.output,this.s4b2.output,this.s6b0.output],this.outConv=e.ops.Conv2d(this.finalUp.output,t.decoder.outputConv,{outChannels:4,kernel:1,stride:1,padding:0,activation:"none"}),this.alpha=e.ops.UpsampleSigmoid(this.outConv.output,{outH:this.outConv.output.h*2,outW:this.outConv.output.w*2}),this.output=this.alpha.output}run(){this.stem.run(),this.s0.run(),this.s1b0.run(),this.s1b1.run(),this.s2b0.run(),this.s2b1.run(),this.s3b0.run(),this.s3b1.run(),this.s3b2.run(),this.s4b0.run(),this.s4b1.run(),this.s4b2.run(),this.s5b0.run(),this.s5b1.run(),this.s5b2.run(),this.s5b3.run(),this.s6b0.run(),this.bottleneck.run(),this.dec0.run(),this.dec1.run(),this.dec2.run(),this.finalUp.run(),this.outConv.run(),this.alpha.run()}};var pr=[[{in:24,mid:144,out:32,k:3,s:2},{in:32,mid:192,out:32,k:3,s:1},{in:32,mid:192,out:32,k:3,s:1}],[{in:32,mid:192,out:48,k:5,s:2},{in:48,mid:288,out:48,k:5,s:1},{in:48,mid:288,out:48,k:5,s:1}],[{in:48,mid:288,out:96,k:3,s:2},{in:96,mid:576,out:96,k:3,s:1},{in:96,mid:576,out:96,k:3,s:1},{in:96,mid:576,out:96,k:3,s:1},{in:96,mid:576,out:96,k:3,s:1}],[{in:96,mid:576,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1},{in:136,mid:816,out:136,k:5,s:1}],[{in:136,mid:816,out:232,k:5,s:2},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1},{in:232,mid:1392,out:232,k:5,s:1}],[{in:232,mid:1392,out:384,k:3,s:1}]],Se=class{constructor(e,r,t){i(this,"output");i(this,"featLowRes");i(this,"encoderTaps");i(this,"stem");i(this,"s0");i(this,"stages");i(this,"bottleneck");i(this,"dec0");i(this,"dec1");i(this,"dec2");i(this,"finalUp");i(this,"outConv");i(this,"alpha");this.stem=e.ops.Conv2d(r,t.encoder.stem,{outChannels:32,kernel:3,stride:2,padding:"same",activation:"relu6"}),this.s0=new Q(e,this.stem.output,t.encoder.s0,{outChannels:24,kernel:3,stride:1,padding:1});let a=[t.encoder.s1,t.encoder.s2,t.encoder.s3,t.encoder.s4,t.encoder.s5,t.encoder.s6];this.stages=[];let o=this.s0.output;for(let f=0;f<pr.length;f++){let d=[];for(let _=0;_<pr[f].length;_++){let b=pr[f][_],x=new k(e,o,a[f][_],{inChannels:b.in,midChannels:b.mid,outChannels:b.out,kernel:b.k,stride:b.s,padding:b.s===2?"same":(b.k-1)/2});d.push(x),o=x.output}this.stages.push(d)}let n=f=>this.stages[f][this.stages[f].length-1].output,s=n(0),p=n(1),c=n(3),l=n(5);this.bottleneck=e.ops.Conv2d(l,t.bottleneck,{outChannels:256,kernel:1,stride:1,padding:0,activation:"relu6"}),this.dec0=new I(e,this.bottleneck.output,c,t.decoder.blocks[0],{outChannels:128}),this.dec1=new I(e,this.dec0.output,p,t.decoder.blocks[1],{outChannels:64}),this.dec2=new I(e,this.dec1.output,s,t.decoder.blocks[2],{outChannels:32}),this.finalUp=e.ops.UpsampleConv1x1(this.dec2.output,t.decoder.finalUpsample,{outH:this.dec2.output.h*2,outW:this.dec2.output.w*2,outChannels:32,activation:"relu6"}),this.featLowRes=this.finalUp.output,this.encoderTaps=[s,p,c,l],this.outConv=e.ops.Conv2d(this.finalUp.output,t.decoder.outputConv,{outChannels:4,kernel:1,stride:1,padding:0,activation:"none"}),this.alpha=e.ops.UpsampleSigmoid(this.outConv.output,{outH:this.outConv.output.h*2,outW:this.outConv.output.w*2}),this.output=this.alpha.output}run(){this.stem.run(),this.s0.run();for(let e of this.stages)for(let r of e)r.run();this.bottleneck.run(),this.dec0.run(),this.dec1.run(),this.dec2.run(),this.finalUp.run(),this.outConv.run(),this.alpha.run()}};var vr=Ue,xr=Be,fi=Se,J={xs:{base:vr,wrapper:{variant:"B",cHigh:4,cLow:4,cUp:2},canvasRes:{w:384,h:240},baseRes:{w:128,h:80},flowFuseStem:!0},small:{base:vr,wrapper:{variant:"A",cHigh:4,cLow:4,cUp:2},canvasRes:{w:384,h:224},baseRes:{w:192,h:112}},medium:{base:xr,wrapper:{variant:"A",cHigh:4,cLow:4,cUp:2},canvasRes:{w:512,h:320},baseRes:{w:256,h:160}},large:{base:xr,wrapper:{variant:"D",cHigh:4,cLow:4,cUp:2},canvasRes:{w:640,h:400},baseRes:{w:256,h:160}},xl:{base:fi,wrapper:{variant:"E",cHigh:4,cLow:4,cUp:2},canvasRes:{w:1280,h:768},baseRes:{w:320,h:192}}};var cr={zoom:1.35,gravity:.5,margin:.04},di={deadband:.09,ease:.07},yr=0,wr=1,mi=2,hi=16,gi={tLo:.15,tHi:2.5,leak:.15,release:.9,tDiv:1,divScale:2},kr=256,_i=[.485,.456,.406],bi=[.229,.224,.225],vi={win:3,thresh:.15,boxScale:2.4},xi=new Set(["medium","large","xl"]),yi=4,wi=.6,ki={webgpu:6,webgl:30},Ti=15,Pi=5,Tr=1e3,Ae=class{constructor(e){i(this,"canvas");i(this,"backend");i(this,"backendKind");i(this,"topology");i(this,"preset",null);i(this,"enabled");i(this,"currentBackground");i(this,"modelTimingCounter",0);i(this,"renderOp");i(this,"flow",null);i(this,"faceChain",null);i(this,"faceCfg",null);i(this,"reframe",null);i(this,"reframeCfg",null);i(this,"reframeSolveOnce",!1);i(this,"faceLive",0);i(this,"faceProbePending",!1);i(this,"faceProbeCounter",0);i(this,"tier",null);i(this,"tierInput",null);i(this,"lastTierWeights",null);i(this,"bgImageInputs",new Map);i(this,"bgVideoInputs",new Map);i(this,"bgVideoPorts",new Map);i(this,"previewCanvas",null);i(this,"previewCtx",null);i(this,"previewBg",null);i(this,"previewEffectSpec",null);i(this,"previewIntervalMs",1e3/Ti);i(this,"lastPreviewAt",0);i(this,"skipCounter",0);i(this,"framesRenderedAt",[]);i(this,"modelRunSamples",[]);i(this,"displayRunSamples",[]);i(this,"skippedCount",0);this.backend=e.backend,this.backendKind=e.backendKind,this.canvas=e.canvas,this.enabled=e.enabled,this.currentBackground=e.background,this.topology=e.topology,this.renderOp=new ke(this.backend)}process(e){this.renderOp.setSource(e);let r=performance.now(),t=this.renderOp.hasNetwork(),a=this.enabled&&t&&this.faceChain!==null,o=this.enabled&&t&&this.currentBackground.kind!=="none",n=o||a,s=this.isPreviewTick(r),p=s&&t&&this.previewBg!==null&&this.previewBg.kind!=="none",c=!1;n&&this.flow?c=this.stepFlow():n&&(this.shouldRunModel()?(this.runModelOnce(),c=!0):this.skippedCount++),!c&&p&&(this.runModelOnce(),c=!0),a&&this.stepFace(c);let l=performance.now();s&&this.previewCanvas?(this.backendKind==="webgl"?this.compositePreviewWebGL(o,p,a):(this.compositeMain(o,a),this.renderOp.compositeTo("preview",this.previewSpec(p))),this.lastPreviewAt=r):this.compositeMain(o,a),this.displayRunSamples.push({ts:performance.now(),ms:performance.now()-l}),this.trimSamples(this.displayRunSamples),this.framesRenderedAt.push(performance.now()),this.trim(this.framesRenderedAt)}compositeMain(e,r){e?this.renderOp.runDisplay():r?this.renderOp.runFgPassthrough():this.renderOp.runPassthrough()}compositePreviewWebGL(e,r,t){this.renderOp.refreshDisplayInput(),this.renderOp.runEffects(),this.renderOp.compositeTo("preview",this.previewSpec(r));let a=this.canvas.transferToImageBitmap();this.previewCtx.transferFromImageBitmap(a),this.renderOp.compositeMain(e?"effect":t?"fg":"raw")}previewSpec(e){return e&&this.previewEffectSpec?this.previewEffectSpec:{mode:"passthrough"}}runModelOnce(){let e=performance.now();this.renderOp.runModel(),this.backendKind==="webgpu"&&this.modelTimingCounter%Pi===0&&this.backend.sync().then(()=>{this.modelRunSamples.push({ts:performance.now(),ms:performance.now()-e}),this.trimSamples(this.modelRunSamples)}).catch(()=>{}),this.modelTimingCounter++}stepFlow(){let e=this.flow,r=!1;return e.networkInput.run(),e.curBaseDown.run(),e.everyFrame?(e.net.run(),e.up.run(),this.runModelOnce(),r=!0,this.backend.copyTensor(e.curBaseDown.output,e.frameAHeld),this.backend.copyTensor(e.tier.output,e.predBuf)):this.shouldRunModel()?(this.runModelOnce(),r=!0,this.backend.copyTensor(e.curBaseDown.output,e.frameAHeld),this.backend.copyTensor(e.tier.output,e.alphaHeld),this.backend.copyTensor(e.tier.output,e.predBuf)):(this.skippedCount++,e.net.run(),e.up.run(),e.predWarp.run(),this.backend.copyTensor(e.predWarp.output,e.predBuf)),e.warm?(e.refWarp.run(),e.stab.run(),this.backend.copyTensor(e.stab.output,e.stabPrev),this.renderOp.applyAlpha(e.stab.output),r):(this.backend.copyTensor(e.tier.output,e.stabPrev),e.warm=r,r)}stepFace(e){let r=this.faceChain;if(e?(r.face.run(),this.backend.copyTensor(r.face.output,r.hmBuf),r.hmHeld&&this.backend.copyTensor(r.face.output,r.hmHeld)):r.hmWarp&&this.flow&&(r.hmFlowDown.run(),r.hmWarp.run(),this.backend.copyTensor(r.hmWarp.output,r.hmBuf)),r.boxOp.run(),this.backend.copyTensor(r.boxOp.output,r.boxStable),r.stage){this.probeFaceOccupancy(r);let t=r.crops.length===1?1:this.faceLive;for(let a=0;a<t;a++)r.crops[a].run(),r.lms[a].run();if(t>0)for(let a of r.packLm)a.run();r.stage.setActiveSlots(t)}if(this.reframe){let t=this.reframe,a=t.auto?t.cmdAuto:this.reframeSolveOnce?t.cmdSolve:t.cmdHold;this.backend.copyTensor(a,t.cmd),this.reframeSolveOnce=!1,t.stateOp.run(),this.backend.copyTensor(t.stateOp.output,t.state)}}buildReframe(){this.reframe=null,this.renderOp.setViewTransform(null);let e=this.faceChain,r=this.reframeCfg;if(!r||!e||!this.preset)return;let t=J[this.preset.model].canvasRes,a=r.auto??!0,o=a!==!1,n={...di,...typeof a=="object"?a:{}},s=f=>this.backend.tensor(1,1,4,new Float32Array(f)),p=this.backend.tensor(1,1,8,new Float32Array(8)),c=s([o?yr:wr,0,0,0]),l=this.backend.ops.ReframeState(e.boxStable,p,c,{zoom:r.zoom??cr.zoom,gravity:r.gravity??cr.gravity,margin:r.margin??cr.margin,deadband:n.deadband,ease:n.ease,aspect:t.w/t.h});this.reframe={stateOp:l,state:p,cmd:c,auto:o,cmdAuto:s([yr,0,0,0]),cmdHold:s([wr,0,0,0]),cmdSolve:s([mi,0,0,0])},this.renderOp.setViewTransform(p)}probeFaceOccupancy(e){let r=e.crops.length;if(r===1)return;let t=ki[this.backendKind];this.faceProbePending||this.faceProbeCounter++%t!==0||(this.faceProbePending=!0,this.backend.readback(e.boxStable).then(a=>{let o=0;for(;o<r&&a[o*4+3]>0;)o++;this.faceLive=o,this.faceProbePending=!1}).catch(()=>{this.faceProbePending=!1}))}isPreviewTick(e){return!this.previewCanvas||this.previewBg===null||!this.enabled?!1:e-this.lastPreviewAt>=this.previewIntervalMs}shouldRunModel(){return this.skipCounter===0?(this.skipCounter=this.preset?.skipFrames??0,!0):(this.skipCounter--,!1)}setBackground(e){this.currentBackground=e,this.renderOp.setBackground(this.translateBackgroundFor("main",e))}setEnabled(e){this.enabled=e}attachPreview(e){if(e.width=this.canvas.width,e.height=this.canvas.height,this.previewCanvas=e,this.backendKind==="webgpu")this.backend.attachCanvas("preview",e);else{let r=e.getContext("bitmaprenderer");if(!r)throw new Error("renderer: failed to get bitmaprenderer context for preview canvas");this.previewCtx=r}}setPreview(e,r){this.previewBg=e,this.previewEffectSpec=e.kind==="none"?null:this.translateBackgroundFor("preview",e),r?.fps&&r.fps>0&&(this.previewIntervalMs=1e3/r.fps),this.lastPreviewAt=0}clearPreview(){this.previewBg=null,this.previewEffectSpec=null;let e=this.bgVideoPorts.get("preview");e&&(e.close(),this.bgVideoPorts.delete("preview"))}setPreset(e,r){let t=J[e.model];if(!t)throw new Error(\`renderer: no TIER_CONFIG entry for model '\${e.model}'\`);let a=ur(r),o=this.backend.ops.Input(t.canvasRes.h,t.canvasRes.w),n=new Te(this.backend,o.output,a.base,a.wrapper,t.wrapper,t.base);if(this.renderOp.attachNetwork(n,o,{upscaler:"bilinear",background:this.translateBackgroundFor("main",this.currentBackground)}),this.flow=null,a.flow){let s=t.baseRes,p=t.canvasRes,c=e.skipFrames===0,l=(E,R)=>this.backend.tensor(E,R,4,new Float32Array(E*R*4)),f=this.backend.ops.BilinearUpsample(o.output,{outH:s.h,outW:s.w}),d=l(s.h,s.w),_=new Ce(this.backend,d,f.output,n.encoderTaps,a.flow,hi,t.flowFuseStem?{fuseStem:!0,halfTap:n.halfTap}:{}),b=this.backend.ops.BilinearUpsample(_.output,{outH:p.h,outW:p.w}),x=p.w/s.w,v=l(p.h,p.w),y=l(p.h,p.w),W=this.backend.ops.Warp(y,b.output,{flowScale:x}),B=Math.max(1,Math.round(p.w/_.output.w)),M=Math.max(1,Math.round(p.h/_.output.h)),T=this.backend.ops.Stabilize(b.output,v,W.output,y,{...gi,stepX:B,stepY:M}),F=c?null:l(p.h,p.w),D=F?this.backend.ops.Warp(F,b.output,{flowScale:x}):null;this.flow={tier:n,everyFrame:c,warm:!1,networkInput:o,curBaseDown:f,frameAHeld:d,net:_,up:b,predBuf:v,stabPrev:y,refWarp:W,stab:T,alphaHeld:F,predWarp:D}}this.preset=e,this.skipCounter=0,this.tier=n,this.tierInput=o,this.lastTierWeights=a,this.buildFaceChain()}setFaceEffects(e){this.faceCfg=e,this.preset&&this.buildFaceChain()}setReframe(e){this.reframeCfg=e,this.preset&&this.buildFaceChain()}reframeNow(){this.reframeSolveOnce=!0}buildFaceChain(){this.faceChain=null,this.reframe=null,this.renderOp.setEffectChain([]),this.renderOp.setViewTransform(null);let e=this.faceCfg,r=this.lastTierWeights;if(!e&&!this.reframeCfg||!this.tier||!this.tierInput||!this.preset)return;if(!r?.face){console.warn(\`[longpipe/renderer] face effects configured but the '\${this.preset.model}' weights have no face blob \\u2014 disabled. Re-export the tier with a face-trained checkpoint.\`);return}let t=new We(this.backend,this.tier.encoderTaps,r.face),a=t.output,o=(T,F,D)=>this.backend.tensor(T,F,D,new Float32Array(T*F*D)),n=o(a.h,a.w,a.c),s=null,p=null,c=null;if(this.flow&&(this.preset.skipFrames??0)>0){let T=J[this.preset.model].baseRes.w;s=o(a.h,a.w,a.c),p=this.backend.ops.BilinearUpsample(this.flow.net.output,{outH:a.h,outW:a.w}),c=this.backend.ops.Warp(s,p.output,{flowScale:a.w/T})}let l=xi.has(this.preset.model)?yi:1,f={...vi,...e?.box??{}},d=l>1?this.backend.ops.FaceBoxesFromHeatmaps(n,{...f,maxFaces:l,tol:wi}):this.backend.ops.FaceBoxFromHeatmaps(n,f),_=o(1,l,4);if(!e){this.faceChain={face:t,hmBuf:n,hmHeld:s,hmFlowDown:p,hmWarp:c,boxOp:d,boxStable:_,crops:[],lms:[],packLm:[],stage:null},this.buildReframe();return}let b=ur(e.landmarkWeights),x=this.tierInput.output,v=Array.from({length:l},(T,F)=>this.backend.ops.CropResample(x,_,{outH:kr,outW:kr,mean:_i,std:bi,slot:F})),y=v.map(T=>new Ge(this.backend,T.output,b)),W=[],B=y[0].output;if(l>1){let T=y.map(F=>F.output);for(;T.length>1;){let F=[];for(let D=0;D<T.length;D+=2){let E=this.backend.ops.ChannelConcat(T[D],T[D+1]);W.push(E),F.push(E.output)}T=F}B=T[0]}let M=this.backend.ops.FaceTouchupStage(this.renderOp.displayImage,B,_,e.topology,{...e.touchup,slots:l});this.renderOp.setEffectChain([M]),this.faceLive=l,this.faceProbeCounter=0,this.faceChain={face:t,hmBuf:n,hmHeld:s,hmFlowDown:p,hmWarp:c,boxOp:d,boxStable:_,crops:v,lms:y,packLm:W,stage:M},this.buildReframe()}destroy(){for(let e of this.bgVideoPorts.values())e.close();this.bgVideoPorts.clear(),this.backend.destroy()}getStats(){let e=performance.now();return this.trimRecent(this.framesRenderedAt,e),this.trimSamplesAt(this.modelRunSamples,e),this.trimSamplesAt(this.displayRunSamples,e),{fps:this.framesRenderedAt.length,modelFps:this.modelRunSamples.length,modelMs:Pr(this.modelRunSamples.map(r=>r.ms)),displayMs:Pr(this.displayRunSamples.map(r=>r.ms)),skipped:this.skippedCount,preset:this.preset?.model??"boot",skipFrames:this.preset?.skipFrames??0,enabled:this.enabled,inputPath:this.topology.input,outputPath:this.topology.output}}translateBackgroundFor(e,r){let t=this.bgVideoPorts.get(e);switch(r.kind!=="video"&&t&&(t.close(),this.bgVideoPorts.delete(e)),r.kind){case"none":return{mode:"solid",color:[0,0,0]};case"color":return{mode:"solid",color:r.rgb};case"blur":return{mode:"blur",sigma:r.sigma};case"image":{let a=this.bgInputFor(this.bgImageInputs,e);return a.setSource(r.bitmap),a.run(),{mode:"image",image:a.output}}case"video":{let a=this.bgInputFor(this.bgVideoInputs,e);return t&&t.close(),this.bgVideoPorts.set(e,r.port),r.port.onmessage=o=>{let n=o.data.frame;try{a.setSource(n),a.run()}finally{n.close()}},r.port.start?.(),{mode:"image",image:a.output}}}}bgInputFor(e,r){let t=e.get(r);return t||(t=this.backend.ops.Input(this.canvas.height,this.canvas.width),e.set(r,t)),t}trim(e){e.length>240&&e.splice(0,e.length-240)}trimSamples(e){e.length>240&&e.splice(0,e.length-240)}trimRecent(e,r){let t=r-Tr,a=0;for(;a<e.length&&e[a]<t;)a++;a>0&&e.splice(0,a)}trimSamplesAt(e,r){let t=r-Tr,a=0;for(;a<e.length&&e[a].ts<t;)a++;a>0&&e.splice(0,a)}};function Pr(u){if(u.length===0)return 0;let e=u.slice().sort((t,a)=>t-a),r=e.length>>1;return e.length%2?e[r]:(e[r-1]+e[r])/2}var oe=new Float32Array(1),fe=new Uint32Array(oe.buffer);function Ci(u){oe[0]=u;let e=fe[0],r=e>>>16&32768,t=e&2147483647,a=(t>>>23)-127+15;if((e&2139095040)===2139095040)return(e&8388607)!==0?r|32256:r|31744;if(a>=31)return r|31744;if(a<=0){if(a<-10)return r;let c=t&8388607|8388608,l=14-a,f=c>>>l,d=c>>>l-1&1,_=(c&(1<<l-1)-1)!==0?1:0;return d&&(_||f&1)&&(f+=1),r|f}let o=t>>>13&1023,n=t>>>12&1,s=(t&4095)!==0?1:0,p=a<<10|o;return n&&(s||o&1)&&(p+=1,(p>>>10&31)===31)?r|31744:r|p}function lr(u){let e=(u&32768)<<16,r=(u&31744)>>>10,t=u&1023;if(r===0){if(t===0)return fe[0]=e,oe[0];let a=t,o=1;for(;(a&1024)===0;)a<<=1,o-=1;return a&=1023,fe[0]=e|o+127-15<<23|a<<13,oe[0]}return r===31?(fe[0]=e|2139095040|t<<13,oe[0]):(fe[0]=e|r+127-15<<23|t<<13,oe[0])}function Le(u){let e=new Uint16Array(u.length);for(let r=0;r<u.length;r++)e[r]=Ci(u[r]);return e}function ae(u){let e=new Float32Array(u.length);for(let r=0;r<u.length;r++)e[r]=lr(u[r]);return e}var h=class{constructor(e){i(this,"backend",e);i(this,"shader","");i(this,"pipeline");i(this,"bindGroup");i(this,"uniformDefs",[]);i(this,"uniformBuffers",{})}createUniform(e,r){this.uniformDefs.push({name:e,type:r})}setUniform(e,r){let t=this.backend.device.createBuffer({size:r.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:!0});r instanceof Uint32Array?new Uint32Array(t.getMappedRange()).set(r):new Float32Array(t.getMappedRange()).set(r),t.unmap(),this.uniformBuffers[e]=t}defaultBindGroup(){let e=[],r=0;for(let t of this.inputs)e.push({binding:r++,resource:{buffer:t.buffer}});for(let t of this.weights)e.push({binding:r++,resource:{buffer:t.buffer}});for(let t of this.uniformDefs)e.push({binding:r++,resource:{buffer:this.uniformBuffers[t.name]}});return e.push({binding:r,resource:{buffer:this.output.buffer}}),this.backend.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:e})}defaultSetup(){let e=this.backend.device.createShaderModule({code:this.shader});this.pipeline=this.backend.device.createComputePipeline({layout:"auto",compute:{module:e,entryPoint:"main"}}),this.bindGroup=this.defaultBindGroup()}run(){let e=this.backend.device.createCommandEncoder(),r=e.beginComputePass();r.setPipeline(this.pipeline),r.setBindGroup(0,this.bindGroup),r.dispatchWorkgroups(...this.dispatch),r.end(),this.backend.device.queue.submit([e.finish()])}};var Cr=\`// Conv2d, output-channel-blocked (K=2) \\u2014 drop-in replacement for conv2d.wgsl.
33
2
  //
34
3
  // Identical math, layout, and output to conv2d.wgsl, but each thread computes 2
35
4
  // output channel-groups (8 channels) for one pixel, loading each input vec4 ONCE
@@ -7037,5 +7006,4 @@ const vec2 VERTS[6] = vec2[6](
7037
7006
  vec2(-1.0,1.0), vec2(1.0,-1.0), vec2(1.0,1.0)
7038
7007
  );
7039
7008
  void main() { gl_Position = vec4(VERTS[gl_VertexID], 0.0, 1.0); }\`,ar=class{constructor(e,r,t){i(this,"backend",e);i(this,"output");i(this,"gl");i(this,"program");i(this,"srcTex");i(this,"uOutW");i(this,"uOutH");i(this,"uSrc");i(this,"source",null);let a=e.gl;this.gl=a,this.output=e.tensor(r,t,4),this.srcTex=a.createTexture(),a.bindTexture(a.TEXTURE_2D,this.srcTex),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MIN_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_MAG_FILTER,a.LINEAR),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_S,a.CLAMP_TO_EDGE),a.texParameteri(a.TEXTURE_2D,a.TEXTURE_WRAP_T,a.CLAMP_TO_EDGE);let o=a.createShader(a.VERTEX_SHADER);a.shaderSource(o,Kn),a.compileShader(o);let n=a.createShader(a.FRAGMENT_SHADER);if(a.shaderSource(n,Da),a.compileShader(n),!a.getShaderParameter(n,a.COMPILE_STATUS))throw new Error(\`Input GLSL compile error: \${a.getShaderInfoLog(n)}\`);if(this.program=a.createProgram(),a.attachShader(this.program,o),a.attachShader(this.program,n),a.linkProgram(this.program),!a.getProgramParameter(this.program,a.LINK_STATUS))throw new Error(\`Input GLSL link error: \${a.getProgramInfoLog(this.program)}\`);this.uSrc=a.getUniformLocation(this.program,"u_src"),this.uOutW=a.getUniformLocation(this.program,"u_out_w"),this.uOutH=a.getUniformLocation(this.program,"u_out_h")}setSource(e){this.source=e}run(){if(!this.source)throw new Error("InputWebGL.run() called before setSource()");let e=this.gl;e.bindTexture(e.TEXTURE_2D,this.srcTex),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.source),e.useProgram(this.program),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.srcTex),e.uniform1i(this.uSrc,0),e.uniform1i(this.uOutW,this.output.w),e.uniform1i(this.uOutH,this.output.h),e.bindFramebuffer(e.FRAMEBUFFER,this.backend.fbo),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,this.output.texture,0),e.viewport(0,0,this.output.texW,this.output.texH),e.bindVertexArray(null),e.drawArrays(e.TRIANGLES,0,6)}};var ee=class u{constructor(e,r,t){i(this,"gl",e);i(this,"canvas",r);i(this,"dtype",t);i(this,"ops");i(this,"presenters");i(this,"fbo");i(this,"textureFormat");this.fbo=e.createFramebuffer(),this.textureFormat=t==="f16"?{internalFormat:e.RGBA16F,format:e.RGBA,type:e.HALF_FLOAT,bytesPerElement:2}:{internalFormat:e.RGBA32F,format:e.RGBA,type:e.FLOAT,bytesPerElement:4},this.ops={Conv2d:(a,o,n)=>new vt(this,a,o,n),ConvTranspose2d:(a,o,n)=>new xt(this,a,o,n),DepthwiseConv2d:(a,o,n)=>new yt(this,a,o,n),Add:(a,o)=>new wt(this,a,o),Sigmoid:a=>new kt(this,a),Tanh:a=>new Tt(this,a),ElementwiseMul:(a,o)=>new Pt(this,a,o),Warp:(a,o,n)=>new Ct(this,a,o,n),FaceBoxFromHeatmaps:(a,o)=>new Wt(this,a,o),FaceBoxesFromHeatmaps:(a,o)=>new Gt(this,a,o),ReframeState:(a,o,n,s)=>new Ut(this,a,o,n,s),Reframe:(a,o)=>new Bt(this,a,o),CropResample:(a,o,n)=>new St(this,a,o,n),FaceTouchupStage:(a,o,n,s,p)=>new Et(this,a,o,n,s,p),Stabilize:(a,o,n,s,p)=>new Rt(this,a,o,n,s,p),BilinearUpsample:(a,o)=>new Dt(this,a,o),Crop:(a,o)=>new Ot(this,a,o),BicubicUpsample:(a,o)=>new It(this,a,o),ChannelConcat:(a,o)=>new Mt(this,a,o),Conv2dAdd:(a,o,n,s)=>new Vt(this,a,o,n,s),ProjResidual:(a,o,n,s)=>new Xt(this,a,o,n,s),ConcatConv2d:(a,o,n,s)=>new jt(this,a,o,n,s),GatesFused:(a,o,n)=>new qt(this,a,o,n),CandUpdateFused:(a,o,n,s,p)=>new $t(this,a,o,n,s,p),ConvExpand:(a,o)=>new Kt(this,a,o),CatConv6to2:(a,o,n)=>new Yt(this,a,o,n),DownAdapter:(a,o,n,s)=>new Qt(this,a,o,n,s),UpFinal:(a,o,n)=>new Jt(this,a,o,n),UpFinalSkip:(a,o,n,s)=>new Zt(this,a,o,n,s),UpsampleConcat:(a,o,n)=>new Ht(this,a,o,n),UpsampleConv1x1:(a,o,n)=>new Nt(this,a,o,n),UpsampleSigmoid:(a,o)=>new zt(this,a,o),Input:(a,o)=>new ar(this,a,o)},this.presenters={CompositeSolid:(a,o,n)=>new er(this,a,o,n),CompositeImage:(a,o,n)=>new tr(this,a,o,n),CompositeImageBilinear:(a,o,n)=>new rr(this,a,o,n),CompositePassthrough:a=>new or(this,a),LandmarkOverlay:(a,o,n,s)=>new Lt(this,a,o,n,s),FaceTouchup:(a,o,n,s,p)=>new Ft(this,a,o,n,s,p)}}static isAvailable(){let e=null;try{return e=new OffscreenCanvas(1,1).getContext("webgl2"),!(!e||!e.getExtension("EXT_color_buffer_float"))}catch{return!1}finally{e?.getExtension("WEBGL_lose_context")?.loseContext()}}static create(e){let r=e.canvas.getContext("webgl2");if(!r)throw new Error("WebGL2 not available");if(!r.getExtension("EXT_color_buffer_float"))throw new Error("EXT_color_buffer_float not available");return new u(r,e.canvas,e.dtype??"f32")}attachCanvas(e){throw new Error(\`WebGLBackend.attachCanvas('\${e}'): WebGL cannot render to a second canvas; use the renderer's snapshot-and-present path for preview output\`)}bindDisplayFramebuffer(){this.gl.bindFramebuffer(this.gl.FRAMEBUFFER,null),this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}toTextureView(e){if(e===null)return null;let r=this.dtype==="f16",t=e instanceof Uint16Array;return r===t?e:r?Le(e):ae(e)}tensor(e,r,t,a){let o=r*(t/4),n=e,s=this.gl,p=s.createTexture(),c=this.textureFormat,l=this.toTextureView(a??null);return s.bindTexture(s.TEXTURE_2D,p),s.texImage2D(s.TEXTURE_2D,0,c.internalFormat,o,n,0,c.format,c.type,l),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MIN_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_MAG_FILTER,s.NEAREST),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_S,s.CLAMP_TO_EDGE),s.texParameteri(s.TEXTURE_2D,s.TEXTURE_WRAP_T,s.CLAMP_TO_EDGE),{h:e,w:r,c:t,texture:p,texW:o,texH:n}}upload(e){return{data:e}}async readback(e){let r=this.gl,t=this.textureFormat;if(r.bindFramebuffer(r.FRAMEBUFFER,this.fbo),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e.texture,0),this.dtype==="f16"){let o=new Uint16Array(e.texW*e.texH*4);return r.readPixels(0,0,e.texW,e.texH,t.format,r.HALF_FLOAT,o),r.bindFramebuffer(r.FRAMEBUFFER,null),ae(o)}let a=new Float32Array(e.texW*e.texH*4);return r.readPixels(0,0,e.texW,e.texH,t.format,r.FLOAT,a),r.bindFramebuffer(r.FRAMEBUFFER,null),a}copyTensor(e,r){if(e.texW!==r.texW||e.texH!==r.texH)throw new Error(\`copyTensor: size mismatch (src \${e.texW}\\xD7\${e.texH} vs dst \${r.texW}\\xD7\${r.texH})\`);let t=this.gl;t.bindFramebuffer(t.FRAMEBUFFER,this.fbo),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e.texture,0),t.bindTexture(t.TEXTURE_2D,r.texture),t.copyTexSubImage2D(t.TEXTURE_2D,0,0,0,0,0,e.texW,e.texH),t.bindFramebuffer(t.FRAMEBUFFER,null)}async sync(){let e=this.gl,r=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);if(!r){e.finish();return}for(e.flush();;){let t=e.clientWaitSync(r,0,0);if(t===e.ALREADY_SIGNALED||t===e.CONDITION_SATISFIED){e.deleteSync(r);return}if(t===e.WAIT_FAILED)throw e.deleteSync(r),new Error("WebGLBackend.sync: clientWaitSync returned WAIT_FAILED");await new Promise(a=>setTimeout(a,1))}}destroy(){this.gl.deleteFramebuffer(this.fbo),this.gl.getExtension("WEBGL_lose_context")?.loseContext()}};var hr=Y("setup_backend");async function Oa(u,e,r={}){let t=u.backend==="webgpu"||u.backend==="auto",a=!!u.outputCanvas,o=()=>u.outputCanvas??new OffscreenCanvas(e.w,e.h),n=null;if(t&&await ne.isAvailable()){let p=u.dtype==="f16"&&!await ne.hasF16Support()?"f32":u.dtype,c=o();try{let l=await ne.create({canvas:c,dtype:p});return l.device.lost.then(f=>{f.reason!=="destroyed"&&r.onContextLost?.({message:\`WebGPU device lost: \${f.reason}\${f.message?" \\u2014 "+f.message:""}\`,source:"backend-lost",recoverable:!1,cause:f})}).catch(()=>{}),{backend:l,resolvedBackend:"webgpu",resolvedDtype:p,canvas:c}}catch(l){hr.warn("WebGPU isAvailable but create() threw; trying WebGL fallback:",l),n=l,a&&hr.warn("transfer-capture topology: WebGL fallback may also fail on the same canvas")}}if(ee.isAvailable()){let p=o();try{let c=ee.create({canvas:p,dtype:u.dtype});return p.addEventListener("webglcontextlost",l=>{r.onContextLost?.({message:"WebGL context lost",source:"backend-lost",recoverable:!1,cause:l})}),{backend:c,resolvedBackend:"webgl",resolvedDtype:u.dtype,canvas:p}}catch(c){hr.warn("WebGL create() threw:",c),n=c}}let s=n?\` (last error: \${n.message??n})\`:"";throw new Error(\`setup_backend: no usable GPU backend\${s}\`)}var Ia=.5,Yn=3,Ma=10,Qn=30,te=Y("autotune");async function za(u,e=Qn){let r=u instanceof ee?Ia*.5:Ia,t=1e3/e*r;te(\`start; budget per source frame: \${t.toFixed(1)}ms (source \${e}fps \\xD7 \${r} safety)\`),te("backend dtype:",u.dtype);let a=null;for(let o of nr)if(o.model!=="xl"){if(!J[o.model]){te("skip",o.model,"(no TIER_CONFIG entry)");continue}try{let n=J[o.model].baseRes;te(\`bench \${o.model} base @ \${n.w}\\xD7\${n.h} skipFrames=\${o.skipFrames} \\u2026\`);let s=await eu(u,o),p=s<=t;if(te(\` \${o.model}: \${s.toFixed(1)}ms / source frame \${p?"\\u2713 within budget":"\\u2717 over budget"}\`),(p||a===null)&&(a=o),!p)break}catch(n){te(" bench failed for",o.model,":",n);break}}if(!a)throw new Error("autotune: no implementable preset available");return te("picked",a.model),a}function Jn(u){let e=Object.create(u);return e.ops={...u.ops,Conv2d:(r,t,a)=>{let o={weights:new Float32Array(a.kernel*a.kernel*r.c*a.outChannels),bias:new Float32Array(a.outChannels)};return u.ops.Conv2d(r,o,a)},DepthwiseConv2d:(r,t,a)=>{let o={weights:new Float32Array(a.kernel*a.kernel*r.c),bias:new Float32Array(r.c)};return u.ops.DepthwiseConv2d(r,o,a)},Conv2dAdd:(r,t,a,o)=>{let n={weights:new Float32Array(o.kernel*o.kernel*r.c*o.outChannels),bias:new Float32Array(o.outChannels)};return u.ops.Conv2dAdd(r,t,n,o)},UpsampleConv1x1:(r,t,a)=>{let o={weights:new Float32Array(r.c*a.outChannels),bias:new Float32Array(a.outChannels)};return u.ops.UpsampleConv1x1(r,o,a)},ProjResidual:(r,t,a,o)=>{let n={weights:new Float32Array(r.c*o.outChannels),bias:new Float32Array(o.outChannels)};return u.ops.ProjResidual(r,t,n,o)},ConcatConv2d:(r,t,a,o)=>{let n={weights:new Float32Array(9*(r.c+t.c)*o.outChannels),bias:new Float32Array(o.outChannels)};return u.ops.ConcatConv2d(r,t,n,o)}},e}function Zn(){let u=new Proxy({},{get:()=>u});return u}async function eu(u,e){let r=J[e.model];if(!r)throw new Error(\`microbench: no TIER_CONFIG entry for '\${e.model}'\`);let t=r.base,a=Jn(u),o=a.tensor(r.baseRes.h,r.baseRes.w,4),n=new t(a,o,Zn());for(let l=0;l<Yn;l++)n.run(),await u.sync();let s=e.skipFrames+1,p=performance.now();for(let l=0;l<Ma;l++)l%s===0&&n.run();return await u.sync(),(performance.now()-p)/Ma}async function Ha(u,e,r){let t;if(u==="auto")t=await za(r);else if(typeof u=="string"){let a=ge(u);if(!a)throw new Error(\`resolve_preset: unknown preset name '\${u}'\`);t=a}else t=u;return t.dtype!==e?{...t,dtype:e}:t}function Na(u){let e=null,r=null;return u.onmessage=t=>{let{frame:a}=t.data;if(r){let o=r;r=null,o(a)}else e&&e.close(),e=a},u.start?.(),new ReadableStream({pull(t){if(e){t.enqueue(e),e=null;return}return new Promise(a=>{r=o=>{t.enqueue(o),a()}})},cancel(){e&&(e.close(),e=null),u.close()}},{highWaterMark:0})}function Va(u){switch(u.topology.input){case"mstp":if(!u.inputReadable)throw new Error("create_input: topology.input='mstp' but InitData.inputReadable missing");return u.inputReadable;case"rvfc-postmessage":if(!u.inputPort)throw new Error("create_input: topology.input='rvfc-postmessage' but InitData.inputPort missing");return Na(u.inputPort)}}function Xa(u){return new TransformStream({transform(e,r){u.process(e);let t=new VideoFrame(u.canvas,{timestamp:e.timestamp});e.close(),r.enqueue(t)}})}function ja(u){return new WritableStream({write(e){u.process(e),e.close()}})}function qa(u,e){return new WritableStream({write(r){u.process(r),r.close();let t=u.canvas.transferToImageBitmap();e.postMessage({bmp:t},[t])},close(){e.close()}})}var tu=Y("create_output");function $a(u,e,r){switch(u.topology.output){case"mstg":{if(!u.outputWritable)throw new Error("create_output: topology.output='mstg' but InitData.outputWritable missing");let t=Xa(e);return t.readable.pipeTo(u.outputWritable,{signal:r}).catch(a=>{r.aborted||tu.warn("mstg downstream pipe failed:",a)}),t.writable}case"transfer-capture":return ja(e);case"bitmap-shuttle":{if(!u.outputPort)throw new Error("create_output: topology.output='bitmap-shuttle' but InitData.outputPort missing");return qa(e,u.outputPort)}}}function Ka(u){if(!u.onFirstFrame)return u.input.pipeTo(u.output,{signal:u.signal});let e=!1,r=u.onFirstFrame,t=new TransformStream({transform(a,o){o.enqueue(a),e||(e=!0,queueMicrotask(r))}});return u.input.pipeThrough(t,{signal:u.signal}).pipeTo(u.output,{signal:u.signal})}var L=Y("worker");L("script loaded");var U=null,ue=null,ir=null;self.onmessage=async function(u){let{cmd:e,data:r,request_id:t}=u.data;L("cmd received:",e,"request_id:",t);try{let a=await ru(e,r);L("cmd ok:",e),du(t,a)}catch(a){L("cmd FAILED:",e,a),de("error",{message:\`\${e} failed: \${a.message??String(a)}\`,source:"worker",recoverable:!1,cause:a})}};async function ru(u,e){switch(u){case"init":return ou(e);case"startRender":return au(e.weights);case"setBackground":return iu(e);case"setEnabled":return su(e.enabled);case"setPreset":return cu(e);case"getStats":return U?.getStats()??null;case"destroy":return lu();case"attachPreview":return nu(e);case"setPreview":return uu(e);case"clearPreview":return pu();case"setTouchup":return gu(e);case"setReframe":return mu(e);case"reframeNow":return hu();default:throw new Error(\`unknown cmd: \${u}\`)}}async function ou(u){if(gr(!!u.debug),L("handleInit: start; topology=",u.topology,"preset=",u.preset,"backend=",u.backend,"dtype=",u.dtype),U)throw new Error("handleInit: already initialized");L("handleInit: setupBackend\\u2026");let e=await Oa(u,u.canvasSize,{onContextLost:o=>{L("GPU context lost:",o.message),de("error",o)}});L("handleInit: backend ready:",e.resolvedBackend,e.resolvedDtype,"canvas:",e.canvas.width,"x",e.canvas.height),L("handleInit: constructing Renderer (boot mode)\\u2026"),U=new Ae({backend:e.backend,backendKind:e.resolvedBackend,canvas:e.canvas,background:u.background,enabled:u.enabled,topology:u.topology}),ue=new AbortController,L("handleInit: createInputStream\\u2026");let r=Va(u);L("handleInit: createOutputSink\\u2026");let t=$a(u,U,ue.signal);L("handleInit: starting pipe (passthrough)\\u2026"),Ka({input:r,output:t,signal:ue.signal}).then(()=>{L("pipe completed (input ended)")}).catch(o=>{if(ue?.signal.aborted){L("pipe aborted (expected on destroy)");return}L("pipe FAILED:",o),de("error",{message:\`pipe failed: \${o.message}\`,source:"worker",recoverable:!1,cause:o})}),L("handleInit: resolvePreset\\u2026");let a=await Ha(u.preset,e.resolvedDtype,e.backend);return L("handleInit: preset resolved:",a),ir=a,L("handleInit: done; returning InitResponse, awaiting startRender"),{resolvedPreset:a,resolvedBackend:e.resolvedBackend,resolvedDtype:e.resolvedDtype}}async function au(u){if(L("handleStartRender: start; weights bytes:",u.byteLength),!U||!ir)throw new Error("handleStartRender: handleInit not completed");L("handleStartRender: attaching network via setPreset\\u2026"),U.setPreset(ir,u),L("handleStartRender: ready (effect mode active)"),de("ready",void 0)}async function iu(u){U?.setBackground(u)}async function su(u){U?.setEnabled(u)}async function nu(u){if(!U)throw new Error("handleAttachPreview: not initialized");U.attachPreview(u.canvas)}async function uu(u){if(!U)throw new Error("handleSetPreview: not initialized");U.setPreview(u.background,u.fps!==void 0?{fps:u.fps}:void 0)}async function pu(){U?.clearPreview()}async function cu(u){if(!U)throw new Error("handleSetPreset: not initialized");if(!u.weights)throw new Error("handleSetPreset: weights required for runtime preset swap");if(u.preset==="auto")throw new Error("handleSetPreset: 'auto' not supported on runtime swap (use at init for autotune)");let e=typeof u.preset=="string"?ge(u.preset)??fu(u.preset):u.preset;return U.setPreset(e,u.weights),{resolvedPreset:e}}async function lu(){ue?.abort(),ue=null,U?.destroy(),U=null,ir=null}function fu(u){throw new Error(\`handleSetPreset: unknown preset '\${u}'\`)}function du(u,e){let r={request_id:u,res:e};self.postMessage(r)}function de(u,e){let r={request_id:u,res:e};self.postMessage(r)}function Qy(u){de("stats",u)}function mu(u){if(!U)throw new Error("setReframe before init");U.setReframe(u)}function hu(){if(!U)throw new Error("reframeNow before init");U.reframeNow()}function gu(u){if(!U)throw new Error("setTouchup before init");U.setFaceEffects(u===null?null:{landmarkWeights:u.landmarkWeights,topology:{count:u.topoCount,uv:u.topoUv,idx:u.topoIdx,weightMask:u.weightMask},touchup:u.params})}export{Qy as emitStats};
7040
- `;var v=g("pipeline");function Oe(){{let t=new Blob([W],{type:"application/javascript"}),e=URL.createObjectURL(t),n=new Worker(e,{type:"module"});return URL.revokeObjectURL(e),n}}var U={strength:.6,amount:8,detail:.35,style:"freq-sep"},We=.15,pe="https://cdn.longpipe.dev/models/v/0.0.5/",Le={background:"blur",preset:"auto",weightsBaseUrl:pe,audio:"passthrough",enabled:true,adaptive:true,debug:false},oe={w:1280,h:720};function ze(t,e){if(e)return e;let r=t.getVideoTracks()[0]?.getSettings()??{};return {w:r.width||oe.w,h:r.height||oe.h}}function ue(t,e,n){let r=n==="f16"?".f16.bin":".bin";return `${t.replace(/\/$/,"")}/model_${e}${r}`}async function le(t,e,n){if(n==="f16"){let i=await fetch(ue(t,e,"f16"));if(i.ok)return i.arrayBuffer()}let r=ue(t,e,"f32"),a=await fetch(r);if(!a.ok)throw new Error(`weights fetch failed: ${a.status} ${r}`);return a.arrayBuffer()}async function He(t,e){let n=t.replace(/\/$/,""),r=(async()=>{if(e==="f16"){let c=await fetch(`${n}/model_landmark_mesh.f16.bin`);if(c.ok)return c.arrayBuffer()}let o=`${n}/model_landmark_mesh.bin`,l=await fetch(o);if(!l.ok)throw new Error(`touchup: landmark weights fetch failed: ${l.status} ${o}`);return l.arrayBuffer()})(),a=fetch(`${n}/face_topology.json`).then(o=>{if(!o.ok)throw new Error(`touchup: face_topology.json fetch failed: ${o.status}`);return o.json()}),i=fetch(`${n}/weight_mask.png`).then(async o=>{if(!o.ok)throw new Error(`touchup: weight_mask.png fetch failed: ${o.status}`);return createImageBitmap(await o.blob())}),[s,u,p]=await Promise.all([r,a,i]);return {landmarkWeights:s,topoCount:u.count,topoUv:new Float32Array(u.uv),topoIdx:new Float32Array(u.idx),weightMask:p}}var L=class{stream;ready;controller;worker;inputCleanup;outputCleanup;adaptive=null;denoiser=null;touchupAssets=null;weightsBaseUrl=pe;resolvedDtype="f32";bgCleanup=null;previewBgCleanup=null;constructor(e,n){let r={...Le,...n};z(r.debug);let a=$(),i=ne(a.input,e),s=ze(e,r.outputResolution),u=se(a.output,s);this.inputCleanup=i.cleanup,this.outputCleanup=u.cleanup;let p=j(r.audio),o;if(p.mode==="denoise"){let h=e.getAudioTracks()[0];h?(this.denoiser=new F(h,{model:p.denoise?.model??"auto",weightsBaseUrl:r.weightsBaseUrl,postFilterBeta:p.denoise?.postFilterBeta,gruLeak:p.denoise?.gruLeak,enabled:p.denoise?.enabled,onError:d=>r.onError?.({message:d,source:"audio",recoverable:true})}),o=this.denoiser.outputTrack):r.onError?.({message:'audio: "denoise" requested but the input stream has no audio track',source:"audio",recoverable:true});}this.stream=X(u.videoTrack,e,p,o),u.startPassthrough?.(e),this.worker=Oe(),this.controller=new D(this.worker),this.ready=new Promise((h,d)=>{this.controller.addPersistentListener("ready",()=>{v("ready handler invoked; resolving .ready"),r.onReady?.(),h();}),this.controller.addPersistentListener("error",f=>{console.error(`[longpipe/pipeline] error (${f.source}):`,f.message),f.recoverable||d(new Error(f.message)),r.onError?.(f);});});let l={topology:a,preset:r.preset,enabled:r.enabled,backend:"auto",dtype:r.dtype??"f16",canvasSize:s,debug:r.debug,...i.initFields,...u.initFields},c=[...i.transferList,...u.transferList];this.weightsBaseUrl=r.weightsBaseUrl,this.bootstrap(l,r.background,c,r.weightsBaseUrl,r.adaptive,r.onError,r.touchup,r.reframe);}async bootstrap(e,n,r,a,i,s,u,p){try{v("normalizing background\u2026");let o=await E(n);this.bgCleanup=o.cleanup??null;let l={...e,background:o.background},c=[...r,...o.transferList??[]];v("sending init\u2026");let h=await this.controller.sendMessage("init",l,c);v("init resolved:",h),v("fetching weights:",h.resolvedPreset.model,h.resolvedDtype);let d=await le(a,h.resolvedPreset.model,h.resolvedDtype);v("weights bytes:",d.byteLength),this.resolvedDtype=h.resolvedDtype,v("sending startRender\u2026"),await this.controller.sendMessage("startRender",{weights:d},[d]),v("startRender resolved; awaiting first frame"),p&&this.setReframe(p).catch(f=>{s?.({message:`reframe init failed: ${f.message??f}`,source:"unknown",recoverable:!0,cause:f});}),u&&this.setTouchup(u).catch(f=>{s?.({message:`touchup init failed: ${f.message??f}`,source:"unknown",recoverable:!0,cause:f});}),l.preset==="auto"&&i&&(this.adaptive=new P({backendKind:h.resolvedBackend,initialModel:h.resolvedPreset.model,fetchWeights:f=>le(a,f,h.resolvedDtype),getStats:()=>this.getStats(),swapPreset:async(f,R)=>{await this.controller.sendMessage("setPreset",{preset:f,weights:R},[R]);},onError:s}),this.adaptive.start());}catch(o){console.error("[longpipe/pipeline] bootstrap failed:",o),this.controller.handleMessage.call(this.controller,{data:{request_id:"error",res:{message:o.message??String(o),source:"worker",recoverable:false,cause:o}}});}}then(e,n){return this.ready.then(()=>e?e(this):this,n)}async setBackground(e){let n=await E(e),r=this.bgCleanup;this.bgCleanup=n.cleanup??null,await this.controller.sendMessage("setBackground",n.background,n.transferList),r?.();}async setTouchup(e){if(await this.ready,e===null){await this.controller.sendMessage("setTouchup",null);return}this.touchupAssets||(this.touchupAssets=await He(this.weightsBaseUrl,this.resolvedDtype));let n={strength:e.strength??U.strength,amount:e.amount??U.amount,detail:e.detail??U.detail,style:e.style??U.style,thresh:We};await this.controller.sendMessage("setTouchup",{...this.touchupAssets,params:n});}async setReframe(e){await this.ready;let n=e===true?{}:e===false||e===null?null:e;await this.controller.sendMessage("setReframe",n);}async reframe(){await this.ready,await this.controller.sendMessage("reframeNow",void 0);}setPreset(e,n){this.controller.sendMessage("setPreset",{preset:e,weights:n});}attachPreview(e){let n=e.transferControlToOffscreen();this.controller.sendMessage("attachPreview",{canvas:n},[n]);}async setPreview(e){let n=await E(e.background),r=this.previewBgCleanup;this.previewBgCleanup=n.cleanup??null,await this.controller.sendMessage("setPreview",{background:n.background,fps:e.fps},n.transferList),r?.();}clearPreview(){this.controller.sendMessage("clearPreview",{}),this.previewBgCleanup?.(),this.previewBgCleanup=null;}setEnabled(e){this.controller.sendMessage("setEnabled",{enabled:e});}async getStats(){return this.controller.sendMessage("getStats",{})}setDenoise(e){if(this.denoiser){if(typeof e=="boolean"){this.denoiser.setEnabled(e);return}(e.postFilterBeta!=null||e.gruLeak!=null)&&this.denoiser.setConfig({postFilterBeta:e.postFilterBeta,gruLeak:e.gruLeak}),e.enabled!=null&&this.denoiser.setEnabled(e.enabled);}}getAudioStats(){return this.denoiser?.getStats()??null}destroy(){this.adaptive?.stop(),this.adaptive=null,this.denoiser?.destroy(),this.denoiser=null,this.bgCleanup?.(),this.bgCleanup=null,this.previewBgCleanup?.(),this.previewBgCleanup=null,this.controller.sendMessage("destroy",{}),this.controller.terminate(),this.inputCleanup(),this.outputCleanup();}};
7041
- export{L as EffectsPipeline};
7009
+ `;var v=g("pipeline");function ve(){{let t=new Blob([B],{type:"application/javascript"}),e=URL.createObjectURL(t),n=new Worker(e,{type:"module"});return URL.revokeObjectURL(e),n}}var F={strength:.6,amount:8,detail:.35,style:"freq-sep"},xe=.15,be={background:"blur",preset:"auto",weightsBaseUrl:a,audio:"passthrough",enabled:true,adaptive:true,debug:false},ee={w:1280,h:720};function we(t,e){if(e)return e;let r=t.getVideoTracks()[0]?.getSettings()??{};return {w:r.width||ee.w,h:r.height||ee.h}}function te(t,e,n){let r=n==="f16"?".f16.bin":".bin";return `${t.replace(/\/$/,"")}/model_${e}${r}`}async function ne(t,e,n){if(n==="f16"){let i=await fetch(te(t,e,"f16"));if(i.ok)return i.arrayBuffer()}let r=te(t,e,"f32"),a=await fetch(r);if(!a.ok)throw new Error(`weights fetch failed: ${a.status} ${r}`);return a.arrayBuffer()}async function ye(t,e){let n=t.replace(/\/$/,""),r=(async()=>{if(e==="f16"){let p=await fetch(`${n}/model_landmark_mesh.f16.bin`);if(p.ok)return p.arrayBuffer()}let s=`${n}/model_landmark_mesh.bin`,o=await fetch(s);if(!o.ok)throw new Error(`touchup: landmark weights fetch failed: ${o.status} ${s}`);return o.arrayBuffer()})(),a=fetch(`${n}/face_topology.json`).then(s=>{if(!s.ok)throw new Error(`touchup: face_topology.json fetch failed: ${s.status}`);return s.json()}),i=fetch(`${n}/weight_mask.png`).then(async s=>{if(!s.ok)throw new Error(`touchup: weight_mask.png fetch failed: ${s.status}`);return createImageBitmap(await s.blob())}),[l,u,c]=await Promise.all([r,a,i]);return {landmarkWeights:l,topoCount:u.count,topoUv:new Float32Array(u.uv),topoIdx:new Float32Array(u.idx),weightMask:c}}var M=class{stream;ready;controller;worker;inputCleanup;outputCleanup;adaptive=null;denoiser=null;touchupAssets=null;weightsBaseUrl=a;resolvedDtype="f32";bgCleanup=null;previewBgCleanup=null;constructor(e,n){let r={...be,...n};W(r.debug);let a=G(),i=K(a.input,e),l=we(e,r.outputResolution),u=Z(a.output,l);this.inputCleanup=i.cleanup,this.outputCleanup=u.cleanup;let c=V(r.audio),s;if(c.mode==="denoise"){let h=e.getAudioTracks()[0];h?(this.denoiser=new b(h,{model:c.denoise?.model??"auto",weightsBaseUrl:r.weightsBaseUrl,postFilterBeta:c.denoise?.postFilterBeta,gruLeak:c.denoise?.gruLeak,enabled:c.denoise?.enabled,onError:d=>r.onError?.({message:d,source:"audio",recoverable:true})}),s=this.denoiser.outputTrack):r.onError?.({message:'audio: "denoise" requested but the input stream has no audio track',source:"audio",recoverable:true});}this.stream=X(u.videoTrack,e,c,s),u.startPassthrough?.(e),this.worker=ve(),this.controller=new S(this.worker),this.ready=new Promise((h,d)=>{this.controller.addPersistentListener("ready",()=>{v("ready handler invoked; resolving .ready"),r.onReady?.(),h();}),this.controller.addPersistentListener("error",f=>{console.error(`[longpipe/pipeline] error (${f.source}):`,f.message),f.recoverable||d(new Error(f.message)),r.onError?.(f);});});let o={topology:a,preset:r.preset,enabled:r.enabled,backend:"auto",dtype:r.dtype??"f16",canvasSize:l,debug:r.debug,...i.initFields,...u.initFields},p=[...i.transferList,...u.transferList];this.weightsBaseUrl=r.weightsBaseUrl,this.bootstrap(o,r.background,p,r.weightsBaseUrl,r.adaptive,r.onError,r.touchup,r.reframe);}async bootstrap(e,n,r,a,i,l,u,c){try{v("normalizing background\u2026");let s=await P(n);this.bgCleanup=s.cleanup??null;let o={...e,background:s.background},p=[...r,...s.transferList??[]];v("sending init\u2026");let h=await this.controller.sendMessage("init",o,p);v("init resolved:",h),v("fetching weights:",h.resolvedPreset.model,h.resolvedDtype);let d=await ne(a,h.resolvedPreset.model,h.resolvedDtype);v("weights bytes:",d.byteLength),this.resolvedDtype=h.resolvedDtype,v("sending startRender\u2026"),await this.controller.sendMessage("startRender",{weights:d},[d]),v("startRender resolved; awaiting first frame"),c&&this.setReframe(c).catch(f=>{l?.({message:`reframe init failed: ${f.message??f}`,source:"unknown",recoverable:!0,cause:f});}),u&&this.setTouchup(u).catch(f=>{l?.({message:`touchup init failed: ${f.message??f}`,source:"unknown",recoverable:!0,cause:f});}),o.preset==="auto"&&i&&(this.adaptive=new T({backendKind:h.resolvedBackend,initialModel:h.resolvedPreset.model,fetchWeights:f=>ne(a,f,h.resolvedDtype),getStats:()=>this.getStats(),swapPreset:async(f,I)=>{await this.controller.sendMessage("setPreset",{preset:f,weights:I},[I]);},onError:l}),this.adaptive.start());}catch(s){console.error("[longpipe/pipeline] bootstrap failed:",s),this.controller.handleMessage.call(this.controller,{data:{request_id:"error",res:{message:s.message??String(s),source:"worker",recoverable:false,cause:s}}});}}then(e,n){return this.ready.then(()=>e?e(this):this,n)}async setBackground(e){let n=await P(e),r=this.bgCleanup;this.bgCleanup=n.cleanup??null,await this.controller.sendMessage("setBackground",n.background,n.transferList),r?.();}async setTouchup(e){if(await this.ready,e===null){await this.controller.sendMessage("setTouchup",null);return}this.touchupAssets||(this.touchupAssets=await ye(this.weightsBaseUrl,this.resolvedDtype));let n={strength:e.strength??F.strength,amount:e.amount??F.amount,detail:e.detail??F.detail,style:e.style??F.style,thresh:xe};await this.controller.sendMessage("setTouchup",{...this.touchupAssets,params:n});}async setReframe(e){await this.ready;let n=e===true?{}:e===false||e===null?null:e;await this.controller.sendMessage("setReframe",n);}async reframe(){await this.ready,await this.controller.sendMessage("reframeNow",void 0);}setPreset(e,n){this.controller.sendMessage("setPreset",{preset:e,weights:n});}attachPreview(e){let n=e.transferControlToOffscreen();this.controller.sendMessage("attachPreview",{canvas:n},[n]);}async setPreview(e){let n=await P(e.background),r=this.previewBgCleanup;this.previewBgCleanup=n.cleanup??null,await this.controller.sendMessage("setPreview",{background:n.background,fps:e.fps},n.transferList),r?.();}clearPreview(){this.controller.sendMessage("clearPreview",{}),this.previewBgCleanup?.(),this.previewBgCleanup=null;}setEnabled(e){this.controller.sendMessage("setEnabled",{enabled:e});}async getStats(){return this.controller.sendMessage("getStats",{})}setDenoise(e){if(this.denoiser){if(typeof e=="boolean"){this.denoiser.setEnabled(e);return}(e.postFilterBeta!=null||e.gruLeak!=null)&&this.denoiser.setConfig({postFilterBeta:e.postFilterBeta,gruLeak:e.gruLeak}),e.enabled!=null&&this.denoiser.setEnabled(e.enabled);}}getAudioStats(){return this.denoiser?.getStats()??null}destroy(){this.adaptive?.stop(),this.adaptive=null,this.denoiser?.destroy(),this.denoiser=null,this.bgCleanup?.(),this.bgCleanup=null,this.previewBgCleanup?.(),this.previewBgCleanup=null,this.controller.sendMessage("destroy",{}),this.controller.terminate(),this.inputCleanup(),this.outputCleanup();}};export{M as EffectsPipeline};
@@ -0,0 +1,14 @@
1
+ type DenoiseModel = 'rnnoise' | 'dfn' | 'dfnint8';
2
+ type DenoiseTier = 'high' | 'mid' | 'low';
3
+ type DenoiseModelOption = 'auto' | DenoiseTier | DenoiseModel;
4
+
5
+ interface AudioStats {
6
+ model: DenoiseModel;
7
+ p50Ms: number | null;
8
+ p95Ms: number | null;
9
+ latencyMs: number;
10
+ active: boolean;
11
+ sampleRate: number;
12
+ }
13
+
14
+ export type { AudioStats as A, DenoiseModelOption as D, DenoiseModel as a, DenoiseTier as b };
@@ -0,0 +1,14 @@
1
+ type DenoiseModel = 'rnnoise' | 'dfn' | 'dfnint8';
2
+ type DenoiseTier = 'high' | 'mid' | 'low';
3
+ type DenoiseModelOption = 'auto' | DenoiseTier | DenoiseModel;
4
+
5
+ interface AudioStats {
6
+ model: DenoiseModel;
7
+ p50Ms: number | null;
8
+ p95Ms: number | null;
9
+ latencyMs: number;
10
+ active: boolean;
11
+ sampleRate: number;
12
+ }
13
+
14
+ export type { AudioStats as A, DenoiseModelOption as D, DenoiseModel as a, DenoiseTier as b };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longpipe",
3
- "version": "0.0.15",
3
+ "version": "0.0.16",
4
4
  "description": "Open-source WebGPU/WebGL2 video effects SDK — virtual backgrounds, background blur, portrait matting in real time in the browser.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -44,10 +44,15 @@
44
44
  "types": "./dist/model.d.ts",
45
45
  "import": "./dist/model.js",
46
46
  "require": "./dist/model.cjs"
47
+ },
48
+ "./audio": {
49
+ "types": "./dist/audio.d.ts",
50
+ "import": "./dist/audio.js",
51
+ "require": "./dist/audio.cjs"
47
52
  }
48
53
  },
49
54
  "scripts": {
50
- "build": "tsup src/index.ts src/model.ts --format esm,cjs --dts",
55
+ "build": "tsup src/index.ts src/model.ts src/audio.ts --format esm,cjs --dts",
51
56
  "typecheck": "tsc --noEmit",
52
57
  "test": "vitest run",
53
58
  "test:watch": "vitest",