longpipe 0.0.14 → 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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';var R=[{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 Ye=false;function ot(i){Ye=i;}function O(i){let t=`[longpipe/${i}]`,e=((...r)=>{Ye&&console.log(t,...r);});return e.warn=(...r)=>{Ye&&console.warn(t,...r);},e}var j=O("adaptive"),tn=2e3,rn=1e4,nn=30,an=20,sn=5e3,on=.3,un=15e3,re=class{constructor(t){this.opts=t;this.currentPresetIdx=R.findIndex(e=>e.model===t.initialModel),this.lastSwapAt=performance.now();}opts;timer=null;currentPresetIdx;lastSwapAt=0;overshootStart=0;headroomStart=0;start(){j(`started; backend=${this.opts.backendKind} initial=${this.opts.initialModel} idx=${this.currentPresetIdx}`),this.timer=setInterval(()=>{this.tick().catch(t=>j("tick failed:",t));},tn);}stop(){this.timer&&clearInterval(this.timer),this.timer=null;}async tick(){if(typeof document<"u"&&document.hidden)return;let t=performance.now();if(t-this.lastSwapAt<rn)return;let e=await this.opts.getStats();if(e.fps<an?(this.overshootStart===0&&(this.overshootStart=t),t-this.overshootStart>=sn&&this.tryDowngrade(e.fps)):this.overshootStart=0,this.opts.backendKind==="webgpu"&&e.modelMs>0){let r=1e3/nn*on;e.modelMs<r?(this.headroomStart===0&&(this.headroomStart=t),t-this.headroomStart>=un&&this.tryUpgrade(e.modelMs,r)):this.headroomStart=0;}}tryDowngrade(t){if(this.currentPresetIdx<=0)return;let e=this.currentPresetIdx-1;j(`downgrade ${R[this.currentPresetIdx].model} \u2192 ${R[e].model} (fps=${t})`),this.swap(e);}tryUpgrade(t,e){if(R[this.currentPresetIdx+1]?.model==="xl"||this.currentPresetIdx>=R.length-1)return;let r=this.currentPresetIdx+1;j(`upgrade ${R[this.currentPresetIdx].model} \u2192 ${R[r].model} (modelMs=${t.toFixed(1)} < ${e.toFixed(1)})`),this.swap(r);}async swap(t){let e=R[t];this.lastSwapAt=performance.now(),this.overshootStart=0,this.headroomStart=0;try{let r=await this.opts.fetchWeights(e.model);await this.opts.swapPreset(e,r),this.currentPresetIdx=t,j(`swap to ${e.model} done`);}catch(r){j("swap failed:",r),this.opts.onError?.({message:`adaptive preset swap failed: ${r.message??String(r)}`,source:"adaptive",recoverable:true,cause:r});}}};async function ut(i){let t,e=false;if(i instanceof HTMLVideoElement){if(t=i.currentSrc||i.src,!t)throw new Error("background video: HTMLVideoElement has no src")}else if(i instanceof Blob)t=URL.createObjectURL(i),e=true;else if(typeof i=="string")t=i;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=t,await new Promise((l,f)=>{r.addEventListener("loadeddata",()=>l(),{once:true}),r.addEventListener("error",()=>f(new Error(`background video: failed to load ${t}`)),{once:true});});try{await r.play();}catch(l){throw new Error(`background video: play() rejected \u2014 ${l.message}`)}let n=new MessageChannel,a=n.port1,s=n.port2,o=false,u=r.requestVideoFrameCallback?.bind(r);if(u){let l=(f,h)=>{if(!o){try{let _=new VideoFrame(r,{timestamp:h.mediaTime*1e6});a.postMessage({frame:_},[_]);}catch{}u(l);}};u(l);}else {let l=()=>{if(!o){try{let f=new VideoFrame(r,{timestamp:performance.now()*1e3});a.postMessage({frame:f},[f]);}catch{}requestAnimationFrame(l);}};requestAnimationFrame(l);}return {port:s,transferList:[s],cleanup:()=>{o=true,a.close(),r.pause(),r.removeAttribute("src"),r.load(),e&&URL.revokeObjectURL(t);}}}var pn=4,Qe=8,pt=16;async function ne(i){if(typeof i=="string")return i==="none"?{background:{kind:"none"}}:i==="blur"?{background:{kind:"blur",sigma:Qe}}:{background:{kind:"image",bitmap:await ct(i)}};if(i instanceof ImageBitmap)return {background:{kind:"image",bitmap:i}};if(typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement)return {background:{kind:"image",bitmap:await createImageBitmap(i)}};if(typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement)return await lt(i);let t=i;if(t.color!==void 0)return {background:{kind:"color",rgb:ln(t.color)}};if(t.blur!==void 0)return {background:{kind:"blur",sigma:cn(t.blur)}};if(t.image!==void 0)return {background:{kind:"image",bitmap:await fn(t.image)}};if(t.video!==void 0)return await lt(t.video);throw new Error(`background: unrecognized input shape \u2014 ${V(i)}`)}async function lt(i){let t;if(typeof i=="string")t=i;else if(typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement)t=i;else if(i&&typeof i=="object"&&"data"in i&&"type"in i)t=i.data instanceof Blob?i.data:new Blob([i.data],{type:i.type});else throw new Error(`background.video: unrecognized shape \u2014 ${V(i)}`);let e=await ut(t);return {background:{kind:"video",port:e.port},transferList:e.transferList,cleanup:e.cleanup}}function ln(i){if(typeof i=="string"){let t=i.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(t))return [parseInt(t.slice(0,2),16)/255,parseInt(t.slice(2,4),16)/255,parseInt(t.slice(4,6),16)/255];if(/^[0-9a-fA-F]{3}$/.test(t))return [parseInt(t[0]+t[0],16)/255,parseInt(t[1]+t[1],16)/255,parseInt(t[2]+t[2],16)/255];throw new Error(`background.color: hex must be #rgb or #rrggbb, got ${V(i)}`)}if(!Array.isArray(i)||i.length!==3||!i.every(t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1))throw new Error(`background.color: expected hex string or [r, g, b] floats in [0, 1], got ${V(i)}`);return [i[0],i[1],i[2]]}function cn(i){if(i===true)return Qe;if("sigma"in i){if(typeof i.sigma!="number"||!Number.isFinite(i.sigma)||i.sigma<0)throw new Error(`background.blur.sigma must be a non-negative number, got ${i.sigma}`);return i.sigma}if("strength"in i){let t=i.strength;if(typeof t=="number"){let e=Math.max(0,Math.min(1,t));return pt*e}if(t==="low")return pn;if(t==="medium")return Qe;if(t==="high")return pt;throw new Error(`background.blur.strength must be 'low' | 'medium' | 'high' | number, got ${V(t)}`)}throw new Error(`background.blur: must be true, { strength }, or { sigma } \u2014 got ${V(i)}`)}async function fn(i){if(i instanceof ImageBitmap)return i;if(typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement)return createImageBitmap(i);if(typeof i=="string")return ct(i);if(i&&typeof i=="object"&&"data"in i&&"type"in i){let t=i.data instanceof Blob?i.data:new Blob([i.data],{type:i.type});return createImageBitmap(t)}throw new Error(`background.image: unrecognized shape \u2014 ${V(i)}`)}async function ct(i){let t=await fetch(i);if(!t.ok)throw new Error(`background: failed to load image from ${i} (HTTP ${t.status})`);let e=await t.blob();return createImageBitmap(e)}function V(i){return i===null?"null":typeof i!="object"?typeof i+"("+String(i)+")":`${i.constructor?.name??"Object"} ${JSON.stringify(i).slice(0,80)}`}function ft(){return {input:"MediaStreamTrackProcessor"in self?"mstp":"rvfc-postmessage",output:"MediaStreamTrackGenerator"in self?"mstg":dn()?"transfer-capture":"bitmap-shuttle"}}var ae=null;function dn(){return ae!==null||(ae=!/Firefox/.test(navigator.userAgent)),ae}function dt(i){return i==="denoise"?{mode:"denoise",denoise:{}}:typeof i=="object"?{mode:"denoise",denoise:i.denoise}:{mode:i}}function ht(i,t,e,r){let n=[i];return e.mode==="passthrough"?n.push(...t.getAudioTracks()):e.mode==="denoise"&&r&&n.push(r),new MediaStream(n)}var X={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"}}},hn={high:"dfn",mid:"dfnint8",low:"rnnoise"},mn=["high","mid","low"];function gn(i){return mn.includes(i)}function mt(i){return gn(i)?hn[i]:i}function gt(i,t){return `${i.replace(/\/$/,"")}/${t}`}async function _t(i){let t=await fetch(i);if(!t.ok)throw new Error(`audio asset fetch failed: ${t.status} ${i}`);return t.arrayBuffer()}async function vt(i,t){let e=X[i],[r,n]=await Promise.all([_t(gt(t,e.wasm)),e.weights?_t(gt(t,e.weights)):Promise.resolve(null)]);return {wasmBytes:r,weights:n}}function ie(){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 _n=1.3,vn=64,xn=3,bn=`
1
+ 'use strict';var R=[{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 Qe=false;function ut(i){Qe=i;}function O(i){let t=`[longpipe/${i}]`,e=((...r)=>{Qe&&console.log(t,...r);});return e.warn=(...r)=>{Qe&&console.warn(t,...r);},e}var j=O("adaptive"),tn=2e3,rn=1e4,nn=30,an=20,sn=5e3,on=.3,un=15e3,ne=class{constructor(t){this.opts=t;this.currentPresetIdx=R.findIndex(e=>e.model===t.initialModel),this.lastSwapAt=performance.now();}opts;timer=null;currentPresetIdx;lastSwapAt=0;overshootStart=0;headroomStart=0;start(){j(`started; backend=${this.opts.backendKind} initial=${this.opts.initialModel} idx=${this.currentPresetIdx}`),this.timer=setInterval(()=>{this.tick().catch(t=>j("tick failed:",t));},tn);}stop(){this.timer&&clearInterval(this.timer),this.timer=null;}async tick(){if(typeof document<"u"&&document.hidden)return;let t=performance.now();if(t-this.lastSwapAt<rn)return;let e=await this.opts.getStats();if(e.fps<an?(this.overshootStart===0&&(this.overshootStart=t),t-this.overshootStart>=sn&&this.tryDowngrade(e.fps)):this.overshootStart=0,this.opts.backendKind==="webgpu"&&e.modelMs>0){let r=1e3/nn*on;e.modelMs<r?(this.headroomStart===0&&(this.headroomStart=t),t-this.headroomStart>=un&&this.tryUpgrade(e.modelMs,r)):this.headroomStart=0;}}tryDowngrade(t){if(this.currentPresetIdx<=0)return;let e=this.currentPresetIdx-1;j(`downgrade ${R[this.currentPresetIdx].model} \u2192 ${R[e].model} (fps=${t})`),this.swap(e);}tryUpgrade(t,e){if(R[this.currentPresetIdx+1]?.model==="xl"||this.currentPresetIdx>=R.length-1)return;let r=this.currentPresetIdx+1;j(`upgrade ${R[this.currentPresetIdx].model} \u2192 ${R[r].model} (modelMs=${t.toFixed(1)} < ${e.toFixed(1)})`),this.swap(r);}async swap(t){let e=R[t];this.lastSwapAt=performance.now(),this.overshootStart=0,this.headroomStart=0;try{let r=await this.opts.fetchWeights(e.model);await this.opts.swapPreset(e,r),this.currentPresetIdx=t,j(`swap to ${e.model} done`);}catch(r){j("swap failed:",r),this.opts.onError?.({message:`adaptive preset swap failed: ${r.message??String(r)}`,source:"adaptive",recoverable:true,cause:r});}}};async function pt(i){let t,e=false;if(i instanceof HTMLVideoElement){if(t=i.currentSrc||i.src,!t)throw new Error("background video: HTMLVideoElement has no src")}else if(i instanceof Blob)t=URL.createObjectURL(i),e=true;else if(typeof i=="string")t=i;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=t,await new Promise((l,f)=>{r.addEventListener("loadeddata",()=>l(),{once:true}),r.addEventListener("error",()=>f(new Error(`background video: failed to load ${t}`)),{once:true});});try{await r.play();}catch(l){throw new Error(`background video: play() rejected \u2014 ${l.message}`)}let n=new MessageChannel,a=n.port1,s=n.port2,o=false,u=r.requestVideoFrameCallback?.bind(r);if(u){let l=(f,h)=>{if(!o){try{let _=new VideoFrame(r,{timestamp:h.mediaTime*1e6});a.postMessage({frame:_},[_]);}catch{}u(l);}};u(l);}else {let l=()=>{if(!o){try{let f=new VideoFrame(r,{timestamp:performance.now()*1e3});a.postMessage({frame:f},[f]);}catch{}requestAnimationFrame(l);}};requestAnimationFrame(l);}return {port:s,transferList:[s],cleanup:()=>{o=true,a.close(),r.pause(),r.removeAttribute("src"),r.load(),e&&URL.revokeObjectURL(t);}}}var pn=4,Je=8,lt=16;async function ae(i){if(typeof i=="string")return i==="none"?{background:{kind:"none"}}:i==="blur"?{background:{kind:"blur",sigma:Je}}:{background:{kind:"image",bitmap:await ft(i)}};if(i instanceof ImageBitmap)return {background:{kind:"image",bitmap:i}};if(typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement)return {background:{kind:"image",bitmap:await createImageBitmap(i)}};if(typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement)return await ct(i);let t=i;if(t.color!==void 0)return {background:{kind:"color",rgb:ln(t.color)}};if(t.blur!==void 0)return {background:{kind:"blur",sigma:cn(t.blur)}};if(t.image!==void 0)return {background:{kind:"image",bitmap:await fn(t.image)}};if(t.video!==void 0)return await ct(t.video);throw new Error(`background: unrecognized input shape \u2014 ${V(i)}`)}async function ct(i){let t;if(typeof i=="string")t=i;else if(typeof HTMLVideoElement<"u"&&i instanceof HTMLVideoElement)t=i;else if(i&&typeof i=="object"&&"data"in i&&"type"in i)t=i.data instanceof Blob?i.data:new Blob([i.data],{type:i.type});else throw new Error(`background.video: unrecognized shape \u2014 ${V(i)}`);let e=await pt(t);return {background:{kind:"video",port:e.port},transferList:e.transferList,cleanup:e.cleanup}}function ln(i){if(typeof i=="string"){let t=i.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{6}$/.test(t))return [parseInt(t.slice(0,2),16)/255,parseInt(t.slice(2,4),16)/255,parseInt(t.slice(4,6),16)/255];if(/^[0-9a-fA-F]{3}$/.test(t))return [parseInt(t[0]+t[0],16)/255,parseInt(t[1]+t[1],16)/255,parseInt(t[2]+t[2],16)/255];throw new Error(`background.color: hex must be #rgb or #rrggbb, got ${V(i)}`)}if(!Array.isArray(i)||i.length!==3||!i.every(t=>typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1))throw new Error(`background.color: expected hex string or [r, g, b] floats in [0, 1], got ${V(i)}`);return [i[0],i[1],i[2]]}function cn(i){if(i===true)return Je;if("sigma"in i){if(typeof i.sigma!="number"||!Number.isFinite(i.sigma)||i.sigma<0)throw new Error(`background.blur.sigma must be a non-negative number, got ${i.sigma}`);return i.sigma}if("strength"in i){let t=i.strength;if(typeof t=="number"){let e=Math.max(0,Math.min(1,t));return lt*e}if(t==="low")return pn;if(t==="medium")return Je;if(t==="high")return lt;throw new Error(`background.blur.strength must be 'low' | 'medium' | 'high' | number, got ${V(t)}`)}throw new Error(`background.blur: must be true, { strength }, or { sigma } \u2014 got ${V(i)}`)}async function fn(i){if(i instanceof ImageBitmap)return i;if(typeof HTMLImageElement<"u"&&i instanceof HTMLImageElement)return createImageBitmap(i);if(typeof i=="string")return ft(i);if(i&&typeof i=="object"&&"data"in i&&"type"in i){let t=i.data instanceof Blob?i.data:new Blob([i.data],{type:i.type});return createImageBitmap(t)}throw new Error(`background.image: unrecognized shape \u2014 ${V(i)}`)}async function ft(i){let t=await fetch(i);if(!t.ok)throw new Error(`background: failed to load image from ${i} (HTTP ${t.status})`);let e=await t.blob();return createImageBitmap(e)}function V(i){return i===null?"null":typeof i!="object"?typeof i+"("+String(i)+")":`${i.constructor?.name??"Object"} ${JSON.stringify(i).slice(0,80)}`}function dt(){return {input:"MediaStreamTrackProcessor"in self?"mstp":"rvfc-postmessage",output:"MediaStreamTrackGenerator"in self?"mstg":dn()?"transfer-capture":"bitmap-shuttle"}}var ie=null;function dn(){return ie!==null||(ie=!/Firefox/.test(navigator.userAgent)),ie}function ht(i){return i==="denoise"?{mode:"denoise",denoise:{}}:typeof i=="object"?{mode:"denoise",denoise:i.denoise}:{mode:i}}function mt(i,t,e,r){let n=[i];return e.mode==="passthrough"?n.push(...t.getAudioTracks()):e.mode==="denoise"&&r&&n.push(r),new MediaStream(n)}var X={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"}}},hn={high:"dfn",mid:"dfnint8",low:"rnnoise"},mn=["high","mid","low"];function gn(i){return mn.includes(i)}function gt(i){return gn(i)?hn[i]:i}function _t(i,t){return `${i.replace(/\/$/,"")}/${t}`}async function vt(i){let t=await fetch(i);if(!t.ok)throw new Error(`audio asset fetch failed: ${t.status} ${i}`);return t.arrayBuffer()}async function xt(i,t){let e=X[i],[r,n]=await Promise.all([vt(_t(t,e.wasm)),e.weights?vt(_t(t,e.weights)):Promise.resolve(null)]);return {wasmBytes:r,weights:n}}function se(){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 _n=1.3,vn=64,xn=3,bn=`
2
2
  self.onmessage = async (e) => {
3
3
  const { wasmUrl, iters, rounds, budget } = e.data
4
4
  try {
@@ -29,7 +29,7 @@ self.onmessage = async (e) => {
29
29
  self.postMessage({ error: (err && err.message) || String(err) })
30
30
  }
31
31
  }
32
- `;async function xt(i,t){if(!ie())return "rnnoise";let e=`${i.replace(/\/$/,"")}/${X.dfn.wasm}`,r=null,n=null;try{r=URL.createObjectURL(new Blob([bn],{type:"application/javascript"})),n=new Worker(r);let a=await new Promise((s,o)=>{n.onmessage=u=>s(u.data),n.onerror=u=>o(new Error(u.message||"probe worker error")),n.postMessage({wasmUrl:e,iters:vn,rounds:xn,budget:_n});});if(a.error)throw new Error(a.error);return a.model??"rnnoise"}catch(a){return t?.(`audio tier probe failed (${a.message??String(a)}); using rnnoise`),"rnnoise"}finally{n?.terminate(),r&&URL.revokeObjectURL(r);}}var Je='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 wn=.03,kn=.995,se=class{constructor(t,e){this.opts=e;this.ctx=new AudioContext({sampleRate:48e3}),this.source=this.ctx.createMediaStreamSource(new MediaStream([t])),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 t=mt(this.opts.model);return X[t].needsSimd&&!ie()?(this.opts.onError?.(`${t} needs wasm SIMD; falling back to rnnoise`),"rnnoise"):t}async init(){let t=this.opts.model==="auto"?await xt(this.opts.weightsBaseUrl,this.opts.onError):this.resolveExplicit();this.model=t;let e=await vt(t,this.opts.weightsBaseUrl);if(await this.ctx.audioWorklet.addModule(Pn()),this.destroyed)return;let r={model:t,wasmBytes:e.wasmBytes,weights:e.weights,enabled:this.opts.enabled??true,postFilterBeta:this.opts.postFilterBeta??wn,gruLeak:this.opts.gruLeak??kn},n=new AudioWorkletNode(this.ctx,"denoise",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:r});n.port.onmessage=a=>{let s=a.data;s.type==="stats"?this.latestStats=s.stats:s.type==="error"?this.opts.onError?.(s.message):s.type==="ready"&&this.opts.onReady?.();},this.node=n,this.source.disconnect(this.dest),this.source.connect(n).connect(this.dest);}setEnabled(t){this.node?.port.postMessage({type:"enabled",value:t});}setConfig(t){this.node?.port.postMessage({type:"config",...t});}getStats(){return this.latestStats}destroy(){this.destroyed=true;try{this.node?.disconnect();}catch{}try{this.source.disconnect();}catch{}this.ctx.close();}};function Pn(){return URL.createObjectURL(new Blob([Je],{type:"application/javascript"}))}var oe=O("worker_controller"),ue=class{worker;listeners=new Map;persistentEvents=new Set;constructor(t){this.worker=t,this.worker.addEventListener("message",this.handleMessage.bind(this)),oe("constructed; message listener attached");}handleMessage(t){let{request_id:e,res:r}=t.data,n=this.listeners.get(e);oe("msg received: request_id=",e,"handler?",!!n,"persistent?",this.persistentEvents.has(e)),n&&(n(r),this.persistentEvents.has(e)||this.listeners.delete(e));}addPersistentListener(t,e){this.persistentEvents.add(t),this.listeners.set(t,e),oe("addPersistentListener:",t);}removePersistentListener(t){this.persistentEvents.delete(t),this.listeners.delete(t);}sendMessage(t,e,r=[]){let n=crypto.randomUUID();return oe("sendMessage:",t,"request_id=",n,"transferables=",r.length),new Promise(a=>{this.listeners.set(n,o=>a(o));let s={cmd:t,data:e,request_id:n};this.worker.postMessage(s,r);})}terminate(){this.worker.terminate(),this.listeners.clear(),this.persistentEvents.clear();}};var bt=O("input-postmessage/main");function yt(i){let t=document.createElement("video");t.srcObject=i,t.muted=true,t.autoplay=true,t.playsInline=true,t.play().catch(p=>{bt.warn("video.play() rejected:",p);});let e=t.requestVideoFrameCallback?.bind(t);if(!e)throw new Error("setupPostMessageInput: requestVideoFrameCallback not supported on this browser");let r=new MessageChannel,n=r.port1,a=r.port2,s=false,o=(p,l)=>{if(!s){try{let f=new VideoFrame(t,{timestamp:l.mediaTime*1e6});n.postMessage({frame:f},[f]);}catch(f){bt.warn("VideoFrame() failed; skipping frame:",f);}e(o);}};return e(o),{port:a,transferList:[a],cleanup:()=>{s=true,n.close(),t.srcObject=null,t.pause();}}}function wt(i){let t=i.getVideoTracks();if(t.length===0)throw new Error("setupMstpInput: input MediaStream has no video tracks");let e=t[0],r=self.MediaStreamTrackProcessor;if(!r)throw new Error("setupMstpInput: MediaStreamTrackProcessor not supported on this browser");let a=new r({track:e}).readable;return {readable:a,transferList:[a],cleanup:()=>{a.cancel().catch(()=>{});}}}function kt(i,t){switch(i){case "mstp":{let e=wt(t);return {initFields:{inputReadable:e.readable},transferList:e.transferList,cleanup:e.cleanup}}case "rvfc-postmessage":{let e=yt(t);return {initFields:{inputPort:e.port},transferList:e.transferList,cleanup:e.cleanup}}}}var Tn=O("bitmap-shuttle/main"),Cn=30;function Pt(i,t=Cn){let e=document.createElement("canvas");e.width=i.w,e.height=i.h;let r=e.getContext("bitmaprenderer");if(!r)throw new Error("setupBitmapShuttleOutput: bitmaprenderer context not available");let a=e.captureStream(t).getVideoTracks();if(a.length===0)throw new Error("setupBitmapShuttleOutput: captureStream produced no video tracks");let s=a[0],o=new MessageChannel,u=o.port1,p=o.port2,l=false,f=null,h=()=>{},_=3,m=0;return u.onmessage=T=>{if(l){if(m++,m<_){T.data.bmp.close();return}h();}try{r.transferFromImageBitmap(T.data.bmp);}catch(b){Tn.warn("transferFromImageBitmap failed:",b);}},u.start(),{videoTrack:s,port:p,transferList:[p],startPassthrough:T=>{if(l)return;l=true;let b=document.createElement("video");b.srcObject=T,b.muted=true,b.playsInline=true,b.play().catch(()=>{}),f=b;let C="requestVideoFrameCallback"in b?k=>{b.requestVideoFrameCallback(k);}:k=>{requestAnimationFrame(k);},B=()=>{if(l){if(b.videoWidth===0){C(B);return}createImageBitmap(b,{resizeWidth:e.width,resizeHeight:e.height,resizeQuality:"medium"}).then(k=>{if(!l){k.close();return}try{r.transferFromImageBitmap(k);}catch{}C(B);}).catch(()=>{C(B);});}};C(B),h=()=>{l=false,f&&(f.srcObject=null,f.pause(),f=null);};},cleanup:()=>{h(),u.onmessage=null,u.close(),s.stop();}}}function Tt(){let i=self.MediaStreamTrackGenerator;if(!i)throw new Error("setupMstgOutput: MediaStreamTrackGenerator not supported on this browser");let t=new i({kind:"video"}),e=t.writable;return {videoTrack:t,writable:e,transferList:[e],cleanup:()=>{e.abort().catch(()=>{}),t.stop();}}}function Ct(i,t=30){let e=document.createElement("canvas");e.width=i.w,e.height=i.h;let n=e.captureStream(t).getVideoTracks();if(n.length===0)throw new Error("setupTransferCaptureOutput: captureStream produced no video tracks");let a=n[0],s=e.transferControlToOffscreen();return {videoTrack:a,canvas:s,transferList:[s],cleanup:()=>{a.stop();}}}function Ut(i,t){switch(i){case "mstg":{let e=Tt();return {videoTrack:e.videoTrack,initFields:{outputWritable:e.writable},transferList:e.transferList,cleanup:e.cleanup}}case "transfer-capture":{let e=Ct(t);return {videoTrack:e.videoTrack,initFields:{outputCanvas:e.canvas},transferList:e.transferList,cleanup:e.cleanup}}case "bitmap-shuttle":{let e=Pt(t);return {videoTrack:e.videoTrack,initFields:{outputPort:e.port},transferList:e.transferList,startPassthrough:e.startPassthrough,cleanup:e.cleanup}}}}var Ze=`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.
32
+ `;async function bt(i,t){if(!se())return "rnnoise";let e=`${i.replace(/\/$/,"")}/${X.dfn.wasm}`,r=null,n=null;try{r=URL.createObjectURL(new Blob([bn],{type:"application/javascript"})),n=new Worker(r);let a=await new Promise((s,o)=>{n.onmessage=u=>s(u.data),n.onerror=u=>o(new Error(u.message||"probe worker error")),n.postMessage({wasmUrl:e,iters:vn,rounds:xn,budget:_n});});if(a.error)throw new Error(a.error);return a.model??"rnnoise"}catch(a){return t?.(`audio tier probe failed (${a.message??String(a)}); using rnnoise`),"rnnoise"}finally{n?.terminate(),r&&URL.revokeObjectURL(r);}}var Ze='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 J="https://cdn.longpipe.dev/models/v/0.0.5/";var wn=.03,kn=.995,oe=class{constructor(t,e={}){this.opts=e;this.ctx=new AudioContext({sampleRate:48e3}),this.source=this.ctx.createMediaStreamSource(new MediaStream([t])),this.dest=this.ctx.createMediaStreamDestination(),this.outputTrack=this.dest.stream.getAudioTracks()[0],this.resume().catch(()=>{}),this.source.connect(this.dest),this.ready=this.init().then(()=>this.node!==null,r=>(this.opts.onError?.(`audio denoise init failed: ${r.message??String(r)}`),false));}opts;outputTrack;ready;ctx;source;dest;node=null;model=null;latestStats=null;destroyed=false;resolveExplicit(){let t=gt(this.opts.model);return X[t].needsSimd&&!se()?(this.opts.onError?.(`${t} needs wasm SIMD; falling back to rnnoise`),"rnnoise"):t}async init(){let t=this.opts.weightsBaseUrl??J,e=(this.opts.model??"auto")==="auto"?await bt(t,this.opts.onError):this.resolveExplicit();this.model=e;let r=await xt(e,t);if(await this.ctx.audioWorklet.addModule(Pn()),this.destroyed)return;let n={model:e,wasmBytes:r.wasmBytes,weights:r.weights,enabled:this.opts.enabled??true,postFilterBeta:this.opts.postFilterBeta??wn,gruLeak:this.opts.gruLeak??kn},a=new AudioWorkletNode(this.ctx,"denoise",{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:n});a.port.onmessage=s=>{let o=s.data;o.type==="stats"?this.latestStats=o.stats:o.type==="error"?this.opts.onError?.(o.message):o.type==="ready"&&this.opts.onReady?.();},this.node=a,this.source.disconnect(this.dest),this.source.connect(a).connect(this.dest);}setEnabled(t){this.node?.port.postMessage({type:"enabled",value:t});}setConfig(t){this.node?.port.postMessage({type:"config",...t});}getStats(){return this.latestStats}async resume(){this.destroyed||this.ctx.state!=="suspended"||await this.ctx.resume();}destroy(){this.destroyed=true;try{this.node?.disconnect();}catch{}try{this.source.disconnect();}catch{}this.ctx.close();}};function Pn(){return URL.createObjectURL(new Blob([Ze],{type:"application/javascript"}))}var ue=O("worker_controller"),pe=class{worker;listeners=new Map;persistentEvents=new Set;constructor(t){this.worker=t,this.worker.addEventListener("message",this.handleMessage.bind(this)),ue("constructed; message listener attached");}handleMessage(t){let{request_id:e,res:r}=t.data,n=this.listeners.get(e);ue("msg received: request_id=",e,"handler?",!!n,"persistent?",this.persistentEvents.has(e)),n&&(n(r),this.persistentEvents.has(e)||this.listeners.delete(e));}addPersistentListener(t,e){this.persistentEvents.add(t),this.listeners.set(t,e),ue("addPersistentListener:",t);}removePersistentListener(t){this.persistentEvents.delete(t),this.listeners.delete(t);}sendMessage(t,e,r=[]){let n=crypto.randomUUID();return ue("sendMessage:",t,"request_id=",n,"transferables=",r.length),new Promise(a=>{this.listeners.set(n,o=>a(o));let s={cmd:t,data:e,request_id:n};this.worker.postMessage(s,r);})}terminate(){this.worker.terminate(),this.listeners.clear(),this.persistentEvents.clear();}};var yt=O("input-postmessage/main");function wt(i){let t=document.createElement("video");t.srcObject=i,t.muted=true,t.autoplay=true,t.playsInline=true,t.play().catch(p=>{yt.warn("video.play() rejected:",p);});let e=t.requestVideoFrameCallback?.bind(t);if(!e)throw new Error("setupPostMessageInput: requestVideoFrameCallback not supported on this browser");let r=new MessageChannel,n=r.port1,a=r.port2,s=false,o=(p,l)=>{if(!s){try{let f=new VideoFrame(t,{timestamp:l.mediaTime*1e6});n.postMessage({frame:f},[f]);}catch(f){yt.warn("VideoFrame() failed; skipping frame:",f);}e(o);}};return e(o),{port:a,transferList:[a],cleanup:()=>{s=true,n.close(),t.srcObject=null,t.pause();}}}function kt(i){let t=i.getVideoTracks();if(t.length===0)throw new Error("setupMstpInput: input MediaStream has no video tracks");let e=t[0],r=self.MediaStreamTrackProcessor;if(!r)throw new Error("setupMstpInput: MediaStreamTrackProcessor not supported on this browser");let a=new r({track:e}).readable;return {readable:a,transferList:[a],cleanup:()=>{a.cancel().catch(()=>{});}}}function Pt(i,t){switch(i){case "mstp":{let e=kt(t);return {initFields:{inputReadable:e.readable},transferList:e.transferList,cleanup:e.cleanup}}case "rvfc-postmessage":{let e=wt(t);return {initFields:{inputPort:e.port},transferList:e.transferList,cleanup:e.cleanup}}}}var Tn=O("bitmap-shuttle/main"),Cn=30;function Tt(i,t=Cn){let e=document.createElement("canvas");e.width=i.w,e.height=i.h;let r=e.getContext("bitmaprenderer");if(!r)throw new Error("setupBitmapShuttleOutput: bitmaprenderer context not available");let a=e.captureStream(t).getVideoTracks();if(a.length===0)throw new Error("setupBitmapShuttleOutput: captureStream produced no video tracks");let s=a[0],o=new MessageChannel,u=o.port1,p=o.port2,l=false,f=null,h=()=>{},_=3,m=0;return u.onmessage=T=>{if(l){if(m++,m<_){T.data.bmp.close();return}h();}try{r.transferFromImageBitmap(T.data.bmp);}catch(b){Tn.warn("transferFromImageBitmap failed:",b);}},u.start(),{videoTrack:s,port:p,transferList:[p],startPassthrough:T=>{if(l)return;l=true;let b=document.createElement("video");b.srcObject=T,b.muted=true,b.playsInline=true,b.play().catch(()=>{}),f=b;let C="requestVideoFrameCallback"in b?k=>{b.requestVideoFrameCallback(k);}:k=>{requestAnimationFrame(k);},B=()=>{if(l){if(b.videoWidth===0){C(B);return}createImageBitmap(b,{resizeWidth:e.width,resizeHeight:e.height,resizeQuality:"medium"}).then(k=>{if(!l){k.close();return}try{r.transferFromImageBitmap(k);}catch{}C(B);}).catch(()=>{C(B);});}};C(B),h=()=>{l=false,f&&(f.srcObject=null,f.pause(),f=null);};},cleanup:()=>{h(),u.onmessage=null,u.close(),s.stop();}}}function Ct(){let i=self.MediaStreamTrackGenerator;if(!i)throw new Error("setupMstgOutput: MediaStreamTrackGenerator not supported on this browser");let t=new i({kind:"video"}),e=t.writable;return {videoTrack:t,writable:e,transferList:[e],cleanup:()=>{e.abort().catch(()=>{}),t.stop();}}}function Ut(i,t=30){let e=document.createElement("canvas");e.width=i.w,e.height=i.h;let n=e.captureStream(t).getVideoTracks();if(n.length===0)throw new Error("setupTransferCaptureOutput: captureStream produced no video tracks");let a=n[0],s=e.transferControlToOffscreen();return {videoTrack:a,canvas:s,transferList:[s],cleanup:()=>{a.stop();}}}function At(i,t){switch(i){case "mstg":{let e=Ct();return {videoTrack:e.videoTrack,initFields:{outputWritable:e.writable},transferList:e.transferList,cleanup:e.cleanup}}case "transfer-capture":{let e=Ut(t);return {videoTrack:e.videoTrack,initFields:{outputCanvas:e.canvas},transferList:e.transferList,cleanup:e.cleanup}}case "bitmap-shuttle":{let e=Tt(t);return {videoTrack:e.videoTrack,initFields:{outputPort:e.port},transferList:e.transferList,startPassthrough:e.startPassthrough,cleanup:e.cleanup}}}}var et=`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
33
  //
34
34
  // Identical math, layout, and output to conv2d.wgsl, but each thread computes 2
35
35
  // output channel-groups (8 channels) for one pixel, loading each input vec4 ONCE
@@ -7037,7 +7037,7 @@ const vec2 VERTS[6] = vec2[6](
7037
7037
  vec2(-1.0,1.0), vec2(1.0,-1.0), vec2(1.0,1.0)
7038
7038
  );
7039
7039
  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 N=O("pipeline");function Un(){{let i=new Blob([Ze],{type:"application/javascript"}),t=URL.createObjectURL(i),e=new Worker(t,{type:"module"});return URL.revokeObjectURL(t),e}}var pe={strength:.6,amount:8,detail:.35,style:"freq-sep"},An=.15,Et="https://cdn.longpipe.dev/models/v/0.0.5/",Sn={background:"blur",preset:"auto",weightsBaseUrl:Et,audio:"passthrough",enabled:true,adaptive:true,debug:false},At={w:1280,h:720};function Bn(i,t){if(t)return t;let r=i.getVideoTracks()[0]?.getSettings()??{};return {w:r.width||At.w,h:r.height||At.h}}function St(i,t,e){let r=e==="f16"?".f16.bin":".bin";return `${i.replace(/\/$/,"")}/model_${t}${r}`}async function Bt(i,t,e){if(e==="f16"){let a=await fetch(St(i,t,"f16"));if(a.ok)return a.arrayBuffer()}let r=St(i,t,"f32"),n=await fetch(r);if(!n.ok)throw new Error(`weights fetch failed: ${n.status} ${r}`);return n.arrayBuffer()}async function En(i,t){let e=i.replace(/\/$/,""),r=(async()=>{if(t==="f16"){let f=await fetch(`${e}/model_landmark_mesh.f16.bin`);if(f.ok)return f.arrayBuffer()}let p=`${e}/model_landmark_mesh.bin`,l=await fetch(p);if(!l.ok)throw new Error(`touchup: landmark weights fetch failed: ${l.status} ${p}`);return l.arrayBuffer()})(),n=fetch(`${e}/face_topology.json`).then(p=>{if(!p.ok)throw new Error(`touchup: face_topology.json fetch failed: ${p.status}`);return p.json()}),a=fetch(`${e}/weight_mask.png`).then(async p=>{if(!p.ok)throw new Error(`touchup: weight_mask.png fetch failed: ${p.status}`);return createImageBitmap(await p.blob())}),[s,o,u]=await Promise.all([r,n,a]);return {landmarkWeights:s,topoCount:o.count,topoUv:new Float32Array(o.uv),topoIdx:new Float32Array(o.idx),weightMask:u}}var et=class{stream;ready;controller;worker;inputCleanup;outputCleanup;adaptive=null;denoiser=null;touchupAssets=null;weightsBaseUrl=Et;resolvedDtype="f32";bgCleanup=null;previewBgCleanup=null;constructor(t,e){let r={...Sn,...e};ot(r.debug);let n=ft(),a=kt(n.input,t),s=Bn(t,r.outputResolution),o=Ut(n.output,s);this.inputCleanup=a.cleanup,this.outputCleanup=o.cleanup;let u=dt(r.audio),p;if(u.mode==="denoise"){let h=t.getAudioTracks()[0];h?(this.denoiser=new se(h,{model:u.denoise?.model??"auto",weightsBaseUrl:r.weightsBaseUrl,postFilterBeta:u.denoise?.postFilterBeta,gruLeak:u.denoise?.gruLeak,enabled:u.denoise?.enabled,onError:_=>r.onError?.({message:_,source:"audio",recoverable:true})}),p=this.denoiser.outputTrack):r.onError?.({message:'audio: "denoise" requested but the input stream has no audio track',source:"audio",recoverable:true});}this.stream=ht(o.videoTrack,t,u,p),o.startPassthrough?.(t),this.worker=Un(),this.controller=new ue(this.worker),this.ready=new Promise((h,_)=>{this.controller.addPersistentListener("ready",()=>{N("ready handler invoked; resolving .ready"),r.onReady?.(),h();}),this.controller.addPersistentListener("error",m=>{console.error(`[longpipe/pipeline] error (${m.source}):`,m.message),m.recoverable||_(new Error(m.message)),r.onError?.(m);});});let l={topology:n,preset:r.preset,enabled:r.enabled,backend:"auto",dtype:r.dtype??"f16",canvasSize:s,debug:r.debug,...a.initFields,...o.initFields},f=[...a.transferList,...o.transferList];this.weightsBaseUrl=r.weightsBaseUrl,this.bootstrap(l,r.background,f,r.weightsBaseUrl,r.adaptive,r.onError,r.touchup,r.reframe);}async bootstrap(t,e,r,n,a,s,o,u){try{N("normalizing background\u2026");let p=await ne(e);this.bgCleanup=p.cleanup??null;let l={...t,background:p.background},f=[...r,...p.transferList??[]];N("sending init\u2026");let h=await this.controller.sendMessage("init",l,f);N("init resolved:",h),N("fetching weights:",h.resolvedPreset.model,h.resolvedDtype);let _=await Bt(n,h.resolvedPreset.model,h.resolvedDtype);N("weights bytes:",_.byteLength),this.resolvedDtype=h.resolvedDtype,N("sending startRender\u2026"),await this.controller.sendMessage("startRender",{weights:_},[_]),N("startRender resolved; awaiting first frame"),u&&this.setReframe(u).catch(m=>{s?.({message:`reframe init failed: ${m.message??m}`,source:"unknown",recoverable:!0,cause:m});}),o&&this.setTouchup(o).catch(m=>{s?.({message:`touchup init failed: ${m.message??m}`,source:"unknown",recoverable:!0,cause:m});}),l.preset==="auto"&&a&&(this.adaptive=new re({backendKind:h.resolvedBackend,initialModel:h.resolvedPreset.model,fetchWeights:m=>Bt(n,m,h.resolvedDtype),getStats:()=>this.getStats(),swapPreset:async(m,W)=>{await this.controller.sendMessage("setPreset",{preset:m,weights:W},[W]);},onError:s}),this.adaptive.start());}catch(p){console.error("[longpipe/pipeline] bootstrap failed:",p),this.controller.handleMessage.call(this.controller,{data:{request_id:"error",res:{message:p.message??String(p),source:"worker",recoverable:false,cause:p}}});}}then(t,e){return this.ready.then(()=>t?t(this):this,e)}async setBackground(t){let e=await ne(t),r=this.bgCleanup;this.bgCleanup=e.cleanup??null,await this.controller.sendMessage("setBackground",e.background,e.transferList),r?.();}async setTouchup(t){if(await this.ready,t===null){await this.controller.sendMessage("setTouchup",null);return}this.touchupAssets||(this.touchupAssets=await En(this.weightsBaseUrl,this.resolvedDtype));let e={strength:t.strength??pe.strength,amount:t.amount??pe.amount,detail:t.detail??pe.detail,style:t.style??pe.style,thresh:An};await this.controller.sendMessage("setTouchup",{...this.touchupAssets,params:e});}async setReframe(t){await this.ready;let e=t===true?{}:t===false||t===null?null:t;await this.controller.sendMessage("setReframe",e);}async reframe(){await this.ready,await this.controller.sendMessage("reframeNow",void 0);}setPreset(t,e){this.controller.sendMessage("setPreset",{preset:t,weights:e});}attachPreview(t){let e=t.transferControlToOffscreen();this.controller.sendMessage("attachPreview",{canvas:e},[e]);}async setPreview(t){let e=await ne(t.background),r=this.previewBgCleanup;this.previewBgCleanup=e.cleanup??null,await this.controller.sendMessage("setPreview",{background:e.background,fps:t.fps},e.transferList),r?.();}clearPreview(){this.controller.sendMessage("clearPreview",{}),this.previewBgCleanup?.(),this.previewBgCleanup=null;}setEnabled(t){this.controller.sendMessage("setEnabled",{enabled:t});}async getStats(){return this.controller.sendMessage("getStats",{})}setDenoise(t){if(this.denoiser){if(typeof t=="boolean"){this.denoiser.setEnabled(t);return}(t.postFilterBeta!=null||t.gruLeak!=null)&&this.denoiser.setConfig({postFilterBeta:t.postFilterBeta,gruLeak:t.gruLeak}),t.enabled!=null&&this.denoiser.setEnabled(t.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();}};var $=new Float32Array(1),J=new Uint32Array($.buffer);function In(i){$[0]=i;let t=J[0],e=t>>>16&32768,r=t&2147483647,n=(r>>>23)-127+15;if((t&2139095040)===2139095040)return (t&8388607)!==0?e|32256:e|31744;if(n>=31)return e|31744;if(n<=0){if(n<-10)return e;let p=r&8388607|8388608,l=14-n,f=p>>>l,h=p>>>l-1&1,_=(p&(1<<l-1)-1)!==0?1:0;return h&&(_||f&1)&&(f+=1),e|f}let a=r>>>13&1023,s=r>>>12&1,o=(r&4095)!==0?1:0,u=n<<10|a;return s&&(o||a&1)&&(u+=1,(u>>>10&31)===31)?e|31744:e|u}function tt(i){let t=(i&32768)<<16,e=(i&31744)>>>10,r=i&1023;if(e===0){if(r===0)return J[0]=t,$[0];let n=r,a=1;for(;(n&1024)===0;)n<<=1,a-=1;return n&=1023,J[0]=t|a+127-15<<23|n<<13,$[0]}return e===31?(J[0]=t|2139095040|r<<13,$[0]):(J[0]=t|e+127-15<<23|r<<13,$[0])}function It(i){let t=new Uint16Array(i.length);for(let e=0;e<i.length;e++)t[e]=In(i[e]);return t}function rt(i){let t=new Float32Array(i.length);for(let e=0;e<i.length;e++)t[e]=tt(i[e]);return t}var c=class{constructor(t){this.backend=t;}backend;shader="";pipeline;bindGroup;uniformDefs=[];uniformBuffers={};createUniform(t,e){this.uniformDefs.push({name:t,type:e});}setUniform(t,e){let r=this.backend.device.createBuffer({size:e.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:true});e instanceof Uint32Array?new Uint32Array(r.getMappedRange()).set(e):new Float32Array(r.getMappedRange()).set(e),r.unmap(),this.uniformBuffers[t]=r;}defaultBindGroup(){let t=[],e=0;for(let r of this.inputs)t.push({binding:e++,resource:{buffer:r.buffer}});for(let r of this.weights)t.push({binding:e++,resource:{buffer:r.buffer}});for(let r of this.uniformDefs)t.push({binding:e++,resource:{buffer:this.uniformBuffers[r.name]}});return t.push({binding:e,resource:{buffer:this.output.buffer}}),this.backend.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:t})}defaultSetup(){let t=this.backend.device.createShaderModule({code:this.shader});this.pipeline=this.backend.device.createComputePipeline({layout:"auto",compute:{module:t,entryPoint:"main"}}),this.bindGroup=this.defaultBindGroup();}run(){let t=this.backend.device.createCommandEncoder(),e=t.beginComputePass();e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.dispatchWorkgroups(...this.dispatch),e.end(),this.backend.device.queue.submit([t.finish()]);}};var Ft=`// Conv2d, output-channel-blocked (K=2) \u2014 drop-in replacement for conv2d.wgsl.
7040
+ `;var N=O("pipeline");function Un(){{let i=new Blob([et],{type:"application/javascript"}),t=URL.createObjectURL(i),e=new Worker(t,{type:"module"});return URL.revokeObjectURL(t),e}}var le={strength:.6,amount:8,detail:.35,style:"freq-sep"},An=.15,Sn={background:"blur",preset:"auto",weightsBaseUrl:J,audio:"passthrough",enabled:true,adaptive:true,debug:false},St={w:1280,h:720};function Bn(i,t){if(t)return t;let r=i.getVideoTracks()[0]?.getSettings()??{};return {w:r.width||St.w,h:r.height||St.h}}function Bt(i,t,e){let r=e==="f16"?".f16.bin":".bin";return `${i.replace(/\/$/,"")}/model_${t}${r}`}async function Et(i,t,e){if(e==="f16"){let a=await fetch(Bt(i,t,"f16"));if(a.ok)return a.arrayBuffer()}let r=Bt(i,t,"f32"),n=await fetch(r);if(!n.ok)throw new Error(`weights fetch failed: ${n.status} ${r}`);return n.arrayBuffer()}async function En(i,t){let e=i.replace(/\/$/,""),r=(async()=>{if(t==="f16"){let f=await fetch(`${e}/model_landmark_mesh.f16.bin`);if(f.ok)return f.arrayBuffer()}let p=`${e}/model_landmark_mesh.bin`,l=await fetch(p);if(!l.ok)throw new Error(`touchup: landmark weights fetch failed: ${l.status} ${p}`);return l.arrayBuffer()})(),n=fetch(`${e}/face_topology.json`).then(p=>{if(!p.ok)throw new Error(`touchup: face_topology.json fetch failed: ${p.status}`);return p.json()}),a=fetch(`${e}/weight_mask.png`).then(async p=>{if(!p.ok)throw new Error(`touchup: weight_mask.png fetch failed: ${p.status}`);return createImageBitmap(await p.blob())}),[s,o,u]=await Promise.all([r,n,a]);return {landmarkWeights:s,topoCount:o.count,topoUv:new Float32Array(o.uv),topoIdx:new Float32Array(o.idx),weightMask:u}}var tt=class{stream;ready;controller;worker;inputCleanup;outputCleanup;adaptive=null;denoiser=null;touchupAssets=null;weightsBaseUrl=J;resolvedDtype="f32";bgCleanup=null;previewBgCleanup=null;constructor(t,e){let r={...Sn,...e};ut(r.debug);let n=dt(),a=Pt(n.input,t),s=Bn(t,r.outputResolution),o=At(n.output,s);this.inputCleanup=a.cleanup,this.outputCleanup=o.cleanup;let u=ht(r.audio),p;if(u.mode==="denoise"){let h=t.getAudioTracks()[0];h?(this.denoiser=new oe(h,{model:u.denoise?.model??"auto",weightsBaseUrl:r.weightsBaseUrl,postFilterBeta:u.denoise?.postFilterBeta,gruLeak:u.denoise?.gruLeak,enabled:u.denoise?.enabled,onError:_=>r.onError?.({message:_,source:"audio",recoverable:true})}),p=this.denoiser.outputTrack):r.onError?.({message:'audio: "denoise" requested but the input stream has no audio track',source:"audio",recoverable:true});}this.stream=mt(o.videoTrack,t,u,p),o.startPassthrough?.(t),this.worker=Un(),this.controller=new pe(this.worker),this.ready=new Promise((h,_)=>{this.controller.addPersistentListener("ready",()=>{N("ready handler invoked; resolving .ready"),r.onReady?.(),h();}),this.controller.addPersistentListener("error",m=>{console.error(`[longpipe/pipeline] error (${m.source}):`,m.message),m.recoverable||_(new Error(m.message)),r.onError?.(m);});});let l={topology:n,preset:r.preset,enabled:r.enabled,backend:"auto",dtype:r.dtype??"f16",canvasSize:s,debug:r.debug,...a.initFields,...o.initFields},f=[...a.transferList,...o.transferList];this.weightsBaseUrl=r.weightsBaseUrl,this.bootstrap(l,r.background,f,r.weightsBaseUrl,r.adaptive,r.onError,r.touchup,r.reframe);}async bootstrap(t,e,r,n,a,s,o,u){try{N("normalizing background\u2026");let p=await ae(e);this.bgCleanup=p.cleanup??null;let l={...t,background:p.background},f=[...r,...p.transferList??[]];N("sending init\u2026");let h=await this.controller.sendMessage("init",l,f);N("init resolved:",h),N("fetching weights:",h.resolvedPreset.model,h.resolvedDtype);let _=await Et(n,h.resolvedPreset.model,h.resolvedDtype);N("weights bytes:",_.byteLength),this.resolvedDtype=h.resolvedDtype,N("sending startRender\u2026"),await this.controller.sendMessage("startRender",{weights:_},[_]),N("startRender resolved; awaiting first frame"),u&&this.setReframe(u).catch(m=>{s?.({message:`reframe init failed: ${m.message??m}`,source:"unknown",recoverable:!0,cause:m});}),o&&this.setTouchup(o).catch(m=>{s?.({message:`touchup init failed: ${m.message??m}`,source:"unknown",recoverable:!0,cause:m});}),l.preset==="auto"&&a&&(this.adaptive=new ne({backendKind:h.resolvedBackend,initialModel:h.resolvedPreset.model,fetchWeights:m=>Et(n,m,h.resolvedDtype),getStats:()=>this.getStats(),swapPreset:async(m,W)=>{await this.controller.sendMessage("setPreset",{preset:m,weights:W},[W]);},onError:s}),this.adaptive.start());}catch(p){console.error("[longpipe/pipeline] bootstrap failed:",p),this.controller.handleMessage.call(this.controller,{data:{request_id:"error",res:{message:p.message??String(p),source:"worker",recoverable:false,cause:p}}});}}then(t,e){return this.ready.then(()=>t?t(this):this,e)}async setBackground(t){let e=await ae(t),r=this.bgCleanup;this.bgCleanup=e.cleanup??null,await this.controller.sendMessage("setBackground",e.background,e.transferList),r?.();}async setTouchup(t){if(await this.ready,t===null){await this.controller.sendMessage("setTouchup",null);return}this.touchupAssets||(this.touchupAssets=await En(this.weightsBaseUrl,this.resolvedDtype));let e={strength:t.strength??le.strength,amount:t.amount??le.amount,detail:t.detail??le.detail,style:t.style??le.style,thresh:An};await this.controller.sendMessage("setTouchup",{...this.touchupAssets,params:e});}async setReframe(t){await this.ready;let e=t===true?{}:t===false||t===null?null:t;await this.controller.sendMessage("setReframe",e);}async reframe(){await this.ready,await this.controller.sendMessage("reframeNow",void 0);}setPreset(t,e){this.controller.sendMessage("setPreset",{preset:t,weights:e});}attachPreview(t){let e=t.transferControlToOffscreen();this.controller.sendMessage("attachPreview",{canvas:e},[e]);}async setPreview(t){let e=await ae(t.background),r=this.previewBgCleanup;this.previewBgCleanup=e.cleanup??null,await this.controller.sendMessage("setPreview",{background:e.background,fps:t.fps},e.transferList),r?.();}clearPreview(){this.controller.sendMessage("clearPreview",{}),this.previewBgCleanup?.(),this.previewBgCleanup=null;}setEnabled(t){this.controller.sendMessage("setEnabled",{enabled:t});}async getStats(){return this.controller.sendMessage("getStats",{})}setDenoise(t){if(this.denoiser){if(typeof t=="boolean"){this.denoiser.setEnabled(t);return}(t.postFilterBeta!=null||t.gruLeak!=null)&&this.denoiser.setConfig({postFilterBeta:t.postFilterBeta,gruLeak:t.gruLeak}),t.enabled!=null&&this.denoiser.setEnabled(t.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();}};var $=new Float32Array(1),Z=new Uint32Array($.buffer);function In(i){$[0]=i;let t=Z[0],e=t>>>16&32768,r=t&2147483647,n=(r>>>23)-127+15;if((t&2139095040)===2139095040)return (t&8388607)!==0?e|32256:e|31744;if(n>=31)return e|31744;if(n<=0){if(n<-10)return e;let p=r&8388607|8388608,l=14-n,f=p>>>l,h=p>>>l-1&1,_=(p&(1<<l-1)-1)!==0?1:0;return h&&(_||f&1)&&(f+=1),e|f}let a=r>>>13&1023,s=r>>>12&1,o=(r&4095)!==0?1:0,u=n<<10|a;return s&&(o||a&1)&&(u+=1,(u>>>10&31)===31)?e|31744:e|u}function rt(i){let t=(i&32768)<<16,e=(i&31744)>>>10,r=i&1023;if(e===0){if(r===0)return Z[0]=t,$[0];let n=r,a=1;for(;(n&1024)===0;)n<<=1,a-=1;return n&=1023,Z[0]=t|a+127-15<<23|n<<13,$[0]}return e===31?(Z[0]=t|2139095040|r<<13,$[0]):(Z[0]=t|e+127-15<<23|r<<13,$[0])}function It(i){let t=new Uint16Array(i.length);for(let e=0;e<i.length;e++)t[e]=In(i[e]);return t}function nt(i){let t=new Float32Array(i.length);for(let e=0;e<i.length;e++)t[e]=rt(i[e]);return t}var c=class{constructor(t){this.backend=t;}backend;shader="";pipeline;bindGroup;uniformDefs=[];uniformBuffers={};createUniform(t,e){this.uniformDefs.push({name:t,type:e});}setUniform(t,e){let r=this.backend.device.createBuffer({size:e.byteLength,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,mappedAtCreation:true});e instanceof Uint32Array?new Uint32Array(r.getMappedRange()).set(e):new Float32Array(r.getMappedRange()).set(e),r.unmap(),this.uniformBuffers[t]=r;}defaultBindGroup(){let t=[],e=0;for(let r of this.inputs)t.push({binding:e++,resource:{buffer:r.buffer}});for(let r of this.weights)t.push({binding:e++,resource:{buffer:r.buffer}});for(let r of this.uniformDefs)t.push({binding:e++,resource:{buffer:this.uniformBuffers[r.name]}});return t.push({binding:e,resource:{buffer:this.output.buffer}}),this.backend.device.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:t})}defaultSetup(){let t=this.backend.device.createShaderModule({code:this.shader});this.pipeline=this.backend.device.createComputePipeline({layout:"auto",compute:{module:t,entryPoint:"main"}}),this.bindGroup=this.defaultBindGroup();}run(){let t=this.backend.device.createCommandEncoder(),e=t.beginComputePass();e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.dispatchWorkgroups(...this.dispatch),e.end(),this.backend.device.queue.submit([t.finish()]);}};var Ft=`// Conv2d, output-channel-blocked (K=2) \u2014 drop-in replacement for conv2d.wgsl.
7041
7041
  //
7042
7042
  // Identical math, layout, and output to conv2d.wgsl, but each thread computes 2
7043
7043
  // output channel-groups (8 channels) for one pixel, loading each input vec4 ONCE
@@ -7207,7 +7207,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7207
7207
  output_buf[baseO + o0] = act(acc0, params.activation);
7208
7208
  if (has1) { output_buf[baseO + o1] = act(acc1, params.activation); }
7209
7209
  }
7210
- `;function A(i,t,e,r){return typeof r=="number"?Math.floor((i+2*r-t)/e)+1:r==="same"?Math.ceil(i/e):Math.floor((i-t)/e)+1}function nt(i,t,e,r){return (i-1)*e-2*r+t}function Dn(i,t,e,r){return Math.floor(Math.max((t-1)*r+e-i,0)/2)}function S(i,t,e,r,n){return typeof i=="number"?i:i==="same"?Dn(t,e,r,n):0}function d(i){return i instanceof Float32Array||i instanceof Uint16Array?i:new Float32Array(i)}function w(i){let t=Math.max(4,Math.ceil(i.length/4)*4),e=new Float32Array(t),r=i instanceof Uint16Array;for(let n=0;n<i.length;n++)e[n]=r?tt(i[n]):i[n];return e}var le=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Wt:Ft;let a=A(e.h,n.kernel,n.stride,n.padding),s=A(e.w,n.kernel,n.stride,n.padding),o=e.c/4,u=n.outChannels/4,p=S(n.padding,e.h,a,n.kernel,n.stride),l=S(n.padding,e.w,s,n.kernel,n.stride);this.output=t.tensor(a,s,n.outChannels),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,a,s,o,u,n.kernel,n.kernel,n.stride,p,l,n.activation==="relu6"?1:n.activation==="relu"?2:n.activation==="leaky"?3:0])),this.defaultSetup(),this.dispatch=[Math.ceil(s/8),Math.ceil(a/8),Math.ceil(u/2)];}};var Dt=`// ConvTranspose2d \u2014 gather form, f32 variant. See conv_transpose2d_f16.wgsl for
7210
+ `;function A(i,t,e,r){return typeof r=="number"?Math.floor((i+2*r-t)/e)+1:r==="same"?Math.ceil(i/e):Math.floor((i-t)/e)+1}function at(i,t,e,r){return (i-1)*e-2*r+t}function Dn(i,t,e,r){return Math.floor(Math.max((t-1)*r+e-i,0)/2)}function S(i,t,e,r,n){return typeof i=="number"?i:i==="same"?Dn(t,e,r,n):0}function d(i){return i instanceof Float32Array||i instanceof Uint16Array?i:new Float32Array(i)}function w(i){let t=Math.max(4,Math.ceil(i.length/4)*4),e=new Float32Array(t),r=i instanceof Uint16Array;for(let n=0;n<i.length;n++)e[n]=r?rt(i[n]):i[n];return e}var ce=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Wt:Ft;let a=A(e.h,n.kernel,n.stride,n.padding),s=A(e.w,n.kernel,n.stride,n.padding),o=e.c/4,u=n.outChannels/4,p=S(n.padding,e.h,a,n.kernel,n.stride),l=S(n.padding,e.w,s,n.kernel,n.stride);this.output=t.tensor(a,s,n.outChannels),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,a,s,o,u,n.kernel,n.kernel,n.stride,p,l,n.activation==="relu6"?1:n.activation==="relu"?2:n.activation==="leaky"?3:0])),this.defaultSetup(),this.dispatch=[Math.ceil(s/8),Math.ceil(a/8),Math.ceil(u/2)];}};var Dt=`// ConvTranspose2d \u2014 gather form, f32 variant. See conv_transpose2d_f16.wgsl for
7211
7211
  // the math; this is the f32 storage build (mat4x4<f32>).
7212
7212
 
7213
7213
  struct Params {
@@ -7355,7 +7355,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7355
7355
 
7356
7356
  output_buf[oy * params.out_w * O + ox * O + o] = act(result, params.activation);
7357
7357
  }
7358
- `;var ce=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Gt:Dt;let a=nt(e.h,n.kernel,n.stride,n.padding),s=nt(e.w,n.kernel,n.stride,n.padding),o=e.c/4,u=n.outChannels/4;this.output=t.tensor(a,s,n.outChannels),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,a,s,o,u,n.kernel,n.kernel,n.stride,n.padding,n.padding,n.activation==="relu6"?1:n.activation==="relu"?2:n.activation==="leaky"?3:0])),this.defaultSetup(),this.dispatch=[Math.ceil(s/8),Math.ceil(a/8),u];}};var Ot=`// Depthwise Conv2d \u2014 groups = in_channels (each channel convolved independently).
7358
+ `;var fe=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Gt:Dt;let a=at(e.h,n.kernel,n.stride,n.padding),s=at(e.w,n.kernel,n.stride,n.padding),o=e.c/4,u=n.outChannels/4;this.output=t.tensor(a,s,n.outChannels),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,a,s,o,u,n.kernel,n.kernel,n.stride,n.padding,n.padding,n.activation==="relu6"?1:n.activation==="relu"?2:n.activation==="leaky"?3:0])),this.defaultSetup(),this.dispatch=[Math.ceil(s/8),Math.ceil(a/8),u];}};var Ot=`// Depthwise Conv2d \u2014 groups = in_channels (each channel convolved independently).
7359
7359
  //
7360
7360
  // Weight layout: [K*K][channel_groups] array of vec4
7361
7361
  // weight index = (ky*kernel_w + kx) * channel_groups + c
@@ -7495,7 +7495,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7495
7495
 
7496
7496
  output_buf[y * params.out_w * C + x * C + c] = result;
7497
7497
  }
7498
- `;var fe=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Mt:Ot;let a=A(e.h,n.kernel,n.stride,n.padding),s=A(e.w,n.kernel,n.stride,n.padding),o=e.c/4,u=S(n.padding,e.h,a,n.kernel,n.stride),p=S(n.padding,e.w,s,n.kernel,n.stride);this.output=t.tensor(a,s,e.c),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,a,s,o,n.kernel,n.kernel,n.stride,u,p,n.activation==="relu6"?1:0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(s/8),Math.ceil(a/8),o];}};var Rt=`// Element-wise add of two tensors \u2014 used for residual connections in MBConv blocks.
7498
+ `;var de=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Mt:Ot;let a=A(e.h,n.kernel,n.stride,n.padding),s=A(e.w,n.kernel,n.stride,n.padding),o=e.c/4,u=S(n.padding,e.h,a,n.kernel,n.stride),p=S(n.padding,e.w,s,n.kernel,n.stride);this.output=t.tensor(a,s,e.c),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,a,s,o,n.kernel,n.kernel,n.stride,u,p,n.activation==="relu6"?1:0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(s/8),Math.ceil(a/8),o];}};var Rt=`// Element-wise add of two tensors \u2014 used for residual connections in MBConv blocks.
7499
7499
  // Operates on the flat float buffer directly; layout is irrelevant for a pure element-wise op.
7500
7500
 
7501
7501
  struct Params {
@@ -7539,7 +7539,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7539
7539
  if (idx >= params.size) { return; }
7540
7540
  output[idx] = input_a[idx] + input_b[idx];
7541
7541
  }
7542
- `;var de=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?zt:Rt;let n=e.h*e.w*e.c;this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n/256),1,1];}};var Lt=`// Element-wise sigmoid: output = 1 / (1 + exp(-x)).
7542
+ `;var he=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?zt:Rt;let n=e.h*e.w*e.c;this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n/256),1,1];}};var Lt=`// Element-wise sigmoid: output = 1 / (1 + exp(-x)).
7543
7543
  // Operates on packed vec4 buffers (NHWC layout). exp() and arithmetic are element-wise on vec4.
7544
7544
 
7545
7545
  struct Params {
@@ -7581,7 +7581,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7581
7581
  let x = vec4<f32>(input_buf[idx]);
7582
7582
  output_buf[idx] = vec4<f16>(1.0 / (1.0 + exp(-x)));
7583
7583
  }
7584
- `;var he=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e){super(t),this.shader=t.dtype==="f16"?Ht:Lt;let r=e.h*e.w*(e.c/4);this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([r,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r/256),1,1];}};var Nt=`// Element-wise tanh \u2014 used by ConvGRU candidate activation.
7584
+ `;var me=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e){super(t),this.shader=t.dtype==="f16"?Ht:Lt;let r=e.h*e.w*(e.c/4);this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([r,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r/256),1,1];}};var Nt=`// Element-wise tanh \u2014 used by ConvGRU candidate activation.
7585
7585
  // Operates on packed vec4 buffers (NHWC layout). tanh() is element-wise on vec4.
7586
7586
 
7587
7587
  struct Params {
@@ -7623,7 +7623,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7623
7623
  let x = vec4<f32>(input_buf[idx]);
7624
7624
  output_buf[idx] = vec4<f16>(tanh(x));
7625
7625
  }
7626
- `;var me=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e){super(t),this.shader=t.dtype==="f16"?Vt:Nt;let r=e.h*e.w*(e.c/4);this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([r,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r/256),1,1];}};var qt=`// Element-wise multiply \u2014 used in ConvGRU for r \u2299 h_prev.
7626
+ `;var ge=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e){super(t),this.shader=t.dtype==="f16"?Vt:Nt;let r=e.h*e.w*(e.c/4);this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([r,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r/256),1,1];}};var qt=`// Element-wise multiply \u2014 used in ConvGRU for r \u2299 h_prev.
7627
7627
  // Same flat-float layout as add.wgsl.
7628
7628
 
7629
7629
  struct Params {
@@ -7667,7 +7667,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7667
7667
  if (idx >= params.size) { return; }
7668
7668
  output[idx] = input_a[idx] * input_b[idx];
7669
7669
  }
7670
- `;var ge=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?jt:qt;let n=e.h*e.w*e.c;this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n/256),1,1];}};var Xt=`// Bilinear gather-warp (f32). See warp_f16.wgsl for the math.
7670
+ `;var _e=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?jt:qt;let n=e.h*e.w*e.c;this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n/256),1,1];}};var Xt=`// Bilinear gather-warp (f32). See warp_f16.wgsl for the math.
7671
7671
 
7672
7672
  struct Params {
7673
7673
  h : u32,
@@ -7759,7 +7759,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
7759
7759
  let bot = mix(samp(x0, y0 + 1, W, H, g), samp(x0 + 1, y0 + 1, W, H, g), tx);
7760
7760
  output_buf[(y * params.w + x) * params.groups + g] = vec4<f16>(mix(top, bot, ty));
7761
7761
  }
7762
- `;var _e=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?$t:Xt,this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e,r],this.createUniform("params","Params");let a=new Uint32Array(4);a[0]=e.h,a[1]=e.w,new Float32Array(a.buffer)[2]=n.flowScale,a[3]=e.c/4,this.setUniform("params",a),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),e.c/4];}};var Kt=`// Face-box decode from 5-keypoint heatmaps (f32). One workgroup: threads 0-4
7762
+ `;var ve=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?$t:Xt,this.output=t.tensor(e.h,e.w,e.c),this.inputs=[e,r],this.createUniform("params","Params");let a=new Uint32Array(4);a[0]=e.h,a[1]=e.w,new Float32Array(a.buffer)[2]=n.flowScale,a[3]=e.c/4,this.setUniform("params",a),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),e.c/4];}};var Kt=`// Face-box decode from 5-keypoint heatmaps (f32). One workgroup: threads 0-4
7763
7763
  // each soft-argmax one channel (peak + windowed centroid \u2014 hard argmax snaps
7764
7764
  // to whole cells and jitters the crop); thread 0 combines the keypoint hull
7765
7765
  // into a pixel-square box.
@@ -7935,7 +7935,7 @@ fn main(@builtin(local_invocation_id) lid: vec3<u32>) {
7935
7935
  let cy = ((y0 + y1) * 0.5 + 0.5) / f32(params.h);
7936
7936
  out_buf[0] = vec4<f16>(vec4<f32>(cx, cy, half_px / f32(params.w), score));
7937
7937
  }
7938
- `;var ve=class extends c{inputs;weights=[];output;dispatch=[1,1,1];shader;constructor(t,e,r){if(super(t),e.c!==8)throw new Error(`FaceBoxFromHeatmaps: expected 8-ch heatmaps (5 real), got ${e.c}`);this.shader=t.dtype==="f16"?Yt:Kt,this.output=t.tensor(1,1,4),this.inputs=[e],this.createUniform("params","Params");let n=new Uint32Array(5);n[0]=e.h,n[1]=e.w,new Int32Array(n.buffer)[2]=r.win;let a=new Float32Array(n.buffer);a[3]=r.thresh,a[4]=r.boxScale,this.setUniform("params",n),this.defaultSetup();}};var Qt=`// MULTI-FACE box decode from 5-keypoint heatmaps (f32) \u2192 1\xD7K\xD74 box tensor.
7938
+ `;var xe=class extends c{inputs;weights=[];output;dispatch=[1,1,1];shader;constructor(t,e,r){if(super(t),e.c!==8)throw new Error(`FaceBoxFromHeatmaps: expected 8-ch heatmaps (5 real), got ${e.c}`);this.shader=t.dtype==="f16"?Yt:Kt,this.output=t.tensor(1,1,4),this.inputs=[e],this.createUniform("params","Params");let n=new Uint32Array(5);n[0]=e.h,n[1]=e.w,new Int32Array(n.buffer)[2]=r.win;let a=new Float32Array(n.buffer);a[3]=r.thresh,a[4]=r.boxScale,this.setUniform("params",n),this.defaultSetup();}};var Qt=`// MULTI-FACE box decode from 5-keypoint heatmaps (f32) \u2192 1\xD7K\xD74 box tensor.
7939
7939
  // The multi-face sibling of face_box.wgsl (which is single-face: one global
7940
7940
  // argmax per channel + hull, so two faces merge into one box).
7941
7941
  //
@@ -8473,7 +8473,7 @@ fn main(@builtin(local_invocation_id) lid: vec3<u32>) {
8473
8473
  out_buf[i] = vec4<f16>(0.0h, 0.0h, 0.0h, 0.0h);
8474
8474
  }
8475
8475
  }
8476
- `;var xe=class extends c{inputs;weights=[];output;dispatch=[1,1,1];shader;constructor(t,e,r){if(super(t),e.c!==8)throw new Error(`FaceBoxesFromHeatmaps: expected 8-ch heatmaps (5 real), got ${e.c}`);if(r.maxFaces<1||r.maxFaces>6)throw new Error(`FaceBoxesFromHeatmaps: maxFaces must be 1..6, got ${r.maxFaces}`);this.shader=t.dtype==="f16"?Jt:Qt,this.output=t.tensor(1,r.maxFaces,4),this.inputs=[e],this.createUniform("params","Params");let n=new ArrayBuffer(32),a=new Uint32Array(n),s=new Int32Array(n),o=new Float32Array(n);a[0]=e.h,a[1]=e.w,s[2]=r.win,o[3]=r.thresh,o[4]=r.boxScale,a[5]=r.maxFaces,o[6]=r.tol,this.setUniform("params",a),this.defaultSetup();}};var Zt=`// Auto-reframe state update (f32) \u2014 one thread, one frame of camera work.
8476
+ `;var be=class extends c{inputs;weights=[];output;dispatch=[1,1,1];shader;constructor(t,e,r){if(super(t),e.c!==8)throw new Error(`FaceBoxesFromHeatmaps: expected 8-ch heatmaps (5 real), got ${e.c}`);if(r.maxFaces<1||r.maxFaces>6)throw new Error(`FaceBoxesFromHeatmaps: maxFaces must be 1..6, got ${r.maxFaces}`);this.shader=t.dtype==="f16"?Jt:Qt,this.output=t.tensor(1,r.maxFaces,4),this.inputs=[e],this.createUniform("params","Params");let n=new ArrayBuffer(32),a=new Uint32Array(n),s=new Int32Array(n),o=new Float32Array(n);a[0]=e.h,a[1]=e.w,s[2]=r.win,o[3]=r.thresh,o[4]=r.boxScale,a[5]=r.maxFaces,o[6]=r.tol,this.setUniform("params",a),this.defaultSetup();}};var Zt=`// Auto-reframe state update (f32) \u2014 one thread, one frame of camera work.
8477
8477
  // In: boxes (1\xD7K\xD74, FaceBoxesFromHeatmaps), prev state, command.
8478
8478
  // Out: new state, 1\xD71\xD78 = two vec4s:
8479
8479
  // [0] (cx, cy, size, moving) \u2014 the view rect; all FRAME FRACTIONS
@@ -8765,7 +8765,7 @@ fn main() {
8765
8765
  1.0,
8766
8766
  ));
8767
8767
  }
8768
- `;var be=class extends c{inputs;weights=[];output;dispatch=[1,1,1];shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?er:Zt,this.output=t.tensor(1,1,8),this.inputs=[e,r,n],this.createUniform("params","Params");let s=new ArrayBuffer(32);new Uint32Array(s,0,1)[0]=e.w*e.h;let o=new Float32Array(s,4,7);o[0]=a.zoom,o[1]=a.gravity,o[2]=a.margin,o[3]=a.deadband,o[4]=a.ease,o[5]=a.aspect,this.setUniform("params",new Uint32Array(s)),this.defaultSetup();}};var tr=`// Apply the reframe crop (f32): sample \`src\` through the view rect. Same shape
8768
+ `;var ye=class extends c{inputs;weights=[];output;dispatch=[1,1,1];shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?er:Zt,this.output=t.tensor(1,1,8),this.inputs=[e,r,n],this.createUniform("params","Params");let s=new ArrayBuffer(32);new Uint32Array(s,0,1)[0]=e.w*e.h;let o=new Float32Array(s,4,7);o[0]=a.zoom,o[1]=a.gravity,o[2]=a.margin,o[3]=a.deadband,o[4]=a.ease,o[5]=a.aspect,this.setUniform("params",new Uint32Array(s)),this.defaultSetup();}};var tr=`// Apply the reframe crop (f32): sample \`src\` through the view rect. Same shape
8769
8769
  // in and out \u2014 this is the geometric slot of the one-compositor design.
8770
8770
  //
8771
8771
  // Applied AFTER the effect chain (touch-up draws its mesh at FULL-frame landmark
@@ -8873,7 +8873,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
8873
8873
  let bot = mix(samp(x0, y0 + 1), samp(x0 + 1, y0 + 1), tx);
8874
8874
  out_buf[gid.y * params.w + gid.x] = vec4<f16>(mix(top, bot, ty));
8875
8875
  }
8876
- `;var ye=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?rr:tr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var nr=`// Box-driven square crop + bilinear resample + channel normalization (f32).
8876
+ `;var we=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?rr:tr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var nr=`// Box-driven square crop + bilinear resample + channel normalization (f32).
8877
8877
  // Reads the box tensor (FaceBoxFromHeatmaps output: cx, cy, halfSide, score in
8878
8878
  // frame fractions; halfSide as a fraction of frame WIDTH) and emits the
8879
8879
  // landmark model's input: ((rgb - mean) / std), .w = 0.
@@ -8995,7 +8995,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
8995
8995
  let n = (v.rgb - params.mean.rgb) / params.stdev.rgb;
8996
8996
  out_buf[y * params.out_w + x] = vec4<f16>(vec4<f32>(n, 0.0));
8997
8997
  }
8998
- `;var we=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?ar:nr,this.output=t.tensor(n.outH,n.outW,4),this.inputs=[e,r];let a=n.slot??0;if(a>=r.w*r.h)throw new Error(`CropResample: slot ${a} out of range for a ${r.h}\xD7${r.w} box tensor`);this.createUniform("params","Params");let s=new ArrayBuffer(64),o=new Uint32Array(s,0,5);o[0]=e.h,o[1]=e.w,o[2]=n.outH,o[3]=n.outW,o[4]=a,new Float32Array(s,32,4).set([...n.mean,0]),new Float32Array(s,48,4).set([...n.std,1]),this.setUniform("params",new Uint32Array(s)),this.defaultSetup(),this.dispatch=[Math.ceil(n.outW/8),Math.ceil(n.outH/8),1];}};var ir=`// Landmark overlay (f32) \u2014 draws the image, then VERTEX-PULLS landmark dots
8998
+ `;var ke=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?ar:nr,this.output=t.tensor(n.outH,n.outW,4),this.inputs=[e,r];let a=n.slot??0;if(a>=r.w*r.h)throw new Error(`CropResample: slot ${a} out of range for a ${r.h}\xD7${r.w} box tensor`);this.createUniform("params","Params");let s=new ArrayBuffer(64),o=new Uint32Array(s,0,5);o[0]=e.h,o[1]=e.w,o[2]=n.outH,o[3]=n.outW,o[4]=a,new Float32Array(s,32,4).set([...n.mean,0]),new Float32Array(s,48,4).set([...n.std,1]),this.setUniform("params",new Uint32Array(s)),this.defaultSetup(),this.dispatch=[Math.ceil(n.outW/8),Math.ceil(n.outH/8),1];}};var ir=`// Landmark overlay (f32) \u2014 draws the image, then VERTEX-PULLS landmark dots
8999
8999
  // straight from the LandmarkNet output tensor: the vertex shader fetches
9000
9000
  // landmark i from the storage buffer and transforms crop coords \u2192 canvas NDC
9001
9001
  // via the box tensor. The per-frame landmark data never touches the CPU.
@@ -9167,7 +9167,7 @@ fn vs_pts(@builtin(vertex_index) vi: u32) -> VOut {
9167
9167
  fn fs_pts(in: VOut) -> @location(0) vec4<f32> {
9168
9168
  return vec4<f32>(params.color.rgb, 1.0);
9169
9169
  }
9170
- `;var ke=class{constructor(t,e,r,n,a){this.backend=t;if(r.c<a.count*2)throw new Error(`LandmarkOverlay: landmarks tensor holds ${r.c/2} points < count ${a.count}`);let s=a.slot??0;if(s>=n.w*n.h)throw new Error(`LandmarkOverlay: slot ${s} out of range for a ${n.h}\xD7${n.w} box tensor`);this.count=a.count,this.drawImage=a.drawImage??true;let o=t.device,u=o.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),p=new ArrayBuffer(64),l=new Uint32Array(p,0,2);l[0]=e.w,l[1]=a.count;let f=new Float32Array(p,8,2);f[0]=a.thresh,f[1]=a.pointSize,new Uint32Array(p,16,1)[0]=s,new Float32Array(p,32,4).set([...a.color,1]),new Float32Array(p,48,4).set([e.w,e.h,0,0]),o.queue.writeBuffer(u,0,p);let h=o.createShaderModule({code:t.dtype==="f16"?sr:ir}),_=[{format:t.canvasFormat}];this.imgPipeline=o.createRenderPipeline({layout:"auto",vertex:{module:h,entryPoint:"vs_img"},fragment:{module:h,entryPoint:"fs_img",targets:_},primitive:{topology:"triangle-list"}}),this.ptsPipeline=o.createRenderPipeline({layout:"auto",vertex:{module:h,entryPoint:"vs_pts"},fragment:{module:h,entryPoint:"fs_pts",targets:_},primitive:{topology:"triangle-list"}}),this.imgBindGroup=o.createBindGroup({layout:this.imgPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:3,resource:{buffer:u}}]}),this.ptsBindGroup=o.createBindGroup({layout:this.ptsPipeline.getBindGroupLayout(0),entries:[{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:n.buffer}},{binding:3,resource:{buffer:u}}]});}backend;imgPipeline;ptsPipeline;imgBindGroup;ptsBindGroup;count;drawImage;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("LandmarkOverlayWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:this.drawImage?"clear":"load",storeOp:"store"}]});this.drawImage&&(e.setPipeline(this.imgPipeline),e.setBindGroup(0,this.imgBindGroup),e.draw(6)),e.setPipeline(this.ptsPipeline),e.setBindGroup(0,this.ptsBindGroup),e.draw(this.count*6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var at=`// UV-space face touch-up (f32) \u2014 five passes, one module:
9170
+ `;var Pe=class{constructor(t,e,r,n,a){this.backend=t;if(r.c<a.count*2)throw new Error(`LandmarkOverlay: landmarks tensor holds ${r.c/2} points < count ${a.count}`);let s=a.slot??0;if(s>=n.w*n.h)throw new Error(`LandmarkOverlay: slot ${s} out of range for a ${n.h}\xD7${n.w} box tensor`);this.count=a.count,this.drawImage=a.drawImage??true;let o=t.device,u=o.createBuffer({size:64,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),p=new ArrayBuffer(64),l=new Uint32Array(p,0,2);l[0]=e.w,l[1]=a.count;let f=new Float32Array(p,8,2);f[0]=a.thresh,f[1]=a.pointSize,new Uint32Array(p,16,1)[0]=s,new Float32Array(p,32,4).set([...a.color,1]),new Float32Array(p,48,4).set([e.w,e.h,0,0]),o.queue.writeBuffer(u,0,p);let h=o.createShaderModule({code:t.dtype==="f16"?sr:ir}),_=[{format:t.canvasFormat}];this.imgPipeline=o.createRenderPipeline({layout:"auto",vertex:{module:h,entryPoint:"vs_img"},fragment:{module:h,entryPoint:"fs_img",targets:_},primitive:{topology:"triangle-list"}}),this.ptsPipeline=o.createRenderPipeline({layout:"auto",vertex:{module:h,entryPoint:"vs_pts"},fragment:{module:h,entryPoint:"fs_pts",targets:_},primitive:{topology:"triangle-list"}}),this.imgBindGroup=o.createBindGroup({layout:this.imgPipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:3,resource:{buffer:u}}]}),this.ptsBindGroup=o.createBindGroup({layout:this.ptsPipeline.getBindGroupLayout(0),entries:[{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:n.buffer}},{binding:3,resource:{buffer:u}}]});}backend;imgPipeline;ptsPipeline;imgBindGroup;ptsBindGroup;count;drawImage;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("LandmarkOverlayWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:this.drawImage?"clear":"load",storeOp:"store"}]});this.drawImage&&(e.setPipeline(this.imgPipeline),e.setBindGroup(0,this.imgBindGroup),e.draw(6)),e.setPipeline(this.ptsPipeline),e.setBindGroup(0,this.ptsBindGroup),e.draw(this.count*6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var it=`// UV-space face touch-up (f32) \u2014 five passes, one module:
9171
9171
  // unwrap : canonical mesh \u2192 512\xB2 atlas; vertex at canonical UV, textured
9172
9172
  // by the frame at its landmark's position (vertex-pulled from the
9173
9173
  // landmark tensor, crop \u2192 frame via the box tensor). The
@@ -9422,7 +9422,7 @@ fn cs_unpack(@builtin(global_invocation_id) gid: vec3<u32>) {
9422
9422
  let v = textureLoad(tex0, vec2<i32>(i32(gid.x), i32(gid.y)), 0);
9423
9423
  unpack_out[gid.y * uni.frame_w + gid.x] = v;
9424
9424
  }
9425
- `;var it=`enable f16;
9425
+ `;var st=`enable f16;
9426
9426
 
9427
9427
  // UV-space face touch-up (f16 storage, f32 math) \u2014 five passes, one module:
9428
9428
  // unwrap : canonical mesh \u2192 512\xB2 atlas; vertex at canonical UV, textured
@@ -9679,7 +9679,7 @@ fn cs_unpack(@builtin(global_invocation_id) gid: vec3<u32>) {
9679
9679
  let v = textureLoad(tex0, vec2<i32>(i32(gid.x), i32(gid.y)), 0);
9680
9680
  unpack_out[gid.y * uni.frame_w + gid.x] = vec4<f16>(v);
9681
9681
  }
9682
- `;var K=512,Pe=class{constructor(t,e,r,n,a,s){this.backend=t;let o=s.slots??1;if(o!==1&&o!==4)throw new Error(`FaceTouchup: slots must be 1 or 4, got ${o}`);let u=o===4?2:1;if(n.w*n.h<o)throw new Error(`FaceTouchup: slots ${o} exceeds the ${n.h}\xD7${n.w} box tensor`);if(r.c<o*956)throw new Error(`FaceTouchup: landmarks tensor holds ${r.c/956} faces < slots ${o}`);this.slots=o,this.activeSlots=o;let p=t.device;this.device=p,this.uvBuf=p.createBuffer({size:a.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),p.queue.writeBuffer(this.uvBuf,0,a.uv.buffer,a.uv.byteOffset,a.uv.byteLength),this.idxBuf=p.createBuffer({size:a.idx.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),p.queue.writeBuffer(this.idxBuf,0,a.idx.buffer,a.idx.byteOffset,a.idx.byteLength);let l=()=>p.createTexture({size:[K,K],format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),f=l(),h=l(),_=l(),m=l(),W=p.createTexture({size:[a.weightMask.width,a.weightMask.height],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});p.queue.copyExternalImageToTexture({source:a.weightMask},{texture:W},[a.weightMask.width,a.weightMask.height]);let D=p.createSampler({magFilter:"linear",minFilter:"linear"}),T=v=>{let y=p.createBuffer({size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),G=new ArrayBuffer(48),g=new Uint32Array(G,0,2);g[0]=e.w,g[1]=e.h;let x=new Float32Array(G,8,8);return x[0]=v.sigma??0,x[1]=s.detail,x[2]=s.strength,x[3]=s.thresh,x[4]=v.dirX??0,x[5]=v.dirY??0,x[6]=e.w,x[7]=e.h,new Uint32Array(G,40,2).set([o,u]),p.queue.writeBuffer(y,0,G),y},b=T({}),C=T({sigma:s.amount,dirX:1/K}),B=T({sigma:s.amount,dirY:1/K}),k=T({sigma:s.amount,dirX:1/K,dirY:1/K}),Z=p.createShaderModule({code:t.dtype==="f16"?it:at}),Ke=[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"float32"}]}],z=(v,y,G,g)=>p.createRenderPipeline({layout:"auto",vertex:{module:Z,entryPoint:v,buffers:g?Ke:[]},fragment:{module:Z,entryPoint:y,targets:[{format:G}]},primitive:{topology:"triangle-list"}}),E=(v,y,G)=>p.createBindGroup({layout:v.getBindGroupLayout(0),entries:[...G,{binding:3,resource:{buffer:y}}]}),M=(v,y)=>({binding:v,resource:{buffer:y}}),P=(v,y)=>({binding:v,resource:y.createView()}),U=e.buffer,I=r.buffer,F=n.buffer,q=z("vs_unwrap","fs_unwrap","rgba8unorm",true),Y=z("vs_pass","fs_pass",t.canvasFormat,false),Q=z("vs_comp","fs_comp",t.canvasFormat,true),ee=(s.style??"freq-sep")==="bilateral"?(()=>{let v=z("vs_quad_fb","fs_bilateral","rgba8unorm",false);return [{pipeline:v,target:m.createView(),verts:3,mesh:false,load:false,bind:E(v,k,[{binding:4,resource:D},P(5,f)])}]})():(()=>{let v=z("vs_quad_fb","fs_blur","rgba8unorm",false),y=z("vs_quad_fb","fs_combine","rgba8unorm",false);return [{pipeline:v,target:h.createView(),verts:3,mesh:false,load:false,bind:E(v,C,[{binding:4,resource:D},P(5,f)])},{pipeline:v,target:_.createView(),verts:3,mesh:false,load:false,bind:E(v,B,[{binding:4,resource:D},P(5,h)])},{pipeline:y,target:m.createView(),verts:3,mesh:false,load:false,bind:E(y,b,[{binding:4,resource:D},P(5,f),P(6,_)])}]})();this.passes=[{pipeline:q,target:f.createView(),verts:a.count,mesh:true,load:false,bind:E(q,b,[M(0,U),M(1,I),M(2,F)])},...ee,{pipeline:Y,target:null,verts:3,mesh:false,load:false,bind:E(Y,b,[M(0,U)])},{pipeline:Q,target:null,verts:a.count,mesh:true,load:true,bind:E(Q,b,[M(0,U),M(1,I),M(2,F),{binding:4,resource:D},P(5,m),P(6,W)])}];}backend;device;passes;uvBuf;idxBuf;slots;activeSlots;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("FaceTouchupWebGPU.run() called before setOutput()");let t=this.device.createCommandEncoder();for(let e of this.passes){let r=t.beginRenderPass({colorAttachments:[{view:e.target??this.outputView,clearValue:[0,0,0,1],loadOp:e.load?"load":"clear",storeOp:"store"}]});r.setPipeline(e.pipeline),r.setBindGroup(0,e.bind),e.mesh&&(r.setVertexBuffer(0,this.uvBuf),r.setVertexBuffer(1,this.idxBuf)),r.draw(e.verts,e.mesh?this.activeSlots:1),r.end();}this.device.queue.submit([t.finish()]),this.outputView=null;}},Te=class{inputs;weights=[];output;device;passes;unpackPipeline;unpackBind;unpackDispatch;uvBuf;idxBuf;meshCount;slots;activeSlots;constructor(t,e,r,n,a,s){let u=s.slots??1;if(u!==1&&u!==4)throw new Error(`FaceTouchup: slots must be 1 or 4, got ${u}`);let p=u===4?2:1;if(n.w*n.h<u)throw new Error(`FaceTouchup: slots ${u} exceeds the ${n.h}\xD7${n.w} box tensor`);if(r.c<u*956)throw new Error(`FaceTouchup: landmarks tensor holds ${r.c/956} faces < slots ${u}`);this.slots=u,this.activeSlots=u;let l=t.device;this.device=l,this.inputs=[e,r,n],this.output=t.tensor(e.h,e.w,4),this.meshCount=a.count,this.uvBuf=l.createBuffer({size:a.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),l.queue.writeBuffer(this.uvBuf,0,a.uv.buffer,a.uv.byteOffset,a.uv.byteLength),this.idxBuf=l.createBuffer({size:a.idx.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),l.queue.writeBuffer(this.idxBuf,0,a.idx.buffer,a.idx.byteOffset,a.idx.byteLength);let f=()=>l.createTexture({size:[512,512],format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=f(),_=f(),m=f(),W=f(),D=t.dtype==="f16"?"rgba16float":"rgba32float",T=l.createTexture({size:[e.w,e.h],format:D,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),b=l.createTexture({size:[a.weightMask.width,a.weightMask.height],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});l.queue.copyExternalImageToTexture({source:a.weightMask},{texture:b},[a.weightMask.width,a.weightMask.height]);let C=l.createSampler({magFilter:"linear",minFilter:"linear"}),B=g=>{let x=l.createBuffer({size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),L=new ArrayBuffer(48),te=new Uint32Array(L,0,2);te[0]=e.w,te[1]=e.h;let H=new Float32Array(L,8,8);return H[0]=g.sigma??0,H[1]=s.detail,H[2]=s.strength,H[3]=s.thresh,H[4]=g.dirX??0,H[5]=g.dirY??0,H[6]=e.w,H[7]=e.h,new Uint32Array(L,40,2).set([u,p]),l.queue.writeBuffer(x,0,L),x},k=B({}),Z=B({sigma:s.amount,dirX:1/512}),Ke=B({sigma:s.amount,dirY:1/512}),z=B({sigma:s.amount,dirX:1/512,dirY:1/512}),E=l.createShaderModule({code:t.dtype==="f16"?it:at}),M=[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"float32"}]}],P=(g,x,L,te)=>l.createRenderPipeline({layout:"auto",vertex:{module:E,entryPoint:g,buffers:te?M:[]},fragment:{module:E,entryPoint:x,targets:[{format:L}]},primitive:{topology:"triangle-list"}}),U=(g,x,L)=>l.createBindGroup({layout:g.getBindGroupLayout(0),entries:[...L,{binding:3,resource:{buffer:x}}]}),I=(g,x)=>({binding:g,resource:{buffer:x}}),F=(g,x)=>({binding:g,resource:x.createView()}),q=e.buffer,Y=r.buffer,Q=n.buffer,ee=P("vs_unwrap","fs_unwrap","rgba8unorm",true),v=P("vs_pass","fs_pass",D,false),y=P("vs_comp","fs_comp",D,true),G=(s.style??"freq-sep")==="bilateral"?(()=>{let g=P("vs_quad_fb","fs_bilateral","rgba8unorm",false);return [{pipeline:g,target:W.createView(),verts:3,mesh:false,load:false,bind:U(g,z,[{binding:4,resource:C},F(5,h)])}]})():(()=>{let g=P("vs_quad_fb","fs_blur","rgba8unorm",false),x=P("vs_quad_fb","fs_combine","rgba8unorm",false);return [{pipeline:g,target:_.createView(),verts:3,mesh:false,load:false,bind:U(g,Z,[{binding:4,resource:C},F(5,h)])},{pipeline:g,target:m.createView(),verts:3,mesh:false,load:false,bind:U(g,Ke,[{binding:4,resource:C},F(5,_)])},{pipeline:x,target:W.createView(),verts:3,mesh:false,load:false,bind:U(x,k,[{binding:4,resource:C},F(5,h),F(6,m)])}]})();this.passes=[{pipeline:ee,target:h.createView(),verts:a.count,mesh:true,load:false,bind:U(ee,k,[I(0,q),I(1,Y),I(2,Q)])},...G,{pipeline:v,target:T.createView(),verts:3,mesh:false,load:false,bind:U(v,k,[I(0,q)])},{pipeline:y,target:T.createView(),verts:a.count,mesh:true,load:true,bind:U(y,k,[I(0,q),I(1,Y),I(2,Q),{binding:4,resource:C},F(5,W),F(6,b)])}],this.unpackPipeline=l.createComputePipeline({layout:"auto",compute:{module:E,entryPoint:"cs_unpack"}}),this.unpackBind=U(this.unpackPipeline,k,[F(5,T),I(7,this.output.buffer)]),this.unpackDispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8)];}setActiveSlots(t){this.activeSlots=Math.max(0,Math.min(t,this.slots));}run(){let t=this.device.createCommandEncoder();for(let r of this.passes){let n=t.beginRenderPass({colorAttachments:[{view:r.target,clearValue:[0,0,0,1],loadOp:r.load?"load":"clear",storeOp:"store"}]});n.setPipeline(r.pipeline),n.setBindGroup(0,r.bind),r.mesh&&(n.setVertexBuffer(0,this.uvBuf),n.setVertexBuffer(1,this.idxBuf)),n.draw(r.verts,r.mesh?this.activeSlots:1),n.end();}let e=t.beginComputePass();e.setPipeline(this.unpackPipeline),e.setBindGroup(0,this.unpackBind),e.dispatchWorkgroups(this.unpackDispatch[0],this.unpackDispatch[1],1),e.end(),this.device.queue.submit([t.finish()]);}};var or=`// Flow-gated temporal stabilizer (f32). See stabilize_f16.wgsl for the math.
9682
+ `;var K=512,Te=class{constructor(t,e,r,n,a,s){this.backend=t;let o=s.slots??1;if(o!==1&&o!==4)throw new Error(`FaceTouchup: slots must be 1 or 4, got ${o}`);let u=o===4?2:1;if(n.w*n.h<o)throw new Error(`FaceTouchup: slots ${o} exceeds the ${n.h}\xD7${n.w} box tensor`);if(r.c<o*956)throw new Error(`FaceTouchup: landmarks tensor holds ${r.c/956} faces < slots ${o}`);this.slots=o,this.activeSlots=o;let p=t.device;this.device=p,this.uvBuf=p.createBuffer({size:a.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),p.queue.writeBuffer(this.uvBuf,0,a.uv.buffer,a.uv.byteOffset,a.uv.byteLength),this.idxBuf=p.createBuffer({size:a.idx.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),p.queue.writeBuffer(this.idxBuf,0,a.idx.buffer,a.idx.byteOffset,a.idx.byteLength);let l=()=>p.createTexture({size:[K,K],format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),f=l(),h=l(),_=l(),m=l(),W=p.createTexture({size:[a.weightMask.width,a.weightMask.height],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});p.queue.copyExternalImageToTexture({source:a.weightMask},{texture:W},[a.weightMask.width,a.weightMask.height]);let D=p.createSampler({magFilter:"linear",minFilter:"linear"}),T=v=>{let y=p.createBuffer({size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),G=new ArrayBuffer(48),g=new Uint32Array(G,0,2);g[0]=e.w,g[1]=e.h;let x=new Float32Array(G,8,8);return x[0]=v.sigma??0,x[1]=s.detail,x[2]=s.strength,x[3]=s.thresh,x[4]=v.dirX??0,x[5]=v.dirY??0,x[6]=e.w,x[7]=e.h,new Uint32Array(G,40,2).set([o,u]),p.queue.writeBuffer(y,0,G),y},b=T({}),C=T({sigma:s.amount,dirX:1/K}),B=T({sigma:s.amount,dirY:1/K}),k=T({sigma:s.amount,dirX:1/K,dirY:1/K}),ee=p.createShaderModule({code:t.dtype==="f16"?st:it}),Ye=[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"float32"}]}],z=(v,y,G,g)=>p.createRenderPipeline({layout:"auto",vertex:{module:ee,entryPoint:v,buffers:g?Ye:[]},fragment:{module:ee,entryPoint:y,targets:[{format:G}]},primitive:{topology:"triangle-list"}}),E=(v,y,G)=>p.createBindGroup({layout:v.getBindGroupLayout(0),entries:[...G,{binding:3,resource:{buffer:y}}]}),M=(v,y)=>({binding:v,resource:{buffer:y}}),P=(v,y)=>({binding:v,resource:y.createView()}),U=e.buffer,I=r.buffer,F=n.buffer,q=z("vs_unwrap","fs_unwrap","rgba8unorm",true),Y=z("vs_pass","fs_pass",t.canvasFormat,false),Q=z("vs_comp","fs_comp",t.canvasFormat,true),te=(s.style??"freq-sep")==="bilateral"?(()=>{let v=z("vs_quad_fb","fs_bilateral","rgba8unorm",false);return [{pipeline:v,target:m.createView(),verts:3,mesh:false,load:false,bind:E(v,k,[{binding:4,resource:D},P(5,f)])}]})():(()=>{let v=z("vs_quad_fb","fs_blur","rgba8unorm",false),y=z("vs_quad_fb","fs_combine","rgba8unorm",false);return [{pipeline:v,target:h.createView(),verts:3,mesh:false,load:false,bind:E(v,C,[{binding:4,resource:D},P(5,f)])},{pipeline:v,target:_.createView(),verts:3,mesh:false,load:false,bind:E(v,B,[{binding:4,resource:D},P(5,h)])},{pipeline:y,target:m.createView(),verts:3,mesh:false,load:false,bind:E(y,b,[{binding:4,resource:D},P(5,f),P(6,_)])}]})();this.passes=[{pipeline:q,target:f.createView(),verts:a.count,mesh:true,load:false,bind:E(q,b,[M(0,U),M(1,I),M(2,F)])},...te,{pipeline:Y,target:null,verts:3,mesh:false,load:false,bind:E(Y,b,[M(0,U)])},{pipeline:Q,target:null,verts:a.count,mesh:true,load:true,bind:E(Q,b,[M(0,U),M(1,I),M(2,F),{binding:4,resource:D},P(5,m),P(6,W)])}];}backend;device;passes;uvBuf;idxBuf;slots;activeSlots;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("FaceTouchupWebGPU.run() called before setOutput()");let t=this.device.createCommandEncoder();for(let e of this.passes){let r=t.beginRenderPass({colorAttachments:[{view:e.target??this.outputView,clearValue:[0,0,0,1],loadOp:e.load?"load":"clear",storeOp:"store"}]});r.setPipeline(e.pipeline),r.setBindGroup(0,e.bind),e.mesh&&(r.setVertexBuffer(0,this.uvBuf),r.setVertexBuffer(1,this.idxBuf)),r.draw(e.verts,e.mesh?this.activeSlots:1),r.end();}this.device.queue.submit([t.finish()]),this.outputView=null;}},Ce=class{inputs;weights=[];output;device;passes;unpackPipeline;unpackBind;unpackDispatch;uvBuf;idxBuf;meshCount;slots;activeSlots;constructor(t,e,r,n,a,s){let u=s.slots??1;if(u!==1&&u!==4)throw new Error(`FaceTouchup: slots must be 1 or 4, got ${u}`);let p=u===4?2:1;if(n.w*n.h<u)throw new Error(`FaceTouchup: slots ${u} exceeds the ${n.h}\xD7${n.w} box tensor`);if(r.c<u*956)throw new Error(`FaceTouchup: landmarks tensor holds ${r.c/956} faces < slots ${u}`);this.slots=u,this.activeSlots=u;let l=t.device;this.device=l,this.inputs=[e,r,n],this.output=t.tensor(e.h,e.w,4),this.meshCount=a.count,this.uvBuf=l.createBuffer({size:a.uv.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),l.queue.writeBuffer(this.uvBuf,0,a.uv.buffer,a.uv.byteOffset,a.uv.byteLength),this.idxBuf=l.createBuffer({size:a.idx.byteLength,usage:GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_DST}),l.queue.writeBuffer(this.idxBuf,0,a.idx.buffer,a.idx.byteOffset,a.idx.byteLength);let f=()=>l.createTexture({size:[512,512],format:"rgba8unorm",usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=f(),_=f(),m=f(),W=f(),D=t.dtype==="f16"?"rgba16float":"rgba32float",T=l.createTexture({size:[e.w,e.h],format:D,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),b=l.createTexture({size:[a.weightMask.width,a.weightMask.height],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT});l.queue.copyExternalImageToTexture({source:a.weightMask},{texture:b},[a.weightMask.width,a.weightMask.height]);let C=l.createSampler({magFilter:"linear",minFilter:"linear"}),B=g=>{let x=l.createBuffer({size:48,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST}),L=new ArrayBuffer(48),re=new Uint32Array(L,0,2);re[0]=e.w,re[1]=e.h;let H=new Float32Array(L,8,8);return H[0]=g.sigma??0,H[1]=s.detail,H[2]=s.strength,H[3]=s.thresh,H[4]=g.dirX??0,H[5]=g.dirY??0,H[6]=e.w,H[7]=e.h,new Uint32Array(L,40,2).set([u,p]),l.queue.writeBuffer(x,0,L),x},k=B({}),ee=B({sigma:s.amount,dirX:1/512}),Ye=B({sigma:s.amount,dirY:1/512}),z=B({sigma:s.amount,dirX:1/512,dirY:1/512}),E=l.createShaderModule({code:t.dtype==="f16"?st:it}),M=[{arrayStride:8,attributes:[{shaderLocation:0,offset:0,format:"float32x2"}]},{arrayStride:4,attributes:[{shaderLocation:1,offset:0,format:"float32"}]}],P=(g,x,L,re)=>l.createRenderPipeline({layout:"auto",vertex:{module:E,entryPoint:g,buffers:re?M:[]},fragment:{module:E,entryPoint:x,targets:[{format:L}]},primitive:{topology:"triangle-list"}}),U=(g,x,L)=>l.createBindGroup({layout:g.getBindGroupLayout(0),entries:[...L,{binding:3,resource:{buffer:x}}]}),I=(g,x)=>({binding:g,resource:{buffer:x}}),F=(g,x)=>({binding:g,resource:x.createView()}),q=e.buffer,Y=r.buffer,Q=n.buffer,te=P("vs_unwrap","fs_unwrap","rgba8unorm",true),v=P("vs_pass","fs_pass",D,false),y=P("vs_comp","fs_comp",D,true),G=(s.style??"freq-sep")==="bilateral"?(()=>{let g=P("vs_quad_fb","fs_bilateral","rgba8unorm",false);return [{pipeline:g,target:W.createView(),verts:3,mesh:false,load:false,bind:U(g,z,[{binding:4,resource:C},F(5,h)])}]})():(()=>{let g=P("vs_quad_fb","fs_blur","rgba8unorm",false),x=P("vs_quad_fb","fs_combine","rgba8unorm",false);return [{pipeline:g,target:_.createView(),verts:3,mesh:false,load:false,bind:U(g,ee,[{binding:4,resource:C},F(5,h)])},{pipeline:g,target:m.createView(),verts:3,mesh:false,load:false,bind:U(g,Ye,[{binding:4,resource:C},F(5,_)])},{pipeline:x,target:W.createView(),verts:3,mesh:false,load:false,bind:U(x,k,[{binding:4,resource:C},F(5,h),F(6,m)])}]})();this.passes=[{pipeline:te,target:h.createView(),verts:a.count,mesh:true,load:false,bind:U(te,k,[I(0,q),I(1,Y),I(2,Q)])},...G,{pipeline:v,target:T.createView(),verts:3,mesh:false,load:false,bind:U(v,k,[I(0,q)])},{pipeline:y,target:T.createView(),verts:a.count,mesh:true,load:true,bind:U(y,k,[I(0,q),I(1,Y),I(2,Q),{binding:4,resource:C},F(5,W),F(6,b)])}],this.unpackPipeline=l.createComputePipeline({layout:"auto",compute:{module:E,entryPoint:"cs_unpack"}}),this.unpackBind=U(this.unpackPipeline,k,[F(5,T),I(7,this.output.buffer)]),this.unpackDispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8)];}setActiveSlots(t){this.activeSlots=Math.max(0,Math.min(t,this.slots));}run(){let t=this.device.createCommandEncoder();for(let r of this.passes){let n=t.beginRenderPass({colorAttachments:[{view:r.target,clearValue:[0,0,0,1],loadOp:r.load?"load":"clear",storeOp:"store"}]});n.setPipeline(r.pipeline),n.setBindGroup(0,r.bind),r.mesh&&(n.setVertexBuffer(0,this.uvBuf),n.setVertexBuffer(1,this.idxBuf)),n.draw(r.verts,r.mesh?this.activeSlots:1),n.end();}let e=t.beginComputePass();e.setPipeline(this.unpackPipeline),e.setBindGroup(0,this.unpackBind),e.dispatchWorkgroups(this.unpackDispatch[0],this.unpackDispatch[1],1),e.end(),this.device.queue.submit([t.finish()]);}};var or=`// Flow-gated temporal stabilizer (f32). See stabilize_f16.wgsl for the math.
9683
9683
 
9684
9684
  struct Params {
9685
9685
  h : u32,
@@ -9791,7 +9791,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
9791
9791
 
9792
9792
  output_buf[idx] = vec4<f16>(f16(stab), f16(env), 0.0h, 0.0h);
9793
9793
  }
9794
- `;var Ce=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n,a,s){super(t),this.shader=t.dtype==="f16"?ur:or,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r,n,a],this.createUniform("params","Params");let o=new Uint32Array(10);o[0]=e.h,o[1]=e.w;let u=new Float32Array(o.buffer);u[2]=s.tLo,u[3]=s.tHi,u[4]=s.leak,u[5]=s.release,u[6]=s.tDiv,u[7]=s.divScale,o[8]=s.stepX,o[9]=s.stepY,this.setUniform("params",o),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var pr=`// Bilinear upsample (arbitrary ratio), align_corners=False (matches PyTorch default).
9794
+ `;var Ue=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n,a,s){super(t),this.shader=t.dtype==="f16"?ur:or,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r,n,a],this.createUniform("params","Params");let o=new Uint32Array(10);o[0]=e.h,o[1]=e.w;let u=new Float32Array(o.buffer);u[2]=s.tLo,u[3]=s.tHi,u[4]=s.leak,u[5]=s.release,u[6]=s.tDiv,u[7]=s.divScale,o[8]=s.stepX,o[9]=s.stepY,this.setUniform("params",o),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var pr=`// Bilinear upsample (arbitrary ratio), align_corners=False (matches PyTorch default).
9795
9795
  // Input/output in NHWC vec4 format: index = y*W*(C/4) + x*(C/4) + c_group.
9796
9796
  // Each thread computes one output pixel for one channel group (vec4 = 4 channels).
9797
9797
 
@@ -9905,7 +9905,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
9905
9905
 
9906
9906
  output_buf[oy * params.out_w * C + ox * C + c] = vec4<f16>(result);
9907
9907
  }
