import{n as e}from"./rolldown-runtime-DAXXjFlN.js";import{dn as t,gr as n}from"./vendor-Dnfj1twE.js";import{F as r,Ht as i,Mt as a,Nt as ee,g as te,gt as o,h as ne,ht as re,ia as ie,mt as ae,or as oe,ra as se,sr as ce,z as le,zt as s}from"./ws-Dl8XkIy4.js";import{a as ue,c as de,d as fe,m as pe,u as c}from"./client-api-D-UNvPyj.js";import{cn as me,dn as he,fn as ge,ln as _e,on as ve,pn as ye,sn as be,un as xe}from"./auth-tS4c9ju3.js";function Se(){return`
const IDX_WRITE = 0;
const IDX_READ = 1;
const IDX_OVERRUN = 2;
const IDX_EPOCH = 4;

class CiderHostCaptureProcessor extends AudioWorkletProcessor {
  constructor() {
    super();
    this._ctrl = null;   // Int32Array over the control header
    this._data = null;   // Float32Array over the interleaved stereo ring
    this._cap = 0;       // ring capacity in stereo frames
    this._ch = 2;
    this._armed = false; // only write while armed (host has reset + started)
    this._epoch = -1;
    this.port.onmessage = (e) => {
      const d = e.data;
      if (!d) return;
      switch (d.cmd) {
        case 'ring': {
          // Adopt the shared buffer transferred in (kept for the session).
          const buf = d.buffer;
          this._ctrl = new Int32Array(buf, 0, d.controlInts);
          this._data = new Float32Array(buf, d.dataByteOffset);
          this._cap = d.capacityFrames | 0;
          this._ch = (d.channels | 0) || 2;
          this._armed = false;
          this._epoch = Atomics.load(this._ctrl, IDX_EPOCH);
          this.port.postMessage({ cmd: 'ring-ready' });
          break;
        }
        case 'arm':
          // Host has reset the ring (write=read=0) and started its reader.
          // Adopt the current epoch so we don't skip the first real block.
          if (this._ctrl) this._epoch = Atomics.load(this._ctrl, IDX_EPOCH);
          this._armed = true;
          this.port.postMessage({ cmd: 'armed' });
          break;
        case 'disarm':
          this._armed = false;
          this.port.postMessage({ cmd: 'disarmed' });
          break;
        case 'release': {
          // Return the buffer to the main thread so it can releaseBuffer().
          this._armed = false;
          if (this._ctrl) {
            const buf = this._ctrl.buffer;
            this._ctrl = null;
            this._data = null;
            try { this.port.postMessage({ cmd: 'released', buffer: buf }, [buf]); }
            catch (_) { /* buffer may already be detached */ }
          }
          break;
        }
      }
    };
  }

  process(inputs) {
    // The node's unwritten, zero-initialized output is connected directly to
    // destination so the engine keeps pulling render quanta without audible output.
    if (!this._armed || !this._ctrl) return true;

    const input = inputs[0];
    if (!input || input.length === 0) return true;
    const L = input[0];
    if (!L || L.length === 0) return true;
    const R = input[1] || L; // duplicate mono to stereo
    const n = L.length;      // 128 frames per quantum

    const ctrl = this._ctrl;
    const data = this._data;
    const cap = this._cap;
    const ch = this._ch;

    // Epoch resync: if the host reset the ring since we last wrote, skip exactly
    // one block so we never clobber the freshly-reset writeIndex with a stale one.
    const ep = Atomics.load(ctrl, IDX_EPOCH);
    if (ep !== this._epoch) {
      this._epoch = ep;
      return true;
    }

    const w = Atomics.load(ctrl, IDX_WRITE);
    const r = Atomics.load(ctrl, IDX_READ);
    let used = w - r;
    if (used < 0) used += cap;

    // Overrun (host fell behind / paused its reader): drop the NEWEST block and
    // bump the counter. NEVER advance readIndex — it is consumer-owned, and a
    // second writer to it would corrupt the single-producer/single-consumer ring.
    if (used + n >= cap) {
      Atomics.add(ctrl, IDX_OVERRUN, 1);
      return true;
    }

    let pos = w;
    for (let i = 0; i < n; i++) {
      const o = pos * ch;
      data[o] = L[i];
      data[o + 1] = R[i];
      pos++;
      if (pos >= cap) pos -= cap;
    }
    // Publish the advanced write index AFTER the sample stores (Atomics.store gives
    // the release barrier the host's acquire-read of writeIndex pairs with).
    Atomics.store(ctrl, IDX_WRITE, pos);
    return true;
  }
}

registerProcessor('cider-host-capture', CiderHostCaptureProcessor);
`}var Ce=e((()=>{}));function we(e,t){t.connect(e.destination);let n=!0;return{disconnect(){if(n){n=!1;try{t.disconnect(e.destination)}catch{}}}}}var Te=e((()=>{}));async function Ee(){let e=null;try{e=xe(await Promise.resolve(l()?.GetDiagnostics?.()))}catch{}return{context:a(),capture:{stage:E,protocol:X,sourceRate:C()?.contextRate??null,customLookaheadMs:Number(window.__ciderAudioCustomLatencyMs)||0,sinkOwner:ae(),selectedSinkCategory:(d()?.deviceId||`default`)==="default"?`default`:`custom`,boundSinkCategory:F?`silent`:(s().audio?.deviceOutput||`default`)==="default"?`default`:`custom`},native:e}}function De(){return ae()!==`chromium`}function l(){try{return window?.chrome?.webview?.hostObjects?.audioBridge??null}catch{return null}}function u(){try{return window?.chrome?.webview??null}catch{return null}}function d(){try{return s().audio?.hostAudioCapture??null}catch{return null}}function Oe(){let e=d();return e?e.mode===`exclusive`?!0:e.mode===`capture`?e.autoEnable?N:!0:!1:!1}function ke(){return d()?.mode===`exclusive`?`exclusive`:`shared`}function Ae(){let e=d();return!!(e?.mode===`capture`&&e.autoEnable&&Array.isArray(e.autoApps)&&e.autoApps.length>0)}function f(){return window.ciderAudioContext??null}function je(){return window.middlewareNode??null}function Me(){try{let e=r?.audioNodes;if(e&&e._safetyLimiter)return e._safetyLimiter}catch{}return window.mkliteOutputLimiter||je()}function Ne(e){if(!D)return!1;if(k===e)return!0;if(k)try{k.disconnect(D)}catch{}try{return e.connect(D),k=e,!0}catch(e){return console.warn(`[HostAudio] tap connect failed`,e),k=null,!1}}function Pe(){let e=``;try{e=String(ie().player.playbackState||``)}catch{return!1}return mt.has(e)?(T??=performance.now(),performance.now()-T>ht):(T=null,!1)}function p(){if(!Oe())return`off`;try{let e=ce();if(!e?.musicKitReady||e?.videoMode||te()?.player?.passthroughMode===!0)return`idle`}catch{return`idle`}return r?.castEnabled===!0||Pe()||!f()||!Me()?`idle`:`armed`}async function Fe(e){if(D&&O===e)return!0;Ie();try{if(_t!==e){let t=Se(),n=URL.createObjectURL(new Blob([t],{type:`application/javascript`}));await e.audioWorklet.addModule(n),URL.revokeObjectURL(n),_t=e}return D=new AudioWorkletNode(e,`cider-host-capture`,{numberOfInputs:1,numberOfOutputs:1,channelCount:2,channelCountMode:`explicit`,channelInterpretation:`speakers`}),Z=we(e,D),D.port.onmessage=Le,O=e,!0}catch(e){return console.warn(`[HostAudio] worklet setup failed`,e),D=null,O=null,!1}}function Ie(){if(Z?.disconnect(),Z=null,D){try{k&&k.disconnect(D)}catch{}try{D.disconnect()}catch{}try{D.port.postMessage({cmd:`release`})}catch{}D.port.onmessage=null}D=null,O=null,k=null,A=!1,Re(),ze(Error(`capture worklet was torn down`)),E===`ring-ready`&&(E=`configured`)}function Le(e){let t=e.data;if(t?.cmd===`released`&&t.buffer)try{u()?.releaseBuffer?.(t.buffer)}catch{}let n=typeof t?.cmd==`string`?Q.get(t.cmd):null;if(n){clearTimeout(n.timer),Q.delete(t.cmd),n.resolve();return}}function Re(){U&&clearTimeout(U),U=null}function ze(e){for(let t of Q.values())clearTimeout(t.timer),t.reject(e);Q.clear()}function Be(e){return new Promise((t,n)=>{let r=setTimeout(()=>{Q.delete(e),n(Error(`worklet ${e} acknowledgement timed out`))},ot);Q.set(e,{resolve:t,reject:n,timer:r})})}async function Ve(e,t){if(!D)throw Error(`capture worklet is unavailable`);let n=Be(t);try{D.port.postMessage({cmd:e})}catch(e){let n=Q.get(t);n&&(clearTimeout(n.timer),Q.delete(t),n.reject(e instanceof Error?e:Error(String(e))))}await n}function He(e){let t=e?.additionalData;if(!t||t.kind!==`ciderHostAudioRing`)return;let n=null;try{n=e.getBuffer(),A=!1,Re();let r=C(),i=n&&r?he(t,n,r):null;if(!n||!i){if(n)try{u()?.releaseBuffer?.(n)}catch{}console.warn(`[HostAudio] rejected malformed shared ring`),S();return}if(!D){try{u()?.releaseBuffer?.(n)}catch{}S();return}let a=Be(`ring-ready`);D.port.postMessage({cmd:`ring`,buffer:n,...i},[n]),n=null,a.then(()=>{!D||E!==`configured`||(E=`ring-ready`,$())}).catch(e=>{console.warn(`[HostAudio] worklet rejected shared ring`,e),S()})}catch(e){if(n)try{u()?.releaseBuffer?.(n)}catch{}console.warn(`[HostAudio] sharedbufferreceived handling failed`,e),S()}}async function Ue(){let e=l();if(!e||!D)return;let t=D,n=O;o(`transitioning`);try{if(!C())throw Error(`source format is not current`);if(J&&(await Qe(),await y(),await Ze()),await Ge(),p()!==`armed`||D!==t||O!==n){await m();return}await Ve(`arm`,`armed`);let r=await Promise.resolve(e.SetSourceAvailable(!0));if(J){let t=_e(r);if(!t?.accepted||!t.renderStarted)throw Error(t?.reason||`host renderer did not acknowledge startup`);await We(e)}if(E=`host-started`,o(`host`),p()!==`armed`||D!==t||O!==n){await m();return}E=`worklet-armed`,Xe(!0),(p()!==`armed`||D!==t||O!==n)&&await m()}catch(e){console.warn(`[HostAudio] host arm transaction failed`,e),await m()}}async function We(e){let t=performance.now()+st;for(;performance.now()<t;){let t=xe(await Promise.resolve(e.GetDiagnostics()));if(t?.renderStarted&&t.pcmReady)return;await new Promise(e=>setTimeout(e,ct))}throw Error(`host PCM readiness timed out`)}async function m(){if(E===`worklet-armed`)try{await Ve(`disarm`,`disarmed`)}catch{}else try{D?.port.postMessage({cmd:`disarm`})}catch{}Xe(!1);let e=l();try{await Promise.resolve(e?.SetSourceAvailable(!1))}catch{}(E===`host-started`||E===`worklet-armed`)&&(E=`ring-ready`),await h()}async function Ge(){if(H=!1,_(),V&&await V,F){B=0;return}let e=f();if(!e||typeof e.setSinkId!=`function`)throw Error(`AudioContext silent sink is unavailable`);await e.setSinkId({type:`none`}),F=!0,I=e,Ke(e),B=0}async function h(){return F?V||(V=(async()=>{let e=I??f();if(!e||e.state===`closed`)return g(),!0;let t=s().audio?.deviceOutput||`default`;if(typeof e.setSinkId==`function`){try{return await e.setSinkId(t),g(),!0}catch(e){console.warn(`[HostAudio] configured sink restore failed`,e)}if(t!=="default")try{return await e.setSinkId(`default`),g(),!0}catch(e){console.warn(`[HostAudio] default sink restore failed`,e)}}return F?(o(`transitioning`),qe(),!1):!0})().finally(()=>{V=null}),V):(_(),B=0,o(`chromium`),!0)}function g(){_(),v(),B=0,F=!1,I=null,o(`chromium`)}function _(){z&&clearTimeout(z),z=null}function Ke(e){v(),typeof e.addEventListener==`function`&&(L=()=>{e.state===`closed`&&g()},R=e,e.addEventListener(`statechange`,L))}function v(){if(R&&L)try{R.removeEventListener(`statechange`,L)}catch{}L=null,R=null}function qe(){if(z||H)return;let e=B<w?lt:ut;B=Math.min(w,B+1),z=setTimeout(()=>{z=null,h()},e)}function Je(){H||!F||ae()!==`transitioning`||(_(),h())}function Ye(){H=!0,_(),v();try{navigator.mediaDevices?.removeEventListener?.(`devicechange`,Je)}catch{}}function Xe(e){if(!e){window.__hostAudioLatencyMs=0;return}let t=l();if(t)try{Promise.resolve(t.GetRenderLatencyMs()).then(e=>{let t=Number(e);window.__hostAudioLatencyMs=Number.isFinite(t)&&t>0?t:0}).catch(()=>{})}catch{}}async function y(){let e=d(),t=l();if(!e||!t)throw Error(`host render mode bridge is unavailable`);let n=ke(),r=Number(e.exclusive?.sampleRate)||0,i=Number(e.exclusive?.bitDepth)||0,a=`${n}:${r}:${i}`;a!==yt&&(b(await Promise.resolve(t.SetRenderMode(n,r,i)),`render mode`),yt=a)}async function Ze(){let e=d(),t=l();if(!e||!t)throw Error(`host gain bridge is unavailable`);let n=Number(e.gainDb),r=Number.isFinite(n)?n:0;r!==vt&&(b(await Promise.resolve(t.SetGainDb(r)),`gain`),vt=r)}async function Qe(){let e=l();if(!e)throw Error(`host output bridge is unavailable`);let t=d()?.deviceId||`default`;t!==bt&&(b(await Promise.resolve(e.SetOutputDevice(t)),`output device`),bt=t)}function b(e,t){let n=_e(e);if(!n?.accepted&&!(!J&&e==null))throw Error(n?.reason||`${t} rejected`)}async function x(){if(P)return;let e=d(),t=l();if(!t||!e||!Ae()){N&&(N=!1,$());return}P=!0;try{let n=!!await Promise.resolve(t.IsAnyAppRunning(JSON.stringify(e.autoApps)));n!==N&&(N=n,$())}catch{}finally{P=!1}}async function S(){return W||(W=(async()=>{if(Re(),A=!1,await m(),D)try{await Ve(`release`,`released`)}catch{}let e=l();if(!e){Ie(),E=`disabled`,G=null,Y=null;return}try{G=null,Y=null,await Promise.resolve(e.SetEnabled(!1)),Ie(),E=`disabled`}catch(e){console.warn(`[HostAudio] SetEnabled(false) failed`,e)}})().finally(()=>{W=null}),W)}function C(){let e=f();return!Y||!G||e!==G||e.sampleRate!==Y.contextRate?null:Y}async function $e(e,t){if(C())return!0;if((E!==`disabled`||D)&&await S(),X===`v1`){let t=me(e.sampleRate);return t?(G=e,Y=t,!0):(console.warn(`[HostAudio] legacy host capture requires a ${ve} Hz AudioContext; received ${e.sampleRate} Hz, keeping Chromium playback`),!1)}if(!Number.isInteger(e.sampleRate)||e.sampleRate<8e3||e.sampleRate>192e3)return console.warn(`[HostAudio] rejected unsupported AudioContext sample rate`,e.sampleRate),!1;if(q&&!St)try{let e=_e(await Promise.resolve(t.BeginSourceFormatSession(xt)));if(!e?.accepted)return console.warn(`[HostAudio] source format session rejected`,e?.reason),!1;St=!0,K=0}catch(e){return console.warn(`[HostAudio] source format session negotiation failed`,e),!1}let n=K+1;K=n;try{let r=ye(await Promise.resolve(t.ConfigureSourceFormat(dt,e.sampleRate,ft,pt,n)),e.sampleRate,n);return r?(G=e,Y=r,!0):(console.warn(`[HostAudio] v2 source format rejected or returned an invalid acknowledgement`),!1)}catch(e){return console.warn(`[HostAudio] v2 source format negotiation failed`,e),!1}}async function et(e){if(!A){A=!0;try{if(await Promise.resolve(e.RequestRing()),!A)return;U=setTimeout(()=>{U=null,A=!1,console.warn(`[HostAudio] shared ring request timed out`),S().finally($)},at)}catch(e){A=!1,console.warn(`[HostAudio] RequestRing failed`,e),await S()}}}async function tt(){W&&await W;let e=l();if(!e){await S();return}if(p()===`off`){(E!==`disabled`||F)&&await S();return}let t=f(),n=Me();if(!t||!n){(E===`host-started`||E===`worklet-armed`)&&await m();return}if(!await $e(t,e)){await h();return}if(E===`disabled`){try{await Promise.resolve(e.SetEnabled(!0)),E=`configured`}catch(e){console.warn(`[HostAudio] SetEnabled(true) failed`,e),await h();return}if(p()===`off`){await S();return}}if(D&&O!==t&&(E===`host-started`||E===`worklet-armed`)&&await m(),!await Fe(t)||!D){await h();return}if(p()===`off`){await S();return}if(!Ne(n)){E===`host-started`||E===`worklet-armed`?await m():await h();return}if(E===`configured`){await et(e);return}p()===`armed`?E===`ring-ready`&&await Ue():(E===`host-started`||E===`worklet-armed`)&&await m()}async function nt(){if(j){M=!0;return}j=!0;try{do M=!1,await tt();while(M)}finally{j=!1}}function rt(){if(gt||!pe(ue())||de()!==`win32`)return;let e=ge(c(`audio:hostCapture`),c(`audio:hostCapture:v2`));if(!e)return;X=e,q=c(`audio:hostCapture:sourceSessions`),J=c(`audio:hostCapture:structuredControls`),X===`v2`&&!q&&(K=Math.max(1,Math.floor(Date.now()/1e3))),gt=!0;try{u()?.addEventListener?.(`sharedbufferreceived`,He)}catch(e){console.warn(`[HostAudio] could not attach sharedbufferreceived listener`,e)}let t=s(),i=e=>{J&&e().catch(e=>{console.warn(`[HostAudio] control update failed`,e),De()&&m()})};n(()=>t.audio?.hostAudioCapture?.mode,()=>{i(y),$()}),n(()=>[t.audio?.hostAudioCapture?.exclusive?.sampleRate,t.audio?.hostAudioCapture?.exclusive?.bitDepth],()=>i(y)),n(()=>t.audio?.hostAudioCapture?.gainDb,()=>i(Ze)),n(()=>t.audio?.hostAudioCapture?.deviceId,()=>i(Qe)),n(()=>[t.audio?.hostAudioCapture?.autoEnable,(t.audio?.hostAudioCapture?.autoApps??[]).join(`,`)],()=>{N=!1,x()});try{let e=ce();n(()=>e.musicKitReady,$),n(()=>e.videoMode,$)}catch{}try{let e=ie();n(()=>e.player.playbackState,$)}catch{}try{window.addEventListener?.(`MKLite:audioPromoted`,$),window.addEventListener?.(`beforeunload`,Ye)}catch{}try{navigator.mediaDevices?.addEventListener?.(`devicechange`,Je)}catch{}try{r.subscribe?.(`ready`,$)}catch{}setInterval(()=>{Ae()?x():N&&(N=!1,$()),Oe()&&$()},it),x(),$()}var it,at,ot,st,ct,lt,w,ut,dt,ft,pt,mt,ht,T,gt,E,D,_t,O,k,A,j,M,N,P,vt,yt,bt,F,I,L,R,z,B,V,H,U,W,G,K,xt,St,q,J,Y,X,Z,Q,$,Ct=e((()=>{re(),ee(),fe(),i(),le(),ne(),oe(),se(),t(),Ce(),Te(),be(),it=2e3,at=3e3,ot=2e3,st=3500,ct=50,lt=250,w=8,ut=2e4,dt=2,ft=2,pt=`f32`,mt=new Set([`none`,`stopped`,`ended`,`completed`]),ht=12e3,T=null,gt=!1,E=`disabled`,D=null,_t=null,O=null,k=null,A=!1,j=!1,M=!1,N=!1,P=!1,vt=null,yt=null,bt=null,F=!1,I=null,L=null,R=null,z=null,B=0,V=null,H=!1,U=null,W=null,G=null,K=0,xt=crypto.randomUUID(),St=!1,q=!1,J=!1,Y=null,X=`v1`,Z=null,Q=new Map,$=()=>{M=!0,nt()}}));Ct();export{Ee as getAudioConversionDiagnostics,rt as initHostAudioCapture,Ct as t};