Initial Adaptive Music v0.5.0 release

This commit is contained in:
Jason committed 2026-12-03 16:11:47 -05:00
commit 14f0d8c26b
114 files changed
+6907

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
import {mountMusicAssignments} from './music-editor.mjs';
import { MusicError } from '../core/controller.mjs';
const namespace = 'adaptive-music';
const key = ref => JSON.stringify([ref?.provider, ref?.id]);
function validChoice(choice) {
return choice && ['native','ma'].includes(choice.provider) && typeof choice.id === 'string' &&
choice.id.length > 0 && choice.id.length <= 256 && typeof choice.name === 'string';
}
// Pass only owned native playlists and controller-authorized MA catalog choices.
// No gateway credential, endpoint or upstream URI belongs in this interface.
export async function savePlaylistConfiguration({ document, game, choices, selected }) {
if (!game.user?.isGM) throw new MusicError('denied');
const choice = selected === '' ? null : choices.find(c => validChoice(c) && key(c) === selected);
if (selected !== '' && !choice) throw new MusicError('denied');
const previous = document.getFlag(namespace, 'music') ?? {};
await document.setFlag(namespace, 'music', { ...previous,
playlist: choice ? { provider: choice.provider, id: choice.id } : null });
}
export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {} }) {
if (!game.user?.isGM || container.querySelector('[data-adaptive-music]')) return null;
if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError});
const dom = container.ownerDocument;
const panel = dom.createElement('fieldset'); panel.dataset.adaptiveMusic = 'configuration';
const legend = dom.createElement('legend'); legend.textContent = 'Adaptive Music'; panel.append(legend);
const label = dom.createElement('label'); label.append(dom.createTextNode('Music playlist '));
const select = dom.createElement('select'); label.append(select); panel.append(label);
const available = choices.filter(validChoice).map(c => ({provider:c.provider,id:c.id,name:c.name}));
const add = (value, text) => { const option = dom.createElement('option'); option.value = value; option.textContent = text; select.append(option); };
add('', 'Use the next applicable music rule');
for (const choice of available) add(key(choice), `${choice.provider === 'ma' ? 'Music Assistant' : 'Foundry'}: ${choice.name}`);
const current = document.getFlag(namespace, 'music')?.playlist;
if (current && !available.some(c => key(c) === key(current))) add(key(current), 'Previously selected playlist is unavailable');
select.value = current ? key(current) : '';
const note = dom.createElement('p'); note.textContent = 'Music Assistant playback requires a separately configured gateway; this development module uses Foundry playlists.'; panel.append(note);
const status = dom.createElement('p'); status.setAttribute('role','status'); panel.append(status);
const save = dom.createElement('button'); save.type = 'button'; save.textContent = 'Save music playlist'; panel.append(save);
let saving = false;
save.addEventListener('click', async () => {
if (saving) return;
saving = true; save.disabled = true;
try {
await savePlaylistConfiguration({document,game,choices:available,selected:select.value});
status.textContent = 'Music playlist saved.';
} catch (error) { status.textContent = 'Music playlist could not be saved.'; onError(new MusicError(error instanceof MusicError ? error.code : 'unavailable')); }
finally { saving = false; save.disabled = false; }
});
container.append(panel); return panel;
}
// Explicit development-only UI bootstrap. Importing this file registers nothing.
export function startConfigurationInterfaces({ game, Hooks, getChoices, onError = () => {} }) {
let disposed = false;
const panels = new Set();
const render = async (app, html) => {
if (!game.user?.isGM) return;
const container = html?.querySelector ? html : html?.[0];
const document = app.document;
if (!document || !container) return;
try {
const choices = await getChoices();
if (disposed) return;
const panel = mountPlaylistConfiguration({document,game,container,choices,onError});
if (panel) panels.add(panel);
} catch { onError(new MusicError('unavailable')); }
};
const hooks = ['renderSceneConfig','renderCombatConfig'].map(event => [event,Hooks.on(event, render)]);
return { dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); } };
}
+34
View File
@@ -0,0 +1,34 @@
import {MusicError} from '../core/controller.mjs';
// Gateway-terminated PCM test transport, NOT a Sendspin pass-through client.
export class ListenerAudio {
#context; #abort; #nodes=new Set(); #fetch;
constructor({fetchImpl=globalThis.fetch,createContext=()=>new AudioContext()}={}){this.#fetch=fetchImpl;this.createContext=createContext;}
async start(request){
const stopped=this.stop();const context=this.createContext();this.#context=context;
// Called directly from Enable Audio; retain the autoplay gesture before network work.
const resumed=context.resume();await stopped;await resumed;if(this.#context!==context)throw new MusicError('stale');const abort=new AbortController();this.#abort=abort;
try{
const response=await this.#fetch(request.url,{...request.options,signal:abort.signal});
if(!response.ok||response.headers.get('X-Audio-Format')!=='pcm16le;rate=24000;channels=2')throw new MusicError('denied');
const reader=response.body.getReader();let pending=new Uint8Array(),next=context.currentTime+0.06;
try{
while(true){const {value,done}=await reader.read();if(done)break;
if(value.length>65536)throw new MusicError('unavailable');
const bytes=new Uint8Array(pending.length+value.length);bytes.set(pending);bytes.set(value,pending.length);let offset=0;
while(offset+1920<=bytes.length){
if(this.#abort!==abort)throw new MusicError('stale');
if(next<context.currentTime)next=context.currentTime+0.02;
if(next-context.currentTime>0.25)throw new MusicError('unavailable');
const buffer=context.createBuffer(2,480,24000),view=new DataView(bytes.buffer,bytes.byteOffset+offset,1920);
for(let sample=0;sample<480;sample++)for(let channel=0;channel<2;channel++)buffer.getChannelData(channel)[sample]=view.getInt16((sample*2+channel)*2,true)/32768;
const node=context.createBufferSource();node.buffer=buffer;node.connect(context.destination);this.#nodes.add(node);node.onended=()=>this.#nodes.delete(node);node.start(next);next+=0.02;offset+=1920;
}
pending=bytes.slice(offset);
}
if(pending.length)throw new MusicError('unavailable');
}finally{await reader.cancel().catch(()=>{});reader.releaseLock();}
}catch(error){if(!abort.signal.aborted)throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
finally{if(this.#abort===abort)await this.stop();}
}
async stop(){this.#abort?.abort();this.#abort=null;for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();const context=this.#context;this.#context=null;if(context)await context.close();}
}
+61
View File
@@ -0,0 +1,61 @@
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';
import {PeerAudio} from '../audio/peer-audio.mjs';
import {ListenerAudio} from './listener-audio.mjs';
import {createSetupClass,createListenerClass} from './setup.mjs';
const id='adaptive-music';
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];
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);
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:gateway?.catalog??[])];
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);}
function listenWebRTC(invite){
if(game.user.isGM||!peers)throw Error('Listener only');
if(!remoteAudio){remoteAudio=document.createElement('audio');document.body.append(remoteAudio);}
remoteAudio.play().catch(()=>{});return peers.listen(invite);
}
function stopWebRTC(){peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
Hooks.once('init',()=>{
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)},
audio:{start:request=>audio.start(request),stop:()=>audio.stop()},getChoices:choices,start,stop,setOverrides,onError,canConnect:()=>!gmHost?.connected&&primaryGM(game.users)===game.user.id});
const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError});
game.settings.registerMenu(id,'listen',{name:'Campaign audio (development)',label:'Enable Audio',hint:'Private WebRTC invitation, or optional companion synthetic test.',icon:'fas fa-headphones',type:Listener,restricted:false});
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Native ownership, world/scene assignments, boss overrides, gateway and audio diagnostics.',icon:'fas fa-music',type:Setup,restricted:true});
}
});
Hooks.once('ready',()=>{
gmHost=new GMAudioHost({authority:gmAuthority});
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=>{if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}remoteAudio.srcObject=stream;remoteAudio.play().catch(onError);}});game.socket.on('disconnect',()=>{stop();gmHost.close();peers.reset();remoteAudio?.pause();});}
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
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(),
async closeGMHost(){stop();peers?.reset();await gmHost.close();},
async mountConfiguration(document,container){return mountPlaylistConfiguration({document,container,game,choices:await choices(),onError});},
enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(),
dispose(){stop();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;}
};
if(game.settings.get(id,'enabled'))start();
});
+48
View File
@@ -0,0 +1,48 @@
import {MusicError} from '../core/controller.mjs';
import {musicFields,referenceKey,selection} from '../core/scene-music.mjs';
const namespace='adaptive-music';
export async function saveMusicAssignments({document,game,choices,values,defaults=false}){
if(!game.user?.isGM||Object.keys(values).some(k=>!musicFields.includes(k)))throw new MusicError('denied');
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
const result={...previous};
for(const field of musicFields){
if(!Object.hasOwn(values,field))continue;
// Keep an unchanged offline catalog selection; never permit a forged new one.
if(values[field]===referenceKey(previous[field]) && previous[field]){if(field==='fallback'&&previous[field].provider!=='native')throw new MusicError('denied');result[field]={provider:previous[field].provider,id:previous[field].id};continue;}
result[field]=selection(values[field],choices,{nativeOnly:field==='fallback'});
}
if(defaults)await game.settings.set(namespace,'musicDefaults',result);else await document.setFlag(namespace,'music',result);
}
export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use world default / silence'}={}){
const select=dom.createElement('select');
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
add('',empty);
for(const c of choices.filter(c=>!nativeOnly||c.provider==='native'))add(referenceKey(c),`${c.provider==='ma'?'MA':'Foundry'}: ${c.name}`);
if(current&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
select.value=referenceKey(current);return select;
}
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
if(!game.user?.isGM)return null;
const dom=container.ownerDocument,panel=dom.createElement('fieldset');panel.dataset.adaptiveMusic='assignments';
const legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':'Scene music';panel.append(legend);
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
const labels={ambient:'Ambient music (base queue)',combat:'Combat music',boss:'Default boss music',fallback:'Native fallback when MA is unavailable'};
const controls={};
for(const field of musicFields){const label=dom.createElement('label');label.textContent=labels[field]+' ';const current=previous[field]??(field==='ambient'?previous.playlist:null);controls[field]=musicSelect(dom,choices,current,{nativeOnly:field==='fallback',empty:defaults?(field==='fallback'?'No native fallback':'No world default'):'Use world default / silence'});label.append(controls[field]);panel.append(label);}
const note=dom.createElement('p');note.textContent='One music layer: combat interrupts ambient music. Concurrent ambient layers and crossfade are not implemented. Native AmbientSound and effects remain separate.';panel.append(note);
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
const button=dom.createElement('button');button.type='button';button.textContent='Save assignments';panel.append(button);
button.addEventListener('click',async()=>{button.disabled=true;try{await saveMusicAssignments({document,game,choices,defaults,values:Object.fromEntries(musicFields.map(k=>[k,controls[k].value]))});status.textContent='Assignments saved.';}catch{status.textContent='Assignments could not be saved.';onError(new MusicError('denied'));}finally{button.disabled=false;}});
container.append(panel);return panel;
}
export function mountBossEditor({document,game,container,choices,onError=()=>{}}){
if(!game.user?.isGM)return null;
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),flag=document.getFlag(namespace,'music')??{};
const label=dom.createElement('label');label.textContent='Boss override ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=flag.boss===true;label.append(enabled);panel.append(label);
const priority=dom.createElement('input');priority.type='number';priority.value=String(flag.priority??0);priority.setAttribute('aria-label','Boss priority');panel.append(priority);
const inactive=dom.createElement('input');inactive.type='checkbox';inactive.checked=flag.inactive===true;const inactiveLabel=dom.createElement('label');inactiveLabel.textContent='Boss inactive ';inactiveLabel.append(inactive);panel.append(inactiveLabel);
const select=musicSelect(dom,choices,flag.playlist,{empty:'Use scene / world boss music'});select.setAttribute('aria-label','Boss playlist');panel.append(select);
const save=dom.createElement('button');save.type='button';save.textContent='Save boss override';panel.append(save);
save.addEventListener('click',async()=>{try{if(!game.user.isGM||!Number.isFinite(Number(priority.value)))throw new MusicError('denied');const previous=document.getFlag(namespace,'music')??{};const playlist=select.value===referenceKey(previous.playlist)?previous.playlist??null:selection(select.value,choices);await document.setFlag(namespace,'music',{...previous,boss:enabled.checked,inactive:inactive.checked,priority:Number(priority.value),playlist});}catch{onError(new MusicError('denied'));}});
container.append(panel);return panel;
}
+35
View File
@@ -0,0 +1,35 @@
import { MusicController } from '../core/controller.mjs';
import { buildMusicState } from '../core/scene-music.mjs';
import { NativeProvider } from '../providers/native/provider.mjs';
export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
// Explicit development bootstrap. No hooks or document mutations occur on import.
// All music configuration uses module-owned flags; no actor/system schema access.
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, onError = () => {} }) {
const flag = d => d?.getFlag('adaptive-music', 'music');
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) },
authority: () => game.ready && primaryGM(game.users) === game.user.id });
let overrides = [];
const refresh = () => {
if (!game.ready || primaryGM(game.users) !== game.user.id) return Promise.resolve();
const scene = [...game.scenes].find(s => s.active);
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
const state=buildMusicState({scene:scene&&{id:scene.id,music:flag(scene)},
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose,
combats:[...game.combats].map(c=>({id:c.id,sceneId:c.scene?.id??c.scene,active:c.active,started:c.started,playlist:flag(c)?.playlist,
bosses:[...c.combatants].map(b=>{const f=flag(b)??flag(b.token)??{};return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};})}))});
return controller.update(state);
};
if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null });
const events = ['updateScene', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'updateUser', 'deletePlaylist', 'deletePlaylistSound'];
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
return { controller, refresh,
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.generation++; controller.abort?.abort(); }
};
}
+66
View File
@@ -0,0 +1,66 @@
import {MusicError} from '../core/controller.mjs';
import {selection} from '../core/scene-music.mjs';
import {mountMusicAssignments,mountBossEditor,musicSelect} from './music-editor.mjs';
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicSetup extends Base {
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music setup'},position:{width:640,height:'auto'}};
async _renderHTML(){
if(!game.user.isGM)throw new MusicError('denied');
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
const text=value=>{const p=dom.createElement('p');p.textContent=value;root.append(p);return p;};
const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status');
const button=(label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw new MusicError('denied');await action();}catch(e){status.textContent=e?.code==='denied'?'Connection or selection denied. Check capability role/expiry, active GM, and native ownership.':e?.code==='stale'?'Controller lease changed. Reconnect with a fresh connection code.':'Gateway unavailable. Check the private same-origin route, TLS, companion process and target diagnostics. Native configuration can be used offline.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;};
const owned=new Set(game.settings.get('adaptive-music','ownedPlaylistIds').split(',').filter(Boolean));
const boxes=[];const ownedPanel=dom.createElement('fieldset');const legend=dom.createElement('legend');legend.textContent='Dedicated native music playlists';ownedPanel.append(legend);
for(const playlist of game.playlists){const label=dom.createElement('label'),input=dom.createElement('input');input.type='checkbox';input.checked=owned.has(playlist.id);label.textContent=playlist.name+' ';label.append(input);ownedPanel.append(label);boxes.push({id:playlist.id,input});}root.append(ownedPanel);
text('Opt in only dedicated music playlists. Do not select AmbientSound, effects or shared playlists. Saving ownership disables automation and requires a reload.');
button('Save native ownership',async()=>{stop();await game.settings.set('adaptive-music','enabled',false);await game.settings.set('adaptive-music','ownedPlaylistIds',boxes.filter(b=>b.input.checked).map(b=>b.id).join(','));status.textContent='Ownership saved. Reload this world before enabling automation.';});
const codeLabel=dom.createElement('label');codeLabel.textContent='Optional companion controller code (memory only; never an MA token) ';const code=dom.createElement('input');code.type='password';code.autocomplete='off';codeLabel.append(code);root.append(codeLabel);
text('Native playback requires no companion. The optional companion uses a private same-origin route. The module-only GM-host API uses private GM-local authentication; see INSTALL.md. Never share MA credentials with listeners.');
const diagnostics=text('Gateway disconnected. Owned native playlists work without it.');
const assignmentRoot=dom.createElement('div');
const show=()=>{const d=gateway.status;diagnostics.textContent=d?`Target: ${d.target}. Playback authorization: ${d.playbackEnabled?'enabled for approved test IDs':'disabled'}. Audio: ${d.audioSource} (test transport only). Sendspin receiver: unavailable. Crossfade: unavailable.`:'Gateway disconnected. Owned native fallback is available.';};
button('Connect and load MA catalog',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);show();await renderAssignments();});
button('Refresh connection diagnostics',async()=>{await gateway.refresh();show();await renderAssignments();});
button('Disconnect gateway',async()=>{await gateway.disconnect();show();status.textContent='Gateway disconnected. Existing MA playback, if any, is retained; automatic fallback cannot bypass an unreachable owned target.';});
const renderAssignments=async()=>{
assignmentRoot.replaceChildren();const choices=await getChoices();
mountMusicAssignments({game,container:assignmentRoot,choices,defaults:true,onError});
const sceneLabel=dom.createElement('label');sceneLabel.textContent='Scene ';const scenes=dom.createElement('select');
for(const scene of game.scenes){const option=dom.createElement('option');option.value=scene.id;option.textContent=scene.name;scenes.append(option);}sceneLabel.append(scenes);assignmentRoot.append(sceneLabel);
const scenePanel=dom.createElement('div');assignmentRoot.append(scenePanel);
const showScene=()=>{scenePanel.replaceChildren();const scene=game.scenes.get(scenes.value);if(scene)mountMusicAssignments({document:scene,game,container:scenePanel,choices,onError});};
const active=[...game.scenes].find(s=>s.active);if(active)scenes.value=active.id;scenes.addEventListener('change',showScene);showScene();
const bossLabel=dom.createElement('label');bossLabel.textContent='Boss combatant ';const bosses=dom.createElement('select'),documents=new Map();
for(const combat of game.combats)for(const combatant of combat.combatants){const option=dom.createElement('option');option.value=combat.id+':'+combatant.id;option.textContent=combatant.name??combatant.id;documents.set(option.value,combatant);bosses.append(option);}bossLabel.append(bosses);assignmentRoot.append(bossLabel);
const bossPanel=dom.createElement('div');assignmentRoot.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss();
const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');assignmentRoot.append(manual);
for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));assignmentRoot.append(b);}
};
await renderAssignments();root.append(assignmentRoot);
const enabledLabel=dom.createElement('label');enabledLabel.textContent='Enable music automation ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=game.settings.get('adaptive-music','enabled');enabledLabel.append(enabled);root.append(enabledLabel);
button('Apply automation setting',async()=>{await game.settings.set('adaptive-music','enabled',enabled.checked);if(enabled.checked)start();else stop();status.textContent=enabled.checked?'Automation enabled. MA assignments require authorized content; otherwise the configured native fallback is selected.':'Automation disabled; current playback is retained.';});
const listenerLabel=dom.createElement('label');listenerLabel.textContent='Separate listener connection code (memory only) ';const listener=dom.createElement('input');listener.type='password';listener.autocomplete='off';listenerLabel.append(listener);root.append(listenerLabel);
text('Enable Audio plays only the companion synthetic PCM test tone. It does not relay the MA DEV player or Sendspin audio. Crossfade is not available.');
// Start directly in the click task so AudioContext.resume retains user activation.
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable synthetic test audio';enable.addEventListener('click',()=>{try{const value=JSON.parse(listener.value);listener.value='';audio.start(gateway.audioRequest(value)).catch(onError);}catch{onError(new MusicError('denied'));}});root.append(enable);
button('Stop test audio',()=>audio.stop());show();return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
};
}
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,Base=globalThis.foundry.applications.api.ApplicationV2}){
return class AdaptiveMusicListener extends Base {
static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio (development)'},position:{width:480}};
async _renderHTML(){
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
const note=dom.createElement('p');note.textContent='Use a private GM WebRTC invitation, or an optional companion test code. No microphone or MA credentials are sent by players. GM-local MA audio remains experimental; never paste an MA token here.';root.append(note);
const label=dom.createElement('label');label.textContent='Listener connection code ';const input=dom.createElement('input');input.type='password';input.autocomplete='off';label.append(input);root.append(label);
const status=dom.createElement('p');status.setAttribute('role','status');root.append(status);
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable Audio';enable.addEventListener('click',()=>{try{const code=JSON.parse(input.value);input.value='';status.textContent='Connecting to campaign audio…';const task=code.transport==='webrtc-v1'?listenWebRTC(code):audio.start(gateway.audioRequest(code));Promise.resolve(task).then(()=>{status.textContent=code.transport==='webrtc-v1'?'Peer negotiation sent; waiting for GM media.':'Audio stopped.';}).catch(()=>{status.textContent='Audio unavailable. Check the private route, listener code and expiry.';onError(new MusicError('unavailable'));});}catch{status.textContent='Invalid listener code.';}});root.append(enable);
const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();});root.append(stop);return root;
}
_replaceHTML(result,content){content.replaceChildren(result);}
};
}