~ knotless Search/
↑↓ move↵ open⇧↵ all results

cameron.stream/prism

Audio-reactive WebGL visualizer for OBS streams

0
0
main
50 lines · 5.2 KB Raw History
'use strict';
// Prism audio server. Serves index.html and streams audio analysis over SSE (/audio).
// Primary source: ./prism-audio (native FFT of system audio, or one app via PRISM_AUDIO_APP).
// Fallback: read-only OBS InputVolumeMeters (RMS/peak only) for the input named OBS_AUDIO_INPUT.
// Never writes OBS settings or controls the stream.
//   PORT=4178 node server.cjs                     production port (default 4180 = staging)
//   PRISM_AUDIO_APP=com.ableton.live              analyse one app instead of all system audio
//   PRISM_AUDIO=off                               disable the native analyser (OBS meter only)
//   OBS_AUDIO_INPUT="macOS Audio Capture"         OBS input used for the fallback meter
const http=require('node:http'),fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'),{spawn}=require('node:child_process');
const port=Number(process.env.PORT||4180),clients=new Set();
const inputName=process.env.OBS_AUDIO_INPUT||'macOS Audio Capture';
const helperPath=process.env.PRISM_AUDIO_BIN||path.join(__dirname,'prism-audio');
const helperArgs=process.env.PRISM_AUDIO_APP?['--app',process.env.PRISM_AUDIO_APP]:[];
let last={status:'waiting'},lastSpectrumAt=0,spectrumState='starting',meterState='starting',ws,closing=false,reconnect,helper,helperRestart,helperDelay=1000;
const config=process.env.OBS_WEBSOCKET_CONFIG||path.join(process.env.HOME,'Library/Application Support/obs-studio/plugin_config/obs-websocket/config.json');
function send(data){const line='data: '+JSON.stringify(data)+'\n\n';for(const c of clients)c.write(line)}
function emit(data){last={...data,at:Date.now()};send(last)}
const spectrumFresh=()=>Date.now()-lastSpectrumAt<500;

// Native spectrum analyser.
function startHelper(){
 if(closing||process.env.PRISM_AUDIO==='off'){spectrumState='off';return}
 if(!fs.existsSync(helperPath)){spectrumState='missing helper';return}
 helper=spawn(helperPath,helperArgs,{stdio:['ignore','pipe','pipe']});let pending='';
 helper.stdout.on('data',d=>{pending+=d;let i;while((i=pending.indexOf('\n'))>=0){const line=pending.slice(0,i);pending=pending.slice(i+1);let v;try{v=JSON.parse(line)}catch{continue}
  if(Array.isArray(v.bands)){lastSpectrumAt=Date.now();spectrumState='audio';helperDelay=1000;emit({status:'audio',source:'spectrum',...v})}
  else if(v.status){spectrumState=v.status+(v.capture?' ('+v.capture+')':'')}
  else if(v.error){spectrumState='error: '+v.error;console.error('prism-audio:',v.error)}}});
 helper.stderr.on('data',d=>console.error('prism-audio:',String(d).trim()));
 helper.on('error',e=>{spectrumState='error: '+e.message});
 helper.on('exit',()=>{helper=null;if(closing)return;helperRestart=setTimeout(startHelper,helperDelay);helperDelay=Math.min(30000,helperDelay*2)});
}

// Fallback loudness meter from OBS.
function connect(){if(closing)return;let cfg;try{cfg=JSON.parse(fs.readFileSync(config,'utf8'))}catch{meterState='OBS config unavailable';reconnect=setTimeout(connect,3000);return}
 ws=new WebSocket('ws://127.0.0.1:'+(cfg.server_port||4455));ws.onmessage=e=>{try{const m=JSON.parse(e.data);if(m.op===0){const d={rpcVersion:1,eventSubscriptions:65536};if(m.d.authentication){const h=s=>crypto.createHash('sha256').update(s).digest('base64');d.authentication=h(h(cfg.server_password+m.d.authentication.salt)+m.d.authentication.challenge)}ws.send(JSON.stringify({op:1,d}))}
 if(m.op===2)meterState='connected';
 if(m.op===5&&m.d.eventType==='InputVolumeMeters'){const source=m.d.eventData.inputs.find(i=>i.inputName===inputName);if(!source){meterState='input "'+inputName+'" not found';return}meterState='audio';if(spectrumFresh())return;const channels=source.inputLevelsMul||[];let rms=0,peak=0;for(const c of channels){rms=Math.max(rms,Number(c[0])||0);peak=Math.max(peak,Number(c[1])||0)}emit({status:'audio',source:'obs-meter',rms,peak,input:source.inputName})}}catch(err){console.error('Meter message:',err.message)}};
 ws.onerror=()=>{};ws.onclose=()=>{meterState='disconnected';if(!spectrumFresh())emit({status:'disconnected'});if(!closing)reconnect=setTimeout(connect,3000)};
}

const server=http.createServer((req,res)=>{
 if(req.url==='/audio'){res.writeHead(200,{'Content-Type':'text/event-stream','Cache-Control':'no-store','Connection':'keep-alive'});res.write('data: '+JSON.stringify(last)+'\n\n');clients.add(res);req.on('close',()=>clients.delete(res));return}
 if(req.url==='/health'){const {bands,...summary}=last;res.setHeader('Content-Type','application/json');res.end(JSON.stringify({...summary,bandCount:bands?.length||0,spectrum:spectrumState,meter:meterState,meterInput:inputName}));return}
 if(req.url!=='/'){res.writeHead(404);res.end();return}
 res.setHeader('Content-Type','text/html; charset=utf-8');res.setHeader('Cache-Control','no-store');fs.createReadStream(path.join(__dirname,'index.html')).pipe(res)});
server.listen(port,'127.0.0.1',()=>{console.log('Prism listening on loopback port '+port);startHelper();connect()});
const heartbeat=setInterval(()=>{for(const c of clients)c.write(': heartbeat\n\n')},10000);
function stop(){closing=true;clearTimeout(reconnect);clearTimeout(helperRestart);clearInterval(heartbeat);helper?.kill();ws?.close();for(const c of clients)c.end();server.close(()=>process.exit())}process.on('SIGTERM',stop);process.on('SIGINT',stop);