import{dn as e,gr as t}from"./vendor-6bGPahzI.js";import{et as n}from"./vendor-quasar-Bl8FKFQs.js";import{$a as r,$n as i,Bn as a,Dn as o,Ei as s,K as ee,Nt as c,On as te,Pt as l,Qn as u,Ti as ne,U as d,Vn as re,Za as ie,fr as ae,g as oe,ga as se,h as ce,jt as f,ma as le,q as p,to as ue,ur as de,wn as fe}from"./ws-BfVPV0ME.js";import{r as pe,t as m}from"./TokenManager-7Ay6nr15.js";import{a as h,c as me,d as g,m as _}from"./client-api-DGgiwyPh.js";import{f as v,p as he,u as ge}from"./uiLogic-CQLv0k29.js";import{n as _e}from"./genten-Dyr_Aj-c.js";import{a as ve,n as ye,o as be,r as xe,s as Se}from"./auth-WD4QDKIv.js";e(),pe(),g(),r(),le(),ne(),de(),u(),a(),fe(),l(),p(),ce(),ge(),be(),ye();function Ce(){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);
          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;
          break;
        case 'disarm':
          this._armed = false;
          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) {
    // ALWAYS return true: a worklet whose process() returns true is never culled,
    // so the tap keeps receiving frames regardless of WebView2 mute state or
    // whether our (output-less) node reaches the destination.
    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 y=16,we=y*4,Te=2e3,Ee=new Set([`none`,`stopped`,`ended`,`completed`]),De=12e3,b=null,x=!1,S=!1,C=null,w=null,T=null,E=null,D=!1,O=!1,k=!1,A=!1,j=!1,M=!1,N=null,P=null,F=!1;function I(){try{return window?.chrome?.webview?.hostObjects?.audioBridge??null}catch{return null}}function L(){try{return window?.chrome?.webview??null}catch{return null}}function R(){try{return f().audio?.hostAudioCapture??null}catch{return null}}function z(){let e=R();return e?e.mode===`exclusive`?!0:e.mode===`capture`?e.autoEnable?j:!0:!1:!1}function Oe(){return R()?.mode===`exclusive`?`exclusive`:`shared`}function B(){let e=R();return!!(e?.mode===`capture`&&e.autoEnable&&Array.isArray(e.autoApps)&&e.autoApps.length>0)}function V(){return window.ciderAudioContext??null}function ke(){return window.middlewareNode??null}function H(){try{let e=d?.audioNodes;if(e&&e._safetyLimiter)return e._safetyLimiter}catch{}return window.mkliteOutputLimiter||ke()}function Ae(e){if(!(!C||E===e)){if(E)try{E.disconnect(C)}catch{}try{e.connect(C),E=e}catch(e){console.warn(`[HostAudio] tap connect failed`,e)}}}function je(){let e=``;try{e=String(s().player.playbackState||``)}catch{return!1}return Ee.has(e)?(b??=performance.now(),performance.now()-b>De):(b=null,!1)}function U(){if(!z())return`off`;try{let e=i();if(!e?.musicKitReady||e?.videoMode||oe()?.player?.passthroughMode===!0)return`idle`}catch{return`idle`}return d?.castEnabled===!0||je()||!V()||!H()?`idle`:`armed`}async function Me(e){if(C&&T===e)return!0;W(),F=!1;try{if(w!==e){let t=Ce(),n=URL.createObjectURL(new Blob([t],{type:`application/javascript`}));await e.audioWorklet.addModule(n),URL.revokeObjectURL(n),w=e}return C=new AudioWorkletNode(e,`cider-host-capture`,{numberOfInputs:1,numberOfOutputs:1,channelCount:2,channelCountMode:`explicit`,channelInterpretation:`speakers`}),C.port.onmessage=Ne,T=e,D=!1,!0}catch(e){return console.warn(`[HostAudio] worklet setup failed`,e),C=null,T=null,!1}}function W(){if(C){try{E&&E.disconnect(C)}catch{}try{C.disconnect()}catch{}try{C.port.postMessage({cmd:`release`})}catch{}C.port.onmessage=null}C=null,T=null,E=null,D=!1,O=!1}function Ne(e){let t=e.data;if(t?.cmd===`released`&&t.buffer)try{L()?.releaseBuffer?.(t.buffer)}catch{}}function Pe(e){try{let t=e?.additionalData;if(!t||t.kind!==`ciderHostAudioRing`)return;let n=e.getBuffer();if(O=!1,!C){try{L()?.releaseBuffer?.(n)}catch{}return}C.port.postMessage({cmd:`ring`,buffer:n,controlInts:t.controlInts??y,dataByteOffset:t.dataByteOffset??we,capacityFrames:t.capacityFrames,channels:t.channels??2},[n]),D=!0,Z()}catch(e){console.warn(`[HostAudio] sharedbufferreceived handling failed`,e)}}async function Fe(){let e=I();if(!(!e||!C)){J(),Y(),await K();try{await e.SetSourceAvailable(!0)}catch(e){console.warn(`[HostAudio] SetSourceAvailable(true) failed`,e);return}if(U()!==`armed`){try{e.SetSourceAvailable(!1)}catch{}return}try{C.port.postMessage({cmd:`arm`})}catch{}k=!0,q(!0)}}function G(){try{C?.port.postMessage({cmd:`disarm`})}catch{}let e=I();Promise.resolve(e?.SetSourceAvailable(!1)).catch(()=>{}).finally(()=>{Ie()}),k=!1,q(!1)}async function K(){if(F)return;let e=V();if(!(!e||typeof e.setSinkId!=`function`))try{await e.setSinkId({type:`none`}),F=!0}catch(e){console.warn(`[HostAudio] setSinkId(silent) failed`,e)}}async function Ie(){if(!F)return;F=!1;let e=V();if(!(!e||typeof e.setSinkId!=`function`))try{let t=f().audio?.deviceOutput||`default`;await e.setSinkId(t)}catch(e){console.warn(`[HostAudio] restore setSinkId failed`,e)}}function q(e){if(!e){window.__hostAudioLatencyMs=0;return}let t=I();if(t)try{Promise.resolve(t.GetRenderLatencyMs()).then(e=>{let t=Number(e);window.__hostAudioLatencyMs=Number.isFinite(t)&&t>0?t:0}).catch(()=>{})}catch{}}function J(){let e=R(),t=I();if(!e||!t)return;let n=Oe(),r=Number(e.exclusive?.sampleRate)||0,i=Number(e.exclusive?.bitDepth)||0,a=`${n}:${r}:${i}`;if(a!==P)try{t.SetRenderMode(n,r,i),P=a}catch{}}function Y(){let e=R(),t=I();if(!e||!t)return;let n=Number(e.gainDb),r=Number.isFinite(n)?n:0;if(r!==N)try{t.SetGainDb(r),N=r}catch{}}async function X(){if(M)return;let e=R(),t=I();if(!t||!e||!B()){j&&(j=!1,Q());return}M=!0;try{let n=!!await Promise.resolve(t.IsAnyAppRunning(JSON.stringify(e.autoApps)));n!==j&&(j=n,Q())}catch{}finally{M=!1}}async function Z(){if(!A){A=!0;try{let e=I();if(!e)return;let t=U();if(t===`off`){if(k&&G(),W(),S){try{e.SetEnabled(!1)}catch{}S=!1}return}if(!S){try{e.SetEnabled(!0)}catch{}S=!0}let n=V(),r=H();if(!n||!r){k&&G();return}if(!await Me(n)||!C)return;if(Ae(r),!D){if(!O){O=!0;try{e.RequestRing()}catch{O=!1}}return}t===`armed`?k||await Fe():k&&G()}finally{A=!1}}}var Q=()=>{Z()};function Le(){if(x||!_(h())||me()!==`win32`)return;x=!0;try{L()?.addEventListener?.(`sharedbufferreceived`,Pe)}catch(e){console.warn(`[HostAudio] could not attach sharedbufferreceived listener`,e)}let e=f();t(()=>e.audio?.hostAudioCapture?.mode,()=>{J(),Q()}),t(()=>[e.audio?.hostAudioCapture?.exclusive?.sampleRate,e.audio?.hostAudioCapture?.exclusive?.bitDepth],()=>J()),t(()=>e.audio?.hostAudioCapture?.gainDb,()=>Y()),t(()=>[e.audio?.hostAudioCapture?.autoEnable,(e.audio?.hostAudioCapture?.autoApps??[]).join(`,`)],()=>{j=!1,X()});try{let e=i();t(()=>e.musicKitReady,Q),t(()=>e.videoMode,Q)}catch{}try{let e=s();t(()=>e.player.playbackState,Q)}catch{}try{window.addEventListener?.(`MKLite:audioPromoted`,Q)}catch{}try{d.subscribe?.(`ready`,Q)}catch{}setInterval(()=>{B()?X():j&&(j=!1,Q()),z()&&Q()},Te),X(),Q()}g(),l(),p(),u();var $=h(),Re=n(()=>{if(localStorage.getItem(`mk-disabled`)===`true`||te())return;m.init();let e=localStorage.getItem(`music.ampwebplay.media-user-token`),t=ae(),n=i(),r=se();async function a(){if(xe(),o(`MusicKit`,`boot:mklite-only`,`info`,`Setting up MKLite-only mode (skipping MusicKit.js)`),n.musicKitReady=!0,t.musicKitLoaded=!0,await m.getDeveloperToken(),n.setAuthorizedStatus(!0),ie.setTokens().catch(e=>{o(`MusicKit`,`boot:mklite-only`,`debug`,`Failed to hand tokens to the native host.`,e)}),await re().init(),c(`remote.enabled`)&&c(`remote.tunnelUUID`)!==``)try{let{apiTokens:e}=c(`connectivity`),{tunnelUUID:t}=c(`remote`);for(let n of e)if(n.method===`tunnel`){ue(`/tunnel/open`,{method:`POST`,body:JSON.stringify({id:t})}).then(()=>{o(`MusicKit`,`boot:mklite-only:remote`,`debug`,`Opened WAN tunnel!`,t)});break}}catch(e){o(`MusicKit`,`boot:mklite-only:remote`,`debug`,`Failed to open WAN tunnel.`,e)}switch($){case`dotnet`:case`naru`:await v();break;case`genten`:case`pixie`:await _e();break}ve(),Se(),ee(),_($)&&(he(!0),Le());let e=Number(localStorage.getItem(`volume`)||1);n.normalizedVolume=Math.min(Math.max(Number.isFinite(e)?e:1,0),1),o(`MusicKit`,`boot:mklite-only`,`info`,`MKLite-only setup complete.`)}window.__BUILDINFO__.IS_PE!==`true`&&(e&&m.isAuthorized()?(o(`MusicKit`,`boot`,`info`,`User has valid music user token, using MKLite-only mode`),a().catch(e=>{o(`MusicKit`,`boot`,`warn`,`MKLite-only setup failed`,e);try{r.reportAppleIssue(`Apple Music initialization failed`,e?.message??void 0,45e3)}catch{}})):o(`MusicKit`,`boot`,`info`,`No valid tokens`))});export{Re as default};