9908
- `;var Ue=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?lr:pr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,r.outH,r.outW,n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var cr=`// Top-left crop (f32). See crop_f16.wgsl.
9908
+ `;var Ae=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?lr:pr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,r.outH,r.outW,n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var cr=`// Top-left crop (f32). See crop_f16.wgsl.
9909
9909
 
9910
9910
  struct Params {
9911
9911
  in_w : u32,
@@ -9951,7 +9951,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
9951
9951
  let G = params.groups;
9952
9952
  output_buf[y * params.out_w * G + x * G + g] = input_buf[y * params.in_w * G + x * G + g];
9953
9953
  }
9954
- `;var Ae=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?fr:cr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.w,r.outH,r.outW,n])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var dr=`// Bicubic upsample (arbitrary scale) \u2014 Keys cubic, a=-0.75 (PyTorch default
9954
+ `;var Se=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?fr:cr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.w,r.outH,r.outW,n])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var dr=`// Bicubic upsample (arbitrary scale) \u2014 Keys cubic, a=-0.75 (PyTorch default
9955
9955
  // for mode='bicubic', align_corners=False). Direct 2D, 4\xD74 = 16 taps per
9956
9956
  // output pixel. NHWC vec4 layout: index = y*W*(C/4) + x*(C/4) + c_group.
