@derushly/editor 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +15 -0
- package/README.md +6 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/server.d.ts +42 -0
- package/dist/server.js +756 -0
- package/package.json +56 -4
- package/ui-dist/THIRD_PARTY_NOTICES.md +2201 -0
- package/ui-dist/assets/dist-DDQ9WcrZ.js +58 -0
- package/ui-dist/assets/index-B1Lor06r.css +1 -0
- package/ui-dist/assets/index-BefJOHLE.js +852 -0
- package/ui-dist/assets/parent-audio-333CSKNZ-x-ixkhjk.js +500 -0
- package/ui-dist/assets/pausedVideoDecoder-3C25UMTR-DnYIc3M4.js +1 -0
- package/ui-dist/assets/previewOffCanvas-CTOQIFXK-DoXeJSRI.js +1 -0
- package/ui-dist/assets/runtime-inline-BT7nvEOP.js +1 -0
- package/ui-dist/assets/src-CYmap0el.js +36 -0
- package/ui-dist/hyperframe.runtime.iife.js +1146 -0
- package/ui-dist/index.html +13 -0
- package/ui-dist/third-party.json +1 -0
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
import{n as e,t}from"./index-BefJOHLE.js";var n=()=>globalThis.__HF_VIRTUAL_TIME__;function r(e,t,...r){return(n()?.originalSetTimeout??setTimeout)(e,t,...r)}function i(e){(n()?.originalClearTimeout??clearTimeout)(e??void 0)}var a=`data-fx-chain`;a.slice(5);var o=1,s=(e=`frequency`,t=`Frequency`,n=1e3,r=20,i=2e4)=>({kind:`number`,key:e,label:t,unit:`Hz`,min:r,max:i,step:1,default:n,scale:`log`,automatable:!0}),c=(e=.707,t=`Bandwidth: higher is narrower.`)=>({kind:`number`,key:`q`,label:`Q`,unit:``,min:.1,max:20,step:.01,default:e,scale:`log`,automatable:!0,hint:t}),l=(e=-40,t=40,n=0)=>({kind:`number`,key:`gain`,label:`Gain`,unit:`dB`,min:e,max:t,step:.1,default:n,automatable:!0}),u={kind:`enum`,key:`poles`,label:`Slope`,options:[{value:`1`,label:`6 dB/oct`},{value:`2`,label:`12 dB/oct`}],default:`2`,hint:`Two poles is the usual biquad; one pole is gentler.`},d=[{id:`gain`,label:`Gain`,group:`dynamics`,description:`Raise or lower the whole signal. Automate it to duck under something else.`,params:[l(-60,12,0)],web:`gain-node`},{id:`peaking`,label:`Peaking EQ`,group:`filter`,description:`Boost or cut a band, leaving everything either side alone.`,params:[s(`frequency`,`Frequency`,1e3),l(-40,40,0),c(1)],web:`biquad-peaking`},{id:`lowshelf`,label:`Low Shelf`,group:`filter`,description:`Lift or drop everything below the corner frequency.`,params:[s(`frequency`,`Frequency`,200,20,2e3),l(-40,40,0)],web:`biquad-lowshelf`},{id:`highshelf`,label:`High Shelf`,group:`filter`,description:`Lift or drop everything above the corner frequency.`,params:[s(`frequency`,`Frequency`,4e3,500,2e4),l(-40,40,0)],web:`biquad-highshelf`},{id:`highpass`,label:`High-pass`,group:`filter`,description:`Remove low frequencies: the usual fix for rumble on a voice.`,params:[s(`frequency`,`Cutoff`,300,20,2e4),c(.707),u],web:`biquad-highpass`},{id:`lowpass`,label:`Low-pass`,group:`filter`,description:`Remove high frequencies, which darkens or muffles a track.`,params:[s(`frequency`,`Cutoff`,8e3,100,2e4),c(.707),u],web:`biquad-lowpass`},{id:`compressor`,label:`Compressor`,group:`dynamics`,description:`Pull loud parts down so the quiet ones can come up.`,params:[{kind:`number`,key:`threshold`,label:`Threshold`,unit:`dB`,min:-60,max:0,step:.5,default:-24,hint:`Level above which the compressor starts working.`},{kind:`number`,key:`ratio`,label:`Ratio`,unit:`:1`,min:1,max:20,step:.1,default:4},{kind:`number`,key:`attack`,label:`Attack`,unit:`ms`,min:.01,max:2e3,step:.1,default:20,scale:`log`},{kind:`number`,key:`release`,label:`Release`,unit:`ms`,min:.01,max:9e3,step:1,default:250,scale:`log`},{kind:`number`,key:`knee`,label:`Knee`,unit:``,min:1,max:8,step:.01,default:2.83,hint:`1 is a hard corner; higher eases into it.`},{kind:`number`,key:`makeup`,label:`Makeup`,unit:`dB`,min:0,max:36,step:.1,default:0},{kind:`number`,key:`mix`,label:`Mix`,unit:``,min:0,max:1,step:.01,default:1,hint:`Below 1 blends the dry signal back in.`}],web:`worklet-compressor`},{id:`limiter`,label:`Limiter`,group:`dynamics`,description:`Peak limiter that follows the signal's level. It has no lookahead, so a fast peak or an inter-sample peak can pass the ceiling; use the true-peak limiter for a delivery limit.`,params:[{kind:`number`,key:`limit`,label:`Ceiling`,unit:`dB`,min:-24,max:0,step:.1,default:-1},{kind:`number`,key:`attack`,label:`Attack`,unit:`ms`,min:.1,max:80,step:.1,default:5},{kind:`number`,key:`release`,label:`Release`,unit:`ms`,min:1,max:8e3,step:1,default:50,scale:`log`},{kind:`number`,key:`level_out`,label:`Output`,unit:`dB`,min:-24,max:24,step:.1,default:0}],web:`worklet-limiter`},{id:`truepeak`,label:`True-peak limiter`,group:`dynamics`,description:`Lookahead limiter that holds a 4x estimate of the inter-sample peak at a dBTP ceiling; full-band noise can land up to about 1.7 dB above it. Adds lookahead plus about 0.3 ms of latency.`,params:[{kind:`number`,key:`ceiling`,label:`Ceiling`,unit:`dBTP`,min:-24,max:0,step:.1,default:-1,hint:`Target true peak, measured on a 4x oversampled signal. Dense full-band sound can end up to about 1.7 dB above it.`},{kind:`number`,key:`lookahead`,label:`Lookahead`,unit:`ms`,min:.5,max:10,step:.1,default:3,hint:`How far ahead the gain starts falling. Longer is smoother and adds the same latency.`},{kind:`number`,key:`release`,label:`Release`,unit:`ms`,min:10,max:2e3,step:1,default:80,scale:`log`}],web:`worklet-truepeak`},{id:`gate`,label:`Noise Gate`,group:`dynamics`,description:`Silence the track when it drops below the threshold.`,params:[{kind:`number`,key:`threshold`,label:`Threshold`,unit:`dB`,min:-80,max:0,step:.5,default:-35},{kind:`number`,key:`range`,label:`Range`,unit:`dB`,min:-80,max:0,step:.5,default:-24,hint:`How far down the gate pulls when closed.`},{kind:`number`,key:`ratio`,label:`Ratio`,unit:`:1`,min:1,max:20,step:.1,default:10},{kind:`number`,key:`attack`,label:`Attack`,unit:`ms`,min:.01,max:9e3,step:.1,default:1,scale:`log`},{kind:`number`,key:`release`,label:`Release`,unit:`ms`,min:.01,max:9e3,step:1,default:100,scale:`log`},{kind:`number`,key:`knee`,label:`Knee`,unit:``,min:1,max:8,step:.01,default:2.83}],web:`worklet-gate`},{id:`saturate`,label:`Saturation`,group:`nonlinear`,description:`Soft-clip the waveform for warmth or outright distortion.`,params:[{kind:`enum`,key:`type`,label:`Curve`,options:[{value:`tanh`,label:`Tanh`},{value:`atan`,label:`Arctan`},{value:`cubic`,label:`Cubic`},{value:`exp`,label:`Exponential`},{value:`alg`,label:`Algebraic`},{value:`quintic`,label:`Quintic`},{value:`sin`,label:`Sine`},{value:`erf`,label:`Error function`},{value:`hard`,label:`Hard clip`}],default:`tanh`},{kind:`number`,key:`threshold`,label:`Threshold`,unit:`dB`,min:-40,max:0,step:.1,default:-6},{kind:`number`,key:`output`,automatable:!0,label:`Output`,unit:`dB`,min:-24,max:24,step:.1,default:0},{kind:`number`,key:`oversample`,label:`Oversample`,unit:`x`,min:1,max:8,step:1,default:4,hint:`Higher costs more but keeps aliasing down.`}],web:`waveshaper`},{id:`bitcrush`,label:`Bitcrush`,group:`nonlinear`,description:`Drop bit depth and sample rate for a lo-fi, digital sound.`,params:[{kind:`number`,key:`bits`,label:`Bit depth`,unit:`bit`,min:1,max:32,step:.1,default:8},{kind:`number`,key:`samples`,label:`Sample hold`,unit:`x`,min:1,max:250,step:1,default:1,hint:`Repeats each sample N times, a crude downsample.`},{kind:`number`,key:`mix`,label:`Mix`,unit:``,min:0,max:1,step:.01,default:1}],web:`worklet-bitcrush`},{id:`pitchshift`,label:`Pitch shift`,group:`time`,description:`Shifts pitch up or down without changing playback speed. Adds ~50 ms of latency.`,params:[{kind:`number`,key:`semitones`,label:`Semitones`,unit:`st`,min:-12,max:12,step:1,default:0},{kind:`number`,key:`mix`,label:`Mix`,unit:``,min:0,max:1,step:.01,default:1}],web:`worklet-pitchshift`},{id:`delay`,label:`Delay`,group:`time`,description:`Repeating echoes behind the dry signal.`,params:[{kind:`number`,key:`time`,automatable:!0,label:`Time`,unit:`ms`,min:1,max:5e3,step:1,default:250,scale:`log`},{kind:`number`,key:`feedback`,automatable:!0,label:`Feedback`,unit:``,min:.01,max:.95,step:.01,default:.35},{kind:`number`,key:`mix`,automatable:!0,label:`Mix`,unit:``,min:0,max:1,step:.01,default:.4}],web:`delay-feedback`},{id:`chorus`,label:`Chorus`,group:`time`,description:`Detuned copies of the signal for width and thickness.`,params:[{kind:`number`,key:`delay`,automatable:!0,label:`Delay`,unit:`ms`,min:1,max:100,step:.1,default:7},{kind:`number`,key:`depth`,automatable:!0,label:`Depth`,unit:`ms`,min:0,max:10,step:.01,default:2},{kind:`number`,key:`speed`,automatable:!0,label:`Rate`,unit:`Hz`,min:.01,max:10,step:.01,default:1},{kind:`number`,key:`mix`,automatable:!0,label:`Mix`,unit:``,min:0,max:1,step:.01,default:.5}],web:`chorus-lfo`},{id:`phaser`,label:`Phaser`,group:`time`,description:`Sweeping notches moving through the spectrum.`,params:[{kind:`number`,key:`in_gain`,automatable:!0,label:`Input`,unit:``,min:0,max:1,step:.01,default:.4},{kind:`number`,key:`out_gain`,automatable:!0,label:`Output`,unit:``,min:0,max:2,step:.01,default:.74},{kind:`number`,key:`delay`,label:`Delay`,unit:`ms`,min:.1,max:5,step:.1,default:3},{kind:`number`,key:`decay`,label:`Decay`,unit:``,min:0,max:.99,step:.01,default:.4},{kind:`number`,key:`speed`,automatable:!0,label:`Rate`,unit:`Hz`,min:.1,max:2,step:.01,default:.5},{kind:`enum`,key:`type`,label:`Waveform`,options:[{value:`0`,label:`Triangular`},{value:`1`,label:`Sinusoidal`}],default:`0`}],web:`allpass-phaser`},{id:`reverb`,label:`Reverb`,group:`time`,description:`Room tail. Both ends convolve the same generated impulse, so preview matches render.`,params:[{kind:`number`,key:`size`,label:`Room size`,unit:``,min:.05,max:1,step:.01,default:.7},{kind:`number`,key:`damping`,label:`Damping`,unit:``,min:0,max:1,step:.01,default:.5,hint:`Higher rolls the top off the tail faster.`},{kind:`number`,key:`wet`,automatable:!0,label:`Wet`,unit:``,min:0,max:1,step:.01,default:.35},{kind:`number`,key:`dry`,automatable:!0,label:`Dry`,unit:``,min:0,max:1,step:.01,default:.7}],web:`convolver`}],f=new Map(d.map(e=>[e.id,e]));function p(e){return f.get(e)}d.map(e=>e.id);function m(e,t){let n=f.get(e);if(!n)return{};let r={};for(let e of n.params){let n=t?.[e.key];if(e.kind===`enum`){let t=e.options.some(e=>e.value===n);r[e.key]=t?n:e.default;continue}let i=typeof n==`number`?n:typeof n==`string`&&n.trim()!==``?Number(n):NaN;r[e.key]=Number.isFinite(i)?Math.min(e.max,Math.max(e.min,i)):e.default}return r}var h=class extends Error{constructor(e){super(e),this.name=`AudioFxChainError`}};function g(e){let t;try{t=JSON.parse(e)}catch(e){throw new h(`Chain file is not valid JSON: ${e.message}`)}if(typeof t!=`object`||!t)throw new h(`Chain file must be a JSON object.`);let n=t;if(n.version!==o)throw new h(`Unsupported chain version: ${String(n.version)}`);if(!Array.isArray(n.nodes))throw new h("Chain file is missing a `nodes` array.");return{version:o,nodes:n.nodes.map(v)}}function _(e){return e.nodes.filter(e=>e.enabled!==!1)}function v(e,t){if(typeof e!=`object`||!e)throw new h(`Node ${t} is not an object.`);let n=e;if(typeof n.type!=`string`||!f.has(n.type))throw new h(`Node ${t} has unknown effect type: ${String(n.type)}`);return S({type:n.type,id:y(n.id),fromCarve:b(n.fromCarve),fromPreset:y(n.fromPreset),label:y(n.label),fromEq:y(n.fromEq),fromLeveller:b(n.fromLeveller),presetAmount:x(n.presetAmount),enabled:n.enabled!==!1,params:m(n.type,n.params??void 0)})}function y(e){return typeof e==`string`&&e?e:void 0}function b(e){return e===!0||void 0}function x(e){if(typeof e==`number`&&Number.isFinite(e))return Math.min(1,Math.max(0,e))}function S(e){for(let t of Object.keys(e))e[t]===void 0&&delete e[t];return e}function ee(e){return 10**(e/20)}var C=ee(12);function w(e){return Number.isFinite(e)?Math.max(0,Math.min(C,e)):1}function T(e,t){return w(e*t)}var E=`data-automation`;E.slice(5);var D=1,te=512,O=class extends Error{constructor(e){super(e),this.name=`AudioAutomationError`}},k=`volume`,ne=`rate`;function A(e){if(e===k)return{kind:`volume`};if(e===ne)return{kind:`rate`};let t=e.split(`.`);if(t.length===3&&t[0]===`fx`&&t[1]===re){let e=t[2];return e?{kind:`preset`,presetId:e}:null}if(t.length!==3||t[0]!==`fx`)return null;let[,n,r]=t;return!n||!r?null:{kind:`fx`,nodeId:n,param:r}}var re=`preset`,ie={min:0,max:1,step:.01,unit:``,label:`Amount`,scale:`linear`,default:1},ae={min:0,max:C,step:.01,unit:``,label:`Volume`,scale:`linear`,default:1};function oe(e){return Math.min(4096,Math.max(2,Math.ceil(e*30)))}function se(e){return!!e.curve||e.viaX!==void 0&&e.viaY!==void 0}function j(e,t,n=!1){let r=w(t),i=T(r,e);return n&&r>0?i/r:i}function ce(e,t,n=!1){let r=[],i=e.points,a=w(t);for(let o=0;o<i.length;o+=1){let s=i[o],c=i[o+1];if(!(c!==void 0&&(a*s.v-C)*(a*c.v-C)<0))r.push({...s,v:j(s.v,t,n)});else if(r.push({t:s.t,v:j(s.v,t,n)}),se(s)){let i=oe(c.t-s.t);for(let a=1;a<i;a+=1){let o=s.t+(c.t-s.t)*a/i;r.push({t:o,v:j(N(e,o),t,n)})}}else{let e=s.t+(C/a-s.v)/(c.v-s.v)*(c.t-s.t);r.push({t:e,v:j(C/a,a,n)})}}return r}var le={min:t,max:10,step:.05,unit:`x`,label:`Speed`,scale:`log`,default:1};function ue(e,t){let n=A(e);if(!n)return null;if(n.kind===`volume`)return ae;if(n.kind===`rate`)return le;if(n.kind===`preset`)return t?.nodes.some(e=>e.fromPreset===n.presetId)?{...ie,label:`${n.presetId} \xB7 Amount`}:null;let r=t?.nodes.find(e=>e.id===n.nodeId);if(!r)return null;let i=p(r.type),a=i?.params.find(e=>e.key===n.param);return!a||a.kind!==`number`?null:{min:a.min,max:a.max,step:a.step,unit:a.unit,label:`${i?.label??r.type} \xB7 ${a.label}`,scale:a.scale===`log`&&a.min>0?`log`:`linear`,default:a.default}}function M(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`&&e.trim()!==``){let t=Number(e);return Number.isFinite(t)?t:null}return null}function de(e){let t=M(e);return t===null||t===0?0:Math.min(1,Math.max(-1,t))}function fe(e,t){let n=M(e),r=M(t);if(n===null||r===null)return null;let i=e=>Math.min(.999,Math.max(.001,e)),a=i(n),o=i(r);return Math.abs(a-o)<1e-6?null:{x:a,y:o}}function pe(e){let t=de(e?.curve),n=fe(e?.viaX,e?.viaY);return{...t?{curve:t}:{},...n?{viaX:n.x,viaY:n.y}:{}}}function me(e,t){let n=M(e?.t),r=M(e?.v);if(n===null||r===null)return null;let i=t?Math.min(t.max,Math.max(t.min,r)):r;return{t:Math.max(0,n),v:i,...pe(e)}}function he(e,t){let n=e.map(e=>me(e,t)).filter(e=>e!==null).sort((e,t)=>e.t-t.t),r=[];for(let e of n)r.length>0&&r[r.length-1].t===e.t?r[r.length-1]=e:r.push(e);return r.slice(0,te)}function ge(e){let t=[];for(let n of e.lanes){if(!A(n.target))continue;let e=n.target===k?ae:n.target===ne?le:null,r=he(n.points??[],e);r.length>0&&t.push({target:n.target,points:r})}return{version:D,lanes:t}}function _e(e,t){let n=[];for(let r of e.lanes){let e=ue(r.target,t);if(!e)continue;let i=he(r.points,e);i.length>0&&n.push({target:r.target,points:i})}return{version:D,lanes:n}}function ve(e){let t;try{t=JSON.parse(e)}catch(e){throw new O(`Automation is not valid JSON: ${e.message}`)}if(typeof t!=`object`||!t)throw new O(`Automation must be a JSON object.`);let n=t;if(n.version!==D)throw new O(`Unsupported automation version: ${String(n.version)}`);if(!Array.isArray(n.lanes))throw new O("Automation is missing a `lanes` array.");return ge({version:D,lanes:n.lanes.map((e,t)=>{if(typeof e!=`object`||!e)throw new O(`Lane ${t} is not an object.`);let n=e;if(typeof n.target!=`string`||!A(n.target))throw new O(`Lane ${t} has an unreadable target: ${String(n.target)}`);if(!Array.isArray(n.points))throw new O(`Lane ${t} is missing a \`points\` array.`);return{target:n.target,points:n.points}})})}function ye(e,t){return t?e**2**(2*t):e}function be(e,t){let n=e-.5,r=t-.5,i=.999,a=n>0?n/(i-e):n<0?-n/(e-.0010000000000000009):0,o=r>0?r/(i-t):r<0?-r/(t-.0010000000000000009):0,s=Math.min(1e6,Math.max(1,a,o));return{cx:e+n/s,cy:t+r/s,w:s}}function xe(e,t,n){let{cx:r,cy:i,w:a}=be(t,n),o=2-2*a,s=Se(e*o-1+2*a*r,-e*o-2*a*r,e),c=1-s,l=c*c+2*a*s*c+s*s;return l>0?(2*a*i*s*c+s*s)/l:e}function Se(e,t,n){if(Math.abs(e)<1e-12)return Math.abs(t)<1e-12?n:-n/t;let r=Math.sqrt(Math.max(0,t*t-4*e*n)),i=(-t+r)/(2*e),a=(-t-r)/(2*e),o=e=>e>=-1e-9&&e<=1+1e-9;return o(i)?Math.min(1,Math.max(0,i)):o(a)?Math.min(1,Math.max(0,a)):n}function Ce(e,t){let n=fe(t.viaX,t.viaY);return n?xe(Math.min(1,Math.max(0,e)),n.x,n.y):ye(e,t.curve)}function we(e,t,n,r){return r===`log`&&e>0&&t>0?Math.exp(Math.log(e)+(Math.log(t)-Math.log(e))*n):e+(t-e)*n}function N(e,t,n=`linear`){let r=e.points;if(r.length===0)return 0;let i=r[0];if(t<=i.t)return i.v;let a=r[r.length-1];if(t>=a.t)return a.v;let o=0,s=r.length-1;for(;s-o>1;){let e=o+s>>1;r[e].t<=t?o=e:s=e}let c=r[o],l=r[s],u=l.t-c.t;return u<=0?l.v:we(c.v,l.v,Ce((t-c.t)/u,c),n)}function Te(e){return e.points.length<=1||e.points.every(t=>t.v===e.points[0].v)}function Ee(e,t,n,r,i=`linear`){let a=Math.max(2,Math.floor(r)),o=new Float32Array(a),s=n-t;for(let n=0;n<a;n+=1)o[n]=N(e,t+s*n/(a-1),i);return o}var De=100,Oe=8,ke=4096,Ae=e=>e;function je(e,t,n){return!se(e)&&t===`linear`&&!n}function Me(e){let t=Math.ceil(e*De);return Math.min(ke,Math.max(Oe,t))}function Ne(e,t,n,r,i){let{scheduledAt:a,elapsed:o,rate:s}=r,c=i??Ae,l=e=>a+(e-o)/s,u=e.points[t],d=e.points[t+1],f=l(d.t),p=Math.max(a,l(u.t));if(f<=p)return[];let m=Math.max(u.t,o),h=je(u,n,i)?[N(e,m,n),d.v]:Ee(e,m,d.t,Me(f-p),n),g=h.length-1;return Array.from(h,(e,t)=>({kind:t===0?`set`:`ramp`,time:t===g?f:p+(f-p)*t/g,value:c(e)}))}function Pe(e,t,n,r){let i=[];for(let a=0;a+1<e.points.length;a+=1)i.push(...Ne(e,a,t,n,r));let a=i[0];return(!a||a.time>n.scheduledAt)&&i.unshift({kind:`set`,time:n.scheduledAt,value:(r??Ae)(N(e,n.elapsed,t))}),i}function Fe(e,t){for(let n of t)n.kind===`set`?e.setValueAtTime(n.value,n.time):e.linearRampToValueAtTime(n.value,n.time)}function P(e){for(let t of e)t.param.cancelScheduledValues(0)}function F(e){for(let t of e){let e=t.param.value;P([t]),t.param.value=e}}function Ie(e,t,n,r){if(t.points.length!==0)for(let i of e)if(P([i]),Te(t)){let e=(i.map??Ae)(t.points[0].v);i.param.setValueAtTime(e,r.scheduledAt)}else Fe(i.param,Pe(t,n,r,i.map))}function Le(e,t,n,r,i){let a=new Map(n.filter(e=>e.id).map(e=>[e.id,e.handle])),o=[];for(let n of e.lanes){let e=A(n.target);if(!e)continue;let s=e.kind===`preset`?i?.[e.presetId]:e.kind===`fx`?a.get(e.nodeId)?.automation?.[e.param]:void 0;if(!s||s.length===0)continue;let c=ue(n.target,t);c&&(Ie(s,n,c.scale,r),o.push(...s))}return o}function Re(e){return e.lanes.find(e=>e.target===k)??null}var ze=`
|
|
2
|
+
const dbToLin = (db) => Math.pow(10, db / 20);
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One-pole envelope followers, one per channel.
|
|
6
|
+
*
|
|
7
|
+
* Per channel matters: the followers advance once per sample, so a single shared
|
|
8
|
+
* follower stepped once per channel per sample. On stereo that ran a 20 ms attack
|
|
9
|
+
* as 10 ms, and gave the right channel a gain computed from an envelope that had
|
|
10
|
+
* already traversed the left, so the two channels ducked by different amounts
|
|
11
|
+
* from the same input and the image pumped.
|
|
12
|
+
*/
|
|
13
|
+
class EnvBank {
|
|
14
|
+
constructor(attackMs, releaseMs) { this.set(attackMs, releaseMs); this.values = []; }
|
|
15
|
+
set(attackMs, releaseMs) {
|
|
16
|
+
this.a = Math.exp(-1 / (sampleRate * Math.max(1e-5, attackMs / 1000)));
|
|
17
|
+
this.r = Math.exp(-1 / (sampleRate * Math.max(1e-5, releaseMs / 1000)));
|
|
18
|
+
}
|
|
19
|
+
push(ch, x) {
|
|
20
|
+
const prev = this.values[ch] ?? 0;
|
|
21
|
+
const m = Math.abs(x);
|
|
22
|
+
const c = m > prev ? this.a : this.r;
|
|
23
|
+
const next = m + c * (prev - m);
|
|
24
|
+
this.values[ch] = next;
|
|
25
|
+
return next;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Soft-knee gain computer in dB, matching acompressor's shape. */
|
|
30
|
+
function kneeGain(envDb, thresholdDb, ratio, kneeDb) {
|
|
31
|
+
const over = envDb - thresholdDb;
|
|
32
|
+
if (kneeDb > 0 && over > -kneeDb && over < kneeDb) {
|
|
33
|
+
const t = (over + kneeDb) / (2 * kneeDb);
|
|
34
|
+
return -((1 - 1 / ratio) * kneeDb * t * t);
|
|
35
|
+
}
|
|
36
|
+
return over > 0 ? -(over * (1 - 1 / ratio)) : 0;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// log10/exp per sample is the single most expensive thing a dynamics processor
|
|
40
|
+
// can do on the audio thread, and every sample below the knee needs neither:
|
|
41
|
+
// its gain is exactly unity. Comparing envelopes in the linear domain lets the
|
|
42
|
+
// quiet majority of samples skip the transcendentals entirely.
|
|
43
|
+
const LN10_OVER_20 = Math.LN10 / 20;
|
|
44
|
+
const dbToLinFast = (db) => Math.exp(db * LN10_OVER_20);
|
|
45
|
+
|
|
46
|
+
class HfCompressor extends AudioWorkletProcessor {
|
|
47
|
+
constructor(o) {
|
|
48
|
+
super();
|
|
49
|
+
this.p = o.processorOptions || {};
|
|
50
|
+
this.env = new EnvBank(this.p.attack ?? 20, this.p.release ?? 250);
|
|
51
|
+
this.port.onmessage = (e) => {
|
|
52
|
+
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
|
53
|
+
this.p = { ...this.p, ...e.data };
|
|
54
|
+
this.env.set(this.p.attack ?? 20, this.p.release ?? 250);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
process(inputs, outputs) {
|
|
58
|
+
if (this.dead) return false;
|
|
59
|
+
const i = inputs[0], o = outputs[0];
|
|
60
|
+
if (!i || !i.length) return true;
|
|
61
|
+
const p = this.p;
|
|
62
|
+
const makeup = dbToLin(p.makeup ?? 0);
|
|
63
|
+
const mix = p.mix ?? 1;
|
|
64
|
+
// Knee is expressed as a ratio in FFmpeg; convert to dB width.
|
|
65
|
+
const kneeDb = 20 * Math.log10(Math.max(1.0001, p.knee ?? 2.83));
|
|
66
|
+
const thresholdDb = p.threshold ?? -24;
|
|
67
|
+
const ratio = p.ratio ?? 4;
|
|
68
|
+
// Below this the gain computer returns unity, so the sample needs no
|
|
69
|
+
// logarithm at all.
|
|
70
|
+
const kneeStartLin = dbToLin(thresholdDb - kneeDb);
|
|
71
|
+
const dry = 1 - mix;
|
|
72
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
73
|
+
const inp = i[ch], out = o[ch];
|
|
74
|
+
for (let n = 0; n < inp.length; n++) {
|
|
75
|
+
const x = inp[n];
|
|
76
|
+
// Per-channel follower, and the sub-knee shortcut: below the knee the
|
|
77
|
+
// gain is exactly unity, so the sample needs no logarithm at all.
|
|
78
|
+
const env = this.env.push(ch, x);
|
|
79
|
+
if (env <= kneeStartLin) {
|
|
80
|
+
out[n] = x * makeup * mix + x * dry;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
const envDb = 20 * Math.log10(env);
|
|
84
|
+
const g = dbToLinFast(kneeGain(envDb, thresholdDb, ratio, kneeDb));
|
|
85
|
+
out[n] = x * g * makeup * mix + x * dry;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
registerProcessor("hf-compressor", HfCompressor);
|
|
92
|
+
|
|
93
|
+
class HfLimiter extends AudioWorkletProcessor {
|
|
94
|
+
constructor(o) {
|
|
95
|
+
super();
|
|
96
|
+
this.p = o.processorOptions || {};
|
|
97
|
+
this.env = new EnvBank(this.p.attack ?? 5, this.p.release ?? 50);
|
|
98
|
+
this.port.onmessage = (e) => {
|
|
99
|
+
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
|
100
|
+
this.p = { ...this.p, ...e.data };
|
|
101
|
+
this.env.set(this.p.attack ?? 5, this.p.release ?? 50);
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
process(inputs, outputs) {
|
|
105
|
+
if (this.dead) return false;
|
|
106
|
+
const i = inputs[0], o = outputs[0];
|
|
107
|
+
if (!i || !i.length) return true;
|
|
108
|
+
const ceiling = dbToLin(this.p.limit ?? -1);
|
|
109
|
+
const outGain = dbToLin(this.p.level_out ?? 0);
|
|
110
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
111
|
+
const inp = i[ch], out = o[ch];
|
|
112
|
+
for (let n = 0; n < inp.length; n++) {
|
|
113
|
+
const x = inp[n];
|
|
114
|
+
const env = this.env.push(ch, x);
|
|
115
|
+
// Only ever attenuate: a limiter that can raise level is a compressor.
|
|
116
|
+
const g = env > ceiling ? ceiling / env : 1;
|
|
117
|
+
out[n] = x * g * outGain;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
registerProcessor("hf-limiter", HfLimiter);
|
|
124
|
+
|
|
125
|
+
class HfGate extends AudioWorkletProcessor {
|
|
126
|
+
constructor(o) {
|
|
127
|
+
super();
|
|
128
|
+
this.p = o.processorOptions || {};
|
|
129
|
+
this.env = new EnvBank(this.p.attack ?? 1, this.p.release ?? 100);
|
|
130
|
+
this.gains = [];
|
|
131
|
+
this.port.onmessage = (e) => {
|
|
132
|
+
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
|
133
|
+
this.p = { ...this.p, ...e.data };
|
|
134
|
+
this.env.set(this.p.attack ?? 1, this.p.release ?? 100);
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
process(inputs, outputs) {
|
|
138
|
+
if (this.dead) return false;
|
|
139
|
+
const i = inputs[0], o = outputs[0];
|
|
140
|
+
if (!i || !i.length) return true;
|
|
141
|
+
const p = this.p;
|
|
142
|
+
const threshold = dbToLin(p.threshold ?? -35);
|
|
143
|
+
const floor = dbToLin(p.range ?? -24);
|
|
144
|
+
const ratio = p.ratio ?? 10;
|
|
145
|
+
// Knee is declared in the registry as a ratio, like the compressor's; a
|
|
146
|
+
// hard threshold ignored it and chattered on material sitting right at the
|
|
147
|
+
// gate point.
|
|
148
|
+
const kneeDb = 20 * Math.log10(Math.max(1.0001, p.knee ?? 2.83));
|
|
149
|
+
const kneeLin = dbToLin((p.threshold ?? -35) + kneeDb);
|
|
150
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
151
|
+
const inp = i[ch], out = o[ch];
|
|
152
|
+
for (let n = 0; n < inp.length; n++) {
|
|
153
|
+
const x = inp[n];
|
|
154
|
+
const env = this.env.push(ch, x);
|
|
155
|
+
let target = 1;
|
|
156
|
+
// Above the threshold the gate is fully open; skip the pow entirely.
|
|
157
|
+
if (env < threshold) {
|
|
158
|
+
const under = env > 1e-9 ? threshold / env : 1e9;
|
|
159
|
+
target = Math.max(floor, 1 / Math.pow(under, ratio - 1));
|
|
160
|
+
if (!isFinite(target)) target = floor;
|
|
161
|
+
}
|
|
162
|
+
// Smooth toward the target so the gate does not click on every sample.
|
|
163
|
+
const held = this.gains[ch] ?? 1;
|
|
164
|
+
const c = target < held ? this.env.r : this.env.a;
|
|
165
|
+
const smoothed = target + c * (held - target);
|
|
166
|
+
this.gains[ch] = smoothed;
|
|
167
|
+
out[n] = x * smoothed;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
registerProcessor("hf-gate", HfGate);
|
|
174
|
+
|
|
175
|
+
class HfBitcrush extends AudioWorkletProcessor {
|
|
176
|
+
constructor(o) {
|
|
177
|
+
super();
|
|
178
|
+
this.p = o.processorOptions || {};
|
|
179
|
+
this.holds = [];
|
|
180
|
+
this.held = [];
|
|
181
|
+
this.start = Math.round((this.p.__hfElapsed ?? 0) * sampleRate);
|
|
182
|
+
this.port.onmessage = (e) => {
|
|
183
|
+
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
|
184
|
+
this.p = { ...this.p, ...e.data };
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
process(inputs, outputs) {
|
|
188
|
+
if (this.dead) return false;
|
|
189
|
+
const i = inputs[0], o = outputs[0];
|
|
190
|
+
if (!i || !i.length) return true;
|
|
191
|
+
const p = this.p;
|
|
192
|
+
const levels = Math.pow(2, (p.bits ?? 8) - 1);
|
|
193
|
+
const step = Math.max(1, Math.round(p.samples ?? 1));
|
|
194
|
+
const mix = p.mix ?? 1;
|
|
195
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
196
|
+
const inp = i[ch], out = o[ch];
|
|
197
|
+
// Primed from the input: a counter seeded mid-hold would otherwise play 0 until it wraps.
|
|
198
|
+
if (this.held[ch] === undefined) this.held[ch] = Math.round(inp[0] * levels) / levels;
|
|
199
|
+
// The hold counter runs from the file's first sample, so a node built part-way in starts where it would be.
|
|
200
|
+
if (this.holds[ch] === undefined) this.holds[ch] = this.start % step;
|
|
201
|
+
for (let n = 0; n < inp.length; n++) {
|
|
202
|
+
// Per channel: advancing one shared counter only on the last channel
|
|
203
|
+
// left every earlier channel either unheld or frozen for a whole
|
|
204
|
+
// 128-sample quantum, clicking once a block.
|
|
205
|
+
if (this.holds[ch] === 0) this.held[ch] = Math.round(inp[n] * levels) / levels;
|
|
206
|
+
out[n] = this.held[ch] * mix + inp[n] * (1 - mix);
|
|
207
|
+
this.holds[ch] = (this.holds[ch] + 1) % step;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
registerProcessor("hf-bitcrush", HfBitcrush);
|
|
214
|
+
|
|
215
|
+
/** Linear-interpolated read, \`delaySamples\` behind the write head. */
|
|
216
|
+
function readTap(ring, write, delaySamples) {
|
|
217
|
+
const len = ring.length;
|
|
218
|
+
const pos = (write - 1 - delaySamples + len) % len;
|
|
219
|
+
const i0 = Math.floor(pos);
|
|
220
|
+
const frac = pos - i0;
|
|
221
|
+
const i1 = (i0 + 1) % len;
|
|
222
|
+
return ring[i0] * (1 - frac) + ring[i1] * frac;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Equal-power-ish crossfade, zero at a tap's reset point, which hides the splice. */
|
|
226
|
+
function xfade(phase) {
|
|
227
|
+
return Math.sin(Math.PI * phase);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Dual-tap granular delay line: two read taps 180° apart in a 100 ms grain,
|
|
232
|
+
* each sweeping at a speed relative to the write head that shifts pitch
|
|
233
|
+
* without changing duration. One tap is always fading in as the other fades
|
|
234
|
+
* out, which hides the splice each tap makes when it wraps.
|
|
235
|
+
*
|
|
236
|
+
* write/phase are block-level state, advanced once per SAMPLE across all
|
|
237
|
+
* channels together (not once per channel). Advancing them inside the
|
|
238
|
+
* per-channel loop would move the tap 2x/4x too fast on a stereo/quad input.
|
|
239
|
+
*/
|
|
240
|
+
class HfPitchshift extends AudioWorkletProcessor {
|
|
241
|
+
constructor(o) {
|
|
242
|
+
super();
|
|
243
|
+
this.p = o.processorOptions || {};
|
|
244
|
+
this.grain = Math.round(sampleRate * 0.1);
|
|
245
|
+
this.buf = [];
|
|
246
|
+
this.write = 0;
|
|
247
|
+
// The taps sweep at a constant rate from the start of the file, so a node built
|
|
248
|
+
// part-way in joins the sweep where it would already be.
|
|
249
|
+
const ratio0 = Math.pow(2, Math.max(-12, Math.min(12, this.p.semitones ?? 0)) / 12);
|
|
250
|
+
const turns = (this.p.__hfElapsed ?? 0) * sampleRate * ((1 - ratio0) / this.grain);
|
|
251
|
+
this.phase = turns - Math.floor(turns);
|
|
252
|
+
// Samples written so far, capped at one grain. The taps read up to a grain
|
|
253
|
+
// behind the write head, so until this fills they would read the ring's
|
|
254
|
+
// zeros, so the head of every clip came out attenuated or silent.
|
|
255
|
+
this.filled = 0;
|
|
256
|
+
// How much of the wet (pitch-shifted) path is currently in the output, and
|
|
257
|
+
// where it is heading. Crossing between dry and wet is a ~50 ms jump in the
|
|
258
|
+
// signal, so it is RAMPED rather than switched: a hard swap either way is a
|
|
259
|
+
// click. Ramping in both directions is also what lets a node return to true
|
|
260
|
+
// bypass at semitones 0. A one-way latch left preview stuck with the delay
|
|
261
|
+
// that the render, building a fresh node from the attribute, does not have.
|
|
262
|
+
this.wet = 0;
|
|
263
|
+
this.wetTarget = 0;
|
|
264
|
+
// ~15 ms one-pole, short enough to feel immediate on a slider drag and long
|
|
265
|
+
// enough that the splice is inaudible.
|
|
266
|
+
this.wetCoef = Math.exp(-1 / (sampleRate * 0.015));
|
|
267
|
+
this.port.onmessage = (e) => {
|
|
268
|
+
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
|
269
|
+
this.p = { ...this.p, ...e.data };
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
process(inputs, outputs) {
|
|
273
|
+
if (this.dead) return false;
|
|
274
|
+
const i = inputs[0], o = outputs[0];
|
|
275
|
+
if (!i || !i.length) return true;
|
|
276
|
+
const p = this.p;
|
|
277
|
+
const semitones = Math.max(-12, Math.min(12, p.semitones ?? 0));
|
|
278
|
+
const mix = Math.max(0, Math.min(1, p.mix ?? 1));
|
|
279
|
+
const grain = this.grain;
|
|
280
|
+
const ringLen = grain * 2;
|
|
281
|
+
const n = i[0] ? i[0].length : 0;
|
|
282
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
283
|
+
if (!this.buf[ch]) this.buf[ch] = new Float32Array(ringLen);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Nothing to shift, or mixed fully out. The grain delay is ~grain/2
|
|
287
|
+
// whatever the ratio, so at semitones=0 this degenerated into a pure 50 ms
|
|
288
|
+
// delay of the signal, while the copy for that exact setting reads
|
|
289
|
+
// "Unchanged pitch".
|
|
290
|
+
this.wetTarget = semitones === 0 ? 0 : mix;
|
|
291
|
+
|
|
292
|
+
// Fully dry AND settled: take the cheap transparent path. The ring keeps
|
|
293
|
+
// filling, so a later shift does not start cold.
|
|
294
|
+
if (this.wetTarget === 0 && this.wet < 1e-4) {
|
|
295
|
+
this.wet = 0;
|
|
296
|
+
let w = this.write;
|
|
297
|
+
for (let s = 0; s < n; s++) {
|
|
298
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
299
|
+
const x = i[ch][s];
|
|
300
|
+
this.buf[ch][w] = x;
|
|
301
|
+
o[ch][s] = x;
|
|
302
|
+
}
|
|
303
|
+
w = (w + 1) % ringLen;
|
|
304
|
+
}
|
|
305
|
+
this.write = w;
|
|
306
|
+
this.filled = Math.min(grain, this.filled + n);
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const ratio = Math.pow(2, semitones / 12);
|
|
311
|
+
const inc = (1 - ratio) / grain;
|
|
312
|
+
let write = this.write, phase = this.phase, filled = this.filled, wetNow = this.wet;
|
|
313
|
+
const target = this.wetTarget, coef = this.wetCoef;
|
|
314
|
+
for (let s = 0; s < n; s++) {
|
|
315
|
+
phase += inc;
|
|
316
|
+
phase -= Math.floor(phase);
|
|
317
|
+
const phaseB = (phase + 0.5) % 1;
|
|
318
|
+
const gA = xfade(phase), gB = xfade(phaseB);
|
|
319
|
+
// Ramp the wet path in as the ring fills rather than reading zeros:
|
|
320
|
+
// 100 ms of unshifted audio at the head of a clip beats 50 ms of silence.
|
|
321
|
+
const warm = filled >= grain ? 1 : filled / grain;
|
|
322
|
+
wetNow = target + coef * (wetNow - target);
|
|
323
|
+
const wetMix = wetNow * warm;
|
|
324
|
+
for (let ch = 0; ch < i.length; ch++) {
|
|
325
|
+
const ring = this.buf[ch];
|
|
326
|
+
const inp = i[ch], out = o[ch];
|
|
327
|
+
const x = inp[s];
|
|
328
|
+
ring[write] = x;
|
|
329
|
+
const wet =
|
|
330
|
+
readTap(ring, write, phase * grain) * gA + readTap(ring, write, phaseB * grain) * gB;
|
|
331
|
+
out[s] = x * (1 - wetMix) + wet * wetMix;
|
|
332
|
+
}
|
|
333
|
+
write = (write + 1) % ringLen;
|
|
334
|
+
if (filled < grain) filled++;
|
|
335
|
+
}
|
|
336
|
+
this.write = write;
|
|
337
|
+
this.phase = phase;
|
|
338
|
+
this.filled = filled;
|
|
339
|
+
this.wet = wetNow;
|
|
340
|
+
return true;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
registerProcessor("hf-pitchshift", HfPitchshift);
|
|
344
|
+
|
|
345
|
+
const TP_OS = 4;
|
|
346
|
+
const TP_HALF = 64;
|
|
347
|
+
const TP_BRANCH = 33;
|
|
348
|
+
const TP_DELAY = 16;
|
|
349
|
+
|
|
350
|
+
function besselI0(x) {
|
|
351
|
+
let sum = 1, term = 1;
|
|
352
|
+
for (let k = 1; k < 40; k++) {
|
|
353
|
+
term *= (x / (2 * k)) * (x / (2 * k));
|
|
354
|
+
sum += term;
|
|
355
|
+
}
|
|
356
|
+
return sum;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Kaiser-windowed sinc, one array per polyphase branch, newest tap first. */
|
|
360
|
+
function tpBranches() {
|
|
361
|
+
const beta = 6;
|
|
362
|
+
const norm = besselI0(beta);
|
|
363
|
+
const branches = [];
|
|
364
|
+
for (let p = 0; p < TP_OS; p++) {
|
|
365
|
+
const taps = new Float64Array(TP_BRANCH);
|
|
366
|
+
let sum = 0;
|
|
367
|
+
for (let j = 0; j < TP_BRANCH; j++) {
|
|
368
|
+
const k = p + TP_OS * j;
|
|
369
|
+
if (k > 2 * TP_HALF) continue;
|
|
370
|
+
const t = (k - TP_HALF) / TP_OS;
|
|
371
|
+
const sinc = t === 0 ? 1 : Math.sin(Math.PI * t) / (Math.PI * t);
|
|
372
|
+
const r = (k - TP_HALF) / TP_HALF;
|
|
373
|
+
taps[j] = sinc * (besselI0(beta * Math.sqrt(Math.max(0, 1 - r * r))) / norm);
|
|
374
|
+
sum += taps[j];
|
|
375
|
+
}
|
|
376
|
+
// Unity gain at DC on every branch, so a steady level reads as itself.
|
|
377
|
+
for (let j = 0; j < TP_BRANCH; j++) taps[j] /= sum;
|
|
378
|
+
branches.push(taps);
|
|
379
|
+
}
|
|
380
|
+
return branches;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
class HfTruePeak extends AudioWorkletProcessor {
|
|
384
|
+
constructor(o) {
|
|
385
|
+
super();
|
|
386
|
+
this.p = o.processorOptions || {};
|
|
387
|
+
this.look = Math.max(1, Math.round((this.p.lookahead ?? 3) * sampleRate / 1000));
|
|
388
|
+
this.delayLen = this.look + TP_DELAY;
|
|
389
|
+
this.branches = tpBranches();
|
|
390
|
+
this.setLevels();
|
|
391
|
+
this.clear();
|
|
392
|
+
this.port.onmessage = (e) => {
|
|
393
|
+
if (e.data && e.data.__hfDispose) { this.dead = true; return; }
|
|
394
|
+
if (e.data && e.data.__hfReset) { this.clear(); return; }
|
|
395
|
+
this.p = { ...this.p, ...e.data };
|
|
396
|
+
this.setLevels();
|
|
397
|
+
};
|
|
398
|
+
}
|
|
399
|
+
/** Back to the state of a fresh processor: no audio in the delay line, no gain reduction. */
|
|
400
|
+
clear() {
|
|
401
|
+
this.ch = [];
|
|
402
|
+
this.rel = 1;
|
|
403
|
+
this.dqIdx = new Int32Array(this.look + 2);
|
|
404
|
+
this.dqVal = new Float64Array(this.look + 2);
|
|
405
|
+
this.dqHead = 0;
|
|
406
|
+
this.dqTail = 0;
|
|
407
|
+
this.t = 0;
|
|
408
|
+
this.avgRing = new Float64Array(this.look + 1).fill(1);
|
|
409
|
+
this.avgPos = 0;
|
|
410
|
+
this.avgSum = this.look + 1;
|
|
411
|
+
}
|
|
412
|
+
setLevels() {
|
|
413
|
+
this.ceiling = Math.pow(10, (this.p.ceiling ?? -1) / 20);
|
|
414
|
+
this.relCoef = 1 - Math.exp(-1 / (sampleRate * Math.max(1e-4, (this.p.release ?? 80) / 1000)));
|
|
415
|
+
}
|
|
416
|
+
channel(c) {
|
|
417
|
+
if (!this.ch[c]) {
|
|
418
|
+
this.ch[c] = {
|
|
419
|
+
delay: new Float32Array(this.delayLen),
|
|
420
|
+
w: 0,
|
|
421
|
+
hist: new Float32Array(TP_BRANCH * 2),
|
|
422
|
+
pos: 0,
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
return this.ch[c];
|
|
426
|
+
}
|
|
427
|
+
/** Largest interpolated magnitude across channels for the newest sample. */
|
|
428
|
+
peak(chans, inputs, n) {
|
|
429
|
+
let peak = 0;
|
|
430
|
+
for (let c = 0; c < chans; c++) {
|
|
431
|
+
const s = this.channel(c);
|
|
432
|
+
const x = inputs[c][n];
|
|
433
|
+
s.pos = (s.pos + 1) % TP_BRANCH;
|
|
434
|
+
s.hist[s.pos] = x;
|
|
435
|
+
s.hist[s.pos + TP_BRANCH] = x;
|
|
436
|
+
const base = s.pos + TP_BRANCH;
|
|
437
|
+
for (let p = 0; p < TP_OS; p++) {
|
|
438
|
+
const taps = this.branches[p];
|
|
439
|
+
let acc = 0;
|
|
440
|
+
for (let j = 0; j < TP_BRANCH; j++) acc += taps[j] * s.hist[base - j];
|
|
441
|
+
const a = acc < 0 ? -acc : acc;
|
|
442
|
+
if (a > peak) peak = a;
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
return peak;
|
|
446
|
+
}
|
|
447
|
+
/** Windowed minimum of the required gain over the last look + 1 values. */
|
|
448
|
+
windowMin(v) {
|
|
449
|
+
const cap = this.dqIdx.length;
|
|
450
|
+
while (this.dqTail !== this.dqHead && this.dqVal[(this.dqTail + cap - 1) % cap] >= v) {
|
|
451
|
+
this.dqTail = (this.dqTail + cap - 1) % cap;
|
|
452
|
+
}
|
|
453
|
+
this.dqIdx[this.dqTail] = this.t;
|
|
454
|
+
this.dqVal[this.dqTail] = v;
|
|
455
|
+
this.dqTail = (this.dqTail + 1) % cap;
|
|
456
|
+
while (this.dqIdx[this.dqHead] <= this.t - (this.look + 1)) {
|
|
457
|
+
this.dqHead = (this.dqHead + 1) % cap;
|
|
458
|
+
}
|
|
459
|
+
this.t++;
|
|
460
|
+
return this.dqVal[this.dqHead];
|
|
461
|
+
}
|
|
462
|
+
process(inputs, outputs) {
|
|
463
|
+
if (this.dead) return false;
|
|
464
|
+
const i = inputs[0], o = outputs[0];
|
|
465
|
+
if (!i || !i.length) return true;
|
|
466
|
+
const chans = i.length;
|
|
467
|
+
const frames = i[0].length;
|
|
468
|
+
for (let n = 0; n < frames; n++) {
|
|
469
|
+
const peak = this.peak(chans, i, n);
|
|
470
|
+
const need = peak > this.ceiling ? this.ceiling / peak : 1;
|
|
471
|
+
const m = this.windowMin(need);
|
|
472
|
+
this.avgSum += m - this.avgRing[this.avgPos];
|
|
473
|
+
this.avgRing[this.avgPos] = m;
|
|
474
|
+
this.avgPos = (this.avgPos + 1) % this.avgRing.length;
|
|
475
|
+
const target = Math.min(1, this.avgSum / this.avgRing.length);
|
|
476
|
+
const released = this.rel + (1 - this.rel) * this.relCoef;
|
|
477
|
+
this.rel = released < target ? released : target;
|
|
478
|
+
if (target >= 1 && this.rel > 0.9999999) this.rel = 1;
|
|
479
|
+
for (let c = 0; c < chans; c++) {
|
|
480
|
+
const s = this.channel(c);
|
|
481
|
+
o[c][n] = s.delay[s.w] * this.rel;
|
|
482
|
+
s.delay[s.w] = i[c][n];
|
|
483
|
+
s.w = (s.w + 1) % this.delayLen;
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
return true;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
registerProcessor("hf-truepeak", HfTruePeak);
|
|
490
|
+
`,Be=new WeakMap;function Ve(e){return He.has(e)}var He=new WeakSet;function Ue(e){let t=Be.get(e);return t||(t=(async()=>{if(!e.audioWorklet)throw Error(`AudioWorklet is unavailable: the page needs a secure context (https, localhost or file://)`);let t=`data:text/javascript;base64,${btoa(String.fromCharCode(...new TextEncoder().encode(ze)))}`;await e.audioWorklet.addModule(t),He.add(e)})().catch(t=>{throw Be.delete(e),t}),Be.set(e,t)),t}function We(e,t,n){let r=.6+Math.max(0,Math.min(1,t))*2.6,i=Math.max(1,Math.floor(e*r)),a=new Float32Array(i),o=Math.round(t*1e3)*0x9e3779b1+Math.round(n*1e3)*40503>>>0,s=()=>(o=o*1664525+0x3c6ef35f>>>0,o/0xffffffff*2-1),c=Math.max(.001,1-Math.max(0,Math.min(1,n))),l=0,u=0;for(let e=0;e<i;e++){l+=c*(s()-l);let t=l*(1-e/i)**2.5;a[e]=t,u+=t*t}let d=Math.sqrt(u);if(d>0)for(let e=0;e<i;e++)a[e]=(a[e]??0)/d;return a}var I=e=>typeof e==`number`?e:Number(e??0),Ge=e=>e/1e3;function Ke(e,t,n,r){let i=Math.max(1,Math.round(e.sampleRate)),a=e.createBuffer(1,i,e.sampleRate),o=a.getChannelData(0);for(let e=0;e<i;e++){let n=e/i;o[e]=t===`sine`?Math.sin(2*Math.PI*n):4*Math.abs((n+.75)%1-.5)-1}let s=e.createBufferSource();s.buffer=a,s.loop=!0,s.playbackRate.value=n;let c=(r*n%1+1)%1*(i/e.sampleRate);return s.start(typeof e.currentTime==`number`?e.currentTime:0,c),s}function qe(e){try{e.stop()}catch{}e.disconnect()}function Je(e,t){return[{param:e},{param:t,map:e=>1-e}]}function Ye(e,t,n){e.gain.value=n,t.gain.value=1-n}function Xe(e,t,n){return{input:e,output:e,update:t,automation:n,dispose:()=>e.disconnect()}}var Ze=new Set([`peaking`,`highpass`,`lowpass`]),Qe=e=>10**(e/20),$e=(e,t)=>{let n=e.createGain(),r=e=>{n.gain.value=Qe(I(e.gain))};return r(t),Xe(n,r,{gain:[{param:n.gain,map:Qe}]})};function L(e,t){return(n,r)=>{let i=n.createBiquadFilter();i.type=e;let a=e=>{i.frequency.value=I(e.frequency),e.q!==void 0&&(i.Q.value=I(e.q)),t&&(i.gain.value=I(e.gain))};return a(r),Xe(i,a,{frequency:[{param:i.frequency}],...Ze.has(e)?{q:[{param:i.Q}]}:{},...t?{gain:[{param:i.gain}]}:{}})}}function et(e){return(t,n)=>{let r=Math.tan(Math.PI*I(n.frequency)/t.sampleRate);return Xe(e===`highpass`?t.createIIRFilter([1/(1+r),-1/(1+r)],[1,(r-1)/(r+1)]):t.createIIRFilter([r/(1+r),r/(1+r)],[1,(r-1)/(r+1)]),()=>{})}}function R(e,t=!1){return(n,r,i)=>{let a=new AudioWorkletNode(n,e,{processorOptions:{...r,__hfElapsed:i}});return{input:a,output:a,update:e=>a.port.postMessage({...e}),...t?{reset:()=>a.port.postMessage({__hfReset:!0})}:{},dispose:()=>{a.port.postMessage({__hfDispose:!0}),a.disconnect()}}}}var tt={tanh:Math.tanh,atan:e=>2/Math.PI*Math.atan(Math.PI/2*e),cubic:e=>Math.abs(e)>=1?Math.sign(e):e-e**3/3,exp:e=>Math.sign(e)*(1-Math.exp(-Math.abs(e))),alg:e=>e/Math.sqrt(1+e*e),quintic:e=>Math.abs(e)>=1?Math.sign(e):e-e**5/5,sin:e=>Math.abs(e)>=1?Math.sign(e):Math.sin(Math.PI/2*e),erf:e=>Math.tanh(1.20211*e),hard:e=>Math.max(-1,Math.min(1,e))},nt=(e,t)=>{let n=e.createWaveShaper(),r=e.createGain(),i=e.createGain();r.connect(n).connect(i);let a=e=>{let t=tt[String(e.type)]??Math.tanh,r=10**(I(e.threshold)/20),a=8192,o=new Float32Array(a);for(let e=0;e<a;e++){let n=e/8191*2-1;o[e]=t(n/Math.max(1e-6,r))*r}n.curve=o,n.oversample=I(e.oversample)>=4?`4x`:I(e.oversample)>=2?`2x`:`none`,i.gain.value=10**(I(e.output)/20)};return a(t),{input:r,output:i,update:a,automation:{output:[{param:i.gain,map:e=>10**(e/20)}]},dispose:()=>{r.disconnect(),n.disconnect(),i.disconnect()}}},rt=(e,t)=>{let n=e.createGain(),r=e.createGain(),i=e.createDelay(5),a=e.createGain(),o=e.createGain(),s=e.createGain();n.connect(i),i.connect(a),a.connect(i),i.connect(o).connect(r),n.connect(s).connect(r);let c=e=>{i.delayTime.value=Math.min(5,I(e.time)/1e3),a.gain.value=I(e.feedback),Ye(o,s,I(e.mix))};return c(t),{input:n,output:r,update:c,automation:{time:[{param:i.delayTime,map:e=>Math.min(5,Ge(e))}],feedback:[{param:a.gain}],mix:Je(o.gain,s.gain)},dispose:()=>[n,r,i,a,o,s].forEach(e=>e.disconnect())}},it=(e,t,n)=>{let r=e.createGain(),i=e.createGain(),a=e.createDelay(.5),o=Ke(e,`sine`,I(t.speed),n),s=e.createGain(),c=e.createGain(),l=e.createGain();o.connect(s).connect(a.delayTime),r.connect(a).connect(c).connect(i),r.connect(l).connect(i);let u=e=>{a.delayTime.value=I(e.delay)/1e3,s.gain.value=I(e.depth)/1e3,o.playbackRate.value=I(e.speed),Ye(c,l,I(e.mix))};return u(t),{input:r,output:i,update:u,automation:{delay:[{param:a.delayTime,map:Ge}],depth:[{param:s.gain,map:Ge}],speed:[{param:o.playbackRate}],mix:Je(c.gain,l.gain)},dispose:()=>{qe(o),[r,i,a,s,c,l].forEach(e=>e.disconnect())}}},at=6,ot={"gain-node":$e,"biquad-peaking":L(`peaking`,!0),"biquad-lowshelf":L(`lowshelf`,!0),"biquad-highshelf":L(`highshelf`,!0),"biquad-highpass":L(`highpass`,!1),"biquad-lowpass":L(`lowpass`,!1),"worklet-compressor":R(`hf-compressor`),"worklet-limiter":R(`hf-limiter`),"worklet-truepeak":R(`hf-truepeak`,!0),"worklet-gate":R(`hf-gate`),"worklet-bitcrush":R(`hf-bitcrush`),"worklet-pitchshift":R(`hf-pitchshift`),waveshaper:nt,"delay-feedback":rt,"chorus-lfo":it,"allpass-phaser":(e,t,n)=>{let r=e.createGain(),i=e.createGain(),a=e.createGain(),o=e.createGain(),s=Ke(e,String(t.type)===`1`?`sine`:`triangle`,I(t.speed),n),c=e.createGain(),l=e.createGain(),u=e.createGain(),d=[];r.connect(a);let f=a;for(let t=0;t<at;t++){let t=e.createBiquadFilter();t.type=`allpass`,t.Q.value=.7071,c.connect(t.frequency),f.connect(t),f=t,d.push(t)}s.connect(c),f.connect(l).connect(o),a.connect(u).connect(o),o.connect(i);let p=e=>{let t=1e3/Math.max(.1,I(e.delay));for(let e of d)e.frequency.value=t;c.gain.value=t*I(e.decay),s.playbackRate.value=I(e.speed),a.gain.value=I(e.in_gain),o.gain.value=I(e.out_gain),l.gain.value=1,u.gain.value=1};return p(t),{input:r,output:i,update:p,automation:{speed:[{param:s.playbackRate}],in_gain:[{param:a.gain}],out_gain:[{param:o.gain}]},dispose:()=>{qe(s),[r,i,a,o,c,l,u,...d].forEach(e=>e.disconnect())}}},convolver:(e,t)=>{let n=e.createGain(),r=e.createGain(),i=e.createConvolver(),a=e.createGain(),o=e.createGain();i.normalize=!1,n.connect(i).connect(a).connect(r),n.connect(o).connect(r);let s=``,c=t=>{let n=`${I(t.size)}:${I(t.damping)}`;if(n!==s){let r=We(e.sampleRate,I(t.size),I(t.damping)),a=e.createBuffer(1,r.length,e.sampleRate);a.getChannelData(0).set(r),i.buffer=a,s=n}a.gain.value=I(t.wet),o.gain.value=I(t.dry)};return c(t),{input:n,output:r,update:c,automation:{wet:[{param:a.gain}],dry:[{param:o.gain}]},dispose:()=>[n,r,i,a,o].forEach(e=>e.disconnect())}}};function st(e){return e.nodes.some(e=>p(e.type)?.web.startsWith(`worklet-`)??!1)}function ct(e,t,n,r=0){let i=p(t);if(!i)throw Error(`Unknown effect type: ${t}`);let a=m(t,n);if((t===`highpass`||t===`lowpass`)&&String(a.poles)===`1`)return et(t)(e,a,r);let o=ot[i.web];if(!o)throw Error(`No Web Audio builder for ${i.web}`);return o(e,a,r)}function lt(e){let t=[];for(let n of e){let e=n.fromPreset,r=t.at(-1);if(r&&r.preset===e)r.nodes.push(n);else{let r=typeof n.presetAmount==`number`?n.presetAmount:1;t.push({...e?{preset:e}:{},amount:Math.min(1,Math.max(0,r)),nodes:[n]})}}return t}function ut(e){return _(e).map(e=>{let t=m(e.type,e.params),n=t.poles===void 0?``:`:${t.poles}`,r=String(t.poles)===`1`?`@${t.frequency}`:``,i=e.type===`phaser`?`~${t.type}`:``,a=e.fromPreset?`%${e.fromPreset}`:``,o=e.type===`truepeak`?`^${t.lookahead}`:``;return`${e.type}${n}${r}${i}${o}${a}`}).join(`|`)}function dt(e,t,n=0){let r=e.createGain(),i=e.createGain(),a=[],o=[],s=lt(_(t)),c=r;for(let t of s){let r=null;if(t.preset){let n=e.createGain(),i=e.createGain(),a=e.createGain(),o=e.createGain();a.gain.value=t.amount,i.gain.value=1-t.amount,c.connect(n),n.connect(i).connect(o),r={entry:n,wet:a,dry:i,join:o},c=n}for(let r of t.nodes){let t=ct(e,r.type,r.params??{},n);c.connect(t.input),c=t.output,a.push({...r.id?{id:r.id}:{},type:r.type,handle:t})}r&&t.preset&&(c.connect(r.wet).connect(r.join),o.push({id:t.preset,...r}),c=r.join)}c.connect(i);let l=ut(t),u={};for(let e of o)(u[e.id]??=[]).push(...Je(e.wet.gain,e.dry.gain));return{input:r,output:i,presets:u,nodes:a,update(e){if(ut(e)!==l)return!1;_(e).forEach((e,t)=>{let n=a[t];n&&(n.handle.update(m(e.type,e.params)),e.id===void 0?delete n.id:n.id=e.id)});let t=0;for(let n of lt(_(e))){if(!n.preset)continue;let e=o[t++];!e||e.id!==n.preset||(e.wet.gain.value=n.amount,e.dry.gain.value=1-n.amount)}return!0},reset(){for(let{handle:e}of a)e.reset?.()},dispose(){for(let{handle:e}of a)e.dispose();for(let{entry:e,wet:t,dry:n,join:r}of o)e.disconnect(),t.disconnect(),n.disconnect(),r.disconnect();r.disconnect(),i.disconnect()}}}var ft={version:1,nodes:[]},pt={version:1,lanes:[]};function mt(e,t,n=E){let r=(n&&typeof e.getAttribute==`function`?e.getAttribute(n):null)??``;if(!r)return pt;try{return _e(ve(r),t)}catch{return pt}}function z(e){let t=(typeof e.getAttribute==`function`?e.getAttribute(a):null)??``;if(!t)return{chain:ft,raw:``};try{return{chain:g(t),raw:t}}catch{return{chain:ft,raw:``}}}function ht(e){return mt(e,z(e).chain)}function gt(e,t,n){let r=Re(t);if(!r)return[];let i=ce(r,e.gain?.()??1,e.gainAhead);return Ie([{param:e.param}],{...r,points:i},ae.scale,n),[{param:e.param}]}function _t(e,t){P([e]),e.param.setValueAtTime(e.gainAhead?1:w(e.gain?.()??1),t.scheduledAt)}function vt(e,t,n,r,i,o={automation:E},s){let{chain:c}=z(t),l=null,u=[],d=!1,f=0,p=()=>{try{l?(n.disconnect(l.input),l.output.disconnect(r),l.dispose()):n.disconnect(r)}catch{}l=null},m=(i,a)=>{if(i.nodes.length===0)n.connect(r);else if(st(i)&&!Ve(e)){n.connect(r);let i=++f;Ue(e).then(()=>{d||i!==f||y(z(t).chain)}).catch(()=>{})}else try{let t=dt(e,i,a);n.connect(t.input),t.output.connect(r),l=t}catch{n.connect(r)}},h=(e,n)=>{if(!n){u=[];return}let r=mt(t,e,o.automation),i=l?Le(r,e,l.nodes,n,l.presets):[],a=s?gt(s,r,n):[];s&&a.length===0&&u.some(e=>e.param===s.param)&&_t(s,n),u=[...i,...a]},g=i?{...i}:null;m(c,g?.elapsed??0),h(c,g);let _=()=>{if(!g)return null;let t=typeof e.currentTime==`number`?e.currentTime:g.scheduledAt;return{scheduledAt:t,elapsed:g.elapsed+(t-g.scheduledAt)*g.rate,rate:g.rate}},v=e=>{let t=_();t&&(F(u),h(e,t))},y=e=>{let t=_();F(u),p(),m(e,t?.elapsed??0),h(e,t)},b=null,x=t;typeof MutationObserver<`u`&&typeof x?.nodeType==`number`&&(b=new MutationObserver(()=>{let e=z(t);u.length>0&&P(u),!l||!l.update(e.chain)?y(e.chain):v(e.chain)}),b.observe(x,{attributes:!0,attributeFilter:[a,...o.automation?[o.automation]:[],...s?.gain?[`data-volume`]:[]]}));let S=e=>{d||(_()&&F(u),g={...e},h(z(t).chain,g))};return{reanchor:e=>{d||(l?.reset(),S(e))},retime:S,setRate:e=>{let n=_();d||!n||!Number.isFinite(e)||e<=0||e===n.rate||(g={...n,rate:e},F(u),h(z(t).chain,g))},dispose:()=>{d=!0,b?.disconnect(),u.length>0&&F(u),l?.dispose()}}}function yt(e){if(e.tagName.toLowerCase()!==`video`||e.hasAttribute(`muted`))return!1;let t=e.getAttribute(`data-has-audio`);return t===null||t===`true`}var bt=`data-hf-render-id`,xt=`hf-audio-group`,St=`data-audio-group`;function B(e){let t=e?.getAttribute(`data-volume`),n=t?parseFloat(t):1;return Number.isFinite(n)?n:1}function Ct(e,t){let n=Array.from(e?.querySelectorAll?.(`${xt}[${bt}]`)??[]).find(e=>e.getAttribute(bt)===t);if(n)return n;let r=e?.getElementById(t)??null;return r&&r.tagName?.toLowerCase()===xt?r:null}function wt(e){let t=e.querySelector(`[data-composition-id]`);return t&&!t.parentElement?.closest(`[data-composition-id]`)?t:null}function Tt(e){return typeof e.tagName!=`string`||typeof e.getAttribute!=`function`||!Et(e)?null:e.getAttribute(St)||null}function Et(e){return e.tagName.toLowerCase()===`audio`||typeof e.hasAttribute==`function`&&yt(e)}function Dt(){return globalThis}function V(e,t){if(typeof window>`u`)return;let n=Dt(),r=n.__hf?.onSwallowed;if(r)try{r({label:e,error:t})}catch{}(n.__hfDebug||n.__HYPERFRAMES_DEBUG)&&console.debug(`[hyperframes] ${e} swallowed:`,t)}var Ot=`http://www.w3.org/1999/xhtml`;function kt(e){return e!=null&&e.nodeType===1}function At(e){return kt(e)&&e.namespaceURI===Ot}function jt(e,t){return At(e)&&e.localName===t}function Mt(e){return jt(e,`video`)}function Nt(e){return jt(e,`audio`)}function Pt(e){return Mt(e)||Nt(e)}function Ft(e){return jt(e,`img`)}function It(e){return kt(e)&&(e.namespaceURI===Ot||e.namespaceURI===`http://www.w3.org/2000/svg`)}function Lt(e){return e+1e-5}function Rt(){let{userAgent:e}=navigator;return/AppleWebKit/.test(e)&&!/Chrom(e|ium)\/|Edg\/|Android/.test(e)}var zt=`hyperframes-studio-preview`,Bt=`hyperframes-preview-for-another-site`;function Vt(e){return e.querySelector(`meta[name="${Bt}"]`)!==null}var Ht=`data-hf-upcoming`,Ut=`data-hf-autostamped`,H=`data-hf-clip-hidden`,Wt=`runtime_media_load_failed`,Gt=[`seconds-time`,`rational-fps`,`seek-keep-playing`,`composition-manifest-v1`,`runtime-data`,`play-range`,`announce-timeline`];function Kt(e,t){let n=Math.abs(e),r=Math.abs(t);for(;r!==0;){let e=n%r;n=r,r=e}return n||1}function qt(e){let t=Number.isFinite(e)&&e>0?e:30,n=Math.abs(t*1001-Math.round(t*1001))<1e-6,r=Number.isInteger(t)?1:n?1001:1e6,i=Math.round(t*r),a=Kt(i,r);return{numerator:i/a,denominator:r/a}}function Jt(e){if(typeof e!=`object`||!e)return null;let t=e;return!Number.isFinite(t.numerator)||!Number.isFinite(t.denominator)||(t.numerator??0)<=0||(t.denominator??0)<=0?null:Number(t.numerator)/Number(t.denominator)}function Yt(e){return{protocolVersion:1,capabilities:Gt,fps:qt(e)}}var Xt=1e3;function Zt(e,t=Xt){if(e.length>t)return{reason:`length`,length:e.length};for(let t=0;t<e.length;t++)if(!(t in e))return{reason:`hole`,length:e.length};return null}function Qt(e,t=Xt){return Array.isArray(e)&&Zt(e,t)===null}var $t=30,en=new Set([`ready`,`state`,`stage-size`]),tn=!1,nn=()=>tn||=typeof document<`u`&&Vt(document),rn=crypto.randomUUID?.()??String(performance.timeOrigin);function an(e){if(!nn()||en.has(e.type))try{let t=Yt($t);window.parent.postMessage({...e,...t,documentId:rn},`*`)}catch(e){V(`bridge.postMessage`,e)}}var on=800,sn=5e3,cn=100,ln=1e3,un=8192;function U(e){return typeof e==`number`&&Number.isFinite(e)}function W(e,t){return e==null?t:U(e)?e:null}function G(e){return typeof e==`string`&&e.length<=ln}function K(e){return e==null||G(e)}function dn(e){if(e===null||G(e))return!0;if(typeof e!=`object`||Array.isArray(e))return!1;let t=e;return K(t.id)&&K(t.hfId)&&K(t.selector)&&(t.selectorIndex==null||U(t.selectorIndex))}function fn(e){if(e===null)return!0;if(typeof e!=`object`||Array.isArray(e))return!1;let t=e;return G(t.id)&&K(t.hfId)&&K(t.domId)&&K(t.sourceFile)}function pn(e,t){let n=e.target??null;if(fn(n)){if(e.time===null)return t.onScrubAudio?.(n,null,0);!U(e.time)||!U(e.volume)||t.onScrubAudio?.(n,Math.max(0,e.time),Math.max(0,Math.min(1,e.volume)))}}function mn(e,t,n){let r=e??null;dn(r)&&n(r,t??null)}new Map(Object.entries({play:(e,t)=>{if(e.playSeq==null)return t.onPlay();!U(e.playSeq)||!Number.isInteger(e.playSeq)||e.playSeq<1||t.onPlay(e.playSeq)},pause:(e,t)=>t.onPause(),"stop-media":(e,t)=>t.onStopMedia(),seek:(e,t)=>{let n=hn(e,t);n!==null&&t.onSeek(n,e.seekMode===`drag`?`drag`:`commit`)},tick:(e,t)=>t.onTick(),"set-muted":(e,t)=>t.onSetMuted(e.muted===!0),"set-volume":(e,t)=>{let n=W(e.volume,1);n!==null&&t.onSetVolume(Math.max(0,Math.min(1,n)))},"set-media-output-muted":(e,t)=>t.onSetMediaOutputMuted(e.muted===!0),"set-native-media-sync-disabled":(e,t)=>t.onSetNativeMediaSyncDisabled(e.disabled===!0),"set-web-audio-media-disabled":(e,t)=>t.onSetWebAudioMediaDisabled(e.disabled===!0),"set-parent-audio":(e,t)=>{let n=e.clips;Qt(n)&&n.every(e=>typeof e==`string`&&e.length<=un)&&t.onSetParentAudio?.(n)},"audio-clock":(e,t)=>{if(e.time===null)return t.onAudioClock?.(null);let{time:n,rate:r,at:i}=e;!U(n)||!U(r)||!U(i)||r<=0||t.onAudioClock?.({time:Math.max(0,n),rate:r,at:i})},"set-playback-rate":(e,t)=>{let n=W(e.playbackRate,1);n!==null&&t.onSetPlaybackRate(n)},"set-idle-heartbeat":(e,t)=>t.onSetIdleHeartbeat(e.slow===!0),"set-display-scale":(e,t)=>{U(e.scale)&&e.scale>0&&t.onSetDisplayScale?.(e.scale)},"set-preview-quality":(e,t)=>{U(e.level)&&t.onSetPreviewQuality?.(e.level)},"set-copies-ahead":(e,t)=>t.onSetCopiesAhead?.(e.on===!0),"retry-preview-copies":(e,t)=>t.onRetryPreviewCopies?.(),"request-preview-facts":(e,t)=>t.onRequestPreviewFacts?.(),"announce-timeline":(e,t)=>t.onAnnounceTimeline?.(),"set-root-duration":(e,t)=>{let n=W(e.durationSeconds,0);n!==null&&t.onSetRootDuration(n)},"set-play-range":(e,t)=>{let n=W(e.startSeconds,0),r=e.endSeconds??null;n===null||r!==null&&!U(r)||t.onSetPlayRange(n,r)},"set-color-grading":(e,t)=>mn(e.target,e.grading,t.onSetColorGrading),"set-color-grading-compare":(e,t)=>mn(e.target,e.compare,t.onSetColorGradingCompare),"enable-pick-mode":(e,t)=>t.onEnablePickMode(),"disable-pick-mode":(e,t)=>t.onDisablePickMode(),"flash-elements":e=>_n(e),"scrub-audio":pn,"set-runtime-data":(e,t)=>{typeof e.channel==`string`&&t.onSetRuntimeData?.(e.channel,e.payload,e.requestId)},"clear-runtime-data":(e,t)=>{typeof e.channel==`string`&&t.onClearRuntimeData?.(e.channel,e.requestId)}}));function hn(e,t){if(e.timeSeconds!=null)return U(e.timeSeconds)?Math.max(0,e.timeSeconds):null;let n=W(e.frame,0);if(n===null)return null;let r=Jt(e.fps)??t.getCanonicalFps();return Math.max(0,n)/r}function gn(e){return!Array.isArray(e)||e.length>cn?null:e.every(G)?e:null}function _n(e){let t=e,n=gn(t.selectors),r=W(t.duration,on);!n||r===null||r<=0||r>sn||yn(n,r)}var vn=`
|
|
491
|
+
.__hf-flash {
|
|
492
|
+
outline: 2px solid rgba(59, 130, 246, 0.6) !important;
|
|
493
|
+
outline-offset: 2px !important;
|
|
494
|
+
animation: __hf-flash-pulse var(--hf-flash-duration, 800ms) ease-out forwards !important;
|
|
495
|
+
}
|
|
496
|
+
@keyframes __hf-flash-pulse {
|
|
497
|
+
0% { outline-color: rgba(59, 130, 246, 0.8); }
|
|
498
|
+
100% { outline-color: transparent; }
|
|
499
|
+
}
|
|
500
|
+
`;function yn(e,t){if(!document.getElementById(`__hf-flash-styles`)){let e=document.createElement(`style`);e.id=`__hf-flash-styles`,e.textContent=vn,document.head.appendChild(e)}for(let n of e)try{document.querySelectorAll(n).forEach(e=>{It(e)&&e.style.setProperty(`--hf-flash-duration`,`${t}ms`),e.classList.add(`__hf-flash`),r(()=>e.classList.remove(`__hf-flash`),t)})}catch(e){V(`bridge.flashElements.querySelector`,e)}}var bn=new WeakMap,xn=new WeakMap;function Sn(e){let t=xn.get(e);return t!==void 0&&t.written===e.getAttribute(`src`)}function Cn(e){return bn.has(e)?bn.get(e)??null:Sn(e)?xn.get(e).authored:e.getAttribute(`src`)}var wn=new WeakMap;function Tn(e){if(Number.isFinite(e.duration))return e.duration;let t=wn.get(e);return t!==void 0&&t.src===e.src?t.seconds:NaN}var q=new Map,En=64;function Dn(e,t=k){let n=`${t}\0${e}`,r=q.get(n);if(r!==void 0)return r;let i=null;try{i=ve(e).lanes.find(e=>e.target===t)??null}catch{i=null}return q.size>En&&q.clear(),q.set(n,i),i}var On=48,kn=new WeakMap;function An(e){let t=e.points,n=t[0].v,r=t[t.length-1].v,i=[0],a=[0],o=t=>{let n=i[i.length-1];if(t<=n)return;let r=N(e,n,`log`);i.push(t),a.push(a[a.length-1]+(r+N(e,t,`log`))/2*(t-n))};o(Math.max(0,t[0].t));for(let e=1;e<t.length;e+=1){let n=t[e-1].t,r=t[e].t;if(!(r<=0))for(let e=1;e<=On;e+=1)o(Math.max(n,0)+(r-n)*e/On)}return{ts:Float64Array.from(i),ss:Float64Array.from(a),firstRate:n,lastRate:r}}function jn(e){let t=kn.get(e);return t||(t=An(e),kn.set(e,t)),t}function Mn(e){return typeof e!=`number`&&e.points.length>0}function Nn(e,t){return typeof e==`number`?e:Mn(e)?N(e,t,`log`):1}function Pn(e,t,n){let r=0,i=e.length-1;for(;i-r>1;){let t=r+i>>1;e[t]<=n?r=t:i=t}return t[r]+(t[i]-t[r])*(n-e[r])/(e[i]-e[r])}function Fn(e,t){if(typeof e==`number`)return t*e;if(!Mn(e))return t;let{ts:n,ss:r,firstRate:i,lastRate:a}=jn(e),o=n.length-1;return t<=0?t*i:t>=n[o]?r[o]+(t-n[o])*a:Pn(n,r,t)}function In(e,t){if(typeof e==`number`)return t/e;if(!Mn(e))return t;let{ts:n,ss:r,firstRate:i,lastRate:a}=jn(e),o=n.length-1;return t<=0?t/i:t>=r[o]?n[o]+(t-r[o])/a:Pn(r,n,t)}function Ln(e){return e?Dn(e,ne):null}function Rn(e,t){return Ln(e)??t}function J(t){return e(e=>t.getAttribute(e),Pt(t)?t.defaultPlaybackRate:1)}function zn(e){return Rn(e.getAttribute(`data-automation`),J(e))}var Bn=`data-fade-in`,Vn=`data-fade-out`;Bn.slice(5),Vn.slice(5),Object.freeze({fadeIn:0,fadeOut:0});function Hn(e){return Number.isFinite(e)&&e>0?e:0}function Un(e){return e==null||e===``?0:Hn(Number.parseFloat(e))}function Wn(e){return{fadeIn:Un(e.getAttribute(Bn)),fadeOut:Un(e.getAttribute(Vn))}}function Gn(e,t){let n=Hn(e.fadeIn),r=Hn(e.fadeOut);if(!Number.isFinite(t)||t<=0)return{fadeIn:n,fadeOut:r};let i=n+r;if(i<=t)return{fadeIn:n,fadeOut:r};let a=t/i;return{fadeIn:n*a,fadeOut:r*a}}function Kn(e,t,n){if(!Number.isFinite(e))return 1;let{fadeIn:r,fadeOut:i}=Gn(n,t),a=1;return r>0&&(a*=qn(e/r)),i>0&&Number.isFinite(t)&&(a*=qn((t-e)/i)),a}function qn(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}function Jn(e){return e.getAttribute(bt)||e.id||null}var Yn=`__render_frame_`,Xn=`__`;function Zn(e){return`${Yn}${e}${Xn}`}function Qn(e){let t=Jn(e);return t?Zn(t):null}function $n(e){let t=Qn(e),n=t?document.getElementById(t):null;if(!n)return null;let r=e.nextElementSibling;for(;r&&r.id!==t;)r=r.nextElementSibling;return r??=n,Ft(r)?r:null}var Y={hueDegrees:{min:0,max:360,inclusiveMax:!1},unit:{min:0,max:1},signedUnit:{min:-1,max:1},secondaryHueRange:{min:0,max:180},secondaryHueSoftness:{min:0,max:180},secondaryHueCombinedMax:180,secondarySoftRangeSoftness:{min:0,max:.5},secondaryHueShift:{min:-180,max:180},effects:{asciiStyle:{min:0,max:7},bloom:{min:0,max:3},bloomRadius:{min:1,max:100},monoScreenShape:{min:0,max:4}}};Y.unit,Y.signedUnit,Y.effects;var er={exposure:0,contrast:0,highlights:0,shadows:0,whites:0,blacks:0,temperature:0,tint:0,vibrance:0,saturation:0},tr={vignette:0,vignetteMidpoint:.5,vignetteRoundness:0,vignetteFeather:.65,grain:0,grainSize:.25,grainRoughness:.5},nr={blur:0,pixelate:0,chromaBleed:0,tapeDamage:0,tapeTracking:0,tapeNoise:1,tapeSpeed:.5,filmArtifacts:0,halftone:0,halftoneSize:0,twoInkPrint:0,twoInkPrintSize:0,ascii:0,asciiSize:5/76,asciiInvert:0,asciiStyle:0,asciiColor:1,asciiRotation:0,dither:0,ditherSize:0,bloom:0,bloomRadius:8,monoScreen:0,monoScreenSize:0,monoScreenAngle:0,monoScreenSpread:0,monoScreenShape:0,monoScreenInvert:0,scanlines:0,scanlineCount:0,scanlineSoftness:0,chromaticAberration:0,chromaticAngle:0,crtCurvature:0,digitalGlitch:0,digitalGlitchColorSplit:0,digitalGlitchLineTear:0,digitalGlitchPixelate:0,digitalGlitchBlockAmount:0,digitalGlitchBlockDisplacement:0,digitalGlitchBlockOpacity:0,digitalGlitchSpeed:0,engraving:0,engravingSpacing:7/17,engravingMinThickness:.2,engravingMaxThickness:3.2/7,engravingAngle:.25,engravingContrast:7/15,engravingSharpness:.59,engravingWave:.2,engravingWaveFrequency:2/9,crosshatch:0,crosshatchSpacing:.28,crosshatchThickness:.25,crosshatchAngle:.25,crosshatchContrast:1/3,crosshatchEdges:.5,crosshatchLineWeight:0,crosshatchWave:.33,crosshatchWaveFrequency:2/9,kuwahara:0,kuwaharaRadius:1/7,kuwaharaSharpness:5/16,kuwaharaSaturation:.5},rr={exposure:.03,contrast:-.12,highlights:-.1,shadows:.16,whites:-.04,blacks:.08,temperature:.13,vibrance:-.08,saturation:-.08},ir={vignette:.18};function X(e,t,n={},r={},i={},a=1){return{id:e,label:t,intensity:a,adjust:{...er,...n},details:{...tr,...r},effects:{...nr,...i}}}var ar=[X(`neutral`,`Neutral`),X(`warm-daylight`,`Warm Daylight`,{exposure:.06,contrast:.07,highlights:-.06,shadows:.08,temperature:.18,saturation:.08}),X(`clean-studio`,`Clean Studio`,{contrast:.08,highlights:-.08,shadows:.06,temperature:-.08,tint:.03,saturation:.04}),X(`skin-soft`,`Skin Soft`,{exposure:.04,contrast:-.03,highlights:-.12,shadows:.12,temperature:.08,tint:.02,saturation:.04}),X(`food-pop`,`Food Pop`,{exposure:.06,contrast:.1,shadows:.06,temperature:.14,vibrance:.1,saturation:.18}),X(`night-lift`,`Night Lift`,{exposure:.08,contrast:.08,highlights:-.18,shadows:.2,blacks:-.08,saturation:.04},{vignette:.12}),X(`muted-editorial`,`Muted Editorial`,{exposure:-.02,contrast:.08,highlights:-.08,shadows:.06,blacks:-.05,temperature:-.03,saturation:-.12},{vignette:.1}),X(`vintage-wash`,`Vintage Wash`,rr,ir),X(`mono-clean`,`Mono Clean`,{contrast:.12,highlights:-.04,shadows:.04,blacks:-.08,saturation:-1}),X(`mono-fade`,`Mono Fade`,{contrast:-.04,highlights:-.06,shadows:.1,blacks:.12,saturation:-1},{vignette:.08}),X(`soft-boost`,`Soft Boost`,{exposure:.06,contrast:-.04,highlights:-.14,shadows:.16,vibrance:.08,saturation:.1}),X(`bright-pop`,`Bright Pop`,{exposure:.12,contrast:.12,whites:.08,blacks:-.04,vibrance:.08,saturation:.14}),X(`deep-contrast`,`Deep Contrast`,{exposure:-.03,contrast:.2,highlights:-.08,shadows:-.08,blacks:-.12,saturation:.06}),X(`creator-camcorder`,`Creator Camcorder`,{contrast:.08,highlights:-.05,shadows:.02,whites:.03,blacks:-.04,temperature:-.03,tint:-.015,vibrance:-.03,saturation:-.06},{vignette:.06,grain:.08,grainSize:.18,grainRoughness:.58},{chromaBleed:.55},.72),X(`vhs-playback`,`VHS Playback`,{contrast:-.04,saturation:-.08},{grain:.16,grainSize:.12,grainRoughness:.72},{tapeDamage:.82,tapeTracking:.85,tapeNoise:.3,tapeSpeed:.5,chromaBleed:.5,chromaticAberration:.18,scanlines:.35,scanlineCount:.17,scanlineSoftness:1,digitalGlitch:.32,digitalGlitchLineTear:.08,digitalGlitchSpeed:.5}),X(`home-movie-8mm`,`8mm Home Movie`,rr,{...ir,vignette:.28,vignetteMidpoint:.54,vignetteFeather:.72,grain:.34,grainSize:.18,grainRoughness:.72},{filmArtifacts:.62},.72),X(`editorial-halftone`,`Editorial Halftone`,{contrast:.04,saturation:.04},{},{halftone:.94,halftoneSize:.36}),X(`two-ink-print`,`Two-Ink Print`,{contrast:.08,highlights:-.06,shadows:.04},{},{twoInkPrint:1,twoInkPrintSize:.42})];new Map(ar.map(e=>[e.id,e])),Y.unit,Y.signedUnit,Y.secondaryHueShift,Y.signedUnit,Y.signedUnit,Y.unit,Y.unit,Y.signedUnit,Y.unit,Y.unit,Y.unit,Y.unit,Y.unit,Y.effects;var or=[`blur`,`pixelate`,`chromaBleed`,`tapeDamage`,`filmArtifacts`,`halftone`,`twoInkPrint`,`ascii`,`dither`,`bloom`,`monoScreen`,`scanlines`,`chromaticAberration`,`crtCurvature`,`digitalGlitch`,`engraving`,`crosshatch`,`kuwahara`],sr=ar.filter(e=>or.some(t=>e.effects[t]>1e-4));ar.filter(e=>!sr.includes(e)),`${Ht}${Ut}`,`${H}`,`${zt}`,`${H}${H}`,`${H}`;var cr=33554432,lr=new Map,ur=new Map;function dr(e){let t=Cn(e);if(!t)return!1;try{return(ur.get(new URL(t,document.baseURI).href)??0)>=cr}catch{return!1}}function fr(e){let t;try{t=new URL(e,document.baseURI).href}catch{return Promise.resolve(null)}let n=lr.get(t);if(n)return n;let r=(async()=>{let e=new AbortController;try{let n=await fetch(t,{headers:{Range:`bytes=0-0`},signal:e.signal}),r=/\/(\d+)$/.exec(n.headers.get(`content-range`)??``)?.[1]??(n.status===200?n.headers.get(`content-length`):null);return r===null?null:(ur.set(t,Number(r)),Number(r))}catch{return null}finally{e.abort()}})();return lr.set(t,r),r}var pr=String.raw`(?:[A-Za-z0-9_-]|[^\x00-\x7f]|\\[0-9a-f]{1,6} |\\[^0-9a-f\n\r\f])+`,mr=String.raw`"(?:[^"\\\n\r\f]|\\\\|\\"|\\a |\\d |\\c )+"`;RegExp(`^\\.(?!-?[0-9]|-$)${pr}$`),RegExp(`^\\[data-(?:composition-id|hf-group)=${mr}\\]$`),window.parent,new Promise(e=>e);function hr(e){return window.__HF_EXPORT_RENDER_SEEK_CONFIG?!0:Mt(e)&&!!$n(e)}var gr=new WeakMap;function _r(e){let t=e.currentSrc||e.getAttribute(`src`)||``;try{return/\.([a-z0-9]{1,5})$/i.exec(new URL(t,document.baseURI).pathname)?.[1]?.toLowerCase()??null}catch{return null}}function vr(e,t,n,r=null){if(hr(e))return;let i=gr.get(e)??new Set;if(i.has(t))return;i.add(t),gr.set(e,i);let a=Cn(e)??``;an({source:`hf-preview`,type:`diagnostic`,code:Wt,details:{asset:a,elementId:e.id||null,kind:e.tagName.toLowerCase(),stage:t,code:n,bytes:r,extension:_r(e)}}),console.info(`[hyperframes] ${Wt}: "${a}" failed at ${t}${n===null?``:` (${n})`}.`)}function yr(e,t){e.getFloatTimeDomainData(t);let n=0;for(let e=0;e<t.length;e++)n=Math.max(n,Math.abs(t[e]??0));return n}function br(e,t){let n=e.createGain();n.channelCount=2,n.channelCountMode=`explicit`;let r=e.createChannelSplitter(2),i=e.createAnalyser(),a=e.createAnalyser();i.fftSize=a.fftSize=2048,t.connect(n),n.connect(r),r.connect(i,0),r.connect(a,1);let o=new Float32Array(new ArrayBuffer(8192)),s=new Float32Array(new ArrayBuffer(8192));return{read:()=>({l:yr(i,o),r:yr(a,s)}),dispose:()=>{try{t.disconnect(n),n.disconnect(),r.disconnect()}catch{}}}}var xr=`runtime_web_audio_bypass`;function Sr(e,t){return typeof e.getAttribute==`function`?e.getAttribute(t):null}function Z(e,t){return Sr(e,t)!==null}function Cr(e){return Z(e,`crossorigin`)?!0:e.crossOrigin!=null}function wr(e){return typeof e.baseURI==`string`&&e.baseURI?e.baseURI:typeof document<`u`?document.baseURI:``}function Tr(e){let t=typeof e.currentSrc==`string`?e.currentSrc:``;if(t)return[t];let n=Sr(e,`src`);if(n)return[n];if(typeof e.querySelectorAll!=`function`)return[];let r=[];for(let t of Array.from(e.querySelectorAll(`source`))){let e=t.getAttribute(`src`);e&&r.push(e)}return r}function Er(e,t){let n;try{n=new URL(e,wr(t))}catch{return null}return n.protocol!==`http:`&&n.protocol!==`https:`?null:n}function Dr(){return typeof window.origin==`string`?window.origin:window.location.origin}function Or(e,t){if(typeof window>`u`)return null;let n=Er(e,t);if(!n)return null;let r=Dr(),i=r===`null`;return!i&&n.origin===r||Cr(t)?null:i?`opaque_document_origin`:`cross_origin_no_cors`}function kr(e){for(let t of Tr(e)){let n=Or(t,e);if(n)return{kind:`decode-only`,reason:n,asset:t}}return{kind:`web-audio`}}function Ar(e){let t=[];Z(e,a)&&t.push(`fx-chain`),Z(e,E)&&t.push(`automation`),Z(e,St)&&t.push(`audio-group`);let n=Number.parseFloat(Sr(e,`data-volume`)??``);return Number.isFinite(n)&&n>1&&t.push(`above-unity-gain`),t}function jr(){return typeof window<`u`&&!!window.__HF_EXPORT_RENDER_SEEK_CONFIG}var Mr=new WeakSet,Nr={cross_origin_no_cors:"cross-origin media without a `crossorigin` opt-in is silent through createMediaElementSource (Web Audio spec); using native playback instead",opaque_document_origin:"this document's security origin is opaque (a sandbox without `allow-same-origin`), so no media is same-origin with it and createMediaElementSource would be silent (Web Audio spec); using native playback instead"},Pr={cross_origin_no_cors:`proxy or download the asset to a same-origin URL to keep it.`,opaque_document_origin:"add `allow-same-origin` to the sandbox, or serve the asset with a `crossorigin` attribute and an `Access-Control-Allow-Origin` of `null` or `*`, to keep it."};function Fr(e,t){if(t.kind===`web-audio`||jr()||Mr.has(e))return;let n=Ar(e);Mr.add(e),an({source:`hf-preview`,type:`diagnostic`,code:xr,details:{asset:t.asset,reason:t.reason,lostProcessing:n,note:Nr[t.reason]}});let r=n.length>0?` Native playback cannot reproduce: ${n.join(`, `)}. Fix: ${Pr[t.reason]}`:``;console.info(`[hyperframes] ${xr}: "${t.asset}" (${t.reason}): Web Audio capture withheld; the track plays through native HTMLMediaElement output.${r}`)}function Ir(e){return new URL(e,document.baseURI).href}var Lr=768e3,Rr=1.5*1024**3,zr=e=>e*Lr,Br=class extends Error{constructor(e){super(`This clip is too long to decode here.`),this.seconds=e,this.name=`AudioTooLong`}seconds},Vr=1e4;function Hr(e){return typeof document>`u`?Promise.resolve(null):new Promise(t=>{let n=document.createElement(`audio`);n.preload=`metadata`;let a=r(()=>o(null),Vr),o=e=>{i(a),n.onloadedmetadata=n.onerror=null,n.removeAttribute(`src`),n.load(),t(e)};n.onloadedmetadata=()=>o(Number.isFinite(n.duration)?n.duration:null),n.onerror=()=>o(null),n.src=e,n.load()})}var Ur=Rr/Lr*1e3;async function Wr(e,t){let n=t!==void 0&&Number.isFinite(t)&&t>0?t:await Hr(e);if(n===null)return`unread`;if(zr(n)>Rr)throw new Br(n);return`read`}var Gr=e=>e<=Ur,Kr={automation:null};function qr(e){return!Number.isFinite(e)||e<=0?1:e}function Jr(e){return w(e)}function Yr(e,t){t||e.paused||!Dt().__hfDebug||console.debug(`[hyperframes] webAudioTransport claimed fallback-playing element:`,e.currentSrc||e.getAttribute(`src`)||``)}function Xr(e,t){let{elapsed:n,mediaStart:r,scheduledAt:i,globalRate:a,mediaRate:o,clipDuration:s,headCut:c}=t,l=Number.isFinite(s)&&s>0,u=Math.max(n,c,0),d=(s-u)*o;if(l&&d<=0)return!1;let f=u>n?i+(u-n)/a:0,p=u*o+r;return e.loop&&(p=e.loopStart+(p-e.loopStart)%(e.loopEnd-e.loopStart)),l?e.start(f,p,d):e.start(f,p),!0}function Zr(e,t,n,r,i){let a=Gn(Wn(t),i);if(a.fadeIn<=0&&a.fadeOut<=0||a.fadeOut>0&&!Number.isFinite(i))return null;let o=e.createGain(),s=o.gain,c=e=>Kn(e,i,a),l=e=>{let t=Math.max(r,e.elapsed),n=t=>e.scheduledAt+Math.max(0,t-e.elapsed)/e.rate;if(s.value=c(t),s.setValueAtTime(c(t),n(t)),a.fadeIn>t&&s.linearRampToValueAtTime(c(a.fadeIn),n(a.fadeIn)),a.fadeOut>0){let e=i-a.fadeOut;e>t&&e>a.fadeIn&&s.setValueAtTime(c(e),n(e)),s.linearRampToValueAtTime(0,n(i))}};return l(n),{node:o,rebook:e=>{s.cancelScheduledValues(0),l(e)}}}function Qr(e,t,n,r,i,a){let o=e.createGain();o.connect(r);let s=e.createGain(),c=Zr(e,t,i,a.from,a.clipDuration);return c&&n.connect(c.node),(c?.node??n).connect(s),{fx:vt(e,t,s,o,i,void 0,{param:o.gain,gain:()=>B(t),gainAhead:!0}),laneNode:o,clipGainNode:s,fades:c}}function Q(e){return e.sourceKind===`buffer`}var $=e=>{let t=e.currentSrc||e.getAttribute(`src`);if(!t)return null;try{let e=new URL(Ir(t));return e.hash=``,e.href}catch{return t}},$r=.015,ei=[`seeked`,`error`,`emptied`,`abort`],ti=[`playing`,`seeked`,`ratechange`],ni=1e4,ri=.25,ii=268435456,ai=2,oi=4,si=class{_fetchInit;_fetches=new AbortController;_busDocument;_givenContext;_ctx=null;_bufferCache=new Map;_decoding=new Map;_pendingDecodeBytes=new Map;_failedSrcs=new Set;_mediaElementSources=new WeakMap;_handedOver=new Set;_activeSources=[];_masterGain=null;_busOut=null;_master=null;_monitorGain=null;_masterVolume=1;_masterMuted=!1;_groups=new Map;_metering=!1;_masterTap=null;_groupTaps=new Map;_rateAnchorCtx=0;_rateAnchorComp=0;_rate=1;_paused=!0;_playGeneration=0;_playingCaptured=new Set;_suspendPending=!1;_restTimer=null;async init(){return this.open()}constructor(e={}){this._fetchInit=e.fetchInit??{},this._busDocument=e.busDocument,this._givenContext=e.context??null}open(){if(this._ctx)return!0;try{return this._ctx=this._givenContext??new AudioContext,this._givenContext=null,this._ctx.onstatechange=()=>this.rest(),this._masterGain=this._ctx.createGain(),this._busOut=this._ctx.createGain(),this._monitorGain=this._ctx.createGain(),this._masterGain.connect(this._busOut),this._busOut.connect(this._monitorGain),this._monitorGain.connect(this._ctx.destination),this.applyMasterGain(),this._metering&&this.attachMasterTap(),!0}catch{return!1}}async wake(){!this._ctx||this._ctx.state===`running`&&!this._suspendPending||(this._suspendPending=!1,await this._ctx.resume())}rest(){this._restTimer!==null&&i(this._restTimer),this._restTimer=null,this._ctx&&this._ctx.state===`running`&&!this._suspendPending&&(this._restTimer=r(()=>{this._restTimer=null,this.suspendIfIdle()},ni))}suspendIfIdle(){for(let e of this._playingCaptured)e.paused&&this._playingCaptured.delete(e);!this._ctx||!this._paused||this._suspendPending||this._playingCaptured.size>0||(this._suspendPending=!0,this._ctx.suspend().catch(e=>{this._suspendPending=!1,V(`webAudioTransport.suspend`,e)}))}get context(){return this._ctx}getTime(){return!this._ctx||this._paused?-1:this._rateAnchorComp+(this._ctx.currentTime-this._rateAnchorCtx)*this._rate}releaseDecodedExcept(e){let t=new Set(e.map($));for(let e of[...this._bufferCache.keys()])t.has(e)||this._bufferCache.delete(e)}decodeAudioElement(e){let t=$(e);if(!t)return Promise.resolve(null);let n=this._decoding.get(t);if(n)return n;this._pendingDecodeBytes.set(t,this.estimateDecodedBytes(e.duration));let r=this.fetchAndDecode(t,e).finally(()=>{this._decoding.delete(t),this._pendingDecodeBytes.delete(t)});return this._decoding.set(t,r),r}fitsDecodeBudget(e){let t=$(e);return t?this._bufferCache.has(t)||this._decoding.has(t)?!0:Number.isFinite(e.duration)?this.decodedBytes()+this.estimateDecodedBytes(e.duration)<=ii:!1:!1}estimateDecodedBytes(e){let t=this._ctx?.sampleRate??48e3;return Number.isFinite(e)?e*t*ai*oi:0}decodedBytes(){let e=0;for(let t of this._bufferCache.values())e+=t.length*t.numberOfChannels*oi;for(let t of this._pendingDecodeBytes.values())e+=t;return e}async mayDecode(e,t){if(this._failedSrcs.has(e))return null;try{return await Wr(e,t.duration)}catch(t){if(!(t instanceof Br))throw t;return this._failedSrcs.add(e),null}}async fetchBytes(e,t,n){if(n.aborted)return null;try{let r=await fetch(e,{cache:`no-store`,...this._fetchInit,signal:n});return n.aborted?null:r.ok?await r.arrayBuffer():(V(`webAudioTransport.fetch`,Error(`${r.status} ${e}`)),vr(t,`fetch`,r.status),null)}catch(e){return V(`webAudioTransport.fetch`,e),n.aborted||vr(t,`fetch`,null),null}}async fetchAndDecode(e,t){if(this._bufferCache.has(e))return this._bufferCache.get(e);let{signal:n}=this._fetches;if(!this._ctx)return null;let r=await this.mayDecode(e,t);if(!r)return null;let i=await this.fetchBytes(e,t,n);return i?r===`unread`&&!Gr(i.byteLength)?(this._failedSrcs.add(e),null):this.decode(e,t,i,n):null}async decode(e,t,n,r){if(!this._ctx)return null;try{let i=await this._ctx.decodeAudioData(n);return r.aborted?null:Number.isFinite(t.duration)&&t.duration-i.duration>ri?(this._failedSrcs.add(e),null):(this._bufferCache.set(e,i),i)}catch(i){return V(`webAudioTransport.decode`,i),r.aborted||(this._failedSrcs.add(e),vr(t,`decode`,null,n.byteLength)),null}}startGeneration(){return this._playGeneration+=1,this._playGeneration}currentGeneration(){return this._playGeneration}acquireMediaElementSource(e){let t=this._mediaElementSources.get(e);if(t){let n=kr(e);if(n.kind!==`web-audio`){try{t.disconnect()}catch{}return this._mediaElementSources.delete(e),Fr(e,n),null}return t}if(!this._ctx)return null;let n=kr(e);if(n.kind!==`web-audio`)return Fr(e,n),null;let r=this._ctx.createMediaElementSource(e);this._mediaElementSources.set(e,r),e.paused||this._playingCaptured.add(e),e.addEventListener(`play`,()=>{this._playingCaptured.add(e),this.wake()});let i=()=>{this._playingCaptured.delete(e),this.rest()};return e.addEventListener(`pause`,i),e.addEventListener(`emptied`,i),r}async scheduleMediaElementPlayback(e,t,n,r,i,a,o=1,s=1/0){if(!this._ctx||!this._masterGain||a!==this._playGeneration)return null;try{if(await this.wake(),a!==this._playGeneration)return null;let c=this.acquireMediaElementSource(e);if(!c)return null;c.disconnect();let l=qr(o),u=this._ctx.createGain();u.gain.value=i;let d=this._ctx.currentTime,f=r-t,p={scheduledAt:d,elapsed:f,rate:l};u.connect(this.resolveDestination(e,d,r,l)??this._masterGain);let m=this._ctx.createGain();c.connect(m);let{fx:h,laneNode:g,clipGainNode:_,fades:v}=Qr(this._ctx,e,m,u,p,{from:Math.max(f,0),clipDuration:s});this._rate=l,this._rateAnchorCtx=d,this._rateAnchorComp=r;let y={fx:h,fades:v,dipNode:m,el:e,sourceNode:c,sourceKind:`media-element`,gainNode:u,laneNode:g,clipGainNode:_,compositionStart:t,mediaStart:n,scheduledAt:d,priorMuted:e.muted,priorVolume:e.volume,mediaPlaybackRate:J(e),bounded:!1,unfollow:this.followElement(e,t,n,h,v)};return e.volume=1,this._activeSources.push(y),this._paused=!1,y}catch(e){return V(`webAudioTransport.mediaElementSource`,e),null}}followElement(e,t,n,r,i){let a=()=>{if(e.paused||!this._ctx)return;let a=zn(e),o=e.currentTime-n,s=e.duration-n;if(e.loop&&s>0){let e=Fn(a,this.getTime()-t);o+=Math.round((e-o)/s)*s}let c=In(a,o),l=e.playbackRate/Nn(a,c);if(!(l>0)||!Number.isFinite(c))return;let u={scheduledAt:this._ctx.currentTime,elapsed:c,rate:l};r?.retime(u),i?.rebook(u)};for(let t of ti)e.addEventListener(t,a);return()=>{for(let t of ti)e.removeEventListener(t,a)}}seekUnderDip(e,t){let n=this._activeSources.find(t=>t.el===e&&t.sourceKind===`media-element`),i=this._ctx;if(!i||!n?.dipNode)return!1;if(n.dipping)return!0;n.dipping=!0;let a=n.dipNode.gain,o=e=>{let t=i.currentTime;a.cancelScheduledValues(t),a.setValueAtTime(a.value,t),a.linearRampToValueAtTime(e,t+$r)},s=()=>{for(let t of ei)e.removeEventListener(t,s);n.dipping=!1,o(1)};return o(0),r(()=>{if(this._activeSources.includes(n)){for(let t of ei)e.addEventListener(t,s);try{e.currentTime=Lt(t+$r*e.playbackRate)}catch(e){V(`webAudioTransport.seekUnderDip`,e),s()}}},$r*1e3),!0}groupInput(e,t,n){let r=this._groups.get(e);if(r){if(r.generation!==this._playGeneration)try{r.reanchor(n),r.generation=this._playGeneration}catch(e){V(`webAudioTransport.groupReanchor`,e)}return r.input}if(!this._ctx||!this._masterGain)return null;let i=this._ctx.createGain(),a=this._ctx.createGain();a.connect(this._masterGain);let o=()=>Ct(t,e),s=o(),c=this._ctx.createGain();c.gain.value=+!s?.hasAttribute(`data-hidden`),c.connect(a);let l=this._ctx.createGain();l.gain.value=Jr(B(s)),l.connect(c);let u={param:l.gain,gain:()=>B(o())},d=vt(this._ctx,s??{getAttribute:()=>null},i,l,n,void 0,s?u:void 0);return this._groups.set(e,{input:i,output:a,isPresent:()=>o()!==null,fader:l,muteGain:c,fx:d,generation:this._playGeneration,reanchor:e=>{P([{param:l.gain}]);let t=o();l.gain.value=Jr(B(t)),c.gain.value=+!t?.hasAttribute(`data-hidden`),d?.reanchor(e),t&&t!==s&>(u,ht(t),e)},dispose:()=>{try{d?.dispose(),i.disconnect(),l.disconnect(),c.disconnect(),a.disconnect()}catch{}}}),this.attachGroupTap(e,a),i}startMetering(){this._metering=!0,this.attachMasterTap();for(let[e,t]of this._groups)this.attachGroupTap(e,t.output)}stopMetering(){this._metering=!1,this._masterTap?.dispose(),this._masterTap=null;for(let e of this._groupTaps.values())e.dispose();this._groupTaps.clear()}readLevels(){let e={};for(let[t,n]of this._groupTaps)this._groups.get(t)?.isPresent()&&(e[t]=n.read());return{master:this._masterTap?.read()??{l:0,r:0},groups:e}}attachMasterTap(){this._ctx&&this._masterGain&&!this._masterTap&&(this._masterTap=br(this._ctx,this._busOut??this._masterGain))}attachGroupTap(e,t){this._metering&&this._ctx&&!this._groupTaps.has(e)&&this._groupTaps.set(e,br(this._ctx,t))}setGroupMuted(e,t){let n=this._groups.get(e);if(n)try{n.muteGain.gain.value=+!t}catch(e){V(`webAudioTransport.setGroupMuted`,e)}}ensureMasterBus(e,t){if(!this._ctx||!this._masterGain||!this._busOut)return;if(this._master){if(this._master.generation===this._playGeneration)return;try{this._master.fx?.reanchor(t),this._master.generation=this._playGeneration}catch(e){V(`webAudioTransport.masterReanchor`,e)}return}let n=wt(e);if(!n)return;this._masterGain.disconnect(this._busOut);let r=vt(this._ctx,n,this._masterGain,this._busOut,t,Kr);this._master={fx:r,generation:this._playGeneration}}resolveDestination(e,t,n,r){if(!this._masterGain)return null;let i={scheduledAt:t,elapsed:n,rate:r},a=this._busDocument===void 0?e.ownerDocument:this._busDocument;if(!a)return this._masterGain;this.ensureMasterBus(a,i);let o=Tt(e);return o?this.groupInput(o,a,i)??this._masterGain:this._masterGain}handleSourceEnded(e,t,n,r){let i=this._activeSources.indexOf(t);if(i!==-1){this._activeSources.splice(i,1),n.muted=r;try{e.disconnect(),t.fx?.dispose(),t.fades?.node.disconnect(),t.clipGainNode.disconnect(),t.laneNode.disconnect(),t.gainNode.disconnect()}catch{}this._activeSources.length===0&&(this._paused=!0)}}async schedulePlayback(e,t,n,r,i,a,o,s=1,c=1/0,l=n){if(!this._ctx||!this._masterGain||o!==this._playGeneration)return null;try{if(await this.wake(),o!==this._playGeneration)return null;let u=i(),d=qr(s),f=J(e),p=d*f,m=this._ctx.createBufferSource();m.buffer=t,m.playbackRate.value=p;let h=Tn(e),g=Number.isFinite(h)?h:t.duration;e.loop&&g>r&&(m.loop=!0,m.loopStart=r,m.loopEnd=g);let _=this._ctx.createGain();_.gain.value=a;let v=u-n,y=this._ctx.currentTime,b={scheduledAt:y,elapsed:v,rate:d};_.connect(this.resolveDestination(e,y,u,d)??this._masterGain);let x=l-n,{fx:S,laneNode:ee,clipGainNode:C,fades:w}=Qr(this._ctx,e,m,_,b,{from:Math.max(v,x,0),clipDuration:c});if(this._rate=d,this._rateAnchorCtx=y,this._rateAnchorComp=u,!Xr(m,{elapsed:v,mediaStart:r,scheduledAt:y,globalRate:d,mediaRate:f,clipDuration:c,headCut:x}))return m.disconnect(),S?.dispose(),w?.node.disconnect(),C.disconnect(),ee.disconnect(),_.disconnect(),null;let T=e.muted;e.muted=!0,Yr(e,T);let E={fx:S,fades:w,el:e,sourceNode:m,sourceKind:`buffer`,gainNode:_,laneNode:ee,clipGainNode:C,compositionStart:n,mediaStart:r,scheduledAt:y,priorMuted:T,priorVolume:e.volume,mediaPlaybackRate:f,bounded:Number.isFinite(c)&&c>0};return this._activeSources.push(E),this._paused=!1,m.addEventListener(`ended`,()=>this.handleSourceEnded(m,E,e,T)),E}catch(e){return V(`webAudioTransport.schedule`,e),null}}releaseRouted(e){let t=this._activeSources.find(t=>t.el===e&&t.sourceKind===`media-element`);t&&(this._activeSources.splice(this._activeSources.indexOf(t),1),this.dispose(t,!1),this._handedOver.add(e))}hasHandedOverSources(){return this._activeSources.some(e=>Q(e)&&this._handedOver.has(e.el))}setRate(e){let t=qr(e);if(t===this._rate)return!1;this._ctx&&!this._paused&&(this._rateAnchorComp=this.getTime(),this._rateAnchorCtx=this._ctx.currentTime),this._rate=t;for(let e of this._activeSources)if(Q(e))try{e.sourceNode.playbackRate.value=t*e.mediaPlaybackRate,e.fx?.setRate(t),this._ctx&&!this._paused&&e.fades?.rebook({scheduledAt:this._ctx.currentTime,elapsed:this.getTime()-e.compositionStart,rate:t})}catch(e){V(`webAudioTransport.setRate`,e)}return this.setBusRate(t),!0}setBusRate(e){let t=[...this._groups.values(),...this._master?[this._master]:[]];for(let n of t)try{n.fx?.setRate(e)}catch(e){V(`webAudioTransport.setRate.bus`,e)}}hasBoundedActiveSources(){return this._activeSources.some(e=>Q(e)&&e.bounded)}stopAll(){for(let e of this._activeSources)this.dispose(e);this._activeSources=[],this.reconnectHandedOver(),this._paused=!0,this._playGeneration+=1,this.rest()}reconnectHandedOver(){for(let e of this._handedOver)try{this._ctx&&this._mediaElementSources.get(e)?.connect(this._ctx.destination)}catch(e){V(`webAudioTransport.reconnectHandedOver`,e)}this._handedOver.clear()}releaseDetached(){this._activeSources=this._activeSources.filter(e=>e.el.isConnected?!0:(this.dispose(e,!1),!1))}dispose(e,t=!0){e.unfollow?.();try{Q(e)&&e.sourceNode.stop(),e.sourceNode.disconnect(),e.fx?.dispose(),e.fades?.node.disconnect(),e.dipNode?.disconnect(),e.clipGainNode.disconnect(),e.laneNode.disconnect(),e.gainNode.disconnect()}catch{}Q(e)?e.el.muted=e.priorMuted:(e.el.volume=e.priorVolume,this._ctx&&t&&e.sourceNode.connect(this._ctx.destination))}setVolume(e){this._masterVolume=Math.max(0,Math.min(1,e)),this.applyMasterGain()}setElementVolume(e,t,n=1,r=t){for(let i of this._activeSources)if(i.el===e)try{i.sourceKind===`media-element`&&(i.el.volume=1),i.gainNode.gain.value=w(i.fades?r:t),i.clipGainNode.gain.value=w(n)}catch(e){V(`webAudioTransport.setElementVolume`,e)}}setMuted(e){this._masterMuted=e,this.applyMasterGain()}applyMasterGain(){this._monitorGain&&(this._monitorGain.gain.value=this._masterMuted?0:this._masterVolume)}ownsClock(){return!this._paused&&this._activeSources.some(Q)}ownsElement(e){return!this._paused&&this._activeSources.some(t=>t.el===e&&Q(t))}routesElement(e){return!this._paused&&this._activeSources.some(t=>t.el===e)}destroy(){this._fetches.abort(),this._fetches=new AbortController,this.stopAll(),this.stopMetering();for(let e of this._groups.values())e.dispose();if(this._groups.clear(),this._master?.fx?.dispose(),this._master=null,this._bufferCache.clear(),this._failedSrcs.clear(),this._mediaElementSources=new WeakMap,this._playingCaptured.clear(),this._suspendPending=!1,this._restTimer!==null&&i(this._restTimer),this._restTimer=null,this._ctx)try{this._ctx.close()}catch{}this._ctx=null,this._masterGain=null,this._busOut=null,this._monitorGain=null,this._masterVolume=1,this._masterMuted=!1}};function ci(e,t){return Rt()&&Nt(e)&&!dr(e)&&t.fitsDecodeBudget(e)&&typeof zn(e)==`number`&&J(e)===1}var li={method:`GET`,credentials:`same-origin`,redirect:`error`},ui=250,di=5e3,fi=[`data-audio-group`],pi=[`pointerdown`,`touchend`,`keydown`],mi=class{constructor(e){this._host=e}_host;_transport=null;_clockTimer=null;_unlock=null;postClaims(){let e=this._host.copies().flatMap(e=>e.claimed&&e.listedKey?[e.listedKey]:[]);this._host.sendControl(`set-parent-audio`,{clips:e})}play(){if(this._host.getPlaybackRate()!==1)return this.release();let e=this._open();if(!e)return;e.context?.state!==`running`&&(e.context?.resume().catch(()=>{}),this._armUnlock(e)),e.stopAll();let t=e.currentGeneration();for(let n of this._host.copies())this._start(e,n,t)}pause(){this._transport?.stopAll(),this._stopClock()}release(){this.pause();let e=this._host.copies().filter(e=>e.claimed);for(let t of e)t.claimed=!1;e.length>0&&this.postClaims()}setRate(e){e!==1&&this.release()}setVolume(e){this._transport?.setVolume(e)}setMuted(e){this._transport?.setMuted(e)}reset(){this.pause(),this._disarmUnlock()}destroy(){this.reset(),this._transport?.destroy(),this._transport=null}_open(){return this._transport??=new si({fetchInit:li,busDocument:null,context:this._host.takeTapContext?.()??void 0}),this._transport.open()?(this._transport.setVolume(this._host.getVolume()),this._transport.setMuted(this._host.getMuted()),this._transport):null}async _start(e,t,n){if(!await hi(e,t)||n!==e.currentGeneration())return;let r=await e.decodeAudioElement(t.el);if(!r||n!==e.currentGeneration()||this._host.isPaused())return;let i=Number.parseFloat(t.el.getAttribute(`data-volume`)??``);await e.schedulePlayback(t.el,r,t.start,t.mediaStart,()=>this._time(e),Number.isFinite(i)?i:1,n,1,t.duration)&&(this._claim(t),this._startClock(e))}_claim(e){e.claimed||(e.claimed=!0,e.el.pause(),this.postClaims())}_time(e){let t=e.getTime();return t>=0?t:this._host.getCurrentTime()}_startClock(e){this._postClock(e),this._clockTimer??=setInterval(()=>this._postClock(e),ui)}_postClock(e){let t=e.getTime();if(t<0)return;let n=performance.timeOrigin+performance.now();this._host.sendControl(`audio-clock`,{time:t,rate:this._host.getPlaybackRate(),at:n})}_stopClock(){this._clockTimer!==null&&clearInterval(this._clockTimer),this._clockTimer!==null&&this._host.sendControl(`audio-clock`,{time:null}),this._clockTimer=null}_armUnlock(e){if(this._unlock)return;let t=()=>{this._disarmUnlock(),e.context?.resume().catch(()=>{})};for(let e of pi)document.addEventListener(e,t,{capture:!0});this._unlock=t}_disarmUnlock(){let e=this._unlock;if(e){for(let t of pi)document.removeEventListener(t,e,{capture:!0});this._unlock=null}}};async function hi(e,t){let{el:n}=t;return!t.listedKey||t.mastered||n.tagName!==`AUDIO`||!gi(n.src)||fi.some(e=>n.hasAttribute(e))?!1:(n.readyState<HTMLMediaElement.HAVE_METADATA&&await _i(n),await fr(n.src),ci(n,e))}function gi(e){try{return new URL(e).origin===location.origin}catch{return!1}}function _i(e){return new Promise(t=>{let n=()=>{clearTimeout(r),e.removeEventListener(`loadedmetadata`,n),e.removeEventListener(`error`,n),t()},r=setTimeout(n,di);e.addEventListener(`loadedmetadata`,n),e.addEventListener(`error`,n)})}export{mi as ParentAudio};
|