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

+90
View File
@@ -0,0 +1,90 @@
import {MusicError} from '../core/controller.mjs';
import {MAReadClient} from '../providers/ma/client.mjs';
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
import {randomKey} from '../providers/ma/webcrypto.mjs';
export function gmAccessPolicy(baseUrl,pageUrl){
const target=new URL(baseUrl),page=new URL(pageUrl);
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
if(page.protocol==='https:'&&target.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(target.hostname))throw new MusicError('mixed-content');
return target;
}
function memoryStorage(values){const map=new Map(Object.entries(values));return {getItem:k=>map.get(k)??null,setItem:(k,v)=>map.set(k,v),removeItem:k=>map.delete(k)};}
export class GMAudioHost{
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock;
constructor({authority,pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
get catalog(){return structuredClone(this.#catalog);}
get session(){return this.#session;}
get stream(){return this.#destination?.stream;}
get connected(){return this.#live;}
supports(ref){return this.#live&&this.#allowed.has(ref.id);}
async readCatalog(profile,{reconnecting=false}={}){
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||profile.targetName!=='Adaptive Music DEV')throw new MusicError('denied');
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();return this.catalog;
}
async start(profile){
if(!this.#authority()||this.#live)throw new MusicError('denied');
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
if(profile.targetName!=='Adaptive Music DEV'||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
// Unlock synchronously in the caller's gesture before SDK/network work.
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
try{
this.#sdk=await this.loadSDK();await unlocked;
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
// Never register a fresh identity or silently select a new/household player.
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32)throw new MusicError('denied');
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join('');
const released=new Promise(resolve=>{this.#releaseLock=resolve;});
await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));});
await this.readCatalog(profile,{reconnecting:true});
const original=await this.#client.queueState({allowUnavailable:true});
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
if(profile.allowSyntheticPlayback===true){
for(const id of Object.keys(profile.syntheticSequences??{})){if(!['synthetic-ambient','synthetic-combat'].includes(id))throw new MusicError('denied');this.#allowed.add(id);}
this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'})));
}
let volumeState=this.#client.targetVolumeState();
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:250,minBufferMs:250,useHardwareVolume:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}});
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);
this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
this.#core.onAudioData=chunk=>this.#schedule(chunk);
this.#core.onConnectionClose=()=>{this.#live=false;this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
this.#session=crypto.randomUUID();this.#live=true;
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
await this.#core.connect();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
}catch(error){await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
}
#authenticatedSocket(base,token,clientId){
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
const fail=()=>{clearTimeout(timer);socket.close();reject(new MusicError('unavailable'));};socket.onerror=fail;socket.onclose=fail;
socket.onopen=()=>socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));
socket.onmessage=event=>{try{if(JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);socket.onerror=null;socket.onclose=null;socket.onmessage=null;resolve(socket);}catch{fail();}};
});
}
#schedule(chunk){
if(!this.#live||!this.#authority()){this.#clear();return;}
if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return;
const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return;
if(chunk.generation!==this.#generation){this.#clear();this.#generation=chunk.generation;}
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
if(!Number.isFinite(lead)||lead>2||lead+frames/chunk.sampleRate<0||this.#nodes.size>=128)return;
const buffer=this.#context.createBuffer(chunk.samples.length,frames,chunk.sampleRate);chunk.samples.forEach((samples,i)=>buffer.getChannelData(i).set(samples));
const node=this.#context.createBufferSource();node.buffer=buffer;node.connect(this.#gain);this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);node.onended=()=>this.#nodes.delete(node);this.#nodes.add(node);node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));
}
#clear(){for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();}
#ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;}
resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
snapshot(ctx){return this.#ready().snapshot(ctx);}
apply(prepared,ctx){return this.#ready().apply(prepared,ctx);}
restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);}
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
async close(){this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
}
+79
View File
@@ -0,0 +1,79 @@
import {MusicError} from '../core/controller.mjs';
import {SignalCodec,newAudioInvite} from './signal-codec.mjs';
export function validateIceServers(servers){
if(!Array.isArray(servers)||servers.length>4)throw new MusicError('denied');
for(const server of servers){
const urls=Array.isArray(server.urls)?server.urls:[server.urls];
if(!urls.length||urls.length>4||urls.some(u=>typeof u!=='string'||!/^(stun|stuns|turn|turns):[^\s@]+$/.test(u)))throw new MusicError('denied');
if(urls.some(u=>/^turns?:/.test(u))&&(!server.username||!server.credential||!Number.isFinite(server.expires)||server.expires<=Date.now()||server.expires>Date.now()+3600000))throw new MusicError('denied');
}
return servers.map(({urls,username,credential})=>({urls,...(username?{username,credential}:{})}));
}
function audioOnly(sdp,remote){
if(typeof sdp!=='string'||sdp.length>65536)throw new MusicError('denied');
const media=sdp.split(/\r?\n/).filter(line=>line.startsWith('m='));
if(media.length!==1||!media[0].startsWith('m=audio ')||/a=sendrecv|a=sendonly/.test(sdp)&&remote==='answer')throw new MusicError('denied');
}
async function gathered(pc){
if(pc.iceGatheringState==='complete')return;
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pc.removeEventListener('icegatheringstatechange',check);reject(new MusicError('unavailable'));},5000);const check=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(timer);pc.removeEventListener('icegatheringstatechange',check);resolve();}};pc.addEventListener('icegatheringstatechange',check);check();});
}
export class PeerAudio{
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0;
constructor({socket,userId,isGM,isAuthorizedUser=()=>true,onStream=()=>{},onError=()=>{},createPeer=config=>new RTCPeerConnection(config)}){
this.#socket=socket;this.#userId=userId;this.#isGM=isGM;this.authorized=isAuthorizedUser;this.#create=createPeer;this.#onStream=onStream;this.#onError=onError;
this.#handler=frame=>{this.#receive(frame).catch(()=>{this.#rejected++;});};this.#disconnect=()=>this.reset();
socket.on('module.adaptive-music',this.#handler);socket.on('disconnect',this.#disconnect);
}
setSource(stream){if(!this.#isGM()||stream.getAudioTracks().length!==1)throw new MusicError('denied');this.#stream=stream;}
invite(userId,{iceServers=[],ttlMs=300000,relayOnly=false}={}){
if(!this.#isGM()||!this.authorized(userId)||!this.#stream||this.#peers.size>=8)throw new MusicError('denied');validateIceServers(iceServers);
const invite=newAudioInvite({session:this.#session,userId,iceServers,ttlMs,relayOnly});this.#entry(invite,'gm');return invite;
}
async listen(invite){
if(this.#isGM()||invite.userId!==this.#userId||this.#peers.size)throw new MusicError('denied');
const entry=this.#entry(invite,'listener');
// Listener sends only a recvonly offer. No microphone or control/data channel.
entry.pc.addTransceiver('audio',{direction:'recvonly'});
await entry.pc.setLocalDescription(await entry.pc.createOffer());await gathered(entry.pc);
await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});
}
#entry(invite,role){
const iceServers=validateIceServers(invite.iceServers??[]);
if(invite.relayOnly&&!iceServers.some(s=>(Array.isArray(s.urls)?s.urls:[s.urls]).some(url=>/^turns?:/.test(url))))throw new MusicError('denied');
const codec=new SignalCodec(invite,role); // Validate before allocating a browser connection.
const pc=this.#create({iceServers,iceTransportPolicy:invite.relayOnly?'relay':'all'}),entry={invite:structuredClone(invite),role,pc,codec,tail:Promise.resolve(),restarts:0,pending:0,signals:0};
entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now()));
pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));};
pc.ondatachannel=event=>event.channel.close();
pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}};
this.#peers.set(invite.peer,entry);return entry;
}
async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);}
async #receive(frame){
const entry=this.#peers.get(frame?.peer);if(!entry||frame.session!==entry.invite.session)return;
if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++;
entry.tail=entry.tail.catch(()=>{}).then(async()=>{
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
const payload=await entry.codec.open(frame);
if(payload.type==='bye'){this.revoke(frame.peer);return;}
if(entry.role==='gm'&&payload.type==='offer'){
// The listener's SDP is recvonly: reject video, data, injected outbound audio.
audioOnly(payload.sdp,'answer');
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc);
await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
}else if(entry.role==='listener'&&payload.type==='answer'){
audioOnly(payload.sdp,'offer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
}else throw new MusicError('denied');
});return entry.tail.finally(()=>{entry.pending--;});
}
async restart(peer){const entry=this.#peers.get(peer);if(!entry||entry.role!=='listener'||++entry.restarts>2)throw new MusicError('denied');await entry.pc.setLocalDescription(await entry.pc.createOffer({iceRestart:true}));await gathered(entry.pc);await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});}
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
reset(){for(const peer of [...this.#peers.keys()])this.revoke(peer);this.#stream=null;this.#session=crypto.randomUUID();}
close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);}
reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);}
diagnostics(){return {rejectedSignals:this.#rejected,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState}))};}
async stats(){const results=[];for(const entry of this.#peers.values()){const stats=await entry.pc.getStats();for(const item of stats.values())if(['inbound-rtp','outbound-rtp','candidate-pair'].includes(item.type))results.push({type:item.type,bytesSent:item.bytesSent,bytesReceived:item.bytesReceived,jitter:item.jitter,packetsLost:item.packetsLost,audioLevel:item.audioLevel,totalAudioEnergy:item.totalAudioEnergy,totalSamplesReceived:item.totalSamplesReceived,currentRoundTripTime:item.currentRoundTripTime});}return results;}
}
+33
View File
@@ -0,0 +1,33 @@
import {MusicError} from '../core/controller.mjs';
const encode=bytes=>btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
const decode=value=>{if(typeof value!=='string'||!/^[A-Za-z0-9_-]+$/.test(value))throw new MusicError('denied');return Uint8Array.from(atob(value.replace(/-/g,'+').replace(/_/g,'/')),c=>c.charCodeAt(0));};
export function newAudioInvite({session,userId,ttlMs=300000,iceServers=[],relayOnly=false}){
if(!session||!userId||!(ttlMs>0&&ttlMs<=1800000))throw new MusicError('denied');
return {transport:'webrtc-v1',session,peer:crypto.randomUUID(),userId,secret:encode(crypto.getRandomValues(new Uint8Array(32))),expires:Date.now()+ttlMs,relayOnly,iceServers:structuredClone(iceServers)};
}
// Module sockets carry only encrypted SDP/ICE control envelopes, never audio or MA credentials.
export class SignalCodec{
#invite;#key;#sent=0;#received=0;#role;
constructor(invite,role){
if(!invite||invite.transport!=='webrtc-v1'||!['gm','listener'].includes(role)||typeof invite.session!=='string'||typeof invite.peer!=='string'||!Number.isFinite(invite.expires)||invite.expires<=Date.now()||invite.expires>Date.now()+1800000||decode(invite.secret).length!==32)throw new MusicError('denied');
this.#invite=structuredClone(invite);this.#role=role;this.#key=crypto.subtle.importKey('raw',decode(invite.secret),'AES-GCM',false,['encrypt','decrypt']);
}
async seal(payload){
if(Date.now()>=this.#invite.expires||this.#sent>=1000||!['offer','answer','bye'].includes(payload?.type)||Object.keys(payload).some(k=>!['type','sdp'].includes(k))||payload.type!=='bye'&&(typeof payload.sdp!=='string'||payload.sdp.length>65536))throw new MusicError('denied');
const frame={v:1,session:this.#invite.session,peer:this.#invite.peer,from:this.#role,seq:++this.#sent};
const plain=new TextEncoder().encode(JSON.stringify(payload));if(plain.length>65536)throw new MusicError('denied');
const iv=crypto.getRandomValues(new Uint8Array(12)),cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(JSON.stringify(frame))},await this.#key,plain);
return {...frame,iv:encode(iv),cipher:encode(new Uint8Array(cipher))};
}
async open(frame){
if(!frame||Object.keys(frame).sort().join(',')!=='cipher,from,iv,peer,seq,session,v'||frame.v!==1||frame.session!==this.#invite.session||frame.peer!==this.#invite.peer||frame.from==this.#role||!['gm','listener'].includes(frame.from)||!Number.isSafeInteger(frame.seq)||frame.seq<=this.#received||frame.seq>1000||typeof frame.cipher!=='string'||frame.cipher.length>88000||Date.now()>=this.#invite.expires)throw new MusicError('denied');
try{
const {iv,cipher,...header}=frame;const nonce=decode(iv);if(nonce.length!==12)throw Error();
const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:nonce,additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key,decode(cipher));
const payload=JSON.parse(new TextDecoder().decode(bytes));
if(!['offer','answer','bye'].includes(payload?.type)||Object.keys(payload).some(k=>!['type','sdp'].includes(k))||payload.type!=='bye'&&(typeof payload.sdp!=='string'||payload.sdp.length>65536))throw Error();
if(Date.now()>=this.#invite.expires||frame.seq<=this.#received)throw Error();
this.#received=frame.seq;return payload;
}catch{throw new MusicError('denied');}
}
}
+82
View File
@@ -0,0 +1,82 @@
// Independent implementation informed by VGM release-1.4.5; see THIRD-PARTY-NOTICES.
export class MusicError extends Error {
constructor(code) { super(code); this.code = code; }
}
export function candidates(state) {
const scene = state.scene;
const combats = (state.combats ?? []).filter(c => c.active && c.started && c.sceneId === scene?.id);
const bosses = combats.flatMap(c => c.bosses ?? []).filter(b => b.active && b.playlist)
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id));
const make = (key, playlist) => ({ key, playlist: playlist ?? null });
return [
...(state.overrides ?? []).slice().reverse().map(o => make(`manual:${o.id}`, o.playlist)),
...bosses.map(b => make(`boss:${scene.id}:${b.id}`, b.playlist)),
...combats.filter(c => c.playlist).sort((a,b) => a.id.localeCompare(b.id))
.map(c => make(`combat:${scene.id}:${c.id}`, c.playlist)),
...(scene?.playlist ? [make(`scene:${scene.id}`, scene.playlist)] : []),
make('default', state.defaultPlaylist)
].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` }));
}
export class MusicController {
constructor({ campaign, session, providers, authority, maxFrames = 16 }) {
Object.assign(this, { campaign, session, providers, authority, maxFrames });
this.dirty = new Set();
this.generation = 0; this.frames = []; this.current = null; this.tail = Promise.resolve();
}
update(state) {
const input = structuredClone(state);
const generation = ++this.generation;
this.abort?.abort(); this.abort = new AbortController();
const context = { campaign: this.campaign, session: this.session, generation,
signal: this.abort.signal, check: () => {
if (generation !== this.generation || !this.authority()) throw new MusicError('stale');
} };
const task = this.tail.catch(() => {}).then(() => this.transition(input, context));
this.tail = task; return task;
}
async transition(state, ctx) {
ctx.check();
const choices = candidates(state), next = choices[0];
const valid = new Set(choices.map(i => i.key));
this.frames = this.frames.filter(f => valid.has(f.intent.key));
if (this.current?.key === next.key) return { unchanged: true };
const provider = next.playlist && this.providers[next.playlist.provider];
if (next.playlist && !provider) throw new MusicError('unsupported');
const prepared = provider ? await provider.resolve(next.playlist, ctx) : null;
ctx.check();
const old = this.current, outgoing = old?.playlist && this.providers[old.playlist.provider];
const snapshot = outgoing ? await outgoing.snapshot(ctx) : null;
ctx.check();
const frame = this.frames.findLast(f => f.intent.key === next.key);
if (old && snapshot && valid.has(old.key)) {
this.frames = this.frames.filter(f => f.intent.key !== old.key);
this.frames.push({ intent: old, snapshot });
this.frames = this.frames.slice(-this.maxFrames);
}
const cleanup = new Set([...this.dirty, outgoing].filter(Boolean));
for (const p of [outgoing, provider]) if (p) this.dirty.add(p);
try {
for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); }
ctx.check();
if (provider) {
if (frame) await provider.restore(frame.snapshot, ctx);
else await provider.apply(prepared, ctx);
}
ctx.check();
} catch (error) {
// Never restore an obsolete transition. Reconciliation is explicit after stale writes.
this.current = null;
if (error.code !== 'stale') {
ctx.check();
for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); }
if (snapshot) { ctx.check(); await outgoing.restore(snapshot, ctx); this.current = old; }
this.dirty.clear();
}
throw error;
}
this.frames = this.frames.filter(f => f.intent.key !== next.key).slice(-this.maxFrames);
this.dirty.clear();
this.current = next;
return { intent: next, restored: Boolean(frame) };
}
}
+21
View File
@@ -0,0 +1,21 @@
import { MusicError } from './controller.mjs';
export const musicFields = ['ambient','combat','boss','fallback'];
export const referenceKey = ref => ref ? JSON.stringify([ref.provider,ref.id]) : '';
export function selection(value, choices, {nativeOnly=false}={}) {
if(value==='')return null;
const choice=choices.find(c=>referenceKey(c)===value && ['native','ma'].includes(c.provider) && typeof c.id==='string' && c.id.length<=256);
if(!choice || nativeOnly && choice.provider!=='native')throw new MusicError('denied');
return {provider:choice.provider,id:choice.id};
}
// Single music layer: ambient is the base queue interrupted by combat/boss/manual.
// These assignments do not address Foundry AmbientSound or sound effects.
export function buildMusicState({scene,combats=[],defaults={},overrides=[],choose=ref=>ref}) {
const config=scene?.music??{};
const ambient=(Object.hasOwn(config,'ambient')?config.ambient:config.playlist)??defaults.ambient??null;
const fallback=config.fallback??defaults.fallback??null;
const selected=ref=>ref ? choose(ref,fallback) : null;
return {scene:scene && {id:scene.id,playlist:selected(ambient)},defaultPlaylist:scene ? null : selected(defaults.ambient),
overrides:overrides.map(o=>({...o,playlist:selected(o.playlist)})),
combats:combats.map(c=>({...c,playlist:selected(c.playlist??config.combat??defaults.combat),
bosses:(c.bosses??[]).map(b=>({...b,playlist:selected(b.playlist??config.boss??defaults.boss)}))}))};
}
+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);}
};
}
+182
View File
@@ -0,0 +1,182 @@
import {randomKey,hmac,base64url} from './webcrypto.mjs';
import { MusicError } from '../../core/controller.mjs';
// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client.
export class MAReadClient {
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain = false; #authorizedMedia = new Set(); #targetVolume;
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
const url = new URL(baseUrl);
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token ||
/[\r\n]/.test(token) || typeof target !== 'string' || !target ||
!Array.isArray(approvedProviders) || approvedProviders.some(p => typeof p !== 'string' || !p)) throw new MusicError('denied');
this.#base = url.origin; this.#token = token; this.#target = target; this.#fetch = fetchImpl;
if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied');
this.#providers = [...new Set(approvedProviders)];
this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign;
if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied');
this.#synthetic = structuredClone(syntheticSequences);
for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri);
this.#expectedName = expectedName; this.#expectedProvider = expectedProvider;
}
async #read(command, args, messageId = 'adaptive-music-read') {
try {
const response = await this.#fetch(`${this.#base}/api`, { method: 'POST', redirect: 'error',
signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ message_id: messageId, command, args }) });
if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable');
const reader = response.body?.getReader();
if (!reader) return null;
const chunks = []; let size = 0;
try {
while (true) {
const { value, done } = await reader.read(); if (done) break;
size += value.byteLength;
if (size > 1048576) { await reader.cancel(); throw new MusicError('unavailable'); }
chunks.push(value);
}
} finally { reader.releaseLock(); }
const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}
const body = new TextDecoder().decode(bytes);
return body ? JSON.parse(body) : null;
} catch (error) {
throw new MusicError(error instanceof MusicError ? error.code : 'unavailable');
}
}
async getOwnedQueue(target) {
if (target !== this.#target) throw new MusicError('denied');
const queue = await this.#read('player_queues/get', { queue_id: this.#target });
if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied');
return { state: queue.state, items: queue.items };
}
async verifyTarget({allowUnavailable=false}={}) {
if(!allowUnavailable && this.#expectedName && this.#expectedProvider){
await this.getOwnedQueue(this.#target);
const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target});
if(active?.queue_id!==this.#target)throw new MusicError('denied');
}
const player = await this.#read('players/get', { player_id: this.#target });
if (player?.player_id !== this.#target || !allowUnavailable&&player.available !== true || player.enabled !== true ||
(this.#expectedName && player.name !== this.#expectedName) ||
(this.#expectedProvider && player.provider !== this.#expectedProvider) ||
!player.provider?.startsWith('sendspin') || player.active_group || player.synced_to ||
['group_members','group_childs','static_group_members'].some(k => !Array.isArray(player[k]) || player[k].some(id => id !== this.#target))) throw new MusicError('denied');
if(!allowUnavailable&&(!this.#expectedName || !this.#expectedProvider))await this.getOwnedQueue(this.#target);
this.#targetVolume=Number.isFinite(player.volume_level)&&typeof player.volume_muted==='boolean'?{volume:Math.min(100,Math.max(0,player.volume_level)),muted:player.volume_muted}:null;
return { dedicated: true, available: player.available===true, standalone: true };
}
targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};}
async catalog() {
if (!this.#providers.length) throw new MusicError('denied');
const next = new Map(); const choices = [];
// Bounded all-or-nothing pagination; a full final page fails rather than truncating silently.
for (const [kind, type] of [['playlists','playlist'],['radios','radio']]) {
let complete = false;
for (let offset = 0; offset < 5000; offset += 100) {
const page = await this.#read(`music/${kind}/library_items`, {
provider: this.#providers, limit: 100, offset, order_by: 'name', summary: false });
if (!Array.isArray(page) || page.length > 100) throw new MusicError('unavailable');
for (const item of page) {
const mapping = Array.isArray(item?.provider_mappings) && [...item.provider_mappings].sort((a,b) => String(a?.provider_instance).localeCompare(String(b?.provider_instance))).find(m => m && this.#providers.includes(m.provider_instance) && m.available === true);
if (!mapping || item.media_type !== type || item.is_playable !== true ||
typeof item.name !== 'string' || typeof mapping.item_id !== 'string') continue;
// Keyed campaign-scoped identity survives restart with the same private key.
const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]);
if (next.has(key)) continue;
const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key])));
next.set(key, { id, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
choices.push({ provider: 'ma', id, kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
}
if (page.length < 100) { complete = true; break; }
}
if (!complete) throw new MusicError('unavailable');
}
this.#catalog = next;
return choices;
}
resolveCatalog(ref) {
if (ref?.provider !== 'ma') throw new MusicError('denied');
const entry = [...this.#catalog.values()].find(e => e.id === ref.id);
if (!entry) throw new MusicError('expired-media');
if(entry.dynamic)throw new MusicError('unsupported');
const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri;
}
resolveMedia(ref) {
if (ref?.provider === 'ma' && Object.hasOwn(this.#synthetic,ref.id)) return [...this.#synthetic[ref.id]];
return [this.resolveCatalog(ref)];
}
async prepareMedia(ref) {
const media=this.resolveMedia(ref);
if(Object.hasOwn(this.#synthetic,ref.id)) {
await this.inspectSynthetic(media);
return media;
}
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id);
if(entry.type==='radio')return media;
const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false});
if(playlist?.is_dynamic!==false)throw new MusicError('unsupported');
const tracks=await this.#read('music/playlists/playlist_tracks',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_dynamic_tracks:false});
if(!Array.isArray(tracks) || !tracks.length || tracks.length>5000)throw new MusicError('unavailable');
return tracks.map(track=>this.mediaURI({media_item:track}));
}
async inspectSynthetic(selected) {
const approved=Object.values(this.#synthetic).flat();
const uris=selected??approved;
if(!Array.isArray(uris) || uris.some(uri=>!approved.includes(uri)))throw new MusicError('denied');
if(!this.#providers.includes('builtin') || !uris.length)throw new MusicError('denied');
const result=[];
for(const uri of uris){
if(typeof uri!=='string' || !uri.startsWith('builtin://track/http://'))throw new MusicError('denied');
const track=await this.#read('music/tracks/get',{item_id:uri.slice('builtin://track/'.length),provider_instance_id_or_domain:'builtin',allow_update_metadata:false});
if(!(track?.duration>=60))throw new MusicError('unavailable');
result.push({duration:track.duration});
}
return result;
}
async queueState({allowUnavailable=false}={}) {
const queue = await this.#read('player_queues/get', {queue_id:this.#target});
if (queue?.queue_id !== this.#target || !allowUnavailable&&(queue.active !== true || queue.available !== true)) throw new MusicError('denied');
return queue;
}
async queueItems(offset = 0) {
if (!Number.isSafeInteger(offset) || offset < 0 || offset >= 5000) throw new MusicError('denied');
const items = await this.#read('player_queues/items', {queue_id:this.#target,limit:100,offset});
if (!Array.isArray(items) || items.length > 100) throw new MusicError('unavailable');
return items;
}
mediaURI(item) {
const media = item?.media_item;
const mapping = Array.isArray(media?.provider_mappings) && media.provider_mappings.find(m => m && this.#providers.includes(m.provider_instance) && m.available === true);
if (!mapping || !['track','radio'].includes(media.media_type) || typeof mapping.item_id !== 'string') throw new MusicError('unsupported');
const uri=`${mapping.provider_instance}://${media.media_type}/${mapping.item_id}`;this.#authorizedMedia.add(uri);return uri;
}
// Server-only fixed command surface, never a browser route. Target is not an argument.
async mutate(action, args, ctx) {
const fields = {stop:[],pause:[],resume:[],clear:[],seek:['position'],shuffle:['shuffle_enabled'],repeat:['repeat_mode'],
play_index:['index','seek_position'],play_media:['media','option','shuffle']};
if (!Object.hasOwn(fields,action) || !args || Object.keys(args).some(k => !fields[action].includes(k)) ||
!this.#expectedName || !this.#expectedProvider || !ctx?.check) throw new MusicError('denied');
if (action === 'seek' && (!Number.isSafeInteger(args.position) || args.position < 0)) throw new MusicError('denied');
if (action === 'shuffle' && typeof args.shuffle_enabled !== 'boolean') throw new MusicError('denied');
if (action === 'repeat' && !['off','one','all'].includes(args.repeat_mode)) throw new MusicError('denied');
if (action === 'play_index' && (!Number.isSafeInteger(args.index) || args.index < 0 || !Number.isSafeInteger(args.seek_position) || args.seek_position < 0)) throw new MusicError('denied');
if (action === 'play_media') {
if (!['replace','add'].includes(args.option) || typeof args.shuffle !== 'boolean' || !Array.isArray(args.media) || !args.media.length || args.media.length > 5000 ||
args.media.some(uri => typeof uri !== 'string' || !this.#authorizedMedia.has(uri) || !this.#providers.some(p => uri.startsWith(`${p}://track/`) || uri.startsWith(`${p}://playlist/`) || uri.startsWith(`${p}://radio/`)))) throw new MusicError('denied');
}
const captured = structuredClone(args);
const operation = this.#writes.catch(() => {}).then(async () => {
ctx.check();
if(this.#uncertain)throw new MusicError('uncertain');
const queue = await this.queueState();
if (queue.is_dynamic !== false || queue.autoplay_enabled !== false || queue.dont_stop_the_music_enabled !== false || queue.overlay_enabled !== false || queue.playback_speed !== 1) throw new MusicError('unsupported');
await this.verifyTarget();
ctx.check(); // Recheck authority after all reads, immediately before dispatch.
try{await this.#read(`player_queues/${action}`, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);}
catch{this.#uncertain=true;throw new MusicError('uncertain');}
ctx.check();
});
this.#writes = operation;
return operation;
}
}
+84
View File
@@ -0,0 +1,84 @@
import {hmac,hex,verifyHmac} from './webcrypto.mjs';
import { MusicError } from '../../core/controller.mjs';
const identity = items => JSON.stringify(items.map(i => i.queue_item_id));
export class MAPlaybackProvider {
#client; #campaign; #session; #fence; #authority; #key; #generation = 0; #prepared = new WeakMap(); #operations = new Map(); #epoch = 0;
constructor({ client, campaign, session, fence, authority, snapshotKey }) {
if (!campaign || !session || !Number.isSafeInteger(fence) || fence < 1 || typeof authority !== 'function' || snapshotKey?.length !== 32) throw new MusicError('denied');
this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey);
}
capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; }
#check(ctx) {
if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale');
ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation;
}
#context(ctx) { return {check:()=>this.#check(ctx)}; }
#once(ctx,label,operation) {
this.#check(ctx);
const key=`${ctx.generation}:${label}`;
if(this.#operations.has(key))return this.#operations.get(key);
for(const previous of this.#operations.keys())if(!previous.startsWith(`${ctx.generation}:`))this.#operations.delete(previous);
const result=operation();this.#operations.set(key,result);return result;
}
async resolve(ref,ctx) {
this.#check(ctx); const media=this.#client.prepareMedia ? await this.#client.prepareMedia(ref) : this.#client.resolveMedia ? this.#client.resolveMedia(ref) : [this.#client.resolveCatalog(ref)]; this.#check(ctx);const prepared=Object.freeze({});this.#prepared.set(prepared,Object.freeze([...media]));return prepared;
}
async #capture(ctx) {
this.#check(ctx);await this.#client.verifyTarget();
const before=await this.#client.queueState();
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1 || before.ended) throw new MusicError('unsupported');
const items=[];
for(let offset=0;offset<5000;offset+=100){this.#check(ctx);const page=await this.#client.queueItems(offset);items.push(...page);if(page.length<100)break;if(offset===4900)throw new MusicError('unsupported');}
const after=await this.#client.queueState();
const again=[];for(let offset=0;offset<items.length;offset+=100)again.push(...await this.#client.queueItems(offset));
const stable=q=>JSON.stringify([q.items,q.current_index,q.current_item?.queue_item_id,q.state,q.shuffle_enabled,q.repeat_mode,q.is_dynamic,q.autoplay_enabled,q.dont_stop_the_music_enabled,q.overlay_enabled,q.playback_speed,q.ended]);
if (before.items!==items.length || stable(before)!==stable(after) || identity(items)!==identity(again)) throw new MusicError('stale');
if (!['idle','playing','paused'].includes(after.state) || !['off','one','all'].includes(after.repeat_mode) ||
(items.length && (!Number.isSafeInteger(after.current_index) || after.current_index<0 || after.current_index>=items.length))) throw new MusicError('unsupported');
const elapsed=after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time;
const position=Math.floor(elapsed ?? 0);
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
this.#check(ctx);
return {version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+300000,
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
}
async #sign(value) { return hex(await hmac(this.#key,'snapshot-v1\0'+JSON.stringify(value))); }
async snapshot(ctx) { const value=await this.#capture(ctx);return {value,signature:await this.#sign(value)}; }
async apply(prepared,ctx) {
this.#check(ctx);if(!this.#prepared.has(prepared))throw new MusicError('denied');
const media=this.#prepared.get(prepared);
return this.#once(ctx,`apply:${JSON.stringify(media)}`,async()=>{
await this.#client.mutate('play_media',{media,option:'replace',shuffle:false},this.#context(ctx));this.#epoch++;
});
}
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>this.#client.mutate('stop',{},this.#context(ctx))); }
async control(action,value,ctx) {
this.#check(ctx);
const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
if(!Object.hasOwn(args,action))throw new MusicError('denied');
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{await this.#client.mutate(action,args[action],this.#context(ctx));this.#epoch++;});
}
async restore(snapshot,ctx) {
this.#check(ctx);
try{snapshot=structuredClone(snapshot);}catch{throw new MusicError('stale');}
const value=snapshot?.value;
if(!value || typeof snapshot.signature!=='string' || !/^[a-f0-9]{64}$/.test(snapshot.signature) ||
!await verifyHmac(this.#key,'snapshot-v1\0'+JSON.stringify(value),snapshot.signature) ||
value.expires<=Date.now() || value.version!==1 || value.campaign!==this.#campaign || value.session!==this.#session || value.fence!==this.#fence || value.generation>ctx.generation)throw new MusicError('stale');
return this.#once(ctx,`restore:${snapshot.signature}`,async()=>{
const write=async(action,args)=>{await this.#client.mutate(action,args,this.#context(ctx));this.#epoch++;};
await write('stop',{});await write('clear',{});
await write('repeat',{repeat_mode:value.repeat});
if(value.items.length){
await write('play_media',{media:value.items.map(i=>i.uri),option:'add',shuffle:false});
// Validate complete ordered occurrences before starting any rebuilt item.
const rebuilt=[];for(let offset=0;offset<value.items.length;offset+=100)rebuilt.push(...await this.#client.queueItems(offset));
if(JSON.stringify(rebuilt.map(i=>this.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported');
await write('play_index',{index:value.index,seek_position:value.position});
if(value.state==='paused')await write('pause',{});
if(value.state==='idle')await write('stop',{});
}
});
}
}
+58
View File
@@ -0,0 +1,58 @@
import { MusicError } from '../../core/controller.mjs';
// Browser-safe client. Only same-origin relative application routes and campaign grants.
export class GatewayClient {
#fetch; #path; #origin; #grant; #fence; #catalog=[]; #status=null;
constructor({path='/adaptive-music-gateway',origin=globalThis.location?.origin,fetchImpl=globalThis.fetch}={}) {
if(typeof path!=='string' || !/^\/[a-zA-Z0-9/_-]+$/.test(path) || path.includes('//') || !origin)throw new MusicError('denied');
this.#path=path.replace(/\/$/,'');this.#origin=origin;this.#fetch=fetchImpl;
}
get connected(){return !!this.#grant&&(!this.#status||this.#status.expiresAt>Date.now());}
get status(){return this.#status&&{...structuredClone(this.#status),playbackEnabled:this.canControl};}
get catalog(){return structuredClone(this.#catalog);}
get canControl(){return this.connected && this.#status?.playbackEnabled===true && this.#status.expiresAt>Date.now();}
supports(ref){return this.canControl && this.#status.allowedIds?.includes(ref.id);}
async #request(action,args={},ctx) {
if(!this.#grant)throw new MusicError('unavailable');ctx?.check();
const grant=this.#grant;
try{
const response=await this.#fetch(this.#path+'/rpc',{method:'POST',redirect:'error',credentials:'omit',cache:'no-store',
signal:AbortSignal.timeout(8000),headers:{'Content-Type':'application/json',Authorization:`Bearer ${grant.token}`},
body:JSON.stringify({action,...args,campaign:grant.campaign,session:grant.session,...(ctx?{generation:ctx.generation,operationId:globalThis.crypto.randomUUID(),fence:this.#fence}:{})})});
const reader=response.body?.getReader();if(!reader)throw new MusicError('unavailable');
const chunks=[];let size=0;
try{while(true){const {value,done}=await reader.read();if(done)break;size+=value.length;if(size>1048576){await reader.cancel();throw new MusicError('unavailable');}chunks.push(value);}}finally{reader.releaseLock();}
const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}const text=new TextDecoder().decode(bytes);
const data=JSON.parse(text);
if(!response.ok)throw new MusicError(['denied','stale','unsupported','unavailable','uncertain','expired-media'].includes(data.code)?data.code:'unavailable');
if(this.#grant!==grant)throw new MusicError('stale');ctx?.check();return data;
}catch(error){if(this.#status)this.#status.playbackEnabled=false;throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
}
async connect(code) {
await this.disconnect();
let grant;try{grant=typeof code==='string'?JSON.parse(code):structuredClone(code);}catch{throw new MusicError('denied');}
if(!grant || Object.keys(grant).sort().join(',')!=='campaign,session,token' || ['token','campaign','session'].some(k=>typeof grant[k]!=='string'||!grant[k]||grant[k].length>512))throw new MusicError('denied');
this.#grant=grant;
try{const lease=await this.#request('connect');this.#fence=lease.fence;return await this.refresh();}
catch(error){await this.disconnect();throw error;}
}
async refresh(){
const status=await this.#request('diagnostics');
if(!status||!['verified','unavailable'].includes(status.target)||typeof status.playbackEnabled!=='boolean'||!Number.isFinite(status.expiresAt)||!Array.isArray(status.allowedIds)||status.allowedIds.some(id=>typeof id!=='string'||id.length>256)||!['none','synthetic-pcm'].includes(status.audioSource))throw new MusicError('unavailable');
this.#status={target:status.target,playbackEnabled:status.playbackEnabled,expiresAt:status.expiresAt,allowedIds:[...status.allowedIds],audioSource:status.audioSource,sendspin:false,crossfade:false,ambientLayers:1};const catalog=await this.#request('catalog');
if(!Array.isArray(catalog)||catalog.length>10000||catalog.some(c=>c?.provider!=='ma'||typeof c.id!=='string'||c.id.length>256||typeof c.name!=='string'||c.name.length>160||!['playlist','radio','sequence'].includes(c.kind)))throw new MusicError('unavailable');
this.#catalog=catalog.map(({provider,id,name,kind})=>({provider,id,name,kind}));return this.status;
}
async renew(){return this.#request('renew',{fence:this.#fence});}
async disconnect(){try{if(this.#grant&&this.#fence)await this.#request('release',{fence:this.#fence});}catch{}finally{this.#grant=null;this.#catalog=[];this.#status=null;this.#fence=null;}}
async resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('unsupported');return this.#request('prepare',{id:ref.id},ctx);}
snapshot(ctx){return this.#request('snapshot',{},ctx);}
apply(prepared,ctx){return this.#request('apply',{handle:prepared.handle},ctx);}
restore(snapshot,ctx){return this.#request('restore',{handle:snapshot.handle},ctx);}
stopOwned(ctx){return this.#request('stop',{},ctx);}
// Listener access is supplied separately, never derived from or shared with the GM grant.
audioRequest(code){
if(!code || Object.keys(code).sort().join(',')!=='campaign,session,token' || ['token','campaign','session'].some(k=>typeof code[k]!=='string'||!code[k]||code[k].length>512))throw new MusicError('denied');
return {url:this.#path+'/audio',options:{method:'POST',redirect:'error',credentials:'omit',cache:'no-store',
headers:{'Content-Type':'application/json',Authorization:`Bearer ${code.token}`},body:JSON.stringify({campaign:code.campaign,session:code.session})}};
}
}
+13
View File
@@ -0,0 +1,13 @@
// Shared Web Crypto implementation: runs in a secure browser and Node 24.
export const randomKey=()=>globalThis.crypto.getRandomValues(new Uint8Array(32));
export const hex=bytes=>[...bytes].map(n=>n.toString(16).padStart(2,'0')).join('');
export async function hmac(key,text){
const imported=await crypto.subtle.importKey('raw',key,{name:'HMAC',hash:'SHA-256'},false,['sign']);
return new Uint8Array(await crypto.subtle.sign('HMAC',imported,new TextEncoder().encode(text)));
}
export async function verifyHmac(key,text,signature){
const imported=await crypto.subtle.importKey('raw',key,{name:'HMAC',hash:'SHA-256'},false,['verify']);
const bytes=Uint8Array.from(signature.match(/../g)??[],s=>parseInt(s,16));
return crypto.subtle.verify('HMAC',imported,bytes,new TextEncoder().encode(text));
}
export const base64url=bytes=>btoa(String.fromCharCode(...bytes)).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'');
+42
View File
@@ -0,0 +1,42 @@
import {MusicError} from '../../core/controller.mjs';
const commands=new Set(['players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
export class GMMAWebSocket{
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;
constructor({baseUrl,token,createSocket=url=>new WebSocket(url)}){this.#base=new URL(baseUrl).origin;this.#token=token;this.#factory=createSocket;}
async connect(){
if(this.#closed)throw new MusicError('unavailable');if(this.#connect)return this.#connect;
this.#connect=new Promise((resolve,reject)=>{
const url=new URL('/ws',this.#base);url.protocol=url.protocol==='https:'?'wss:':'ws:';const socket=this.#socket=this.#factory(url.href);
const id='auth-'+crypto.randomUUID(),timer=setTimeout(()=>{reject(new MusicError('unavailable'));this.close();},8000);
socket.onopen=()=>socket.send(JSON.stringify({message_id:id,command:'auth',args:{token:this.#token}}));
socket.onmessage=event=>{
if(typeof event.data!=='string'||event.data.length>1048576){this.close();return;}
let msg;try{msg=JSON.parse(event.data);}catch{this.close();return;}
if(msg.message_id===id){clearTimeout(timer);if(msg.result?.authenticated===true)resolve();else{reject(new MusicError('denied'));this.close();}return;}
const pending=this.#pending.get(msg.message_id);if(!pending)return; // Drop unsolicited metadata/events.
if(Object.hasOwn(msg,'error_code')){pending.fail(new MusicError('unavailable'));return;}
pending.bytes+=event.data.length;if(pending.bytes>1048576){pending.fail(new MusicError('unavailable'));return;}
if(msg.partial===true){if(!Array.isArray(msg.result)||pending.parts.length+msg.result.length>5000){pending.fail(new MusicError('unavailable'));return;}pending.parts.push(...msg.result);return;}
pending.finish(pending.parts.length?[...pending.parts,...(Array.isArray(msg.result)?msg.result:[])]:msg.result);
};
socket.onerror=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.close();};
socket.onclose=()=>{clearTimeout(timer);reject(new MusicError('unavailable'));this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));};
});return this.#connect;
}
fetch=async(url,options)=>{
if(url!==this.#base+'/api'||options.method!=='POST'||options.redirect!=='error')throw new MusicError('denied');
let request;try{request=JSON.parse(options.body);}catch{throw new MusicError('denied');}
if(!commands.has(request.command))throw new MusicError('denied');await this.connect();
if(options.signal?.aborted||this.#pending.size>=16)throw new MusicError('unavailable');
return new Promise((resolve,reject)=>{
const id=crypto.randomUUID();let pending;
const cleanup=()=>{clearTimeout(timer);options.signal?.removeEventListener('abort',abort);this.#pending.delete(id);};
const finish=value=>{cleanup();const body=JSON.stringify(value??null);if(body.length>1048576){reject(new MusicError('unavailable'));return;}resolve(new Response(body,{headers:{'Content-Type':'application/json'}}));};
const fail=error=>{cleanup();reject(error);};const abort=()=>fail(new MusicError('unavailable'));const timer=setTimeout(abort,5000);
pending={parts:[],bytes:0,finish,fail};this.#pending.set(id,pending);options.signal?.addEventListener('abort',abort,{once:true});
try{this.#socket.send(JSON.stringify({...request,message_id:id}));}catch{fail(new MusicError('unavailable'));}
});
};
close(){if(this.#closed)return;this.#closed=true;for(const p of [...this.#pending.values()])p.fail(new MusicError('unavailable'));this.#socket?.close();this.#token=null;}
}
+71
View File
@@ -0,0 +1,71 @@
// Per-sound stop and pausedTime approach adapted from VGM (MIT), release-1.4.5.
// Copyright (c) 2025 3 Death Saves. Full notice: licenses/VGM-MIT.txt.
import { MusicError } from '../../core/controller.mjs';
export class NativeProvider {
constructor({ playlists, ownedPlaylistIds, campaign, session, sceneConflict = () => false }) {
Object.assign(this, { playlists, campaign, session, sceneConflict });
this.owned = new Set(ownedPlaylistIds);
}
capabilities() { return { seek: true, exactOrderRestore: false, concurrentLayers: false, volume: true }; }
playlist(id, ctx) {
ctx.check();
if (ctx.campaign !== this.campaign || ctx.session !== this.session || !this.owned.has(id)) throw new MusicError('denied');
const p = this.playlists.get(id);
if (!p) throw new MusicError('unavailable');
if (this.sceneConflict(id)) throw new MusicError('scene-conflict');
return p;
}
async resolve(ref, ctx) {
const p = this.playlist(ref.id, ctx);
// Sequential single-track start only; automatic shuffled order is not an exact restore API.
if (p.mode !== 0) throw new MusicError('unsupported');
const sound = [...p.sounds].sort((a,b) => a.sort-b.sort || a.id.localeCompare(b.id))[0];
if (!sound) throw new MusicError('unavailable');
return { id: p.id, soundId: sound.id };
}
async snapshot(ctx) {
const playlists = [...this.owned].map(id => {
const p = this.playlist(id, ctx);
return { id, mode: p.mode, sounds: [...p.sounds].map(s => ({
id: s.id, playing: s.playing, pausedTime: s.playing ? (s.sound?.currentTime ?? 0) : s.pausedTime,
repeat: s.repeat, volume: s.volume
})) };
});
return { version: 1, campaign: ctx.campaign, session: ctx.session, generation: ctx.generation, playlists };
}
async stopOwned(ctx) {
for (const id of this.owned) {
const p = this.playlist(id, ctx);
const updates = [...p.sounds].filter(s => s.playing).map(s => ({ _id: s.id, playing: false, pausedTime: null }));
if (updates.length) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }
}
}
async apply(prepared, ctx) {
const p = this.playlist(prepared.id, ctx);
if (p.mode !== 0) throw new MusicError('unsupported');
if (!p.sounds.get(prepared.soundId)) throw new MusicError('unavailable');
ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', [{ _id: prepared.soundId, playing: true, pausedTime: 0 }]);
}
async restore(snapshot, ctx) {
ctx.check();
if (snapshot.version !== 1 || snapshot.campaign !== ctx.campaign || snapshot.session !== ctx.session ||
snapshot.generation > ctx.generation) throw new MusicError('stale');
// Validate the entire restore before any mutation; never silently restart nonseekable audio.
const plans = snapshot.playlists.map(saved => {
const p = this.playlist(saved.id, ctx);
if (p.mode !== saved.mode || p.mode !== 0) throw new MusicError('unsupported');
if (p.sounds.size !== saved.sounds.length) throw new MusicError('expired-media');
const updates = saved.sounds.map(s => {
const live = p.sounds.get(s.id);
if (!live) throw new MusicError('expired-media');
const offset = s.pausedTime;
const duration = live.sound?.duration;
if (offset != null && (!Number.isFinite(offset) || offset < 0 ||
(offset > 0 && !(Number.isFinite(duration) && duration > 0)))) throw new MusicError('unsupported');
return { _id: s.id, playing: s.playing, pausedTime: offset == null ? null : Math.min(offset, Math.max(0, (duration ?? 0)-0.01)), repeat: s.repeat, volume: s.volume };
});
return { p, updates };
});
for (const { p, updates } of plans) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }
}
}