9957
9957
 
@@ -10087,7 +10087,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10087
10087
 
10088
10088
  output_buf[oy * params.out_w * C + ox * C + c] = vec4<f16>(acc);
10089
10089
  }
10090
- `;var Se=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?hr:dr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,r.outH,r.outW,n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var mr=`// Channel concatenation: output = cat(A, B, dim=channel).
10090
+ `;var Be=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?hr:dr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,r.outH,r.outW,n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var mr=`// Channel concatenation: output = cat(A, B, dim=channel).
10091
10091
  // Both A and B must share the same H\xD7W and be in NHWC vec4 format.
10092
10092
  // Output layout: for each (y, x), the first a_groups vec4s come from A,
10093
10093
  // followed by b_groups vec4s from B.
@@ -10173,7 +10173,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10173
10173
  output_buf[out_idx] = input_b[y * W * Bg + x * Bg + c_b];
10174
10174
  }
10175
10175
  }
10176
- `;var Be=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?gr:mr;let n=e.c/4,a=r.c/4,s=n+a;this.output=t.tensor(e.h,e.w,e.c+r.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n,a,s,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),s];}};var _r=`// Conv2d + skip add fused.
10176
+ `;var Ee=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?gr:mr;let n=e.c/4,a=r.c/4,s=n+a;this.output=t.tensor(e.h,e.w,e.c+r.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n,a,s,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),s];}};var _r=`// Conv2d + skip add fused.
10177
10177
  // Identical to conv2d.wgsl except skip is an activation input (binding 1),
