Adaptive Music v0.8.3 multiplayer and floating music controls
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
acc8cbafc6
commit
fbc265b526
33 files changed
+1673
-131
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {activeMusicGM,isMusicListener} from '../foundry/authority.mjs';
|
||||
const ns='adaptive-music',flag='audioPublicKey',channel='module.adaptive-music';
|
||||
const encode=a=>btoa(String.fromCharCode(...a));
|
||||
const decode=s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));
|
||||
@@ -24,7 +25,7 @@ export class AutoListeners {
|
||||
}
|
||||
recipientKey(user){const value=user?.getFlag(ns,flag);return valid(value)?value:null;}
|
||||
async send(user,invite){
|
||||
if(!this.#isGM()||!this.#public||!user.active||user.isGM||user.isBanned||invite.userId!==user.id)throw new MusicError('denied');
|
||||
if(!this.#isGM()||!this.#public||!user.active||!isMusicListener(user)||invite.userId!==user.id)throw new MusicError('denied');
|
||||
const recipient=this.recipientKey(user);if(!recipient)throw new MusicError('unavailable');
|
||||
const header={type:'audio-invite-v1',campaign:this.#game.world.id,from:this.#game.user.id,to:user.id,sender:this.#public.epoch,recipient:recipient.epoch,id:crypto.randomUUID()};
|
||||
const iv=crypto.getRandomValues(new Uint8Array(12)),key=await this.#key(recipient,'encrypt');
|
||||
@@ -33,16 +34,17 @@ export class AutoListeners {
|
||||
this.#socket.emit(channel,{...header,iv:encode(iv),cipher:encode(new Uint8Array(cipher))});
|
||||
}
|
||||
async receive(packet){
|
||||
if(this.#closed||!this.#keys||this.#game.user.isGM||packet?.type!=='audio-invite-v1'||packet.to!==this.#game.user.id||packet.campaign!==this.#game.world.id||packet.recipient!==this.#public.epoch)return;
|
||||
if(this.#closed||!this.#keys||!isMusicListener(this.#game.user)||packet?.type!=='audio-invite-v1'||packet.to!==this.#game.user.id||packet.campaign!==this.#game.world.id||packet.recipient!==this.#public.epoch)return;
|
||||
if(Object.keys(packet).sort().join(',')!=='campaign,cipher,from,id,iv,recipient,sender,to,type'||typeof packet.id!=='string'||packet.id.length!==36||typeof packet.cipher!=='string'||packet.cipher.length>16384||typeof packet.iv!=='string'||packet.iv.length!==16||this.#pending>=2||this.#received.has(packet.id)||this.#received.size>=256)throw new MusicError('denied');
|
||||
const gms=[...this.#game.users].filter(u=>u.active&&u.isGM),gm=gms[0];
|
||||
if(gms.length!==1||gm.id!==packet.from||gm.isBanned)throw new MusicError('denied');
|
||||
const gm=activeMusicGM(this.#game.users);
|
||||
if(gm?.id!==packet.from)throw new MusicError('denied');
|
||||
const remote=this.recipientKey(gm);if(remote?.epoch!==packet.sender)throw new MusicError('denied');
|
||||
const localEpoch=this.#public.epoch;this.#pending++;
|
||||
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||gm.isBanned||[...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||
|
||||
activeMusicGM(this.#game.users)?.id!==gm.id||!isMusicListener(this.#game.user))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);
|
||||
|
||||
+16
-2
@@ -19,6 +19,7 @@ function browserAudioContext(){
|
||||
catch{throw new MusicError('audio-context-unavailable');}
|
||||
}
|
||||
export class GMAudioHost{
|
||||
#monitor; #monitorLevel=1;
|
||||
#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};}
|
||||
@@ -101,7 +102,15 @@ export class GMAudioHost{
|
||||
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: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.#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);
|
||||
const output=this.#meter??this.#gain;
|
||||
output.connect(this.#destination);
|
||||
this.#monitor=this.#context.createGain();
|
||||
this.#monitor.gain.value=this.#monitorLevel;
|
||||
output.connect(this.#monitor);
|
||||
this.#monitor.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');
|
||||
@@ -195,5 +204,10 @@ export class GMAudioHost{
|
||||
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||
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;this.#timeline=null;this.#transitionGain=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
setMonitorLevel(level){
|
||||
if(!Number.isFinite(level)||level<0||level>1)throw new MusicError('denied');
|
||||
this.#monitorLevel=level;
|
||||
this.#monitor?.gain.setTargetAtTime(level,this.#context.currentTime,0.015);
|
||||
}
|
||||
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.#monitor=null;this.#timeline=null;this.#transitionGain=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
}
|
||||
Reference in new issue
Block a user