import{Ar as e,dr as t,sn as n}from"./vendor-Dcerr41Y.js";import{nt as r}from"./vendor-quasar-CU_esu6y.js";import{r as i,t as a}from"./TokenManager-ScrAtveA.js";import{$ as o,$i as ee,$r as te,Br as s,Dt as ne,Ir as c,Ki as re,Ot as ie,Q as l,Qr as ae,St as u,W as oe,Wi as se,Y as d,Yn as f,Zn as p,Zr as m,b as h,dt as ce,h as g,m as _,pt as le,qi as ue,ra as v,ta as de,ut as fe,x as y,xt as pe,y as b,zr as me}from"./ws-DjAvcWfg.js";import{f as he,p as ge,u as _e}from"./uiLogic-BTPJY3mm.js";import{n as ve}from"./genten-WA_8obfb.js";import{n as ye,t as be}from"./smart-playlist-store-U6zHlhLg.js";n(),i(),v(),re(),ae(),s(),f(),ne(),pe(),le(),fe(),d(),y(),_(),_e();function xe(){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 x=16,Se=x*4,Ce=2e3,we=new Set([`none`,`stopped`,`ended`,`completed`]),Te=12e3,S=null,C=!1,w=!1,T=null,E=null,D=null,O=null,k=!1,A=!1,j=!1,M=!1,N=!1,P=!1,F=null,I=null,L=!1;function R(){try{return window?.chrome?.webview?.hostObjects?.audioBridge??null}catch{return null}}function z(){try{return window?.chrome?.webview??null}catch{return null}}function B(){try{return b().audio?.hostAudioCapture??null}catch{return null}}function V(){let e=B();return e?e.mode===`exclusive`?!0:e.mode===`capture`?e.autoEnable?N:!0:!1:!1}function Ee(){return B()?.mode===`exclusive`?`exclusive`:`shared`}function H(){let e=B();return!!(e?.mode===`capture`&&e.autoEnable&&Array.isArray(e.autoApps)&&e.autoApps.length>0)}function U(){return window.ciderAudioContext??null}function De(){return window.middlewareNode??null}function Oe(){try{let e=c?.audioNodes;if(e&&e._safetyLimiter)return e._safetyLimiter}catch{}return De()}function ke(e){if(!(!T||O===e)){if(O)try{O.disconnect(T)}catch{}try{e.connect(T),O=e}catch(e){console.warn(`[HostAudio] tap connect failed`,e)}}}function Ae(){let e=``;try{e=String(u().player.playbackState||``)}catch{return!1}return we.has(e)?(S??=performance.now(),performance.now()-S>Te):(S=null,!1)}function je(){if(!V())return`off`;try{let e=g();if(!e?.musicKitReady||e?.videoMode||ie()?.player?.passthroughMode===!0)return`idle`}catch{return`idle`}return c?.castEnabled===!0||Ae()||!U()||!Oe()?`idle`:`armed`}async function Me(e){if(T&&D===e)return!0;Ne(),L=!1;try{if(E!==e){let t=xe(),n=URL.createObjectURL(new Blob([t],{type:`application/javascript`}));await e.audioWorklet.addModule(n),URL.revokeObjectURL(n),E=e}return T=new AudioWorkletNode(e,`cider-host-capture`,{numberOfInputs:1,numberOfOutputs:1,channelCount:2,channelCountMode:`explicit`,channelInterpretation:`speakers`}),T.port.onmessage=Pe,D=e,k=!1,!0}catch(e){return console.warn(`[HostAudio] worklet setup failed`,e),T=null,D=null,!1}}function Ne(){if(T){try{O&&O.disconnect(T)}catch{}try{T.disconnect()}catch{}try{T.port.postMessage({cmd:`release`})}catch{}T.port.onmessage=null}T=null,D=null,O=null,k=!1,A=!1}function Pe(e){let t=e.data;if(t?.cmd===`released`&&t.buffer)try{z()?.releaseBuffer?.(t.buffer)}catch{}}function Fe(e){try{let t=e?.additionalData;if(!t||t.kind!==`ciderHostAudioRing`)return;let n=e.getBuffer();if(A=!1,!T){try{z()?.releaseBuffer?.(n)}catch{}return}T.port.postMessage({cmd:`ring`,buffer:n,controlInts:t.controlInts??x,dataByteOffset:t.dataByteOffset??Se,capacityFrames:t.capacityFrames,channels:t.channels??2},[n]),k=!0,Ve()}catch(e){console.warn(`[HostAudio] sharedbufferreceived handling failed`,e)}}async function Ie(){let e=R();if(!(!e||!T)){G(),Be(),await Le();try{await e.SetSourceAvailable(!0)}catch(e){console.warn(`[HostAudio] SetSourceAvailable(true) failed`,e);return}if(je()!==`armed`){try{e.SetSourceAvailable(!1)}catch{}return}try{T.port.postMessage({cmd:`arm`})}catch{}j=!0,ze(!0)}}function W(){try{T?.port.postMessage({cmd:`disarm`})}catch{}let e=R();Promise.resolve(e?.SetSourceAvailable(!1)).catch(()=>{}).finally(()=>{Re()}),j=!1,ze(!1)}async function Le(){if(L)return;let e=U();if(!(!e||typeof e.setSinkId!=`function`))try{await e.setSinkId({type:`none`}),L=!0}catch(e){console.warn(`[HostAudio] setSinkId(silent) failed`,e)}}async function Re(){if(!L)return;L=!1;let e=U();if(!(!e||typeof e.setSinkId!=`function`))try{let t=b().audio?.deviceOutput||`default`;await e.setSinkId(t)}catch(e){console.warn(`[HostAudio] restore setSinkId failed`,e)}}function ze(e){if(!e){window.__hostAudioLatencyMs=0;return}let t=R();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 G(){let e=B(),t=R();if(!e||!t)return;let n=Ee(),r=Number(e.exclusive?.sampleRate)||0,i=Number(e.exclusive?.bitDepth)||0,a=`${n}:${r}:${i}`;if(a!==I)try{t.SetRenderMode(n,r,i),I=a}catch{}}function Be(){let e=B(),t=R();if(!e||!t)return;let n=Number(e.gainDb),r=Number.isFinite(n)?n:0;if(r!==F)try{t.SetGainDb(r),F=r}catch{}}async function K(){if(P)return;let e=B(),t=R();if(!t||!e||!H()){N&&(N=!1,q());return}P=!0;try{let n=!!await Promise.resolve(t.IsAnyAppRunning(JSON.stringify(e.autoApps)));n!==N&&(N=n,q())}catch{}finally{P=!1}}async function Ve(){if(!M){M=!0;try{let e=R();if(!e)return;let t=je();if(t===`off`){if(j&&W(),Ne(),w){try{e.SetEnabled(!1)}catch{}w=!1}return}if(!w){try{e.SetEnabled(!0)}catch{}w=!0}let n=U(),r=Oe();if(!n||!r){j&&W();return}if(!await Me(n)||!T)return;if(ke(r),!k){if(!A){A=!0;try{e.RequestRing()}catch{A=!1}}return}t===`armed`?j||await Ie():j&&W()}finally{M=!1}}}var q=()=>{Ve()};function He(){if(C||ee()!==`dotnet`||de()!==`win32`)return;C=!0;try{z()?.addEventListener?.(`sharedbufferreceived`,Fe)}catch(e){console.warn(`[HostAudio] could not attach sharedbufferreceived listener`,e)}let e=b();t(()=>e.audio?.hostAudioCapture?.mode,()=>{G(),q()}),t(()=>[e.audio?.hostAudioCapture?.exclusive?.sampleRate,e.audio?.hostAudioCapture?.exclusive?.bitDepth],()=>G()),t(()=>e.audio?.hostAudioCapture?.gainDb,()=>Be()),t(()=>[e.audio?.hostAudioCapture?.autoEnable,(e.audio?.hostAudioCapture?.autoApps??[]).join(`,`)],()=>{N=!1,K()});try{let e=g();t(()=>e.musicKitReady,q),t(()=>e.videoMode,q)}catch{}try{let e=u();t(()=>e.player.playbackState,q)}catch{}try{window.addEventListener?.(`MKLite:audioPromoted`,q)}catch{}try{c.subscribe?.(`ready`,q)}catch{}setInterval(()=>{H()?K():N&&(N=!1,q()),V()&&q()},Ce),K(),q()}y(),_(),be(),n();var Ue=p(),J=null;async function Y(e){if(localStorage.getItem(`mk-disabled`)!==`true`&&!oe(`no-mktasks-caching`))return J||(J=(async()=>{let e=g();try{await Promise.all([e.refreshPlaylists(),Ge().then(()=>Ke()),e.updatePinnedItems()])}catch(e){console.warn(`[MusicKit Task] background refresh task failed`,e)}try{await ye().refreshDue()}catch(e){console.warn(`[MusicKit Task] smart playlist refresh failed`,e)}})().finally(()=>{J=null}),J)}var X=null,Z=e(Date.now());function Q(){if(localStorage.getItem(`mk-disabled`)===`true`||X)return;let e=h(`appleMusic.backgroundRefreshTime`)??300;e<60&&(e=60),console.debug(`[MusicKit Task] Starting background refresh`),Date.now()-Z.value>300*1e3&&(console.debug(`[MusicKit Task] Running background refresh after window focus`),Y(),Z.value=Date.now()),X=setInterval(()=>{Ue.windowIsHidden||(console.debug(`[MusicKit Task] Running background refresh`),Y(),Z.value=Date.now())},e*1e3)}function We(){X&&=(console.debug(`[MusicKit Task] Stopping background refresh`),clearInterval(X),null)}t(()=>Ue.windowIsHidden,e=>{if(e){We();return}Q()});async function Ge(){console.debug(`[MusicKit Task] Getting social badging`);let e=g();e.socialBadges=(await m(`/v1/social/badging-map`)).data.results?.badgingMap??{}}async function Ke(){let e=g(),t=e.socialBadges,n=[...new Set(Object.values(t).flat())],r=Array(n.length),i=0,a=async()=>{for(let e=i++;e<n.length;e=i++){let t=n[e];try{r[e]=(await m(`/v1/social/$STOREFRONT/social-profiles/${t}`)).data.data[0]}catch(e){console.error(e)}}};await Promise.all(Array.from({length:Math.min(5,n.length)},()=>a()));let o=r.reduce((e,t)=>(t?.id&&(e[t.id]=t),e),{});try{let e=await m(`/v1/me/social-profile/`).then(e=>e.data.data[0]);o[e.id]=e}catch{}e.mergeSocialProfiles(o)}v(),y(),s(),f(),_(),d();var $=ee(),qe=r(()=>{if(localStorage.getItem(`mk-disabled`)===`true`||o())return;a.init();let e=localStorage.getItem(`music.ampwebplay.media-user-token`),t=p(),n=g(),r=te();async function i(){if(l(`MusicKit`,`boot:mklite-only`,`info`,`Setting up MKLite-only mode (skipping MusicKit.js)`),n.musicKitReady=!0,t.musicKitLoaded=!0,await a.getDeveloperToken(),n.setAuthorizedStatus(!0),se.setTokens(),await ce().init(),h(`remote.enabled`)&&h(`remote.tunnelUUID`)!==``)try{let{apiTokens:e}=h(`connectivity`),{tunnelUUID:t}=h(`remote`);for(let n of e)if(n.method===`tunnel`){ue(`/tunnel/open`,{method:`POST`,body:JSON.stringify({id:t})}).then(()=>{l(`MusicKit`,`boot:mklite-only:remote`,`debug`,`Opened WAN tunnel!`,t)});break}}catch(e){l(`MusicKit`,`boot:mklite-only:remote`,`debug`,`Failed to open WAN tunnel.`,e)}$===`dotnet`?await he():($===`genten`||$===`universal`)&&await ve(),Y(),Q(),me(),$===`dotnet`&&(ge(!0),He());let e=Number(localStorage.getItem(`volume`)||1);n.normalizedVolume=Math.min(Math.max(Number.isFinite(e)?e:1,0),1),l(`MusicKit`,`boot:mklite-only`,`info`,`MKLite-only setup complete.`)}window.__BUILDINFO__.IS_PE!==`true`&&(e&&a.isAuthorized()?(l(`MusicKit`,`boot`,`info`,`User has valid music user token, using MKLite-only mode`),i().catch(e=>{l(`MusicKit`,`boot`,`warn`,`MKLite-only setup failed`,e);try{r.reportAppleIssue(`Apple Music initialization failed`,e?.message??void 0,45e3)}catch{}})):l(`MusicKit`,`boot`,`info`,`No valid tokens`))});export{qe as default};