10178
10178
  // added element-wise to the conv result at write time.
10179
10179
  // Eliminates the separate add dispatch and its intermediate buffer round-trip.
@@ -10321,7 +10321,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10321
10321
  let out_idx = y * params.out_w * O + x * O + o;
10322
10322
  output_buf[out_idx] = result + skip_buf[out_idx];
10323
10323
  }
10324
- `;var Ee=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?vr:_r;let s=A(e.h,a.kernel,a.stride,a.padding),o=A(e.w,a.kernel,a.stride,a.padding),u=e.c/4,p=a.outChannels/4,l=S(a.padding,e.h,s,a.kernel,a.stride),f=S(a.padding,e.w,o,a.kernel,a.stride);this.output=t.tensor(s,o,a.outChannels),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(d(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o,u,p,a.kernel,a.kernel,a.stride,l,f,a.activation==="relu6"?1:0])),this.defaultSetup(),this.dispatch=[Math.ceil(o/8),Math.ceil(s/8),p];}};var xr=`// proj_residual: bespoke 1\xD71 conv (no activation) + residual add, fused.
10324
+ `;var Ie=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?vr:_r;let s=A(e.h,a.kernel,a.stride,a.padding),o=A(e.w,a.kernel,a.stride,a.padding),u=e.c/4,p=a.outChannels/4,l=S(a.padding,e.h,s,a.kernel,a.stride),f=S(a.padding,e.w,o,a.kernel,a.stride);this.output=t.tensor(s,o,a.outChannels),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(d(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o,u,p,a.kernel,a.kernel,a.stride,l,f,a.activation==="relu6"?1:0])),this.defaultSetup(),this.dispatch=[Math.ceil(o/8),Math.ceil(s/8),p];}};var xr=`// proj_residual: bespoke 1\xD71 conv (no activation) + residual add, fused.
10325
10325
  // Specializes conv2d_add to kernel=1 / stride=1 / pad=0 / no activation: drops
