Release v0.7.0 - Automatic pairing and validated MA audio playback
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
83d168f5a1
commit
1ed30567fb
48 files changed
+2717
-742
No files matched your search
+88
-40
@@ -4,23 +4,39 @@ import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
|
||||
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
|
||||
import {randomKey} from '../providers/ma/webcrypto.mjs';
|
||||
export function gmAccessPolicy(baseUrl,pageUrl){
|
||||
const target=new URL(baseUrl),page=new URL(pageUrl);
|
||||
let target,page;try{target=new URL(baseUrl);page=new URL(pageUrl);}catch{throw new MusicError('address-invalid');}
|
||||
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
|
||||
if(page.protocol==='https:'&&target.protocol!=='https:')throw new MusicError('mixed-content');
|
||||
if(page.protocol!=='https:'&&!['localhost','127.0.0.1','[::1]'].includes(page.hostname))throw new MusicError('insecure-context');
|
||||
return target;
|
||||
}
|
||||
function memoryStorage(values){const map=new Map(Object.entries(values));return {getItem:k=>map.get(k)??null,setItem:(k,v)=>map.set(k,v),removeItem:k=>map.delete(k)};}
|
||||
function memoryStorage(values){return {getItem:k=>values[k]??null,setItem:(k,v)=>{values[k]=v;},removeItem:k=>{delete values[k];}};}
|
||||
export class GMAudioHost{
|
||||
#authority;#sdk;#core;#context;#destination;#nodes=new Set();#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0;
|
||||
#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(){return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback};}
|
||||
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};}
|
||||
get catalog(){return structuredClone(this.#catalog);}
|
||||
get session(){return this.#session;}
|
||||
get stream(){return this.#destination?.stream;}
|
||||
get connected(){return this.#live;}
|
||||
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
|
||||
async inspect(profile){
|
||||
async prepare(profile){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);this.#phase='API authentication';
|
||||
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||
try{
|
||||
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'providers',args:{provider_type:'music'}})});
|
||||
const providers=await response.json();
|
||||
if(!Array.isArray(providers))throw new MusicError('catalog-empty');
|
||||
const approvedProviders=providers.filter(p=>p.available===true&&typeof p.instance_id==='string').map(p=>p.instance_id);
|
||||
if(!approvedProviders.length)throw new MusicError('catalog-empty');
|
||||
const sdk=await this.loadSDK(),identityStorage=profile.identityStorage??{},identity=sdk.loadSendspinClientIdentity(memoryStorage(identityStorage));
|
||||
const catalogKey=profile.catalogKey??btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode('adaptive-music-catalog-v1:'+profile.campaign+':'+identityStorage['sendspin-identity-sk'])))));
|
||||
this.#phase='authenticated';
|
||||
return {...profile,maUrl:base.origin,identityStorage,target:identity.clientId,targetName:profile.targetName||'Adaptive Music campaign',approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign,autoProvision:true,campaignOwned:true,webSocketAuthLogSafe:true};
|
||||
}finally{transport.close();}
|
||||
}
|
||||
async inspect(profile,{transport:existingTransport}={}){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
@@ -28,7 +44,7 @@ export class GMAudioHost{
|
||||
if(typeof sk!=='string'||!/^[A-Za-z0-9_-]{43}$/.test(sk))throw new MusicError('identity-required');
|
||||
const sdk=await this.loadSDK(),identity=sdk.loadSendspinClientIdentity(memoryStorage(profile.identityStorage));
|
||||
if(profile.target&&profile.target!==identity.clientId)throw new MusicError('identity-mismatch');
|
||||
const transport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||
const transport=existingTransport??new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||
const read=async(command,args)=>{
|
||||
const response=await transport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command,args})});return response.json();
|
||||
};
|
||||
@@ -40,79 +56,111 @@ export class GMAudioHost{
|
||||
if(!approvedProviders.length)throw new MusicError('catalog-empty');
|
||||
const catalogKey=profile.catalogKey??btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode('adaptive-music-catalog-v1:'+profile.campaign+':'+sk)))));
|
||||
return {...profile,maUrl:base.origin,target:identity.clientId,expectedProvider:player.provider,approvedProviders,catalogKey,namespace:profile.namespace??profile.campaign};
|
||||
}finally{transport.close();}
|
||||
}finally{if(!existingTransport)transport.close();}
|
||||
}
|
||||
async refreshCatalog(){if(!this.#client||!this.#authority())throw new MusicError('denied');await this.#client.verifyTarget({allowUnavailable:!this.#live});this.#catalog=await this.#client.catalog();return this.catalog;}
|
||||
resumeAudio(){return this.#context?.resume();}
|
||||
async readCatalog(profile,{reconnecting=false}={}){
|
||||
async readCatalog(profile,{reconnecting=false,preserveTransport=false}={}){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)throw new MusicError('denied');
|
||||
this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});
|
||||
if(!preserveTransport){this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});}
|
||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
|
||||
}
|
||||
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
|
||||
#connectionLost(epoch,stage){
|
||||
if(epoch!==this.#epoch||!this.#live)return;
|
||||
void this.close();
|
||||
this.#status='connection-lost';this.#phase=stage;
|
||||
this.onDisconnect();
|
||||
}
|
||||
async #start(profile){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
if(!profile.targetName||typeof profile.target!=='string'||!profile.expectedProvider?.startsWith('sendspin')||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
|
||||
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');};
|
||||
// Unlock synchronously in the caller's gesture before SDK/network work.
|
||||
this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();
|
||||
this.#lastError=undefined;this.#attachedQueue=false;this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
|
||||
try{
|
||||
this.#sdk=await this.loadSDK();await unlocked;check();
|
||||
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
|
||||
// Never register a fresh identity or silently select a new/household player.
|
||||
if(identity.clientId!==profile.target)throw new MusicError('identity-mismatch');
|
||||
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32)throw new MusicError('denied');
|
||||
if(!globalThis.navigator?.locks)throw new MusicError('unsupported');
|
||||
const lockName='adaptive-music-'+Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(base.origin+profile.target))),n=>n.toString(16).padStart(2,'0')).join('');
|
||||
const released=new Promise(resolve=>{this.#releaseLock=resolve;});
|
||||
await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));});
|
||||
await this.readCatalog(profile,{reconnecting:true});check();
|
||||
const original=await this.#client.queueState({allowUnavailable:true});check();
|
||||
if(original.items!==0||original.state!=='idle')throw new MusicError('reconcile-required');
|
||||
await new Promise((resolve,reject)=>{navigator.locks.request(lockName,{ifAvailable:true},async lock=>{if(!lock){reject(new MusicError('denied'));return;}resolve();await released;}).catch(()=>reject(new MusicError('unavailable')));});check();
|
||||
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.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');
|
||||
this.#core.onStreamStart=(format,isFormatUpdate)=>{if(!isFormatUpdate)this.#clear();};this.#core.onStreamClear=timestamp=>this.#clear(timestamp);this.#core.onStreamEnd=()=>this.#clear();
|
||||
this.#phase='Noise handshake';await this.#core.connect();check();
|
||||
if(profile.autoProvision){
|
||||
this.#phase='receiver pairing';
|
||||
await this.#apiTransport.fetch(base.origin+'/api',{method:'POST',redirect:'error',body:JSON.stringify({command:'sendspin/pair_web_player',args:{pairing_token:this.#core.pairingToken}})});
|
||||
}
|
||||
this.#phase='clock synchronization';const deadline=Date.now()+15000;
|
||||
while(!this.#core.timeSyncInfo.synced&&Date.now()<deadline){check();await new Promise(resolve=>setTimeout(resolve,50));}
|
||||
if(!this.#core.timeSyncInfo.synced)throw new MusicError('sendspin-sync-failed');check();
|
||||
if(profile.autoProvision){this.#phase='dedicated receiver verification';Object.assign(profile,await this.inspect(profile,{transport:this.#apiTransport}));check();}
|
||||
await this.readCatalog(profile,{reconnecting:true,preserveTransport:true});check();
|
||||
this.#phase='dedicated queue verification';
|
||||
await this.#client.verifyTarget({checkRegistration:check});
|
||||
const original=await this.#client.queueState();check();
|
||||
this.#attachedQueue=original.items!==0||original.state!=='idle';
|
||||
if(this.#attachedQueue&&!profile.campaignOwned)throw new MusicError('reconcile-required');
|
||||
if(profile.allowSyntheticPlayback===true){
|
||||
for(const id of Object.keys(profile.syntheticSequences??{})){if(!['synthetic-ambient','synthetic-combat'].includes(id))throw new MusicError('denied');this.#allowed.add(id);}
|
||||
this.#catalog.push(...[...this.#allowed].map(id=>({provider:'ma',id,kind:'sequence',name:'Generated '+id.slice(10)+' sequence'})));
|
||||
}
|
||||
let volumeState=this.#client.targetVolumeState();
|
||||
this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);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:true,getExternalVolume:()=>volumeState,onVolumeCommand:(volume,muted)=>{volumeState={volume,muted};},unpairedAccess:false,reconnect:{enabled:false}});
|
||||
this.#gain=this.#context.createGain();this.#gain.connect(this.#destination);this.#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=()=>{const wasLive=this.#live;this.#status='connection-lost';this.#live=false;if(wasLive)this.onDisconnect();this.#clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();};
|
||||
this.#core.onStreamClear=()=>this.#clear();this.#core.onStreamEnd=()=>this.#clear();
|
||||
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;
|
||||
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;this.#phase='ready';
|
||||
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
|
||||
await this.#core.connect();check();const deadline=Date.now()+10000;while(this.#live&&!this.#core.timeSyncInfo.synced&&Date.now()<deadline)await new Promise(resolve=>setTimeout(resolve,50));if(!this.#live||!this.#core.timeSyncInfo.synced)throw new MusicError('unavailable');await this.#client.verifyTarget();check();return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false};
|
||||
}catch(error){if(epoch===this.#epoch)await this.close();throw new MusicError(error instanceof MusicError?error.code:'unavailable');}
|
||||
return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false,attachedExistingQueue:this.#attachedQueue};
|
||||
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw new MusicError(this.#lastError.code);}
|
||||
}
|
||||
#authenticatedSocket(base,token,clientId){
|
||||
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
|
||||
return new Promise((resolve,reject)=>{const socket=this.createSocket(url.href);this.#socket=socket;socket.binaryType='arraybuffer';const timer=setTimeout(()=>{socket.close();reject(new MusicError('unavailable'));},8000);
|
||||
const fail=()=>{clearTimeout(timer);socket.close();reject(new MusicError('unavailable'));};socket.onerror=fail;socket.onclose=fail;
|
||||
socket.onopen=()=>socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));
|
||||
socket.onmessage=event=>{try{if(JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);socket.onerror=null;socket.onclose=null;socket.onmessage=null;resolve(socket);}catch{fail();}};
|
||||
return new Promise((resolve,reject)=>{
|
||||
let socket,opened=false,settled=false;
|
||||
const fail=code=>{if(settled)return;settled=true;clearTimeout(timer);if(socket){socket.onopen=socket.onmessage=socket.onerror=socket.onclose=null;socket.close();}reject(new MusicError(code));};
|
||||
const timer=setTimeout(()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed'),8000);
|
||||
try{socket=this.createSocket(url.href);this.#socket=socket;}catch{fail('ws-upgrade-failed');return;}
|
||||
socket.binaryType='arraybuffer';
|
||||
socket.onerror=()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed');socket.onclose=()=>fail(opened?'sendspin-auth-failed':'ws-upgrade-failed');
|
||||
socket.onopen=()=>{opened=true;try{socket.send(JSON.stringify({type:'auth',token,client_id:clientId}));}catch{fail('sendspin-auth-failed');}};
|
||||
socket.onmessage=event=>{try{if(typeof event.data!=='string'||event.data.length>65536||JSON.parse(event.data).type!=='auth_ok')throw Error();clearTimeout(timer);settled=true;socket.onopen=socket.onerror=socket.onclose=socket.onmessage=null;resolve(socket);}catch{fail('sendspin-auth-failed');}};
|
||||
});
|
||||
}
|
||||
#schedule(chunk){
|
||||
if(!this.#live||!this.#authority()){this.#clear();return;}
|
||||
if(!this.#core.timeSyncInfo.synced||!Array.isArray(chunk.samples)||chunk.samples.length>2||!chunk.samples.length||!Number.isFinite(chunk.sampleRate)||chunk.sampleRate<8000||chunk.sampleRate>96000)return;
|
||||
const frames=chunk.samples[0].length;if(frames<1||frames>chunk.sampleRate/4||chunk.samples.some(c=>c.length!==frames))return;
|
||||
if(chunk.generation!==this.#generation){this.#clear();this.#generation=chunk.generation;}
|
||||
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;
|
||||
if(!Number.isFinite(lead)||lead>2||lead+frames/chunk.sampleRate<0||this.#nodes.size>=128)return;
|
||||
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.onended=()=>this.#nodes.delete(node);this.#nodes.add(node);node.start(Math.max(this.#context.currentTime+0.01,this.#context.currentTime+lead));
|
||||
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++;
|
||||
}
|
||||
#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;
|
||||
}
|
||||
for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();this.#bufferedBytes=0;
|
||||
}
|
||||
#clear(){for(const node of this.#nodes){try{node.stop();}catch{}}this.#nodes.clear();}
|
||||
#ready(){if(!this.#live||!this.#authority()||!this.#provider)throw new MusicError('stale');return this.#provider;}
|
||||
resolve(ref,ctx){if(!this.supports(ref))throw new MusicError('denied');return this.#ready().resolve(ref,ctx);}
|
||||
snapshot(ctx){return this.#ready().snapshot(ctx);}
|
||||
apply(prepared,ctx){return this.#ready().apply(prepared,ctx);}
|
||||
restore(snapshot,ctx){return this.#ready().restore(snapshot,ctx);}
|
||||
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;}}
|
||||
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);}
|
||||
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;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||
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();}
|
||||
}
|
||||
+30
-14
@@ -9,20 +9,30 @@ export function validateIceServers(servers){
|
||||
}
|
||||
return servers.map(({urls,username,credential})=>({urls,...(username?{username,credential}:{})}));
|
||||
}
|
||||
function audioOnly(sdp,remote){
|
||||
if(typeof sdp!=='string'||sdp.length>65536)throw new MusicError('denied');
|
||||
const media=sdp.split(/\r?\n/).filter(line=>line.startsWith('m='));
|
||||
if(media.length!==1||!media[0].startsWith('m=audio ')||/a=sendrecv|a=sendonly/.test(sdp)&&remote==='answer')throw new MusicError('denied');
|
||||
export function validateAudioSDP(sdp,remote){
|
||||
if(typeof sdp!=='string'||sdp.length>65536||!['offer','answer'].includes(remote))throw new MusicError('denied');
|
||||
const sections=[[]];
|
||||
for(const line of sdp.split(/\r?\n/)){if(line.startsWith('m='))sections.push([]);sections.at(-1).push(line);}
|
||||
if(sections.length!==2||!sections[1][0].startsWith('m=audio '))throw new MusicError('denied');
|
||||
const directions=lines=>lines.filter(line=>/^a=(sendrecv|sendonly|recvonly|inactive)$/.test(line));
|
||||
const session=directions(sections[0]),media=directions(sections[1]);
|
||||
if(session.length>1||media.length>1)throw new MusicError('denied');
|
||||
// SDP media attributes override session defaults. Firefox inserts session-level
|
||||
// sendrecv after ICE gathering even when the sole audio media is recvonly.
|
||||
const effective=media[0]??session[0]??'a=sendrecv';
|
||||
const expected=remote==='offer'?'a=recvonly':'a=sendonly';
|
||||
if(effective!==expected&&effective!=='a=inactive')throw new MusicError('denied');
|
||||
}
|
||||
|
||||
async function gathered(pc){
|
||||
if(pc.iceGatheringState==='complete')return;
|
||||
await new Promise((resolve,reject)=>{const timer=setTimeout(()=>{pc.removeEventListener('icegatheringstatechange',check);reject(new MusicError('unavailable'));},5000);const check=()=>{if(pc.iceGatheringState==='complete'){clearTimeout(timer);pc.removeEventListener('icegatheringstatechange',check);resolve();}};pc.addEventListener('icegatheringstatechange',check);check();});
|
||||
}
|
||||
export class PeerAudio{
|
||||
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0;
|
||||
#socket;#userId;#isGM;#peers=new Map();#session=crypto.randomUUID();#stream;#handler;#disconnect;#create;#onStream;#onError; #rejected=0; #lastSignalError;
|
||||
constructor({socket,userId,isGM,isAuthorizedUser=()=>true,onStream=()=>{},onError=()=>{},createPeer=config=>new RTCPeerConnection(config)}){
|
||||
this.#socket=socket;this.#userId=userId;this.#isGM=isGM;this.authorized=isAuthorizedUser;this.#create=createPeer;this.#onStream=onStream;this.#onError=onError;
|
||||
this.#handler=frame=>{this.#receive(frame).catch(()=>{this.#rejected++;});};this.#disconnect=()=>this.reset();
|
||||
this.#handler=frame=>{this.#receive(frame).catch(error=>{this.#rejected++;this.#lastSignalError={code:['denied','stale','unavailable'].includes(error.code)?error.code:'browser-error',name:/^[A-Za-z]{1,40}$/.test(error.name??'')?error.name:undefined,stage:this.#peers.get(frame?.peer)?.stage};});};this.#disconnect=()=>this.reset();
|
||||
socket.on('module.adaptive-music',this.#handler);socket.on('disconnect',this.#disconnect);
|
||||
}
|
||||
setSource(stream){if(!this.#isGM()||stream.getAudioTracks().length!==1)throw new MusicError('denied');this.#stream=stream;}
|
||||
@@ -47,7 +57,13 @@ export class PeerAudio{
|
||||
entry.timer=setTimeout(()=>this.revoke(invite.peer),Math.max(1,invite.expires-Date.now()));
|
||||
pc.ontrack=event=>{if(role!=='listener'||event.track.kind!=='audio'){event.track.stop();return;}this.#onStream(event.streams[0]??new MediaStream([event.track]));};
|
||||
pc.ondatachannel=event=>event.channel.close();
|
||||
pc.onconnectionstatechange=()=>{if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}};
|
||||
pc.onconnectionstatechange=()=>{
|
||||
clearTimeout(entry.disconnectTimer);
|
||||
if(pc.connectionState==='connected')clearTimeout(entry.handshakeTimer);
|
||||
if(['failed','closed'].includes(pc.connectionState)){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}
|
||||
else if(pc.connectionState==='disconnected')entry.disconnectTimer=setTimeout(()=>{if(pc.connectionState!=='connected'){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}},10000);
|
||||
};
|
||||
entry.handshakeTimer=setTimeout(()=>{if(pc.connectionState!=='connected'){this.#onError(new MusicError('unavailable'));this.revoke(invite.peer);}},20000);
|
||||
this.#peers.set(invite.peer,entry);return entry;
|
||||
}
|
||||
async #send(entry,payload){if(this.#peers.get(entry.invite.peer)!==entry)return;const frame=await entry.codec.seal(payload);if(this.#peers.get(entry.invite.peer)!==entry||entry.invite.expires<=Date.now())return;this.#socket.emit('module.adaptive-music',frame);}
|
||||
@@ -56,25 +72,25 @@ export class PeerAudio{
|
||||
if(entry.pending>=4||++entry.signals>64)throw new MusicError('denied');entry.pending++;
|
||||
entry.tail=entry.tail.catch(()=>{}).then(async()=>{
|
||||
if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))throw new MusicError('denied');
|
||||
const payload=await entry.codec.open(frame);
|
||||
entry.stage='decrypt signal';const payload=await entry.codec.open(frame);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.
|
||||
audioOnly(payload.sdp,'answer');
|
||||
validateAudioSDP(payload.sdp,'offer');
|
||||
if(!entry.started){entry.pc.addTrack(this.#stream.getAudioTracks()[0],this.#stream);entry.started=true;}
|
||||
await entry.pc.setRemoteDescription({type:'offer',sdp:payload.sdp});
|
||||
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);
|
||||
await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
|
||||
entry.stage='send answer';await this.#send(entry,{type:'answer',sdp:entry.pc.localDescription.sdp});
|
||||
}else if(entry.role==='listener'&&payload.type==='answer'){
|
||||
audioOnly(payload.sdp,'offer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
|
||||
validateAudioSDP(payload.sdp,'answer');await entry.pc.setRemoteDescription({type:'answer',sdp:payload.sdp});
|
||||
}else throw new MusicError('denied');
|
||||
});return entry.tail.finally(()=>{entry.pending--;});
|
||||
}
|
||||
async restart(peer){const entry=this.#peers.get(peer);if(!entry||entry.role!=='listener'||++entry.restarts>2)throw new MusicError('denied');await entry.pc.setLocalDescription(await entry.pc.createOffer({iceRestart:true}));await gathered(entry.pc);await this.#send(entry,{type:'offer',sdp:entry.pc.localDescription.sdp});}
|
||||
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
|
||||
revoke(peer){const entry=this.#peers.get(peer);if(!entry)return;clearTimeout(entry.timer);clearTimeout(entry.handshakeTimer);clearTimeout(entry.disconnectTimer);this.#peers.delete(peer);entry.pc.onconnectionstatechange=null;entry.pc.ontrack=null;entry.pc.close();}
|
||||
reset(){for(const peer of [...this.#peers.keys()])this.revoke(peer);this.#stream=null;this.#session=crypto.randomUUID();}
|
||||
close(){this.reset();this.#socket.off('module.adaptive-music',this.#handler);this.#socket.off('disconnect',this.#disconnect);}
|
||||
reconcile(){for(const [peer,entry]of this.#peers)if(entry.role==='gm'&&(!this.#isGM()||!this.authorized(entry.invite.userId)))this.revoke(peer);}
|
||||
diagnostics(){return {rejectedSignals:this.#rejected,peers:[...this.#peers.values()].map(e=>({role:e.role,connection:e.pc.connectionState,ice:e.pc.iceConnectionState,signaling:e.pc.signalingState}))};}
|
||||
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;}
|
||||
}
|
||||
Reference in new issue
Block a user