2026-12-03 16:11:47 -05:00
import { startNativeRuntime , primaryGM } from './runtime.mjs' ;
import { startConfigurationInterfaces , mountPlaylistConfiguration } from './configuration.mjs' ;
import { GatewayClient } from '../providers/ma/remote.mjs' ;
import { GMAudioHost } from '../audio/gm-host.mjs' ;
2026-12-03 20:11:10 -05:00
import { AutoListeners } from '../audio/auto-listeners.mjs' ;
2026-12-03 16:11:47 -05:00
import { PeerAudio } from '../audio/peer-audio.mjs' ;
import { ListenerAudio } from './listener-audio.mjs' ;
import { createSetupClass , createListenerClass } from './setup.mjs' ;
const id = 'adaptive-music' ;
2026-12-03 20:11:10 -05:00
let runtime , interfaces , gateway , audio , renewTimer , gmHost , peers , remoteAudio ; let authorityHooks = []; let bootstrap , privateProfile , inviteTimer , latestInvite , listenerStopped = false , listenerState = 'Waiting for GM audio.' , inviteTail = Promise . resolve (); const sentInvites = new Map (); let connectionGeneration = 0 ; let listenerContext , listenerSource ;
2026-12-03 16:11:47 -05:00
const gmAuthority = ()=> game . ready && game . user . isGM && primaryGM ( game . users ) === game . user . id && [... game . users ]. filter ( u => u . active && u . isGM ). length === 1 && game . socket ? . connected === true ;
const owned = ()=> game . settings . get ( id , 'ownedPlaylistIds' ). split ( ',' ). map ( s => s . trim ()). filter ( Boolean );
2026-12-03 20:11:10 -05:00
const choices = async ()=>[...[... game . playlists ]. filter ( p => owned (). includes ( p . id )). map ( p =>({ provider : 'native' , id : p . id , name : p . name })),...( gmHost ? . catalog . length ? gmHost . catalog . filter ( c => c . kind === 'playlist' || c . kind === 'sequence' ) : gateway ? . catalog ?? [])];
2026-12-03 16:11:47 -05:00
const onError = ()=> ui . notifications . warn ( 'Adaptive Music could not complete the operation. Open Adaptive Music setup for connection diagnostics and ownership checks.' );
function start (){
if ( ! game . user . isGM || runtime ) return ;
runtime = startNativeRuntime ({ game , Hooks , campaign : game . world . id , session : gmHost ? . connected ? gmHost . session : globalThis . crypto . randomUUID (), ownedPlaylistIds : owned (), maProvider : gmHost ? . connected ? gmHost : gateway , onError });
runtime . refresh (). catch ( onError );
}
function stop (){ runtime ? . dispose (); runtime = null ;}
function setOverrides ( value ){ if ( ! runtime ) throw Error ( 'Automation is disabled' ); return runtime . setOverrides ( value );}
2026-12-03 20:11:10 -05:00
function ensureRemoteAudio (){ if ( ! remoteAudio ){ remoteAudio = document . createElement ( 'audio' ); remoteAudio . autoplay = true ; document . body . append ( remoteAudio );} return remoteAudio ;}
function attachListenerSource ( stream ){ listenerSource ? . disconnect (); if ( listenerContext ){ listenerSource = listenerContext . createMediaStreamSource ( stream ); listenerSource . connect ( listenerContext . destination ); remoteAudio . muted = true ;}}
function resumeListener (){ if ( game . user . isGM ) return gmHost . resumeAudio (); listenerStopped = false ; const element = ensureRemoteAudio (); let resumed = Promise . resolve (); if ( globalThis . AudioContext ){ listenerContext ??= new AudioContext (); resumed = listenerContext . resume (); if ( element . srcObject ) attachListenerSource ( element . srcObject );} const play = element . play (); play . catch (()=>{}); if ( ! peers . diagnostics (). peers . length ) bootstrap ? . start (). catch ( onError ); return resumed . then (()=>{ listenerState = element . srcObject ? 'Campaign audio enabled.' : 'Audio enabled. Waiting for GM audio.' ;});}
function sendInvites (){
inviteTail = inviteTail . catch (()=>{}). then ( async ()=>{
if ( ! bootstrap ||! gmHost ? . connected ||! gmAuthority ()) return ;
for ( const user of game . users ){
if ( ! user . active || user . isGM || user . isBanned ) continue ; const key = bootstrap . recipientKey ( user ); if ( ! key ) continue ;
const previous = sentInvites . get ( user . id ); if ( previous ? . epoch === key . epoch && previous . until > Date . now () && peers . hasListener ( user . id )) continue ;
try { const invite = peers . invite ( user . id ,{ ttlMs : 1800000 ,...( privateProfile ? . listenerNetwork ?? {})}); await bootstrap . send ( user , invite ); sentInvites . set ( user . id ,{ epoch : key . epoch , until : Date . now () + 1200000 });} catch { onError ();}
}
}); return inviteTail ;
}
const connection = {
get status (){ return {...( gmHost ? . status ?? { state : 'disconnected' , catalog : 0 , audioContext : 'closed' }), selectedTarget : privateProfile ? . target , selectedName : privateProfile ? . targetName , peers : peers ? . diagnostics (). peers . filter ( p => p . connection === 'connected' ). length ?? 0 };},
async test ( profile ){ if ( gmHost . connected || gmHost . status . state === 'connecting' || gateway . connected ) throw { code : 'denied' }; stop (); const generation =++ connectionGeneration ; const old = privateProfile ; privateProfile = null ; await gmHost . close (); const candidate = {... old ,... profile , token : profile . token || old ? . token , identityStorage : profile . identityStorage ? .[ 'sendspin-identity-sk' ] ? profile . identityStorage : old ? . identityStorage , campaign : game . world . id }; const result = await gmHost . inspect ( candidate ); await gmHost . readCatalog ( result ,{ reconnecting : true }); if ( generation !== connectionGeneration ) throw { code : 'stale' }; privateProfile = result ; return { target : result . target , targetName : result . targetName };},
async connect ( target ){ if ( ! privateProfile || target !== privateProfile . target || gateway . connected ) throw { code : 'denied' }; stop (); const pending = gmHost . start ( privateProfile ); await pending ; peers . setSource ( gmHost . stream ); sentInvites . clear (); await sendInvites (); if ( game . settings . get ( id , 'enabled' )) start ();},
refresh : ()=> gmHost . refreshCatalog (), resume : ()=> gmHost . resumeAudio (),
async disconnect (){ connectionGeneration ++ ; stop (); peers ? . reset (); sentInvites . clear (); privateProfile = null ; await gmHost . close ();}
};
2026-12-03 16:11:47 -05:00
function listenWebRTC ( invite ){
if ( game . user . isGM ||! peers ) throw Error ( 'Listener only' );
2026-12-03 20:11:10 -05:00
ensureRemoteAudio (). play (). catch (()=>{}); listenerState = 'Connecting to GM audio…' ; return peers . listen ( invite );
2026-12-03 16:11:47 -05:00
}
2026-12-03 20:11:10 -05:00
function stopWebRTC (){ listenerStopped = true ; listenerState = 'Audio stopped.' ; listenerSource ? . disconnect (); listenerSource = null ; listenerContext ? . suspend (); peers ? . reset (); remoteAudio ? . pause (); if ( remoteAudio ) remoteAudio . srcObject = null ;}
2026-12-03 16:11:47 -05:00
Hooks . once ( 'init' ,()=>{
2026-12-03 20:11:10 -05:00
game . settings . register ( id , 'advancedDevelopment' ,{ name : 'Show advanced development controls' , hint : 'Optional companion and manual test capabilities. Not needed for normal music setup.' , scope : 'client' , config : true , type : Boolean , default : false });
2026-12-03 16:11:47 -05:00
game . settings . register ( id , 'enabled' ,{ name : 'Enable music automation' , hint : 'Configure through Adaptive Music setup. Defaults off.' , scope : 'world' , config : false , type : Boolean , default : false });
game . settings . register ( id , 'ownedPlaylistIds' ,{ scope : 'world' , config : false , type : String , default : '' , requiresReload : true });
game . settings . register ( id , 'musicDefaults' ,{ scope : 'world' , config : false , type : Object , default : {}});
if ( game . settings . registerMenu ){
// The factory reads live module state when the settings menu is rendered.
const Setup = createSetupClass ({ game , gateway : { get status (){ return gateway ? . status ;}, connect : async code =>{ if ( gmHost ? . connected ) throw Error ( 'Disconnect GM host first' ); const result = await gateway . connect ( code ); await runtime ? . refresh (); return result ;}, refresh : ()=> gateway . refresh (), disconnect : ()=> gateway . disconnect (), audioRequest : code => gateway . audioRequest ( code )},
2026-12-03 20:11:10 -05:00
audio : { start : request => audio . start ( request ), stop : ()=> audio . stop ()}, getChoices : choices , start , stop , setOverrides , onError , canConnect : ()=> ! gmHost ? . connected && primaryGM ( game . users ) === game . user . id , connection });
const Listener = createListenerClass ({ game , gateway : { audioRequest : code => gateway . audioRequest ( code )}, audio : { start : request => audio . start ( request ), stop : ()=> audio . stop ()}, listenWebRTC , stopWebRTC , onError , resumeListener , listenerStatus : ()=> listenerState });
game . settings . registerMenu ( id , 'listen' ,{ name : 'Campaign audio' , label : 'Enable Audio' , hint : 'Connects automatically to GM audio. Enable sound if your browser asks.' , icon : 'fas fa-headphones' , type : Listener , restricted : false });
game . settings . registerMenu ( id , 'setup' ,{ name : 'Adaptive Music setup' , label : 'Configure music' , hint : 'Music Assistant connection, scene music and Foundry fallback.' , icon : 'fas fa-music' , type : Setup , restricted : true });
2026-12-03 16:11:47 -05:00
}
});
Hooks . once ( 'ready' ,()=>{
2026-12-03 20:11:10 -05:00
gmHost = new GMAudioHost ({ authority : gmAuthority , onDisconnect : ()=>{ stop (); peers ? . reset (); sentInvites . clear (); onError ();}});
if ( game . socket ){ peers = new PeerAudio ({ socket : game . socket , userId : game . user . id , isGM : gmAuthority , isAuthorizedUser : id =>{ const user = game . users . get ( id ); return user ? . active &&! user . isGM &&! user . isBanned ;}, onError , onStream : stream =>{ ensureRemoteAudio (). srcObject = stream ; attachListenerSource ( stream );( listenerContext ? . state === 'running' ? Promise . resolve () : remoteAudio . play ()). then (()=>{ listenerState = 'Campaign audio connected.' ;}). catch (()=>{ listenerState = 'GM audio connected. Select Enable Audio to allow sound.' ; ui . notifications . info ( 'Adaptive Music: open Campaign audio and select Enable Audio to allow sound.' );});}}); game . socket . on ( 'disconnect' ,()=>{ stop (); privateProfile = null ; gmHost . close (); peers . reset (); sentInvites . clear (); latestInvite = null ; listenerState = 'Foundry disconnected. Waiting for the GM to reconnect.' ; remoteAudio ? . pause ();});}
if ( game . socket ) authorityHooks = [ 'updateUser' , 'deleteUser' ]. map ( event =>[ event , Hooks . on ( event ,()=>{ peers . reconcile (); if ( ! game . user . isGM && [... game . users ]. filter ( u => u . active && u . isGM ). length !== 1 ){ peers . reset (); remoteAudio ? . pause (); latestInvite = null ; listenerState = 'Waiting for one active GM.' ;} sendInvites (); if ( gmHost . connected &&! gmAuthority ()){ stop (); gmHost . close (); peers . reset (); remoteAudio ? . pause ();}})]);
if ( game . socket && game . user . setFlag ){ bootstrap = new AutoListeners ({ game , isGM : gmAuthority , onInvite : async invite =>{ latestInvite = invite ; if ( listenerStopped ) return ; peers . reset (); await listenWebRTC ( invite );}}); bootstrap . start (). then ( sendInvites ). catch ( onError ); inviteTimer = setInterval (()=>{ sendInvites (); if ( game . user . isGM && runtime &&! gmHost . connected && privateProfile ){ stop (); peers . reset (); sentInvites . clear (); onError ();}}, 15000 );}
2026-12-03 16:11:47 -05:00
gateway = new GatewayClient ({ origin : globalThis . location ? . origin ?? 'http://localhost' }); audio = new ListenerAudio ();
if ( game . user . isGM ){ interfaces = startConfigurationInterfaces ({ game , Hooks , getChoices : choices , onError }); renewTimer = setInterval (()=>{ if ( gateway . connected && primaryGM ( game . users ) === game . user . id ) gateway . renew (). catch ( onError );}, 10000 );}
game . modules . get ( id ). api = {
startDevelopment : start , stopDevelopment : stop , setOverrides ,
async connectGateway ( code ){ if ( ! game . user . isGM || primaryGM ( game . users ) !== game . user . id || gmHost ? . connected ) throw Error ( 'Controller unavailable' ); const result = await gateway . connect ( code ); await runtime ? . refresh (); return result ;},
gatewayDiagnostics : ()=> gateway . status ,
async readGMCatalog ( profile ){ if ( runtime || gateway . connected ) throw Error ( 'Stop automation and disconnect optional companion first' ); return gmHost . readCatalog ({... profile , campaign : game . world . id });},
async startGMHost ( profile ){ if ( runtime || gateway . connected ) throw Error ( 'Stop automation and disconnect optional companion first' ); const result = await gmHost . start ({... profile , campaign : game . world . id }); peers . setSource ( gmHost . stream ); return result ;},
inviteListener : ( userId , options )=> peers . invite ( userId , options ),
listenWebRTC ,
peerStats : ()=> peers . stats (),
2026-12-03 20:11:10 -05:00
async closeGMHost (){ await connection . disconnect ();},
2026-12-03 16:11:47 -05:00
async mountConfiguration ( document , container ){ return mountPlaylistConfiguration ({ document , container , game , choices : await choices (), onError });},
enableAudio ( code ){ return audio . start ( gateway . audioRequest ( code ));}, stopAudio : ()=> audio . stop (),
2026-12-03 20:11:10 -05:00
dispose (){ stop (); listenerSource ? . disconnect (); listenerContext ? . close (); privateProfile = null ; bootstrap ? . close (); clearInterval ( inviteTimer ); for ( const [ event , hook ] of authorityHooks ) Hooks . off ( event , hook ); authorityHooks = []; interfaces ? . dispose (); clearInterval ( renewTimer ); gateway . disconnect (); audio . stop (); gmHost ? . close (); peers ? . close (); remoteAudio ? . pause (); remoteAudio ? . remove (); interfaces = null ;}
2026-12-03 16:11:47 -05:00
};
if ( game . settings . get ( id , 'enabled' )) start ();
});