10326
10326
  // the kernel loop, the padding checks, and the activation branch. Used by the
10327
10327
  // MBConv project+residual tail. Both inputs share the same spatial resolution.
@@ -10408,7 +10408,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10408
10408
 
10409
10409
  output_buf[pix * O + o] = result;
10410
10410
  }
10411
- `;var Ie=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?br:xr;let s=e.c/4,o=a.outChannels/4;this.output=t.tensor(e.h,e.w,a.outChannels),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(d(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),o];}};var yr=`// concat_conv2d: fuses [concat(a, b) \u2192 conv 3\xD73 (pad 1) \u2192 relu6] into one
10411
+ `;var Fe=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?br:xr;let s=e.c/4,o=a.outChannels/4;this.output=t.tensor(e.h,e.w,a.outChannels),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(d(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),o];}};var yr=`// concat_conv2d: fuses [concat(a, b) \u2192 conv 3\xD73 (pad 1) \u2192 relu6] into one
10412
10412
  // dispatch. Both inputs are already at the output resolution (the upstream
10413
10413
  // upsample stays a separate dispatch writing a clean intermediate, so the conv
10414
10414
  // reads are plain-indexed). Identical math to conv2d; the only difference is
@@ -10523,7 +10523,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10523
10523
  result = clamp(result, vec4<f16>(0.0h), vec4<f16>(6.0h));
