Adaptive Music v0.8.0 release candidate
Validate and generate manual release / package (push) Waiting to run

This commit is contained in:
Jason committed 2026-12-05 09:40:14 -05:00
1 parent 8c07a468a4
commit 95b0427aa1
48 files changed
+3631 -313

No files matched your search

+1 -1
View File
@@ -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
View File
@@ -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();}
}
+136
View File
@@ -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;
}
}
+13 -5
View File
@@ -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;}
}