Adaptive Music v0.8.0 release candidate
Validate and generate manual release / package (push) Waiting to run
Validate and generate manual release / package (push) Waiting to run
This commit is contained in:
1 parent
8c07a468a4
commit
95b0427aa1
48 files changed
+3631
-313
No files matched your search
@@ -42,7 +42,7 @@ export class AutoListeners {
|
||||
try{
|
||||
const {iv,cipher,...header}=packet;
|
||||
const plain=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(iv),additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key(remote,'decrypt'),decode(cipher));
|
||||
if(this.#closed||this.#public.epoch!==localEpoch||this.#received.has(packet.id)||this.recipientKey(gm)?.epoch!==remote.epoch||!gm.active||!gm.isGM||[...this.#game.users].filter(u=>u.active&&u.isGM).length!==1)throw new MusicError('stale');
|
||||
if(this.#closed||this.#public.epoch!==localEpoch||this.#received.has(packet.id)||this.recipientKey(gm)?.epoch!==remote.epoch||!gm.active||!gm.isGM||gm.isBanned||[...this.#game.users].filter(u=>u.active&&u.isGM).length!==1)throw new MusicError('stale');
|
||||
const invite=JSON.parse(new TextDecoder().decode(plain));
|
||||
if(invite.transport!=='webrtc-v1'||invite.userId!==this.#game.user.id||invite.expires<=Date.now()||invite.expires>Date.now()+1800000)throw new MusicError('denied');
|
||||
this.#received.add(packet.id);await this.#onInvite(invite);
|
||||
|
||||
+51
-22
@@ -1,3 +1,4 @@
|
||||
import {PcmTimeline} from './pcm-timeline.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {MAReadClient} from '../providers/ma/client.mjs';
|
||||
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
|
||||
@@ -11,10 +12,16 @@ export function gmAccessPolicy(baseUrl,pageUrl){
|
||||
return target;
|
||||
}
|
||||
function memoryStorage(values){return {getItem:k=>values[k]??null,setItem:(k,v)=>{values[k]=v;},removeItem:k=>{delete values[k];}};}
|
||||
function browserAudioContext(){
|
||||
const Constructor=globalThis.AudioContext??globalThis.webkitAudioContext;
|
||||
if(!Constructor)throw new MusicError('audio-context-unavailable');
|
||||
try{return new Constructor();}
|
||||
catch{throw new MusicError('audio-context-unavailable');}
|
||||
}
|
||||
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; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0; #phase='idle'; #frames=0; #samples=0; #energy=0; #lastAudio=0; #attachedQueue=false; #lastError; #scheduled=0; #late=0; #ahead=0; #lastLead=0; #bufferedBytes=0; #meter;
|
||||
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=()=>new AudioContext(),createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.onDisconnect=onDisconnect;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
|
||||
get status(){let outputRMS=0;if(this.#meter){const data=new Float32Array(this.#meter.fftSize);this.#meter.getFloatTimeDomainData(data);outputRMS=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);}return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback,stage:this.#phase,decodedFrames:this.#frames,lastAudioAt:this.#lastAudio,outputRMS,rms:this.#samples?Math.sqrt(this.#energy/this.#samples):0,attachedExistingQueue:this.#attachedQueue,volume:this.#core?.volume??100,muted:this.#core?.muted??false,pauseMode:this.#client?.supportsNativePause()===false?'emulated':'native',scheduledFrames:this.#scheduled,droppedLate:this.#late,droppedAhead:this.#ahead,lastLeadSeconds:this.#lastLead,audioTime:this.#context?.currentTime,lastError:this.#lastError};}
|
||||
#authority;#sdk;#core;#context;#destination;#timeline;#transitionGain;#transitioning=false;#fadeNext=false;#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0; #phase='idle'; #frames=0; #samples=0; #energy=0; #lastAudio=0; #attachedQueue=false; #lastError; #meter;
|
||||
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=browserAudioContext,createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.onDisconnect=onDisconnect;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
|
||||
get status(){let outputRMS=0;if(this.#meter){const data=new Float32Array(this.#meter.fftSize);this.#meter.getFloatTimeDomainData(data);outputRMS=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);}return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback,stage:this.#phase,decodedFrames:this.#frames,lastAudioAt:this.#lastAudio,outputRMS,rms:this.#samples?Math.sqrt(this.#energy/this.#samples):0,attachedExistingQueue:this.#attachedQueue,volume:this.#core?.volume??100,muted:this.#core?.muted??false,pauseMode:this.#client?.supportsNativePause()===false?'emulated':'native',...this.#timeline?.diagnostics,audioTime:this.#context?.currentTime,lastError:this.#lastError};}
|
||||
get catalog(){return structuredClone(this.#catalog);}
|
||||
get session(){return this.#session;}
|
||||
get stream(){return this.#destination?.stream;}
|
||||
@@ -81,9 +88,9 @@ export class GMAudioHost{
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
if(!profile.targetName||typeof profile.target!=='string'||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
|
||||
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
|
||||
this.#lastError=undefined;this.#attachedQueue=false;this.#context=audioContext??this.createContext();const unlocked=audioContext?null:this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
|
||||
this.#lastError=undefined;this.#attachedQueue=this.#transitioning=this.#fadeNext=false;this.#context=audioContext??this.createContext();if(!audioContext)void this.#context.resume().catch(()=>{});this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=0;
|
||||
try{
|
||||
this.#sdk=await this.loadSDK();await unlocked;check();
|
||||
this.#sdk=await this.loadSDK();check();
|
||||
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
|
||||
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
|
||||
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
|
||||
@@ -93,8 +100,8 @@ export class GMAudioHost{
|
||||
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket,onDisconnect:()=>this.#connectionLost(epoch,'API connection lost')});
|
||||
await this.#apiTransport.connect();check();
|
||||
this.#phase='Sendspin authentication';this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);check();
|
||||
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:false,unpairedAccess:false,reconnect:{enabled:false}});
|
||||
this.#gain=this.#context.createGain();this.#meter=this.#context.createAnalyser?.();if(this.#meter){this.#gain.connect(this.#meter);this.#meter.connect(this.#destination);this.#meter.connect(this.#context.destination);}else{this.#gain.connect(this.#destination);this.#gain.connect(this.#context.destination);}
|
||||
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:350,minBufferMs:350,useHardwareVolume:false,unpairedAccess:false,reconnect:{enabled:false}});
|
||||
this.#transitionGain=this.#context.createGain();this.#gain=this.#context.createGain();this.#transitionGain.connect(this.#gain);this.#timeline=new PcmTimeline(this.#context,this.#transitionGain);this.#meter=this.#context.createAnalyser?.();if(this.#meter){this.#gain.connect(this.#meter);this.#meter.connect(this.#destination);this.#meter.connect(this.#context.destination);}else{this.#gain.connect(this.#destination);this.#gain.connect(this.#context.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.#connectionLost(epoch,'Sendspin connection lost');
|
||||
@@ -142,29 +149,51 @@ export class GMAudioHost{
|
||||
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;
|
||||
this.#frames++;this.#lastAudio=Date.now();for(const channel of chunk.samples)for(const sample of channel){this.#samples++;this.#energy+=sample*sample;}
|
||||
const lead=(chunk.serverTimeUs-this.#core.getCurrentServerTimeUs())/1000000;
|
||||
this.#lastLead=lead;if(!Number.isFinite(lead)||this.#nodes.size>=512||this.#bufferedBytes+frames*chunk.samples.length*4>2097152)return;
|
||||
if(lead>6){this.#ahead++;return;}if(lead+frames/chunk.sampleRate<0){this.#late++;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.adaptiveBytes=frames*chunk.samples.length*4;node.adaptiveServerStart=chunk.serverTimeUs;node.adaptiveServerEnd=chunk.serverTimeUs+frames/chunk.sampleRate*1000000;node.onended=()=>{if(this.#nodes.delete(node))this.#bufferedBytes-=node.adaptiveBytes;};this.#nodes.add(node);this.#bufferedBytes+=node.adaptiveBytes;node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));this.#scheduled++;
|
||||
const start=this.#timeline.push(chunk,this.#core.getCurrentServerTimeUs());
|
||||
if(start!==false&&this.#fadeNext&&!this.#transitioning){
|
||||
this.#fadeNext=false;
|
||||
const gain=this.#transitionGain.gain;
|
||||
gain.setValueAtTime(0,start);
|
||||
gain.linearRampToValueAtTime(1,start+0.35);
|
||||
}
|
||||
}
|
||||
#clear(fromTimestampUs){
|
||||
if(Number.isFinite(fromTimestampUs)){
|
||||
const when=Math.max(this.#context.currentTime,this.#context.currentTime+(fromTimestampUs-this.#core.getCurrentServerTimeUs())/1000000);
|
||||
for(const node of this.#nodes)if(node.adaptiveServerEnd>fromTimestampUs){try{node.stop(node.adaptiveServerStart>=fromTimestampUs?0:when);}catch{}}
|
||||
return;
|
||||
this.#timeline?.clear(fromTimestampUs);
|
||||
if(!Number.isFinite(fromTimestampUs)&&this.#transitioning)this.#fadeNext=true;
|
||||
}
|
||||
async fade(audible, ctx){
|
||||
const context=this.#context,param=this.#transitionGain?.gain;
|
||||
if(!param||context.state!=='running')return;
|
||||
const now=context.currentTime,duration=audible?0.35:0.22;
|
||||
this.#transitioning=!audible;
|
||||
if(audible&&this.#fadeNext)return;
|
||||
if(typeof param.cancelAndHoldAtTime==='function')param.cancelAndHoldAtTime(now);
|
||||
else {param.cancelScheduledValues(now);param.setValueAtTime(param.value,now);}
|
||||
param.linearRampToValueAtTime(audible?1:0,now+duration);
|
||||
if(!audible){
|
||||
await new Promise(resolve=>setTimeout(resolve, duration*1000));
|
||||
ctx?.check();
|
||||
}
|
||||
for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();this.#bufferedBytes=0;
|
||||
}
|
||||
#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);}
|
||||
async #observe(operation){try{return await operation();}catch(error){this.#lastError={code:error.code??'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(error.code==='uncertain')this.#phase='queue reconciliation required';throw error;}}
|
||||
snapshot(ctx){return this.#observe(()=>this.#ready().snapshot(ctx));}
|
||||
async #observe(operation){
|
||||
try{return await operation();}
|
||||
catch(error){
|
||||
if(error.upstreamCode===22&&['players/get','player_queues/get','player_queues/get_active_queue'].includes(error.command)){
|
||||
error=Object.assign(new MusicError('receiver-access-lost'),{command:error.command,upstreamCode:error.upstreamCode});
|
||||
}
|
||||
this.#lastError={code:error.code??'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};
|
||||
if(['uncertain','receiver-access-lost'].includes(error.code))this.#phase='queue reconciliation required';
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
apply(prepared,ctx){return this.#observe(()=>this.#ready().apply(prepared,ctx));}
|
||||
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,ctx));}
|
||||
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
|
||||
stopOwned(ctx){return this.#observe(()=>this.#ready().stopOwned(ctx));}
|
||||
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||
playbackStatus(){return this.#ready().playbackStatus();}
|
||||
playbackStatus(){return this.#observe(()=>this.#ready().playbackStatus());}
|
||||
setVolume(value){this.#ready();if(!Number.isFinite(value)||value<0||value>100)throw new MusicError('denied');this.#core.setVolume(Math.round(value));}
|
||||
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;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;this.#meter=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;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;this.#meter=null;this.#timeline=null;this.#transitionGain=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// Keep the Web Audio timeline sample-continuous across Sendspin packets.
|
||||
// The upstream timestamp is a stream coordinate. AudioContext.currentTime is
|
||||
// quantized by the render thread, so mapping each packet independently is noisy.
|
||||
const startupBuffer = 0.12;
|
||||
const schedulingGuard = 0.008;
|
||||
const maximumLead = 8;
|
||||
const timestampToleranceUs = 1500;
|
||||
const maximumBytes = 8 * 1024 * 1024;
|
||||
|
||||
export class PcmTimeline {
|
||||
#context;
|
||||
#output;
|
||||
#sources = new Set();
|
||||
#bytes = 0;
|
||||
#nextTime;
|
||||
#nextTimestamp;
|
||||
#format;
|
||||
#paused = false;
|
||||
#stats = {scheduledFrames:0, droppedLate:0, droppedAhead:0, bufferOverruns:0,
|
||||
underruns:0, sourceGaps:0, sourceOverlaps:0, gapMs:0, overlapMs:0, lastLeadSeconds:0};
|
||||
|
||||
constructor(context, output) {
|
||||
this.#context = context;
|
||||
this.#output = output;
|
||||
}
|
||||
|
||||
get diagnostics() {
|
||||
return {...this.#stats, bufferedMs:Math.round(Math.max(0, (this.#nextTime ?? 0) - this.#context.currentTime) * 1000)};
|
||||
}
|
||||
|
||||
push({samples,sampleRate,serverTimeUs}, serverNowUs) {
|
||||
const now = this.#context.currentTime;
|
||||
if (this.#context.state === 'suspended' || this.#context.state === 'interrupted') {
|
||||
if (!this.#paused) this.clear();
|
||||
this.#paused = true;
|
||||
return false;
|
||||
}
|
||||
this.#paused = false;
|
||||
const lead = (serverTimeUs - serverNowUs) / 1e6;
|
||||
if (!Number.isFinite(lead)) return false;
|
||||
this.#stats.lastLeadSeconds = lead;
|
||||
if (lead > maximumLead) { this.#stats.droppedAhead++; return false; }
|
||||
|
||||
const frames = samples[0].length;
|
||||
const duration = frames / sampleRate;
|
||||
if (lead + duration + startupBuffer <= 0) { this.#stats.droppedLate++; return false; }
|
||||
|
||||
// Count actual discontinuities in the source separately from render starvation.
|
||||
let offset = 0;
|
||||
let time = this.#nextTime;
|
||||
const format = `${sampleRate}:${samples.length}`;
|
||||
const timestampDelta = serverTimeUs - (this.#nextTimestamp ?? serverTimeUs);
|
||||
if (this.#format === format && Math.abs(timestampDelta) > timestampToleranceUs) {
|
||||
if (timestampDelta < 0) {
|
||||
this.#stats.sourceOverlaps++;
|
||||
this.#stats.overlapMs += -timestampDelta / 1000;
|
||||
offset = Math.min(frames, Math.round(-timestampDelta * sampleRate / 1e6));
|
||||
if (offset === frames) return false;
|
||||
} else {
|
||||
this.#stats.sourceGaps++;
|
||||
this.#stats.gapMs += timestampDelta / 1000;
|
||||
time += timestampDelta / 1e6;
|
||||
}
|
||||
}
|
||||
|
||||
const target = now + lead + startupBuffer + offset / sampleRate;
|
||||
if (time === undefined || this.#format !== format) {
|
||||
time = Math.max(now + schedulingGuard, this.#nextTime ?? 0, target);
|
||||
} else if (time < now + schedulingGuard) {
|
||||
this.#stats.underruns++;
|
||||
time = Math.max(now + schedulingGuard, target);
|
||||
}
|
||||
const bytes = (frames - offset) * samples.length * 4;
|
||||
if (this.#sources.size >= 768 || this.#bytes + bytes > maximumBytes) {
|
||||
this.#stats.bufferOverruns++;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Correct slow drift without moving packet boundaries around. Ignore render
|
||||
// quantum noise. The maximum slew (0.1%) keeps pitch changes small.
|
||||
const error = target - time;
|
||||
const rate = Math.abs(error) <= 0.005 ? 1 : 1 - Math.max(-0.001,Math.min(0.001,error / 8));
|
||||
const buffer = this.#context.createBuffer(samples.length, frames - offset, sampleRate);
|
||||
samples.forEach((channel,index) => buffer.getChannelData(index).set(channel.subarray(offset)));
|
||||
const source = this.#context.createBufferSource();
|
||||
source.buffer = buffer;
|
||||
source.playbackRate.value = rate;
|
||||
source.connect(this.#output);
|
||||
const length = (frames - offset) / sampleRate / rate;
|
||||
const item = {source,bytes,start:time,end:time+length,serverStart:serverTimeUs+offset/sampleRate*1e6,serverEnd:serverTimeUs+duration*1e6,rate};
|
||||
this.#sources.add(item);
|
||||
this.#bytes += bytes;
|
||||
source.onended = () => {
|
||||
source.disconnect();
|
||||
if (this.#sources.delete(item)) this.#bytes -= bytes;
|
||||
};
|
||||
source.start(time);
|
||||
this.#stats.scheduledFrames++;
|
||||
this.#format = format;
|
||||
this.#nextTime = item.end;
|
||||
this.#nextTimestamp = item.serverEnd;
|
||||
return time;
|
||||
}
|
||||
|
||||
clear(timestamp) {
|
||||
if (Number.isFinite(timestamp)) {
|
||||
let retainedEnd;
|
||||
let retainedTimestamp;
|
||||
for (const item of this.#sources) {
|
||||
if (item.serverStart >= timestamp) {
|
||||
item.source.stop();
|
||||
this.#sources.delete(item);
|
||||
this.#bytes -= item.bytes;
|
||||
} else {
|
||||
const end = Math.min(item.end, item.start+(timestamp-item.serverStart)/1e6/item.rate);
|
||||
if (item.serverEnd > timestamp) {
|
||||
item.source.stop(Math.max(this.#context.currentTime,end));
|
||||
item.end=end;
|
||||
item.serverEnd=timestamp;
|
||||
}
|
||||
if (retainedEnd === undefined || end > retainedEnd) {
|
||||
retainedEnd = end;
|
||||
retainedTimestamp = Math.min(timestamp,item.serverEnd);
|
||||
}
|
||||
}
|
||||
}
|
||||
this.#nextTime = retainedEnd;
|
||||
this.#nextTimestamp = retainedTimestamp;
|
||||
return;
|
||||
}
|
||||
for (const item of this.#sources) item.source.stop();
|
||||
this.#sources.clear();
|
||||
this.#bytes = 0;
|
||||
this.#format = this.#nextTime = this.#nextTimestamp = undefined;
|
||||
}
|
||||
}
|
||||
@@ -54,7 +54,8 @@ export class PeerAudio{
|
||||
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()));
|
||||
// Expiry closes signaling. A connected stream retains its authorization until revoked.
|
||||
entry.timer=setTimeout(()=>{if(pc.connectionState!=='connected')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=()=>{
|
||||
@@ -69,10 +70,16 @@ export class PeerAudio{
|
||||
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++;
|
||||
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');
|
||||
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);entry.stage='validate SDP';
|
||||
const check=()=>{
|
||||
if(this.#peers.get(frame.peer)!==entry||entry.invite.expires<=Date.now())throw new MusicError('stale');
|
||||
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
|
||||
};
|
||||
check();
|
||||
if(entry.signals>=64)throw new MusicError('denied');
|
||||
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);
|
||||
check();entry.signals++;entry.stage='validate SDP';
|
||||
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.
|
||||
@@ -80,6 +87,7 @@ export class PeerAudio{
|
||||
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
|
||||
entry.stage='apply offer';await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
|
||||
await entry.pc.setLocalDescription(await entry.pc.createAnswer());await gathered(entry.pc);
|
||||
check();
|
||||
entry.stage='send answer';await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
|
||||
}else if(entry.role==='listener'&&payload.type==='answer'){
|
||||
validateAudioSDP(payload.sdp,'answer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
|
||||
@@ -92,5 +100,5 @@ export class PeerAudio{
|
||||
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,lastSignalError:this.#lastSignalError,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState,stage:e.stage}))};}
|
||||
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;}
|
||||
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,concealedSamples:item.concealedSamples,silentConcealedSamples:item.silentConcealedSamples,concealmentEvents:item.concealmentEvents,jitterBufferDelay:item.jitterBufferDelay,jitterBufferEmittedCount:item.jitterBufferEmittedCount,currentRoundTripTime:item.currentRoundTripTime});}return results;}
|
||||
}
|
||||
+36
-9
@@ -17,7 +17,11 @@ export function candidates(state) {
|
||||
make('default', state.defaultPlaylist)
|
||||
].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` }));
|
||||
}
|
||||
const samePlaylist = (a, b) => Boolean(a && b && a.provider === b.provider && a.id === b.id);
|
||||
|
||||
export class MusicController {
|
||||
#pending;
|
||||
#stateSignature;
|
||||
constructor({ campaign, session, providers, authority, maxFrames = 16 }) {
|
||||
Object.assign(this, { campaign, session, providers, authority, maxFrames });
|
||||
this.dirty = new Set();
|
||||
@@ -25,19 +29,33 @@ export class MusicController {
|
||||
}
|
||||
update(state) {
|
||||
const input = structuredClone(state);
|
||||
const signature=JSON.stringify(candidates(input).map(intent=>intent.key));
|
||||
if(this.#pending?.signature===signature&&this.#pending.generation===this.generation)return this.#pending.task;
|
||||
if(!this.#pending&&this.current&&this.#stateSignature===signature&&!this.dirty.size&&this.authority())return Promise.resolve({unchanged:true});
|
||||
const context = this.#nextContext();
|
||||
return this.#enqueue(() => this.transition(input, context));
|
||||
const task=this.#enqueue(() => this.transition(input, context)).then(result=>{
|
||||
this.#stateSignature=signature;
|
||||
return result;
|
||||
}).finally(()=>{
|
||||
if(this.#pending?.task===task)this.#pending=undefined;
|
||||
});
|
||||
this.#pending={signature,generation:context.generation,task};
|
||||
return task;
|
||||
}
|
||||
control(action, value) {
|
||||
if (!['pause', 'resume', 'stop', 'seek'].includes(action) || !this.providers.ma?.control) {
|
||||
if (!['pause', 'resume', 'stop', 'seek', 'next', 'repeat'].includes(action) || !this.providers.ma?.control) {
|
||||
return Promise.reject(new MusicError('unsupported'));
|
||||
}
|
||||
const expected = this.generation;
|
||||
return this.#enqueue(() => {
|
||||
return this.#enqueue(async () => {
|
||||
if (expected !== this.generation) throw new MusicError('stale');
|
||||
const context = this.#nextContext();
|
||||
context.check();
|
||||
return this.providers.ma.control(action, value, context);
|
||||
const provider=this.providers.ma;
|
||||
try{
|
||||
if(['pause','stop','next','seek'].includes(action))await provider.fade?.(false,context);
|
||||
return await provider.control(action,value,context);
|
||||
}finally{await provider.fade?.(true);}
|
||||
});
|
||||
}
|
||||
cancel() {
|
||||
@@ -62,6 +80,10 @@ export class MusicController {
|
||||
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 };
|
||||
if(samePlaylist(this.current?.playlist,next.playlist)){
|
||||
this.current=next;
|
||||
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;
|
||||
@@ -70,14 +92,17 @@ export class MusicController {
|
||||
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 });
|
||||
if (old && snapshot) {
|
||||
const shared = choices.filter(intent => samePlaylist(intent.playlist, old.playlist));
|
||||
const aliases = new Set(shared.map(intent => intent.key));
|
||||
this.frames = this.frames.filter(f => !aliases.has(f.intent.key));
|
||||
this.frames.push(...shared.map(intent => ({intent, 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 {
|
||||
await outgoing?.fade?.(false,ctx);
|
||||
for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); }
|
||||
ctx.check();
|
||||
if (provider) {
|
||||
@@ -88,15 +113,17 @@ export class MusicController {
|
||||
} catch (error) {
|
||||
// Stale or uncertain writes require explicit reconciliation.
|
||||
this.current = null;
|
||||
if (error.code !== 'stale' && error.code !== 'uncertain') {
|
||||
if (!['stale','uncertain','receiver-access-lost'].includes(error.code)) {
|
||||
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;
|
||||
} finally {
|
||||
await outgoing?.fade?.(true);
|
||||
}
|
||||
this.frames = this.frames.filter(f => f.intent.key !== next.key).slice(-this.maxFrames);
|
||||
this.frames = this.frames.filter(f => !samePlaylist(f.intent.playlist,next.playlist)).slice(-this.maxFrames);
|
||||
this.dirty.clear();
|
||||
this.current = next;
|
||||
return { intent: next, restored: Boolean(frame) };
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {mountMusicAssignments} from './music-editor.mjs';
|
||||
import {mountMusicAssignments,playlistDragType} from './music-editor.mjs';
|
||||
import {referenceKey} from '../core/scene-music.mjs';
|
||||
import { MusicError } from '../core/controller.mjs';
|
||||
const namespace = 'adaptive-music';
|
||||
const key = ref => JSON.stringify([ref?.provider, ref?.id]);
|
||||
@@ -16,9 +17,9 @@ export async function savePlaylistConfiguration({ document, game, choices, selec
|
||||
await document.setFlag(namespace, 'music', { ...previous,
|
||||
playlist: choice ? { provider: choice.provider, id: choice.id } : null });
|
||||
}
|
||||
export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {} }) {
|
||||
export function mountPlaylistConfiguration({ document, game, container, choices, onError = () => {},sceneSheet=false }) {
|
||||
if (!game.user?.isGM || container.querySelector('[data-adaptive-music]')) return null;
|
||||
if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError});
|
||||
if(document.documentName==='Scene')return mountMusicAssignments({document,game,container,choices,onError,sceneSheet});
|
||||
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);
|
||||
@@ -31,7 +32,7 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
|
||||
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 note = dom.createElement('p'); note.textContent = 'Connect Music Assistant in Adaptive Music setup to load playlists. Saved selections remain available after reload.'; 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;
|
||||
@@ -47,21 +48,64 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
|
||||
container.append(panel); return panel;
|
||||
}
|
||||
// Explicit development-only UI bootstrap. Importing this file registers nothing.
|
||||
export function startConfigurationInterfaces({ game, Hooks, getChoices, onError = () => {} }) {
|
||||
export function startConfigurationInterfaces({ game, Hooks, getChoices, openPlayback, onError = () => {} }) {
|
||||
let disposed = false;
|
||||
const panels = new Set();
|
||||
const render = async (app, html) => {
|
||||
if (!game.user?.isGM) return;
|
||||
for(const panel of panels)if(panel.isConnected===false)panels.delete(panel);
|
||||
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});
|
||||
const sceneSheet=document.documentName==='Scene';
|
||||
const target=sceneSheet?(container.querySelector('[data-tab="ambience"].tab,[data-tab="audio"].tab,[data-tab="basic"].tab')??container.querySelector('.window-content')??container):container;
|
||||
const panel = mountPlaylistConfiguration({document,game,container:target,choices,onError,sceneSheet});
|
||||
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(); } };
|
||||
const renderDirectory=async (_app,html)=>{
|
||||
const container=html?.querySelector?html:html?.[0];
|
||||
if(!game.user?.isGM||!container)return;
|
||||
try{
|
||||
const choices=(await getChoices()).filter(choice=>choice.provider==='ma');
|
||||
if(disposed||!game.user?.isGM)return;
|
||||
for(const panel of panels)if(panel.isConnected===false)panels.delete(panel);
|
||||
const dom=container.ownerDocument,existing=container.querySelector('.adaptive-catalog');
|
||||
const details=existing??dom.createElement('details');
|
||||
if(!existing){
|
||||
details.className='adaptive-catalog';
|
||||
const summary=dom.createElement('summary');summary.textContent='Adaptive Music';details.append(summary);
|
||||
const playback=dom.createElement('button');playback.type='button';playback.textContent='Music controls';
|
||||
playback.addEventListener('click',()=>openPlayback?.());details.append(playback);
|
||||
const nativeList=container.querySelector('.directory-list');
|
||||
if(nativeList)nativeList.before(details);else container.append(details);
|
||||
panels.add(details);
|
||||
}
|
||||
const entries=choices.map(choice=>[referenceKey(choice),choice.name]);
|
||||
const previous=details.querySelector('ul');
|
||||
if(JSON.stringify(entries)===JSON.stringify([...previous?.children??[]].map(entry=>[entry.dataset.reference,entry.textContent])))return;
|
||||
const list=dom.createElement('ul');
|
||||
for(const [reference,name] of entries){
|
||||
const entry=dom.createElement('li');entry.textContent=name;entry.draggable=true;entry.dataset.reference=reference;
|
||||
entry.addEventListener('dragstart',event=>{
|
||||
if(!event.dataTransfer)return;
|
||||
event.dataTransfer.setData(playlistDragType,reference);event.dataTransfer.effectAllowed='copy';
|
||||
});
|
||||
list.append(entry);
|
||||
}
|
||||
previous?.remove();
|
||||
if(entries.length)details.append(list);
|
||||
}catch{
|
||||
onError(new MusicError('unavailable'));
|
||||
}
|
||||
};
|
||||
const hooks = [['renderSceneConfig',render],['renderCombatConfig',render],['renderPlaylistDirectory',renderDirectory]]
|
||||
.map(([event,handler])=>[event,Hooks.on(event,handler)]);
|
||||
return {
|
||||
refreshDirectory:app=>renderDirectory(app,app?.element),
|
||||
dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); }
|
||||
};
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs
|
||||
const messages={
|
||||
'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.',
|
||||
'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.',
|
||||
'private-credential-write-failed':'Connected, but the browser could not remember the credential on this device.',
|
||||
'receiver-storage-write-failed':'The browser could not update the remembered receiver. Check site storage before reconnecting.',
|
||||
'private-credential-corrupt':'The device credential could not be unlocked. Use Forget Credentials and enter a valid token.',
|
||||
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
|
||||
'token-required':'Enter a Music Assistant access token for this server.',
|
||||
'token-invalid':'Remove line breaks from the access token and try again.',
|
||||
@@ -18,24 +21,32 @@ const messages={
|
||||
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
|
||||
'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.',
|
||||
'sendspin-sync-failed':'Sendspin did not complete pairing and clock synchronization. Retry the remembered receiver; transport HTTP 101 alone does not prove a working audio receiver.',
|
||||
'audio-context-unavailable':'This browser could not start Web Audio. Check the browser’s audio output and whether another device is using it exclusively.',
|
||||
'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.',
|
||||
'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.',
|
||||
'reconcile-required':'This dedicated receiver has an existing queue. Playback was left untouched. Resume the remembered receiver after reviewing its queue in MA, or use a new dedicated receiver.',
|
||||
'catalog-empty':'No available music providers were returned. Check the dedicated MA account’s music-provider access.',
|
||||
'unsupported':'This queue or browser feature is unsupported. Use a standalone receiver with a static queue, shuffle and autoplay off, and a browser with Web Locks, Web Audio and WebRTC.',
|
||||
'private-storage-unavailable':'This browser denied private receiver storage. Allow site storage for Foundry, then retry. No MA token is stored there.',
|
||||
'private-storage-unavailable':'This browser denied private storage. Allow site storage for this Foundry address and retry.',
|
||||
'private-storage-corrupt':'The remembered receiver could not be decrypted. Use Forget remembered receiver below to create a replacement. Existing MA queues are left untouched.',
|
||||
'identity-mismatch':'The remembered receiver identity does not match this connection. Forget that receiver to create a new campaign receiver.',
|
||||
'dedicated-target-required':'The receiver did not match the identity and name created for this campaign. No unrelated player was selected.',
|
||||
'receiver-queue-unavailable':'MA did not make this receiver’s queue available after connection. Retry connecting the remembered receiver.',
|
||||
'receiver-access-lost':'Music Assistant withdrew this receiver’s queue access. If another MA browser player uses this token, give the two players separate tokens. Review the dedicated receiver before reconnecting.',
|
||||
'denied':'The dedicated receiver, account permission or active GM check failed. Keep one active GM and verify that this account can control its campaign receiver.',
|
||||
'stale':'GM authority or the connection changed during setup. Keep one active GM, then retry.',
|
||||
'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.',
|
||||
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
|
||||
};
|
||||
export const connectionMessage=error=>error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command)?'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped; an unconfirmed queue write is never retried.':messages[error?.code]??messages.unavailable;
|
||||
export function connectionMessage(error){
|
||||
if(error?.code==='ws-upgrade-failed'&&error.stage==='Sendspin authentication')return 'The browser could not open the receiver’s /sendspin WebSocket. Check both routes from this Foundry page.';
|
||||
if(error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command))return 'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped after an unconfirmed queue write.';
|
||||
return messages[error?.code]??messages.unavailable;
|
||||
}
|
||||
|
||||
function failureStage(error) {
|
||||
if(error?.code==='audio-context-unavailable')return 'Browser audio unavailable';
|
||||
if(error?.stage==='Sendspin authentication'&&error.code==='ws-upgrade-failed')return 'Receiver connection failed';
|
||||
if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed';
|
||||
if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed';
|
||||
if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed';
|
||||
@@ -75,14 +86,17 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
const initial=connection.draftFields??{};
|
||||
make('h2','Connect Music Assistant');
|
||||
make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.');
|
||||
if(initial.savedConnection)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
|
||||
if(initial.savedConnection&&!initial.deviceCredential)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
|
||||
const fields=make('div');fields.className='adaptive-fields';
|
||||
const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??'';
|
||||
const token=input(fields,'Private GM access token','password');
|
||||
const remember=input(fields,'Remember credentials and reconnect on this trusted device','checkbox');remember.checked=initial.deviceCredential===true;
|
||||
make('p','Use a revocable Music Assistant token. Remembered credentials belong to this browser profile. Enable this only on a device and Foundry site you trust.');
|
||||
const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
|
||||
const actions=make('div');actions.className='adaptive-actions';
|
||||
const state=make('p');state.className='adaptive-state';
|
||||
const status=make('p');status.setAttribute('role','status');
|
||||
const automaticFailure=make('p');automaticFailure.hidden=true;
|
||||
const advanced=make('details');make('summary','Advanced',advanced);
|
||||
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields';
|
||||
const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
|
||||
@@ -91,7 +105,7 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
|
||||
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
|
||||
const report=make('div');report.setAttribute('aria-live','polite');
|
||||
let transportResults=[],busy=false;
|
||||
let transportResults=[],busy=false,hadDeviceCredential=initial.deviceCredential;
|
||||
const run=async(action,label)=>{
|
||||
if(busy||!game.user.isGM)return;
|
||||
busy=true;retainError.hidden=true;render();
|
||||
@@ -118,7 +132,9 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
let maUrl;
|
||||
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
|
||||
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
|
||||
if(!token.value.trim()&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
|
||||
const draft=connection.draftFields??{};
|
||||
const usingDevice=draft.deviceCredential&&draft.maUrl===maUrl;
|
||||
if(!token.value.trim()&&!usingDevice&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
|
||||
if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
|
||||
const targetName=name.value.trim();
|
||||
if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
|
||||
@@ -127,7 +143,7 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
|
||||
status.textContent='Contacting Music Assistant…';
|
||||
let result;
|
||||
try{result=await connection.open({maUrl,token:token.value.trim(),...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
|
||||
try{result=await connection.open({maUrl,token:token.value.trim(),remember:remember.checked,...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
|
||||
finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
|
||||
address.value=connection.draftFields?.maUrl??address.value;
|
||||
await onCatalog();
|
||||
@@ -136,8 +152,11 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
connect.className='adaptive-primary';
|
||||
const nextButton=button(actions,'Choose scene music',()=>next?.());
|
||||
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
|
||||
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. The receiver is remembered for next time.';await onCatalog();
|
||||
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. Automatic reconnection is paused until you connect again.';await onCatalog();
|
||||
},'Disconnect failed'));
|
||||
const forgetCredentials=button(actions,'Forget Credentials',()=>run(async()=>{
|
||||
await connection.forgetCredentials();remember.checked=false;token.value='';status.textContent='Credentials removed from this device.';await onCatalog();
|
||||
},'Could not forget credentials'));
|
||||
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
|
||||
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
|
||||
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
|
||||
@@ -145,7 +164,7 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
},'Browser connection check failed'));
|
||||
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
|
||||
const d=connection.status;
|
||||
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
|
||||
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,bufferedMs:d.bufferedMs,underruns:d.underruns,bufferOverruns:d.bufferOverruns,sourceGaps:d.sourceGaps,sourceOverlaps:d.sourceOverlaps,gapMs:d.gapMs,overlapMs:d.overlapMs,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
|
||||
status.textContent='Connection diagnostics copied.';
|
||||
},'Could not copy diagnostics'));
|
||||
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
|
||||
@@ -156,17 +175,25 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
|
||||
if(advancedContent)advanced.append(advancedContent);
|
||||
function render(){
|
||||
const d=connection.status,connected=d.state==='connected';
|
||||
const label=connected?'Connected':busy?'Working':d.state==='connection-lost'?'Connection lost':'Disconnected';
|
||||
const connecting=busy||d.deviceReconnect;
|
||||
const label=connected?'Connected':connecting?'Working':d.state==='connection-lost'?'Connection lost':d.deviceError?'Automatic connection failed':'Disconnected';
|
||||
const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
|
||||
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
|
||||
if(state.textContent!==summary)state.textContent=summary;
|
||||
state.dataset.connected=String(connected);
|
||||
connect.hidden=connected;connect.disabled=busy;connect.textContent=busy?'Connecting…':'Connect';
|
||||
automaticFailure.hidden=connected||connecting||!d.deviceError;
|
||||
if(!automaticFailure.hidden)automaticFailure.textContent=connectionMessage({code:d.deviceError});
|
||||
connect.hidden=connected;connect.disabled=connecting;connect.textContent=connecting?'Connecting…':'Connect';
|
||||
disconnect.hidden=!connected;disconnect.disabled=busy;
|
||||
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
|
||||
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
|
||||
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy;
|
||||
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token';
|
||||
const draft=connection.draftFields;
|
||||
forgetCredentials.hidden=!draft?.deviceCredential&&d.deviceError!=='private-credential-corrupt';forgetCredentials.disabled=connecting;
|
||||
if(!address.value&&draft?.deviceCredential&&!hadDeviceCredential)address.value=draft.maUrl;
|
||||
if(draft?.deviceCredential&&!hadDeviceCredential)remember.checked=true;
|
||||
hadDeviceCredential=draft?.deviceCredential;
|
||||
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry,remember])field.disabled=connected||connecting;
|
||||
token.placeholder=retainedToken()||connection.draftFields?.deviceCredential?'Retained for this address':'Paste your access token';
|
||||
}
|
||||
address.addEventListener('input',render);
|
||||
render();
|
||||
|
||||
+121
-25
@@ -8,29 +8,47 @@ import {GMAudioHost,gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||
import {AutoListeners} from '../audio/auto-listeners.mjs';
|
||||
import {PeerAudio} from '../audio/peer-audio.mjs';
|
||||
import {ListenerAudio} from './listener-audio.mjs';
|
||||
import {createSetupClass,createListenerClass} from './setup.mjs';
|
||||
import {createSetupClass,createListenerClass,createPlaybackClass} from './setup.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {openAccountConnection,sealAccountConnection} from './account-connection.mjs';
|
||||
const id='adaptive-music';
|
||||
const receiverVault=new ReceiverVault();
|
||||
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl});
|
||||
const credentialScope=()=>receiverScope({});
|
||||
const accountScope=()=>JSON.stringify([location.origin,game.world.id,game.user.id]);
|
||||
const savedConnection=()=>game.settings.get(id,'savedConnection');
|
||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource;
|
||||
let automationRunning=false,previousController;
|
||||
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;
|
||||
let automationRunning=false,previousController,savedDevice,deviceReconnect=false,devicePaused=false,deviceError,connectionOpening=false;
|
||||
let playbackApp,setupType;
|
||||
const gmAuthority=()=>game.ready&&game.user.isGM&&!game.user.isBanned&&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.filter(c=>c.kind==='playlist'||c.kind==='sequence'):gateway?.catalog??[])];
|
||||
const onError=error=>{if(error?.code==='uncertain')stop();ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
|
||||
const queueNeedsReview=error=>['uncertain','receiver-access-lost'].includes(error?.code);
|
||||
const onError=error=>{if(queueNeedsReview(error)){devicePaused=true;stop();}ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
|
||||
function openSetup(){
|
||||
const existing=foundry.applications.instances.get('adaptive-music-setup');
|
||||
if(existing)return existing.bringToFront();
|
||||
return new setupType().render({force:true});
|
||||
}
|
||||
function openPlayback(){
|
||||
if(!game.user.isGM)return;
|
||||
if(!playbackApp){
|
||||
const Playback=createPlaybackClass({game,connection,getChoices:choices,start,stop,setOverrides,onError,openSetup});
|
||||
playbackApp=new Playback();
|
||||
}
|
||||
return playbackApp.render({force:true});
|
||||
}
|
||||
function ensureRuntime(){
|
||||
runtime??=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,
|
||||
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError});
|
||||
return runtime;
|
||||
}
|
||||
function start(){
|
||||
function start({preserveQueue=false}={}){
|
||||
if(!gmAuthority()||automationRunning)return;
|
||||
automationRunning=true;
|
||||
return ensureRuntime().refresh().catch(onError);
|
||||
const active=ensureRuntime();
|
||||
if(preserveQueue)return active.deferUntilMusicChanges();
|
||||
return active.refresh().catch(error=>{if(error.code!=='stale')onError(error);});
|
||||
}
|
||||
function stop(){
|
||||
automationRunning=false;
|
||||
@@ -45,21 +63,25 @@ function sendInvites(){
|
||||
if(!bootstrap||!gmHost?.connected||!gmAuthority())return;
|
||||
for(const user of game.users){
|
||||
if(!user.active||user.isGM||user.isBanned)continue;const key=bootstrap.recipientKey(user);if(!key)continue;
|
||||
const previous=sentInvites.get(user.id);if(previous?.epoch===key.epoch&&previous.until>Date.now()&&peers.hasListener(user.id))continue;
|
||||
try{const invite=peers.invite(user.id,{ttlMs:1800000,...(privateProfile?.listenerNetwork??{})});await bootstrap.send(user,invite);sentInvites.set(user.id,{epoch:key.epoch,until:Date.now()+1200000});}catch{onError();}
|
||||
const previous=sentInvites.get(user.id);if(previous?.epoch===key.epoch&&peers.hasListener(user.id))continue;
|
||||
try{const invite=peers.invite(user.id,{ttlMs:1800000,...(privateProfile?.listenerNetwork??{})});await bootstrap.send(user,invite);sentInvites.set(user.id,{epoch:key.epoch});}catch{onError();}
|
||||
}
|
||||
});return inviteTail;
|
||||
}
|
||||
const connection={
|
||||
get draftFields(){return {maUrl:privateDraft?.maUrl,targetName:privateDraft?.targetName,retainedToken:!!privateDraft?.token,savedConnection:savedConnection()?.version===1};},
|
||||
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning};},
|
||||
get draftFields(){return {maUrl:privateDraft?.maUrl??savedDevice?.maUrl,targetName:privateDraft?.targetName??savedDevice?.targetName,retainedToken:!!privateDraft?.token,deviceCredential:!!savedDevice,savedConnection:savedConnection()?.version===1};},
|
||||
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),deviceReconnect,deviceError:deviceError?.code,hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange};},
|
||||
async open(profile){
|
||||
if(!gmAuthority()||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
|
||||
if(!gmAuthority()||connectionOpening||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
|
||||
// Claim browser audio activation before authentication performs asynchronous work.
|
||||
const audioContext=gmHost.createContext();
|
||||
connectionOpening=true;
|
||||
const generation=connectionGeneration;
|
||||
try{
|
||||
void audioContext.resume().catch(()=>{});
|
||||
if(!profile.token&&savedDevice&&(!profile.maUrl||profile.maUrl===savedDevice.maUrl)){
|
||||
profile={...savedDevice,...profile,maUrl:savedDevice.maUrl,token:savedDevice.token,targetName:profile.targetName??savedDevice.targetName};
|
||||
}
|
||||
if(!profile.maUrl){
|
||||
const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope());
|
||||
gmAccessPolicy(remembered.maUrl,location.href);
|
||||
@@ -67,11 +89,26 @@ const connection={
|
||||
}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
const {target}=await connection.test(profile);
|
||||
return await connection.connect(target,{audioContext});
|
||||
const result=await connection.connect(target,{audioContext,automatic:profile.automatic===true});
|
||||
if(generation+1===connectionGeneration&&gmAuthority()){
|
||||
if(profile.remember){
|
||||
const credential={maUrl:privateProfile.maUrl,targetName:privateProfile.targetName,token:privateProfile.token,auto:true};
|
||||
try{
|
||||
savedDevice=credential;
|
||||
await receiverVault.saveCredential(credentialScope(),credential);
|
||||
}
|
||||
catch{onError(new MusicError('private-credential-write-failed'));}
|
||||
}else if(savedDevice||deviceError?.code==='private-credential-corrupt'){
|
||||
try{await receiverVault.forgetCredential(credentialScope());savedDevice=null;}
|
||||
catch{onError(new MusicError('private-credential-write-failed'));}
|
||||
}
|
||||
if(generation+1===connectionGeneration){devicePaused=false;deviceError=undefined;}
|
||||
}
|
||||
return result;
|
||||
}catch(error){
|
||||
if(audioContext.state!=='closed')await audioContext.close();
|
||||
if(!gmHost.connected&&audioContext.state!=='closed')await audioContext.close();
|
||||
throw error;
|
||||
}
|
||||
}finally{connectionOpening=false;}
|
||||
},
|
||||
async test(profile){
|
||||
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
|
||||
@@ -88,12 +125,17 @@ const connection={
|
||||
}catch(error){error.stage??='API authentication';throw error;}
|
||||
finally{connectionTesting=false;}
|
||||
},
|
||||
async connect(target,{resumeAutomation=true,audioContext}={}){
|
||||
async connect(target,{resumeAutomation=true,audioContext,automatic=false}={}){
|
||||
if(!privateProfile||target!==privateProfile.target||gateway.connected)throw new MusicError('denied');
|
||||
stop();const profile=privateProfile,generation=connectionGeneration;
|
||||
let result;
|
||||
try{result=await gmHost.start(profile,{audioContext});}
|
||||
finally{if(generation===connectionGeneration)await receiverVault.save(receiverScope(profile),profile);}
|
||||
finally{
|
||||
if(generation===connectionGeneration){
|
||||
try{await receiverVault.save(receiverScope(profile),profile);}
|
||||
catch{onError(new MusicError('receiver-storage-write-failed'));}
|
||||
}
|
||||
}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
try{
|
||||
const saved=await sealAccountConnection(profile,profile.token,accountScope());
|
||||
@@ -101,39 +143,81 @@ const connection={
|
||||
}catch{onError(new MusicError('saved-connection-write-failed'));}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();
|
||||
if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
void interfaces?.refreshDirectory(ui.playlists);
|
||||
if(resumeAutomation&&game.settings.get(id,'enabled')&&(!result.attachedExistingQueue||automatic))start({preserveQueue:result.attachedExistingQueue});
|
||||
return result;
|
||||
},
|
||||
async reconnect(){if(!privateProfile||!gmAuthority())throw {code:'denied'};const generation=++connectionGeneration;stop();peers?.reset();sentInvites.clear();await gmHost.close();if(generation!==connectionGeneration)throw {code:'stale'};return connection.connect(privateProfile.target,{resumeAutomation:false});},
|
||||
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
|
||||
async refresh(){const catalog=await gmHost.refreshCatalog();await interfaces?.refreshDirectory(ui.playlists);return catalog;},
|
||||
resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
|
||||
async playback(){
|
||||
if(!gmAuthority())throw new MusicError('denied');
|
||||
const current=runtime?.controller.current?.playlist;
|
||||
const available=await choices();
|
||||
const playlist=available.find(choice=>choice.provider===current?.provider&&(choice.id===current.id||choice.legacyId===current.id))?.name;
|
||||
if(current?.provider==='native'){
|
||||
const sound=[...game.playlists.get(current.id)?.sounds??[]].find(sound=>sound.playing);
|
||||
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??''};
|
||||
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??'',playlist};
|
||||
}
|
||||
if(gmHost.connected){
|
||||
const priorError=gmHost.status.lastError?.code;
|
||||
try{return {source:'Music Assistant',...await gmHost.playbackStatus(),playlist};}
|
||||
catch(error){if(queueNeedsReview(error)&&priorError!==error.code)onError(error);throw error;}
|
||||
}
|
||||
if(gmHost.connected)return {source:'Music Assistant',...await gmHost.playbackStatus()};
|
||||
return {state:'idle',title:''};
|
||||
},
|
||||
control(action,value){
|
||||
if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied');
|
||||
if(action==='stop'&&automationRunning&&runtime?.controller.current?.playlist)return setOverrides([{id:'gm-stop',playlist:null}]);
|
||||
return ensureRuntime().controller.control(action,value);
|
||||
},
|
||||
async forgetCredentials(){
|
||||
devicePaused=true;
|
||||
await connection.disconnect({retainCredential:false});
|
||||
await receiverVault.forgetCredential(credentialScope());
|
||||
savedDevice=null;deviceError=undefined;
|
||||
},
|
||||
async forgetReceiver(){
|
||||
const scope=privateDraft&&receiverScope(privateDraft);
|
||||
await connection.disconnect();
|
||||
const profile=privateDraft??savedDevice,scope=profile&&receiverScope(profile);
|
||||
await connection.forgetCredentials();
|
||||
await game.settings.set(id,'savedConnection',{});
|
||||
if(scope)await receiverVault.forget(scope);
|
||||
},
|
||||
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();}
|
||||
async disconnect({retainCredential=true}={}){
|
||||
devicePaused=true;connectionGeneration++;stop();peers?.reset();sentInvites.clear();
|
||||
privateProfile=null;privateDraft=null;await gmHost.close();
|
||||
void interfaces?.refreshDirectory(ui.playlists);
|
||||
if(retainCredential&&savedDevice?.auto){
|
||||
savedDevice={...savedDevice,auto:false};
|
||||
await receiverVault.saveCredential(credentialScope(),savedDevice);
|
||||
}
|
||||
}
|
||||
};
|
||||
async function reconnectTrustedDevice(){
|
||||
if(deviceReconnect||connectionOpening||devicePaused||!savedDevice?.auto||!gmAuthority()||gmHost.connected||gateway.connected)return;
|
||||
deviceReconnect=true;
|
||||
try{
|
||||
await connection.open({...savedDevice,remember:true,automatic:true});
|
||||
if(gmHost.status.audioContext!=='running')ui.notifications.info('Adaptive Music connected. Open Playback and select Enable GM audio if your browser requires it.');
|
||||
}catch(error){
|
||||
deviceError=error;
|
||||
if(error.code==='ws-auth-denied')devicePaused=true;
|
||||
onError(error);
|
||||
if(game.settings.get(id,'enabled'))void start();
|
||||
}finally{deviceReconnect=false;}
|
||||
}
|
||||
function listenWebRTC(invite){
|
||||
if(game.user.isGM||!peers)throw Error('Listener only');
|
||||
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
|
||||
}
|
||||
function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
|
||||
Hooks.once('init',()=>{
|
||||
Hooks.on('getSceneControlButtons',controls=>{
|
||||
if(!game.user?.isGM||!controls.tokens?.tools)return;
|
||||
const tools=controls.tokens.tools;
|
||||
tools.adaptiveMusic={name:'adaptiveMusic',title:'Adaptive Music controls',icon:'fa-solid fa-music',order:Object.keys(tools).length,button:true,onChange:openPlayback};
|
||||
});
|
||||
game.settings.register(id,'savedConnection',{scope:'user',config:false,type:Object,default:{}});
|
||||
game.settings.register(id,'advancedDevelopment',{name:'Show advanced development controls',hint:'Optional companion and manual test capabilities. Not needed for normal music setup.',scope:'client',config:true,type:Boolean,default:false});
|
||||
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});
|
||||
@@ -144,6 +228,7 @@ Hooks.once('init',()=>{
|
||||
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,connection});
|
||||
const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError,resumeListener,listenerStatus:()=>listenerState});
|
||||
setupType=Setup;
|
||||
game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Enable Audio',hint:'Connects automatically to GM audio. Enable sound if your browser asks.',icon:'fas fa-headphones',type:Listener,restricted:false});
|
||||
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Music Assistant connection, scene music and Foundry fallback.',icon:'fas fa-music',type:Setup,restricted:true});
|
||||
}
|
||||
@@ -154,7 +239,19 @@ Hooks.once('ready',()=>{
|
||||
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(!game.user.isGM&&[...game.users].filter(u=>u.active&&u.isGM).length!==1){peers.reset();remoteAudio?.pause();latestInvite=null;listenerState='Waiting for one active GM.';}sendInvites();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
|
||||
if(game.socket&&game.user.setFlag){bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{latestInvite=invite;if(listenerStopped)return;peers.reset();await listenWebRTC(invite);}});bootstrap.start().then(sendInvites).catch(onError);inviteTimer=setInterval(()=>{sendInvites();if(game.user.isGM&&runtime&&!gmHost.connected&&privateProfile){stop();peers.reset();sentInvites.clear();onError();}},15000);}
|
||||
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);}
|
||||
if(game.user.isGM){
|
||||
interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,openPlayback,onError});
|
||||
void interfaces.refreshDirectory(ui.playlists);
|
||||
if(game.world?.id)receiverVault.loadCredential(credentialScope()).then(credential=>{
|
||||
if(!devicePaused&&!connectionOpening&&connectionGeneration===0)savedDevice=credential;
|
||||
if(!savedDevice?.auto&&game.settings.get(id,'enabled'))return start();
|
||||
return reconnectTrustedDevice();
|
||||
}).catch(error=>{deviceError=error;onError(error);if(game.settings.get(id,'enabled'))void start();});
|
||||
renewTimer=setInterval(()=>{
|
||||
if(gateway.connected&&primaryGM(game.users)===game.user.id)gateway.renew().catch(onError);
|
||||
if(!deviceError||['ws-upgrade-failed','ws-disconnected','ws-auth-timeout'].includes(deviceError.code))void reconnectTrustedDevice();
|
||||
},15000);
|
||||
}
|
||||
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;},
|
||||
@@ -169,5 +266,4 @@ Hooks.once('ready',()=>{
|
||||
enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(),
|
||||
dispose(){stop();listenerSource?.disconnect();listenerContext?.close();privateProfile=null;bootstrap?.close();clearInterval(inviteTimer);for(const [event,hook]of authorityHooks)Hooks.off(event,hook);authorityHooks=[];interfaces?.dispose();clearInterval(renewTimer);gateway.disconnect();audio.stop();gmHost?.close();peers?.close();remoteAudio?.pause();remoteAudio?.remove();interfaces=null;}
|
||||
};
|
||||
if(game.settings.get(id,'enabled'))start();
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {musicFields,referenceKey,selection} from '../core/scene-music.mjs';
|
||||
const namespace='adaptive-music';
|
||||
export const playlistDragType='application/x-adaptive-music-playlist';
|
||||
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')??{};
|
||||
@@ -22,15 +23,33 @@ export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use wor
|
||||
if(current&&!replacement&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
|
||||
select.value=referenceKey(replacement||current);return select;
|
||||
}
|
||||
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
|
||||
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{},sceneSheet=false}){
|
||||
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 legend=dom.createElement('legend');legend.textContent=defaults?'World music defaults':sceneSheet?'Adaptive Music':'Scene music';panel.append(legend);
|
||||
const previous=defaults?game.settings.get(namespace,'musicDefaults')??{}:document.getFlag(namespace,'music')??{};
|
||||
const labels={ambient:'Ambient playlist',combat:'Combat playlist',boss:'Default boss music',fallback:'Foundry fallback playlist'};
|
||||
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);
|
||||
for(const field of musicFields){
|
||||
const label=dom.createElement('label');label.textContent=labels[field]+' ';
|
||||
const current=previous[field]??(field==='ambient'?previous.playlist:null);
|
||||
const select=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(select);panel.append(label);
|
||||
if(field==='fallback')continue;
|
||||
label.addEventListener('dragover',event=>{if(event.dataTransfer?.types.includes(playlistDragType)){event.preventDefault();event.dataTransfer.dropEffect='copy';}});
|
||||
label.addEventListener('drop',event=>{
|
||||
if(!event.dataTransfer?.types.includes(playlistDragType))return;
|
||||
event.preventDefault();event.stopPropagation();
|
||||
const value=event.dataTransfer.getData(playlistDragType);
|
||||
if(choices.some(choice=>choice.provider==='ma'&&referenceKey(choice)===value))select.value=value;
|
||||
});
|
||||
}
|
||||
if(sceneSheet&&!choices.some(choice=>choice.provider==='ma')){
|
||||
const note=dom.createElement('p');note.textContent='Connect Music Assistant to choose playlists for this scene.';panel.append(note);
|
||||
}
|
||||
if(document?.playlist){
|
||||
const note=dom.createElement('p');note.textContent='This scene uses a Foundry soundtrack. Clear the native playlist to let Adaptive Music control the scene’s music.';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;}});
|
||||
|
||||
@@ -4,13 +4,14 @@ import {referenceKey,selection} from '../core/scene-music.mjs';
|
||||
const clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
|
||||
const states={playing:'Playing',paused:'Paused',idle:'Stopped'};
|
||||
|
||||
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError}) {
|
||||
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError,openSetup}) {
|
||||
const dom=container.ownerDocument;
|
||||
const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||
make('h2','Playback');
|
||||
const now=make('section');now.className='adaptive-now';
|
||||
const state=make('p','Stopped',now);state.className='adaptive-state';
|
||||
const track=make('h3','Nothing playing',now);
|
||||
const playlist=make('p',null,now);
|
||||
const timing=make('p',null,now);
|
||||
const controls=make('div');controls.className='adaptive-actions';
|
||||
const output=make('div');output.className='adaptive-fields';
|
||||
@@ -18,6 +19,11 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
volume.type='range';volume.min='0';volume.max='100';volume.value='100';
|
||||
const seekLabel=make('label','Playback position',output),seek=make('input',null,seekLabel);
|
||||
seek.type='range';seek.min='0';seek.max='0';seek.step='1';seek.value='0';
|
||||
const repeatLabel=make('label','Repeat',output),repeat=make('select',null,repeatLabel);
|
||||
repeat.setAttribute('aria-label','Repeat');
|
||||
for(const [value,label] of [['off','Off'],['all','Playlist'],['one','Track']]){
|
||||
const option=make('option',label,repeat);option.value=value;
|
||||
}
|
||||
const summary=make('div');summary.className='adaptive-playback-summary';
|
||||
const automationText=make('p',null,summary),listeners=make('p',null,summary);
|
||||
const status=make('p');status.setAttribute('role','status');
|
||||
@@ -30,6 +36,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume'));
|
||||
toggle.className='adaptive-primary';
|
||||
const stopTrack=button(controls,'Stop playback',()=>connection.control('stop'));
|
||||
const skip=button(controls,'Skip track',()=>connection.control('next'));
|
||||
const unlock=button(controls,'Enable GM audio',()=>connection.resume());
|
||||
const automation=button(summary,'Enable automation',async()=>{
|
||||
const enable=!isRunning();
|
||||
@@ -43,13 +50,18 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
const label=make('label','Override playlist',manual),select=make('select',null,label);
|
||||
const manualActions=make('div',null,manual);manualActions.className='adaptive-actions';
|
||||
button(manualActions,'Apply override',()=>setOverrides([{id:'gm-manual',playlist:selection(select.value,getChoices())}]));
|
||||
button(manualActions,'Clear override',()=>setOverrides([]));
|
||||
const automatic=button(controls,'Return to scene music',()=>setOverrides([]));
|
||||
if(openSetup)button(manualActions,'Open Adaptive Music setup',openSetup);
|
||||
function isRunning(){return connection?.status.automationRunning??game.settings.get('adaptive-music','enabled');}
|
||||
|
||||
volume.addEventListener('input',()=>{volumeEditing=true;volume.setAttribute('aria-valuetext',`${volume.value}%`);});
|
||||
volume.addEventListener('change',()=>run(()=>connection.setVolume(Number(volume.value))).finally(()=>{volumeEditing=false;}));
|
||||
seek.addEventListener('input',()=>{seekEditing=true;seek.setAttribute('aria-valuetext',clock(Number(seek.value)));});
|
||||
seek.addEventListener('change',()=>run(()=>connection.control('seek',Number(seek.value))).finally(()=>{seekEditing=false;}));
|
||||
repeat.addEventListener('change',()=>{
|
||||
const mode=repeat.value;
|
||||
void run(()=>connection.control('repeat',mode));
|
||||
});
|
||||
|
||||
async function run(action){
|
||||
if(busy||!game.user.isGM)return;
|
||||
@@ -60,9 +72,11 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
}
|
||||
function render(){
|
||||
const d=connection?.status??{},connected=d.state==='connected',playing=trackStatus?.state==='playing',paused=trackStatus?.state==='paused';
|
||||
const canControl=connected&&trackStatus?.source==='Music Assistant'&&d.lastError?.code!=='uncertain';
|
||||
const queueError=['uncertain','receiver-access-lost'].includes(d.lastError?.code);
|
||||
const canControl=connected&&trackStatus?.source==='Music Assistant'&&!queueError;
|
||||
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
|
||||
track.textContent=trackStatus?.title||'Nothing playing';
|
||||
playlist.textContent=trackStatus?.playlist||'';
|
||||
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:'';
|
||||
if(!volumeEditing){volume.value=String(d.volume??100);volume.setAttribute('aria-valuetext',`${volume.value}%`);}
|
||||
if(!seekEditing){
|
||||
@@ -71,13 +85,19 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
}
|
||||
toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused);
|
||||
stopTrack.disabled=busy||!canControl||!(playing||paused);
|
||||
skip.disabled=busy||!canControl||!playing;
|
||||
automatic.hidden=!d.overrideActive&&!d.awaitingSceneChange;automatic.disabled=busy;
|
||||
volume.disabled=busy||!connected;seek.disabled=busy||!canControl||!(playing||paused)||Number(seek.max)<=0;
|
||||
repeat.disabled=busy||!canControl||!trackStatus?.repeat;
|
||||
repeat.value=trackStatus?.repeat??'off';
|
||||
unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
|
||||
const enabled=isRunning();
|
||||
automationText.textContent=enabled?'Automation active':game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
|
||||
automationText.textContent=enabled
|
||||
? d.overrideActive?'Manual override active':d.awaitingSceneChange?'Automation will resume at the next scene cue':'Automation active'
|
||||
: game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
|
||||
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
|
||||
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
|
||||
if(d.lastError?.code==='uncertain'){
|
||||
if(queueError){
|
||||
failure.textContent=`Queue needs review. ${connectionMessage(d.lastError)}`;failure.hidden=false;
|
||||
}
|
||||
const choices=getChoices();const display=JSON.stringify(choices.map(choice=>[referenceKey(choice),choice.name]));
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
// GM browser profile only. A non-extractable key protects the stored receiver
|
||||
// material; same-origin scripts and the browser profile owner remain trusted.
|
||||
// MA access tokens are intentionally excluded from the serialization surface.
|
||||
// Receiver records never contain the optional device credential.
|
||||
export class ReceiverVault{
|
||||
#database;#tail=Promise.resolve();
|
||||
async #db(){
|
||||
if(!globalThis.indexedDB)throw new MusicError('private-storage-unavailable');
|
||||
this.#database??=new Promise((resolve,reject)=>{const request=indexedDB.open('adaptive-music-private-receivers',1);request.onupgradeneeded=()=>request.result.createObjectStore('records');request.onsuccess=()=>resolve(request.result);request.onerror=()=>reject(new MusicError('private-storage-unavailable'));request.onblocked=()=>reject(new MusicError('private-storage-unavailable'));});
|
||||
this.#database??=new Promise((resolve,reject)=>{
|
||||
let blocked=false;
|
||||
const request=indexedDB.open('adaptive-music-private-receivers',1);
|
||||
request.onupgradeneeded=()=>request.result.createObjectStore('records');
|
||||
request.onsuccess=()=>{
|
||||
const db=request.result;
|
||||
if(blocked){db.close();return;}
|
||||
db.onversionchange=()=>{db.close();this.#database=undefined;};
|
||||
resolve(db);
|
||||
};
|
||||
request.onerror=()=>reject(new MusicError('private-storage-unavailable'));
|
||||
request.onblocked=()=>{blocked=true;reject(new MusicError('private-storage-unavailable'));};
|
||||
}).catch(()=>{
|
||||
this.#database=undefined;
|
||||
throw new MusicError('private-storage-unavailable');
|
||||
});
|
||||
return this.#database;
|
||||
}
|
||||
async #scope({campaign,userId,maUrl}){
|
||||
@@ -38,5 +53,41 @@ export class ReceiverVault{
|
||||
await this.#transaction(id,{key,iv,data});
|
||||
});this.#tail=op;return op;
|
||||
}
|
||||
async forget(scope){await this.#tail.catch(()=>{});await this.#transaction(await this.#scope(scope),undefined,true);}
|
||||
forget(scope){
|
||||
const operation=this.#tail.catch(()=>{}).then(async()=>this.#transaction(await this.#scope(scope),undefined,true));
|
||||
this.#tail=operation;
|
||||
return operation;
|
||||
}
|
||||
async #credentialId({campaign,userId}){
|
||||
return 'credential:'+await this.#scope({campaign,userId,maUrl:globalThis.location.origin});
|
||||
}
|
||||
async loadCredential(scope){
|
||||
const id=await this.#credentialId(scope);
|
||||
const record=await this.#transaction(id);
|
||||
if(!record)return null;
|
||||
try{
|
||||
const bytes=await crypto.subtle.decrypt({name:'AES-GCM',iv:record.iv,additionalData:new TextEncoder().encode(id)},record.key,record.data);
|
||||
const value=JSON.parse(new TextDecoder().decode(bytes));
|
||||
if(value.version!==1||typeof value.maUrl!=='string'||typeof value.token!=='string'||typeof value.auto!=='boolean')throw Error();
|
||||
return value;
|
||||
}catch{throw new MusicError('private-credential-corrupt');}
|
||||
}
|
||||
saveCredential(scope,{maUrl,token,targetName,auto}){
|
||||
const operation=this.#tail.catch(()=>{}).then(async()=>{
|
||||
const id=await this.#credentialId(scope);
|
||||
const bytes=new TextEncoder().encode(JSON.stringify({version:1,maUrl,token,targetName,auto}));
|
||||
if(typeof token!=='string'||!token||bytes.length>8192||typeof auto!=='boolean')throw new MusicError('private-credential-write-failed');
|
||||
const key=await crypto.subtle.generateKey({name:'AES-GCM',length:256},false,['encrypt','decrypt']);
|
||||
const iv=crypto.getRandomValues(new Uint8Array(12));
|
||||
const data=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:new TextEncoder().encode(id)},key,bytes);
|
||||
await this.#transaction(id,{key,iv,data});
|
||||
});
|
||||
this.#tail=operation;
|
||||
return operation;
|
||||
}
|
||||
forgetCredential(scope){
|
||||
const operation=this.#tail.catch(()=>{}).then(async()=>this.#transaction(await this.#credentialId(scope),undefined,true));
|
||||
this.#tail=operation;
|
||||
return operation;
|
||||
}
|
||||
}
|
||||
+30
-11
@@ -1,4 +1,4 @@
|
||||
import { MusicController } from '../core/controller.mjs';
|
||||
import { candidates,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)
|
||||
@@ -16,26 +16,45 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
|
||||
if (previousController) {
|
||||
controller.generation = previousController.generation;
|
||||
controller.tail = previousController.tail;
|
||||
const previous=previousController.current;
|
||||
// The MA session is disposable. Native playback lives in Foundry and
|
||||
// remains the outgoing source when the browser connects to MA.
|
||||
if(previous?.playlist?.provider==='native'&&provider.owned.has(previous.playlist.id))controller.current=previous;
|
||||
if(previousController.dirty.has(previousController.providers.native))controller.dirty.add(provider);
|
||||
}
|
||||
let overrides = [];
|
||||
const refresh = () => {
|
||||
if (!isEnabled() || !authority()) return Promise.resolve();
|
||||
let overrides = [],deferredState;
|
||||
const getState = () => {
|
||||
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)},
|
||||
const nativeScenePlaylist=scene?.playlist?.id??scene?.playlist;
|
||||
const choose=(ref,fallback)=>{
|
||||
if(nativeScenePlaylist)return null;
|
||||
return ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
|
||||
};
|
||||
return 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};})}))});
|
||||
};
|
||||
const refresh = () => {
|
||||
if (!isEnabled() || !authority()) return Promise.resolve();
|
||||
const state=getState();
|
||||
const intent=candidates(state)[0].key;
|
||||
if(deferredState===intent)return Promise.resolve();
|
||||
deferredState=undefined;
|
||||
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(); },
|
||||
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'deletePlaylist', 'deletePlaylistSound'];
|
||||
const subscriptions = events.map(event => [event, Hooks.on(event, (document,changes) => {
|
||||
if(event==='updateSetting'&&!['adaptive-music.musicDefaults','adaptive-music.defaultPlaylist'].includes(document?.key))return;
|
||||
if(event==='updateScene'&&changes&&!Object.hasOwn(changes,'active')&&!Object.hasOwn(changes,'flags')&&!Object.hasOwn(changes,'playlist'))return;
|
||||
refresh().catch(error=>{if(error.code!=='stale')onError(error);});
|
||||
})]);
|
||||
return { controller, refresh,get overrideActive(){return overrides.length>0;},get awaitingSceneChange(){return deferredState!==undefined;},
|
||||
deferUntilMusicChanges:()=>{deferredState=candidates(getState())[0].key;},
|
||||
setOverrides: value => { deferredState=undefined;overrides = structuredClone(value); return refresh(); },
|
||||
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
|
||||
};
|
||||
}
|
||||
+25
-1
@@ -53,6 +53,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
|
||||
make('h2','Assign scene music',scenePanel);
|
||||
const sceneLabel=make('label','Scene',scenePanel),scenes=make('select',null,sceneLabel);
|
||||
scenes.setAttribute('aria-label','Scene');
|
||||
for(const scene of game.scenes)addOption(scenes,scene.id,scene.name);
|
||||
const selected=game.scenes.get(this.#scene)??[...game.scenes].find(scene=>scene.active);
|
||||
if(selected)scenes.value=selected.id;
|
||||
@@ -81,7 +82,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.';
|
||||
},ownershipStatus);
|
||||
|
||||
let choices=[];
|
||||
let choices=[],lastCatalog=connection?.status.catalog;
|
||||
const showScene=()=>{
|
||||
this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value);
|
||||
if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError});
|
||||
@@ -92,6 +93,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
if(document)mountBossEditor({document,game,container:bossBody,choices,onError});
|
||||
};
|
||||
const refreshAssignments=async()=>{
|
||||
lastCatalog=connection?.status.catalog;
|
||||
choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren();
|
||||
mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError});
|
||||
};
|
||||
@@ -117,6 +119,9 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
this.#timer=setInterval(()=>{
|
||||
if(!root.isConnected)return;
|
||||
if(this.#tab==='connection')refreshConnection();
|
||||
if(connection?.status.catalog!==lastCatalog){
|
||||
lastCatalog=connection?.status.catalog;void refreshAssignments();
|
||||
}
|
||||
if(this.#tab==='playback')void refreshPlayback();
|
||||
},1500);
|
||||
}
|
||||
@@ -127,6 +132,25 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
};
|
||||
}
|
||||
|
||||
export function createPlaybackClass({game,connection,getChoices,start,stop,setOverrides,onError,openSetup,Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
return class AdaptiveMusicControls extends Base {
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-controls',window:{title:'Adaptive Music playback',resizable:true},position:{width:500,height:525}};
|
||||
#timer;
|
||||
async _renderHTML(){
|
||||
const root=document.createElement('div');
|
||||
root.className='adaptive-music-setup';
|
||||
let choices=await getChoices();
|
||||
const refresh=mountPlaybackPanel({game,container:root,connection,getChoices:()=>choices,start,stop,setOverrides,onError,openSetup});
|
||||
clearInterval(this.#timer);
|
||||
this.#timer=setInterval(async()=>{if(root.isConnected){choices=await getChoices();await refresh();}},1500);
|
||||
void refresh();
|
||||
return root;
|
||||
}
|
||||
_replaceHTML(result,content){content.replaceChildren(result);}
|
||||
_onClose(...args){clearInterval(this.#timer);super._onClose?.(...args);}
|
||||
};
|
||||
}
|
||||
|
||||
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,listenerStatus=()=>'Waiting for the GM to connect Music Assistant.',resumeListener=()=>{},Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
return class AdaptiveMusicListener extends Base {
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio'},position:{width:480}};
|
||||
|
||||
@@ -166,7 +166,7 @@ export class MAReadClient {
|
||||
}
|
||||
// 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'],
|
||||
const fields = {stop:[],pause:[],resume:[],next:[],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');
|
||||
|
||||
@@ -4,14 +4,28 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
|
||||
const base=new URL(baseUrl);
|
||||
if(base.username||base.password||base.search||base.hash||base.pathname!=='/'||!['https:','http:'].includes(base.protocol))throw {code:'address-invalid'};
|
||||
if(globalThis.location?.protocol==='https:'&&base.protocol!=='https:')throw {code:'mixed-content'};
|
||||
// Permissions are advisory. Browser support and names vary, and "prompt"
|
||||
// does not establish that this particular destination needs permission.
|
||||
const permissions={};
|
||||
for(const name of ['local-network','local-network-access','local-network-devices','loopback-network']){
|
||||
try{
|
||||
const state=(await globalThis.navigator?.permissions?.query({name}))?.state;
|
||||
if(['granted','prompt','denied'].includes(state))permissions[name]=state;
|
||||
}catch{}
|
||||
}
|
||||
const results=[];
|
||||
// Sequential, bounded and deliberately unauthenticated. No player or queue commands.
|
||||
for(const path of ['/ws','/sendspin']){
|
||||
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
|
||||
results.push(await new Promise(resolve=>{
|
||||
let socket,timer,done=false,csp=false;
|
||||
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code});};
|
||||
const policy=event=>{if(event.disposition==='enforce'&&['connect-src','default-src'].includes(event.effectiveDirective)&&event.blockedURI===url.href){csp=true;finish('csp-blocked');}};
|
||||
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code,...(Object.keys(permissions).length&&{permissions})});};
|
||||
const policy=event=>{
|
||||
if(event.disposition!=='enforce'||!['connect-src','default-src'].includes(event.effectiveDirective))return;
|
||||
if(event.blockedURI===url.href||event.blockedURI===url.origin||event.blockedURI===url.origin+'/'){
|
||||
csp=true;finish('csp-blocked');
|
||||
}
|
||||
};
|
||||
events?.addEventListener('securitypolicyviolation',policy);
|
||||
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs);
|
||||
try{socket=createSocket(url.href);socket.onopen=()=>finish('upgrade-ok');socket.onerror=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);socket.onclose=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);}catch{setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),50);}
|
||||
@@ -19,9 +33,13 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
|
||||
}
|
||||
return results;
|
||||
}
|
||||
export const diagnosticMessage=result=>({
|
||||
export const diagnosticMessage=result=>{
|
||||
const hint=result.code!=='upgrade-ok'&&Object.entries(result.permissions??{}).some(([permission,state])=>permission!=='loopback-network'&&state==='denied')
|
||||
? ' This Foundry site also reports denied local network access. If the proxy is on your private network, review Foundry’s site permission in the browser.' : '';
|
||||
return ({
|
||||
'upgrade-ok':'WebSocket upgrade succeeded from this page. Authentication, receiver pairing and audio are still untested.',
|
||||
'csp-blocked':'This page’s enforced Content Security Policy blocked the connection. Ask the Foundry host administrator to allow the exact trusted MA WSS origin in connect-src; retain existing policy restrictions.',
|
||||
'upgrade-timeout':'No WebSocket upgrade within 5 seconds. Check the private route and compare from the MA page. Browser APIs cannot identify DNS, TLS or firewall causes.',
|
||||
'upgrade-failed':'The browser did not expose a successful upgrade. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.'
|
||||
}[result.code]??'Diagnostic unavailable.');
|
||||
}[result.code]??'Diagnostic unavailable.')+hint;
|
||||
};
|
||||
@@ -21,6 +21,7 @@ export class MAPlaybackProvider {
|
||||
title: typeof item?.name === 'string' ? item.name.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 180) : '',
|
||||
duration: Number.isFinite(item?.duration) ? Math.max(0, Math.floor(item.duration)) : 0,
|
||||
position,
|
||||
repeat: queue.repeat_mode,
|
||||
};
|
||||
}
|
||||
#check(ctx) {
|
||||
@@ -41,7 +42,7 @@ export class MAPlaybackProvider {
|
||||
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');
|
||||
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1) 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();
|
||||
@@ -50,12 +51,12 @@ export class MAPlaybackProvider {
|
||||
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 elapsed=after.ended ? 0 : 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);
|
||||
const value={version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+43200000,
|
||||
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
|
||||
state:after.ended?'idle':after.state,ended:after.ended===true,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
|
||||
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
|
||||
if(this.#paused){if(value.state!=='idle'||JSON.stringify(value.items)!==JSON.stringify(this.#paused.items))throw new MusicError('stale');return {...value,state:'paused',index:this.#paused.index,position:this.#paused.position};}
|
||||
return value;
|
||||
@@ -72,16 +73,18 @@ export class MAPlaybackProvider {
|
||||
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>{this.#paused=undefined;return 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}};
|
||||
const args={pause:{},resume:{},stop:{},next:{},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()=>{
|
||||
if(action==='pause'&&this.#client.supportsNativePause?.()===false){
|
||||
const captured=await this.#capture(ctx);if(!captured.items.length)return;
|
||||
const captured=await this.#capture(ctx);if(!captured.items.length||captured.ended)return;
|
||||
await this.#client.mutate('stop',{},this.#context(ctx));this.#paused=captured;
|
||||
}else if(action==='resume'&&this.#paused){
|
||||
const captured=await this.#capture(ctx);await this.#client.mutate('play_index',{index:captured.index,seek_position:captured.position},this.#context(ctx));this.#paused=undefined;
|
||||
}else if(action==='seek'&&this.#paused){
|
||||
const captured=await this.#capture(ctx);if(!Number.isSafeInteger(value)||value<0||!(captured.items[captured.index]?.duration>value))throw new MusicError('unsupported');this.#paused={...captured,position:value};
|
||||
}else if(action==='next'&&this.#paused){
|
||||
throw new MusicError('unsupported');
|
||||
}else{if(action==='stop')this.#paused=undefined;await this.#client.mutate(action,args[action],this.#context(ctx));}
|
||||
this.#epoch++;
|
||||
});
|
||||
@@ -103,8 +106,11 @@ export class MAPlaybackProvider {
|
||||
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');
|
||||
if(value.state==='paused'&&this.#client.supportsNativePause?.()===false)this.#paused=structuredClone(value);
|
||||
else{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',{});
|
||||
else if(!value.ended){
|
||||
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',{});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {MusicError} from '../../core/controller.mjs';
|
||||
const commands=new Set(['sendspin/pair_web_player','providers','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)]);
|
||||
const commands=new Set(['sendspin/pair_web_player','providers','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','next','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;#authenticated=false;#onDisconnect;
|
||||
|
||||
@@ -24,7 +24,7 @@ export class NativeProvider {
|
||||
return { id: p.id, soundId: sound.id };
|
||||
}
|
||||
async snapshot(ctx) {
|
||||
const playlists = [...this.owned].map(id => {
|
||||
const playlists = [...this.owned].filter(id=>!this.sceneConflict(id)).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,
|
||||
@@ -35,6 +35,7 @@ export class NativeProvider {
|
||||
}
|
||||
async stopOwned(ctx) {
|
||||
for (const id of this.owned) {
|
||||
if(this.sceneConflict(id))continue;
|
||||
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); }
|
||||
|
||||
Reference in new issue
Block a user