10524
10524
  output_buf[(y * p.w + x) * O + o] = result;
10525
10525
  }
10526
- `;var Fe=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?wr:yr;let s=e.c/4,o=r.c/4,u=a.outChannels/4;this.output=t.tensor(e.h,e.w,a.outChannels),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(d(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o,u,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),u];}};var kr=`// gates_fused: ConvGRU z + r gates, fused into one dispatch.
10526
+ `;var We=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?wr:yr;let s=e.c/4,o=r.c/4,u=a.outChannels/4;this.output=t.tensor(e.h,e.w,a.outChannels),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(d(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o,u,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),u];}};var kr=`// gates_fused: ConvGRU z + r gates, fused into one dispatch.
10527
10527
  // Production config (c_up=2, split_ratio=0.5 \u2192 passthrough=1, recurrent=1):
10528
10528
  // u_in : c_up=2 packed in a vec4 (.x = passthrough a, .y = recurrent b)
10529
10529
  // h_prev : hidden carrier \u2014 recurrent state in .z (see cand_update_fused: the
@@ -10610,7 +10610,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10610
10610
  let r = 1.0h / (1.0h + exp(-r_pre));
10611
10611
  output_buf[y * params.w + x] = vec4<f16>(z, r, 0.0h, 0.0h);
10612
10612
  }
10613
- `;var We=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Pr:kr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Tr=`// cand_update_fused: ConvGRU candidate path + state update + output, fused.
10613
+ `;var De=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Pr:kr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Tr=`// cand_update_fused: ConvGRU candidate path + state update + output, fused.
10614
10614
  // Production config (c_up=2, recurrent=1):
10615
10615
  // u_in : c_up=2 (.x = a passthrough, .y = b recurrent)
10616
10616
  // h_prev : hidden carrier \u2014 recurrent state in .z (the previous frame's
@@ -10709,7 +10709,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10709
10709
  let b_out = u_cur.y + gamma_buf[0].x * h_new;
10710
10710
  output_buf[cur] = vec4<f16>(u_cur.x, b_out, h_new, 0.0h);
10711
10711
  }
10712
- `;var De=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a,s){super(t),this.shader=t.dtype==="f16"?Cr:Tr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r,n],this.weights=[t.upload(d(a.weights)),t.upload(w(a.bias)),t.upload(w(s))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Ur=`// conv_expand: bespoke N\u21922 conv 3\xD73 (pad 1) + relu (wrapper expand_feat).
10712
+ `;var Ge=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a,s){super(t),this.shader=t.dtype==="f16"?Cr:Tr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r,n],this.weights=[t.upload(d(a.weights)),t.upload(w(a.bias)),t.upload(w(s))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Ur=`// conv_expand: bespoke N\u21922 conv 3\xD73 (pad 1) + relu (wrapper expand_feat).
10713
10713
  // Expands feat_lr (in_c, mult of 4) to the c_up=2 carrier \u2014 output .xy = the 2
10714
10714
  // native channels, .zw = 0. mat4x2 per (kpos, in_group) with a vec2 accumulator.
10715
10715
  // Weight: 9 * in_groups mat4x2 (8 floats each, col-major). Bias .xy.
@@ -10783,7 +10783,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10783
10783
  result = max(result, vec2<f16>(0.0h));
10784
10784
  output_buf[y * params.w + x] = vec4<f16>(result, 0.0h, 0.0h);
10785
10785
  }
10786
- `;var Ge=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?Ar:Ur;let n=e.c/4;this.output=t.tensor(e.h,e.w,4),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(w(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Sr=`// cat_conv_6to2: fused concat(u, d) + 6\u21922 conv 3\xD73 (pad 1) + relu (E up1_combine).
10786
+ `;var Oe=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?Ar:Ur;let n=e.c/4;this.output=t.tensor(e.h,e.w,4),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(w(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Sr=`// cat_conv_6to2: fused concat(u, d) + 6\u21922 conv 3\xD73 (pad 1) + relu (E up1_combine).
10787
10787
  // u = c_up=2 carrier (.xy); d = c_high=4 (full vec4). Both same resolution.
10788
10788
  // Channel order concat([u, d]) = (u.x, u.y, d.x, d.y, d.z, d.w), split into
10789
10789
  // v3a = (u.x, u.y, d.x) v3b = d.yzw
@@ -10862,7 +10862,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10862
10862
  result = max(result, vec2<f16>(0.0h));
10863
10863
  output_buf[y * params.w + x] = vec4<f16>(result, 0.0h, 0.0h);
10864
10864
  }
10865
- `;var Oe=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Br:Sr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Er=`// down_adapter: fused stride-N 3\xD73 conv (4\u21924) + relu + 1\xD71 adapter (4\u21923, no
10865
+ `;var Me=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Br:Sr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Er=`// down_adapter: fused stride-N 3\xD73 conv (4\u21924) + relu + 1\xD71 adapter (4\u21923, no
10866
10866
  // act) into one dispatch. E variant: down2 (c_high=4 \u2192 c_low=4, stride 2) +
10867
10867
  // adapter. A/B variant: down1 (RGB .xyz \u2192 4, stride 2/3) + adapter (the down
10868
10868
  // weight's 4th input column is zeroed at export for RGB input). Symmetric pad.
@@ -10955,7 +10955,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
10955
10955
  let adapt_out = adapt_w[0] * down_out + adapt_b[0];
10956
10956
  output_buf[y * p.out_w + x] = vec4<f16>(adapt_out.xyz, 0.0h);
10957
10957
  }
10958
- `;var Me=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?Ir:Er;let s=A(e.h,3,a.stride,1),o=A(e.w,3,a.stride,1),u=S(1,e.h,s,3,a.stride),p=S(1,e.w,o,3,a.stride);this.output=t.tensor(s,o,4),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(w(r.bias)),t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o,a.stride,u,p,0])),this.defaultSetup(),this.dispatch=[Math.ceil(o/8),Math.ceil(s/8),1];}};var Fr=`// up_final: fused concat(u, rgb) \u2192 conv 3\xD73 5\u21921 \u2192 sigmoid (A/B alpha head).
10958
+ `;var Re=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?Ir:Er;let s=A(e.h,3,a.stride,1),o=A(e.w,3,a.stride,1),u=S(1,e.h,s,3,a.stride),p=S(1,e.w,o,3,a.stride);this.output=t.tensor(s,o,4),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(w(r.bias)),t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,s,o,a.stride,u,p,0])),this.defaultSetup(),this.dispatch=[Math.ceil(o/8),Math.ceil(s/8),1];}};var Fr=`// up_final: fused concat(u, rgb) \u2192 conv 3\xD73 5\u21921 \u2192 sigmoid (A/B alpha head).
10959
10959
  // u = c_up=2 carrier (.xy); rgb = x_hr (.xyz). 5 inputs \u2192 1 alpha (output .x).
10960
10960
  // Weight: 18 vec4 \u2014 [0..8] = (w0, w1, 0, 0) for u per kpos; [9..17] =
10961
10961
  // (w2, w3, w4, 0) for rgb per kpos. Bias .x.
@@ -11023,7 +11023,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
11023
11023
 
11024
11024
  output_buf[y * params.w + x] = vec4<f16>(1.0h / (1.0h + exp(-acc)), 0.0h, 0.0h, 0.0h);
11025
11025
  }
11026
- `;var Re=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Wr:Fr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Dr=`// up_final_skip: C/D alpha head. Fused concat(u, d_full, rgb) \u2192 conv 3\xD73 9\u21921
11026
+ `;var ze=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Wr:Fr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r],this.weights=[t.upload(d(n.weights)),t.upload(w(n.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Dr=`// up_final_skip: C/D alpha head. Fused concat(u, d_full, rgb) \u2192 conv 3\xD73 9\u21921
11027
11027
  // \u2192 sigmoid. u = c_up=2 (.xy); d_full = c_high=4 full-res skip (full vec4);
11028
11028
  // rgb = x_hr (.xyz). Channel order concat = 2 + 4 + 3 = 9. Output .x = alpha.
11029
11029
  // Weight: 27 vec4 (3 per kpos): [kpos*3+0]=(w0,w1,0,0) u; [kpos*3+1]=(w2..w5)
@@ -11096,7 +11096,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
11096
11096
 
11097
11097
  output_buf[y * params.w + x] = vec4<f16>(1.0h / (1.0h + exp(-acc)), 0.0h, 0.0h, 0.0h);
11098
11098
  }
11099
- `;var ze=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?Gr:Dr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r,n],this.weights=[t.upload(d(a.weights)),t.upload(w(a.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Or=`// Bilinear upsample + channel concat fused.
11099
+ `;var Le=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n,a){super(t),this.shader=t.dtype==="f16"?Gr:Dr,this.output=t.tensor(e.h,e.w,4),this.inputs=[e,r,n],this.weights=[t.upload(d(a.weights)),t.upload(w(a.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(e.w/8),Math.ceil(e.h/8),1];}};var Or=`// Bilinear upsample + channel concat fused.
11100
11100
  // input_a is the decoder tensor at small spatial resolution (in_h \xD7 in_w).
11101
11101
  // input_b is the encoder skip feature already at output resolution (out_h \xD7 out_w).
11102
11102
  // For output channels 0..a_groups-1: bilinearly interpolate from input_a.
@@ -11217,7 +11217,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
11217
11217
  output_buf[out_idx] = input_b[oy * params.out_w * params.b_groups + ox * params.b_groups + c_b];
11218
11218
  }
11219
11219
  }
11220
- `;var Le=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Mr:Or;let a=e.c/4,s=r.c/4,o=a+s;this.output=t.tensor(n.outH,n.outW,e.c+r.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n.outH,n.outW,a,s,o,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n.outW/8),Math.ceil(n.outH/8),o];}};var Rr=`// Bilinear upsample + 1\xD71 pointwise conv fused.
11220
+ `;var He=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?Mr:Or;let a=e.c/4,s=r.c/4,o=a+s;this.output=t.tensor(n.outH,n.outW,e.c+r.c),this.inputs=[e,r],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n.outH,n.outW,a,s,o,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n.outW/8),Math.ceil(n.outH/8),o];}};var Rr=`// Bilinear upsample + 1\xD71 pointwise conv fused.
11221
11221
  // For each output pixel, bilinearly samples the small input for each in_group,
11222
11222
  // immediately applies the 1\xD71 conv weights, and writes the activated result.
11223
11223
  // Eliminates the intermediate full-resolution upsample buffer.
@@ -11351,7 +11351,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
11351
11351
 
11352
11352
  output_buf[oy * params.out_w * params.out_groups + ox * params.out_groups + og] = result;
11353
11353
  }
11354
- `;var He=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?zr:Rr;let a=e.c/4,s=n.outChannels/4;this.output=t.tensor(n.outH,n.outW,n.outChannels),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n.outH,n.outW,a,s,n.activation==="relu6"?1:0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n.outW/8),Math.ceil(n.outH/8),s];}};var Lr=`// Bilinear upsample + sigmoid fused.
11354
+ `;var Ne=class extends c{inputs;weights;output;dispatch;shader;constructor(t,e,r,n){super(t),this.shader=t.dtype==="f16"?zr:Rr;let a=e.c/4,s=n.outChannels/4;this.output=t.tensor(n.outH,n.outW,n.outChannels),this.inputs=[e],this.weights=[t.upload(d(r.weights)),t.upload(d(r.bias))],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,n.outH,n.outW,a,s,n.activation==="relu6"?1:0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(n.outW/8),Math.ceil(n.outH/8),s];}};var Lr=`// Bilinear upsample + sigmoid fused.
11355
11355
  // Identical to bilinear_upsample.wgsl except sigmoid is applied at write time.
11356
11356
  // Eliminates the intermediate full-resolution buffer and the separate sigmoid dispatch.
11357
11357
 
@@ -11460,7 +11460,7 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
11460
11460
 
11461
11461
  output_buf[oy * params.out_w * C + ox * C + c] = vec4<f16>(1.0 / (1.0 + exp(-result)));
11462
11462
  }
11463
- `;var Ne=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?Hr:Lr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,r.outH,r.outW,n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var Nr=`// Composite an RGBA image over a solid background, gated by a 1-ch alpha.
11463
+ `;var Ve=class extends c{inputs;weights=[];output;dispatch;shader;constructor(t,e,r){super(t),this.shader=t.dtype==="f16"?Hr:Lr;let n=e.c/4;this.output=t.tensor(r.outH,r.outW,e.c),this.inputs=[e],this.createUniform("params","Params"),this.setUniform("params",new Uint32Array([e.h,e.w,r.outH,r.outW,n,0,0,0])),this.defaultSetup(),this.dispatch=[Math.ceil(r.outW/8),Math.ceil(r.outH/8),n];}};var Nr=`// Composite an RGBA image over a solid background, gated by a 1-ch alpha.
11464
11464
  // Fragment writes the canvas's swapchain texture (premultiplied output).
11465
11465
  //
11466
11466
  // Caller invariants (matched in CompositeSolidWebGPU):
@@ -11554,7 +11554,7 @@ fn fs(in: VertexOut) -> @location(0) vec4<f32> {
11554
11554
  let rgb = fg * a + params.bgColor.rgb * (1.0 - a);
11555
11555
  return vec4<f32>(rgb, 1.0);
11556
11556
  }
11557
- `;var Ve=class{constructor(t,e,r,n){this.backend=t;if(e.h!==r.h||e.w!==r.w)throw new Error(`CompositeSolid: image (${e.h}\xD7${e.w}) and alpha (${r.h}\xD7${r.w}) must match. Run the upscaler first.`);let a=t.device;this.uniformBuffer=a.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let s=new ArrayBuffer(32);new Uint32Array(s,0,1)[0]=e.w,new Float32Array(s,16,4).set([n[0],n[1],n[2],0]),a.queue.writeBuffer(this.uniformBuffer,0,s);let o=t.dtype==="f16"?Vr:Nr,u=a.createShaderModule({code:o});this.pipeline=a.createRenderPipeline({layout:"auto",vertex:{module:u,entryPoint:"vs"},fragment:{module:u,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=a.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:this.uniformBuffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositeSolidWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var qr=`// Like composite_solid but bg is an NHWC vec4 storage buffer (e.g. virtual
11557
+ `;var qe=class{constructor(t,e,r,n){this.backend=t;if(e.h!==r.h||e.w!==r.w)throw new Error(`CompositeSolid: image (${e.h}\xD7${e.w}) and alpha (${r.h}\xD7${r.w}) must match. Run the upscaler first.`);let a=t.device;this.uniformBuffer=a.createBuffer({size:32,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let s=new ArrayBuffer(32);new Uint32Array(s,0,1)[0]=e.w,new Float32Array(s,16,4).set([n[0],n[1],n[2],0]),a.queue.writeBuffer(this.uniformBuffer,0,s);let o=t.dtype==="f16"?Vr:Nr,u=a.createShaderModule({code:o});this.pipeline=a.createRenderPipeline({layout:"auto",vertex:{module:u,entryPoint:"vs"},fragment:{module:u,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=a.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:this.uniformBuffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositeSolidWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var qr=`// Like composite_solid but bg is an NHWC vec4 storage buffer (e.g. virtual
11558
11558
  // background image, or a blurred copy of the input).
11559
11559
 
11560
11560
  struct VertexOut {
@@ -11640,7 +11640,7 @@ fn fs(in: VertexOut) -> @location(0) vec4<f32> {
11640
11640
  let rgb = fg * a + bgc * (1.0 - a);
11641
11641
  return vec4<f32>(rgb, 1.0);
11642
11642
  }
11643
- `;var qe=class{constructor(t,e,r,n){this.backend=t;if(e.h!==r.h||e.w!==r.w||e.h!==n.h||e.w!==n.w)throw new Error(`CompositeImage: image (${e.h}\xD7${e.w}), alpha (${r.h}\xD7${r.w}), and bg (${n.h}\xD7${n.w}) must all match. Run upscaler / resizer first.`);let a=t.device;this.uniformBuffer=a.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let s=new ArrayBuffer(16);new Uint32Array(s,0,1)[0]=e.w,a.queue.writeBuffer(this.uniformBuffer,0,s);let o=t.dtype==="f16"?jr:qr,u=a.createShaderModule({code:o});this.pipeline=a.createRenderPipeline({layout:"auto",vertex:{module:u,entryPoint:"vs"},fragment:{module:u,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=a.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:n.buffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositeImageWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var Xr=`// Like composite_image but bg is sampled bilinearly \u2014 bg may be smaller than
11643
+ `;var je=class{constructor(t,e,r,n){this.backend=t;if(e.h!==r.h||e.w!==r.w||e.h!==n.h||e.w!==n.w)throw new Error(`CompositeImage: image (${e.h}\xD7${e.w}), alpha (${r.h}\xD7${r.w}), and bg (${n.h}\xD7${n.w}) must all match. Run upscaler / resizer first.`);let a=t.device;this.uniformBuffer=a.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let s=new ArrayBuffer(16);new Uint32Array(s,0,1)[0]=e.w,a.queue.writeBuffer(this.uniformBuffer,0,s);let o=t.dtype==="f16"?jr:qr,u=a.createShaderModule({code:o});this.pipeline=a.createRenderPipeline({layout:"auto",vertex:{module:u,entryPoint:"vs"},fragment:{module:u,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=a.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:n.buffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositeImageWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var Xr=`// Like composite_image but bg is sampled bilinearly \u2014 bg may be smaller than
11644
11644
  // (image, alpha). Used by CompositorBlur to skip the final full-res upsample
11645
11645
  // in the blur pyramid and let this shader's own per-pixel scan do the
11646
11646
  // expansion (the work is already happening here for the composite anyway).
@@ -11766,7 +11766,7 @@ fn fs(in: VertexOut) -> @location(0) vec4<f32> {
11766
11766
  let rgb = fg * a + bgc * (1.0 - a);
11767
11767
  return vec4<f32>(rgb, 1.0);
11768
11768
  }
11769
- `;var je=class{constructor(t,e,r,n){this.backend=t;if(e.h!==r.h||e.w!==r.w)throw new Error(`CompositeImageBilinear: image (${e.h}\xD7${e.w}) and alpha (${r.h}\xD7${r.w}) must match.`);let a=t.device;this.uniformBuffer=a.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let s=new ArrayBuffer(16),o=new Uint32Array(s);o[0]=e.w,o[1]=e.h,o[2]=n.w,o[3]=n.h,a.queue.writeBuffer(this.uniformBuffer,0,s);let u=t.dtype==="f16"?$r:Xr,p=a.createShaderModule({code:u});this.pipeline=a.createRenderPipeline({layout:"auto",vertex:{module:p,entryPoint:"vs"},fragment:{module:p,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=a.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:n.buffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositeImageBilinearWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var Kr=`// Passthrough "compositor" \u2014 writes the image directly to the canvas
11769
+ `;var Xe=class{constructor(t,e,r,n){this.backend=t;if(e.h!==r.h||e.w!==r.w)throw new Error(`CompositeImageBilinear: image (${e.h}\xD7${e.w}) and alpha (${r.h}\xD7${r.w}) must match.`);let a=t.device;this.uniformBuffer=a.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let s=new ArrayBuffer(16),o=new Uint32Array(s);o[0]=e.w,o[1]=e.h,o[2]=n.w,o[3]=n.h,a.queue.writeBuffer(this.uniformBuffer,0,s);let u=t.dtype==="f16"?$r:Xr,p=a.createShaderModule({code:u});this.pipeline=a.createRenderPipeline({layout:"auto",vertex:{module:p,entryPoint:"vs"},fragment:{module:p,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=a.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:r.buffer}},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:n.buffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositeImageBilinearWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var Kr=`// Passthrough "compositor" \u2014 writes the image directly to the canvas
11770
11770
  // swapchain texture with no alpha math and no background. Used by RenderOp
11771
11771
  // when the renderer is in disabled state, so the output canvas reflects
11772
11772
  // the unmodified input frame instead of a stale matted result.
@@ -11840,7 +11840,7 @@ fn fs(in: VertexOut) -> @location(0) vec4<f32> {
11840
11840
  let i = y * params.width + x;
11841
11841
  return vec4<f32>(vec3<f32>(image[i].rgb), 1.0);
11842
11842
  }
11843
- `;var Xe=class{constructor(t,e){this.backend=t;let r=t.device;this.uniformBuffer=r.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let n=new ArrayBuffer(16);new Uint32Array(n,0,1)[0]=e.w,r.queue.writeBuffer(this.uniformBuffer,0,n);let a=t.dtype==="f16"?Yr:Kr,s=r.createShaderModule({code:a});this.pipeline=r.createRenderPipeline({layout:"auto",vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=r.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:this.uniformBuffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositePassthroughWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var Qr=`// Input op \u2014 sample a regular 2D source texture (RGBA8 unorm) into the NHWC
11843
+ `;var $e=class{constructor(t,e){this.backend=t;let r=t.device;this.uniformBuffer=r.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let n=new ArrayBuffer(16);new Uint32Array(n,0,1)[0]=e.w,r.queue.writeBuffer(this.uniformBuffer,0,n);let a=t.dtype==="f16"?Yr:Kr,s=r.createShaderModule({code:a});this.pipeline=r.createRenderPipeline({layout:"auto",vertex:{module:s,entryPoint:"vs"},fragment:{module:s,entryPoint:"fs",targets:[{format:t.canvasFormat}]},primitive:{topology:"triangle-list"}}),this.bindGroup=r.createBindGroup({layout:this.pipeline.getBindGroupLayout(0),entries:[{binding:0,resource:{buffer:e.buffer}},{binding:1,resource:{buffer:this.uniformBuffer}}]});}backend;pipeline;bindGroup;uniformBuffer;outputView=null;setOutput(t){this.outputView=t.createView();}run(){if(!this.outputView)throw new Error("CompositePassthroughWebGPU.run() called before setOutput()");let t=this.backend.device.createCommandEncoder(),e=t.beginRenderPass({colorAttachments:[{view:this.outputView,clearValue:[0,0,0,1],loadOp:"clear",storeOp:"store"}]});e.setPipeline(this.pipeline),e.setBindGroup(0,this.bindGroup),e.draw(6),e.end(),this.backend.device.queue.submit([t.finish()]),this.outputView=null;}};var Qr=`// Input op \u2014 sample a regular 2D source texture (RGBA8 unorm) into the NHWC
11844
11844
  // vec4<f32> output buffer at the target resolution. Used for ImageBitmap
11845
11845
  // sources, which are uploaded into a persistent staging texture via
11846
11846
  // copyExternalImageToTexture before each dispatch.
@@ -11960,4 +11960,4 @@ fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
11960
11960
  let rgba = textureSampleBaseClampToEdge(src_tex, src_sampler, uv);
11961
11961
  output_buf[y * params.out_w + x] = vec4<f16>(rgba);
11962
11962
  }
11963
- `;var ai=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,$e=class{output;device;dtype;sampler;uniformBuffer;dispatch;pipeline2d=null;pipelineExternal=null;stagingTex=null;stagingW=0;stagingH=0;source=null;constructor(t,e,r){this.device=t.device,this.dtype=t.dtype,this.output=t.tensor(e,r,4),this.sampler=this.device.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.uniformBuffer=this.device.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let n=new ArrayBuffer(16);new Uint32Array(n,0,2).set([r,e]),this.device.queue.writeBuffer(this.uniformBuffer,0,n),this.dispatch=[Math.ceil(r/8),Math.ceil(e/8),1],this.pipeline2d=this.buildPipeline(this.dtype==="f16"?Jr:Qr);}setSource(t){this.source=t;}run(){if(!this.source)throw new Error("InputWebGPU.run() called before setSource()");ai(this.source)?this.runExternal(this.source):this.run2d(this.source);}run2d(t){this.ensureStagingTexture(t.width,t.height),this.device.queue.copyExternalImageToTexture({source:t,flipY:false},{texture:this.stagingTex},[t.width,t.height]);let e=this.device.createBindGroup({layout:this.pipeline2d.getBindGroupLayout(0),entries:[{binding:0,resource:this.stagingTex.createView()},{binding:1,resource:this.sampler},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:this.output.buffer}}]});this.dispatchOnce(this.pipeline2d,e);}runExternal(t){this.pipelineExternal||(this.pipelineExternal=this.buildPipeline(this.dtype==="f16"?en:Zr));let e=this.device.importExternalTexture({source:t}),r=this.device.createBindGroup({layout:this.pipelineExternal.getBindGroupLayout(0),entries:[{binding:0,resource:e},{binding:1,resource:this.sampler},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:this.output.buffer}}]});this.dispatchOnce(this.pipelineExternal,r);}ensureStagingTexture(t,e){this.stagingTex&&this.stagingW===t&&this.stagingH===e||(this.stagingTex?.destroy(),this.stagingTex=this.device.createTexture({size:[t,e,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT}),this.stagingW=t,this.stagingH=e);}buildPipeline(t){let e=this.device.createShaderModule({code:t});return this.device.createComputePipeline({layout:"auto",compute:{module:e,entryPoint:"main"}})}dispatchOnce(t,e){let r=this.device.createCommandEncoder(),n=r.beginComputePass();n.setPipeline(t),n.setBindGroup(0,e),n.dispatchWorkgroups(...this.dispatch),n.end(),this.device.queue.submit([r.finish()]);}};var ii=navigator.gpu?GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST:0,st=class i{constructor(t,e,r){this.device=t;this.canvas=e;this.dtype=r;this.bytesPerElement=r==="f16"?2:4;let n=e.getContext("webgpu");if(!n)throw new Error("Failed to get WebGPU context from canvas");this.canvasFormat=navigator.gpu.getPreferredCanvasFormat(),this.configureContext(n),this.canvasContext=n,this.contexts.set("main",n),this.ops={Conv2d:(a,s,o)=>new le(this,a,s,o),ConvTranspose2d:(a,s,o)=>new ce(this,a,s,o),DepthwiseConv2d:(a,s,o)=>new fe(this,a,s,o),Add:(a,s)=>new de(this,a,s),Sigmoid:a=>new he(this,a),Tanh:a=>new me(this,a),ElementwiseMul:(a,s)=>new ge(this,a,s),Warp:(a,s,o)=>new _e(this,a,s,o),FaceBoxFromHeatmaps:(a,s)=>new ve(this,a,s),FaceBoxesFromHeatmaps:(a,s)=>new xe(this,a,s),ReframeState:(a,s,o,u)=>new be(this,a,s,o,u),Reframe:(a,s)=>new ye(this,a,s),CropResample:(a,s,o)=>new we(this,a,s,o),FaceTouchupStage:(a,s,o,u,p)=>new Te(this,a,s,o,u,p),Stabilize:(a,s,o,u,p)=>new Ce(this,a,s,o,u,p),BilinearUpsample:(a,s)=>new Ue(this,a,s),Crop:(a,s)=>new Ae(this,a,s),BicubicUpsample:(a,s)=>new Se(this,a,s),ChannelConcat:(a,s)=>new Be(this,a,s),Conv2dAdd:(a,s,o,u)=>new Ee(this,a,s,o,u),ProjResidual:(a,s,o,u)=>new Ie(this,a,s,o,u),ConcatConv2d:(a,s,o,u)=>new Fe(this,a,s,o,u),GatesFused:(a,s,o)=>new We(this,a,s,o),CandUpdateFused:(a,s,o,u,p)=>new De(this,a,s,o,u,p),ConvExpand:(a,s)=>new Ge(this,a,s),CatConv6to2:(a,s,o)=>new Oe(this,a,s,o),DownAdapter:(a,s,o,u)=>new Me(this,a,s,o,u),UpFinal:(a,s,o)=>new Re(this,a,s,o),UpFinalSkip:(a,s,o,u)=>new ze(this,a,s,o,u),UpsampleConcat:(a,s,o)=>new Le(this,a,s,o),UpsampleConv1x1:(a,s,o)=>new He(this,a,s,o),UpsampleSigmoid:(a,s)=>new Ne(this,a,s),Input:(a,s)=>new $e(this,a,s)},this.presenters={CompositeSolid:(a,s,o,u="main")=>{let p=new Ve(this,a,s,o);return {run:()=>{p.setOutput(this.getCurrentDisplayTexture(u)),p.run();}}},CompositeImage:(a,s,o,u="main")=>{let p=new qe(this,a,s,o);return {run:()=>{p.setOutput(this.getCurrentDisplayTexture(u)),p.run();}}},CompositeImageBilinear:(a,s,o,u="main")=>{let p=new je(this,a,s,o);return {run:()=>{p.setOutput(this.getCurrentDisplayTexture(u)),p.run();}}},CompositePassthrough:(a,s="main")=>{let o=new Xe(this,a);return {run:()=>{o.setOutput(this.getCurrentDisplayTexture(s)),o.run();}}},LandmarkOverlay:(a,s,o,u,p="main")=>{let l=new ke(this,a,s,o,u);return {run:()=>{l.setOutput(this.getCurrentDisplayTexture(p)),l.run();}}},FaceTouchup:(a,s,o,u,p,l="main")=>{let f=new Pe(this,a,s,o,u,p);return {run:()=>{f.setOutput(this.getCurrentDisplayTexture(l)),f.run();}}}};}device;canvas;dtype;ops;presenters;canvasContext;canvasFormat;bytesPerElement;contexts=new Map;configureContext(t){t.configure({device:this.device,format:this.canvasFormat,alphaMode:"premultiplied"});}attachCanvas(t,e){if(t==="main")throw new Error("attachCanvas: 'main' is reserved for the create() canvas");let r=e.getContext("webgpu");if(!r)throw new Error(`attachCanvas: failed to get WebGPU context for target '${t}'`);this.configureContext(r),this.contexts.set(t,r);}static async isAvailable(){return navigator.gpu?await navigator.gpu.requestAdapter()!==null:false}static async hasF16Support(){if(!navigator.gpu)return false;let t=await navigator.gpu.requestAdapter();return t?t.features.has("shader-f16"):false}static async create(t){let e=t.dtype??"f32",r=t.device;if(r){if(e==="f16"&&!r.features.has("shader-f16"))throw new Error("WebGPU dtype='f16' requested but supplied device lacks `shader-f16`")}else {let n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU adapter not available");if(e==="f16"&&!n.features.has("shader-f16"))throw new Error("WebGPU dtype='f16' requested but adapter lacks `shader-f16` feature");r=await n.requestDevice({requiredFeatures:e==="f16"?["shader-f16"]:[]});}return new i(r,t.canvas,e)}getCurrentDisplayTexture(t="main"){let e=this.contexts.get(t);if(!e)throw new Error(`getCurrentDisplayTexture: no canvas attached for target '${t}'`);return e.getCurrentTexture()}tensor(t,e,r,n){let s=t*e*r*this.bytesPerElement,o=this.device.createBuffer({size:s,usage:ii,mappedAtCreation:n!==void 0});if(n!==void 0){let u=o.getMappedRange();this.writeView(u,n),o.unmap();}return {h:t,w:e,c:r,buffer:o}}upload(t){let r=t.length*this.bytesPerElement,n=this.device.createBuffer({size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,mappedAtCreation:true});return this.writeView(n.getMappedRange(),t),n.unmap(),{buffer:n}}writeView(t,e){let r=this.dtype==="f16",n=e instanceof Uint16Array;if(r===n){r?new Uint16Array(t).set(e):new Float32Array(t).set(e);return}r?new Uint16Array(t).set(It(e)):new Float32Array(t).set(rt(e));}async readback(t){let e=this.device.createBuffer({size:t.buffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),r=this.device.createCommandEncoder();r.copyBufferToBuffer(t.buffer,0,e,0,t.buffer.size),this.device.queue.submit([r.finish()]),await e.mapAsync(GPUMapMode.READ);let n=e.getMappedRange(),a=this.dtype==="f16"?rt(new Uint16Array(n.slice(0))):new Float32Array(n.slice(0));return e.unmap(),e.destroy(),a}copyTensor(t,e){if(t.buffer.size!==e.buffer.size)throw new Error(`copyTensor: size mismatch (src ${t.buffer.size} vs dst ${e.buffer.size})`);let r=this.device.createCommandEncoder();r.copyBufferToBuffer(t.buffer,0,e.buffer,0,t.buffer.size),this.device.queue.submit([r.finish()]);}async sync(){await this.device.queue.onSubmittedWorkDone();}destroy(){this.device.destroy();}};exports.EffectsPipeline=et;exports.WebGPUBackend=st;
11963
+ `;var ai=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,Ke=class{output;device;dtype;sampler;uniformBuffer;dispatch;pipeline2d=null;pipelineExternal=null;stagingTex=null;stagingW=0;stagingH=0;source=null;constructor(t,e,r){this.device=t.device,this.dtype=t.dtype,this.output=t.tensor(e,r,4),this.sampler=this.device.createSampler({magFilter:"linear",minFilter:"linear",addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}),this.uniformBuffer=this.device.createBuffer({size:16,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});let n=new ArrayBuffer(16);new Uint32Array(n,0,2).set([r,e]),this.device.queue.writeBuffer(this.uniformBuffer,0,n),this.dispatch=[Math.ceil(r/8),Math.ceil(e/8),1],this.pipeline2d=this.buildPipeline(this.dtype==="f16"?Jr:Qr);}setSource(t){this.source=t;}run(){if(!this.source)throw new Error("InputWebGPU.run() called before setSource()");ai(this.source)?this.runExternal(this.source):this.run2d(this.source);}run2d(t){this.ensureStagingTexture(t.width,t.height),this.device.queue.copyExternalImageToTexture({source:t,flipY:false},{texture:this.stagingTex},[t.width,t.height]);let e=this.device.createBindGroup({layout:this.pipeline2d.getBindGroupLayout(0),entries:[{binding:0,resource:this.stagingTex.createView()},{binding:1,resource:this.sampler},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:this.output.buffer}}]});this.dispatchOnce(this.pipeline2d,e);}runExternal(t){this.pipelineExternal||(this.pipelineExternal=this.buildPipeline(this.dtype==="f16"?en:Zr));let e=this.device.importExternalTexture({source:t}),r=this.device.createBindGroup({layout:this.pipelineExternal.getBindGroupLayout(0),entries:[{binding:0,resource:e},{binding:1,resource:this.sampler},{binding:2,resource:{buffer:this.uniformBuffer}},{binding:3,resource:{buffer:this.output.buffer}}]});this.dispatchOnce(this.pipelineExternal,r);}ensureStagingTexture(t,e){this.stagingTex&&this.stagingW===t&&this.stagingH===e||(this.stagingTex?.destroy(),this.stagingTex=this.device.createTexture({size:[t,e,1],format:"rgba8unorm",usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT}),this.stagingW=t,this.stagingH=e);}buildPipeline(t){let e=this.device.createShaderModule({code:t});return this.device.createComputePipeline({layout:"auto",compute:{module:e,entryPoint:"main"}})}dispatchOnce(t,e){let r=this.device.createCommandEncoder(),n=r.beginComputePass();n.setPipeline(t),n.setBindGroup(0,e),n.dispatchWorkgroups(...this.dispatch),n.end(),this.device.queue.submit([r.finish()]);}};var ii=navigator.gpu?GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST:0,ot=class i{constructor(t,e,r){this.device=t;this.canvas=e;this.dtype=r;this.bytesPerElement=r==="f16"?2:4;let n=e.getContext("webgpu");if(!n)throw new Error("Failed to get WebGPU context from canvas");this.canvasFormat=navigator.gpu.getPreferredCanvasFormat(),this.configureContext(n),this.canvasContext=n,this.contexts.set("main",n),this.ops={Conv2d:(a,s,o)=>new ce(this,a,s,o),ConvTranspose2d:(a,s,o)=>new fe(this,a,s,o),DepthwiseConv2d:(a,s,o)=>new de(this,a,s,o),Add:(a,s)=>new he(this,a,s),Sigmoid:a=>new me(this,a),Tanh:a=>new ge(this,a),ElementwiseMul:(a,s)=>new _e(this,a,s),Warp:(a,s,o)=>new ve(this,a,s,o),FaceBoxFromHeatmaps:(a,s)=>new xe(this,a,s),FaceBoxesFromHeatmaps:(a,s)=>new be(this,a,s),ReframeState:(a,s,o,u)=>new ye(this,a,s,o,u),Reframe:(a,s)=>new we(this,a,s),CropResample:(a,s,o)=>new ke(this,a,s,o),FaceTouchupStage:(a,s,o,u,p)=>new Ce(this,a,s,o,u,p),Stabilize:(a,s,o,u,p)=>new Ue(this,a,s,o,u,p),BilinearUpsample:(a,s)=>new Ae(this,a,s),Crop:(a,s)=>new Se(this,a,s),BicubicUpsample:(a,s)=>new Be(this,a,s),ChannelConcat:(a,s)=>new Ee(this,a,s),Conv2dAdd:(a,s,o,u)=>new Ie(this,a,s,o,u),ProjResidual:(a,s,o,u)=>new Fe(this,a,s,o,u),ConcatConv2d:(a,s,o,u)=>new We(this,a,s,o,u),GatesFused:(a,s,o)=>new De(this,a,s,o),CandUpdateFused:(a,s,o,u,p)=>new Ge(this,a,s,o,u,p),ConvExpand:(a,s)=>new Oe(this,a,s),CatConv6to2:(a,s,o)=>new Me(this,a,s,o),DownAdapter:(a,s,o,u)=>new Re(this,a,s,o,u),UpFinal:(a,s,o)=>new ze(this,a,s,o),UpFinalSkip:(a,s,o,u)=>new Le(this,a,s,o,u),UpsampleConcat:(a,s,o)=>new He(this,a,s,o),UpsampleConv1x1:(a,s,o)=>new Ne(this,a,s,o),UpsampleSigmoid:(a,s)=>new Ve(this,a,s),Input:(a,s)=>new Ke(this,a,s)},this.presenters={CompositeSolid:(a,s,o,u="main")=>{let p=new qe(this,a,s,o);return {run:()=>{p.setOutput(this.getCurrentDisplayTexture(u)),p.run();}}},CompositeImage:(a,s,o,u="main")=>{let p=new je(this,a,s,o);return {run:()=>{p.setOutput(this.getCurrentDisplayTexture(u)),p.run();}}},CompositeImageBilinear:(a,s,o,u="main")=>{let p=new Xe(this,a,s,o);return {run:()=>{p.setOutput(this.getCurrentDisplayTexture(u)),p.run();}}},CompositePassthrough:(a,s="main")=>{let o=new $e(this,a);return {run:()=>{o.setOutput(this.getCurrentDisplayTexture(s)),o.run();}}},LandmarkOverlay:(a,s,o,u,p="main")=>{let l=new Pe(this,a,s,o,u);return {run:()=>{l.setOutput(this.getCurrentDisplayTexture(p)),l.run();}}},FaceTouchup:(a,s,o,u,p,l="main")=>{let f=new Te(this,a,s,o,u,p);return {run:()=>{f.setOutput(this.getCurrentDisplayTexture(l)),f.run();}}}};}device;canvas;dtype;ops;presenters;canvasContext;canvasFormat;bytesPerElement;contexts=new Map;configureContext(t){t.configure({device:this.device,format:this.canvasFormat,alphaMode:"premultiplied"});}attachCanvas(t,e){if(t==="main")throw new Error("attachCanvas: 'main' is reserved for the create() canvas");let r=e.getContext("webgpu");if(!r)throw new Error(`attachCanvas: failed to get WebGPU context for target '${t}'`);this.configureContext(r),this.contexts.set(t,r);}static async isAvailable(){return navigator.gpu?await navigator.gpu.requestAdapter()!==null:false}static async hasF16Support(){if(!navigator.gpu)return false;let t=await navigator.gpu.requestAdapter();return t?t.features.has("shader-f16"):false}static async create(t){let e=t.dtype??"f32",r=t.device;if(r){if(e==="f16"&&!r.features.has("shader-f16"))throw new Error("WebGPU dtype='f16' requested but supplied device lacks `shader-f16`")}else {let n=await navigator.gpu.requestAdapter();if(!n)throw new Error("WebGPU adapter not available");if(e==="f16"&&!n.features.has("shader-f16"))throw new Error("WebGPU dtype='f16' requested but adapter lacks `shader-f16` feature");r=await n.requestDevice({requiredFeatures:e==="f16"?["shader-f16"]:[]});}return new i(r,t.canvas,e)}getCurrentDisplayTexture(t="main"){let e=this.contexts.get(t);if(!e)throw new Error(`getCurrentDisplayTexture: no canvas attached for target '${t}'`);return e.getCurrentTexture()}tensor(t,e,r,n){let s=t*e*r*this.bytesPerElement,o=this.device.createBuffer({size:s,usage:ii,mappedAtCreation:n!==void 0});if(n!==void 0){let u=o.getMappedRange();this.writeView(u,n),o.unmap();}return {h:t,w:e,c:r,buffer:o}}upload(t){let r=t.length*this.bytesPerElement,n=this.device.createBuffer({size:r,usage:GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_DST,mappedAtCreation:true});return this.writeView(n.getMappedRange(),t),n.unmap(),{buffer:n}}writeView(t,e){let r=this.dtype==="f16",n=e instanceof Uint16Array;if(r===n){r?new Uint16Array(t).set(e):new Float32Array(t).set(e);return}r?new Uint16Array(t).set(It(e)):new Float32Array(t).set(nt(e));}async readback(t){let e=this.device.createBuffer({size:t.buffer.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),r=this.device.createCommandEncoder();r.copyBufferToBuffer(t.buffer,0,e,0,t.buffer.size),this.device.queue.submit([r.finish()]),await e.mapAsync(GPUMapMode.READ);let n=e.getMappedRange(),a=this.dtype==="f16"?nt(new Uint16Array(n.slice(0))):new Float32Array(n.slice(0));return e.unmap(),e.destroy(),a}copyTensor(t,e){if(t.buffer.size!==e.buffer.size)throw new Error(`copyTensor: size mismatch (src ${t.buffer.size} vs dst ${e.buffer.size})`);let r=this.device.createCommandEncoder();r.copyBufferToBuffer(t.buffer,0,e.buffer,0,t.buffer.size),this.device.queue.submit([r.finish()]);}async sync(){await this.device.queue.onSubmittedWorkDone();}destroy(){this.device.destroy();}};exports.EffectsPipeline=tt;exports.WebGPUBackend=ot;