45 lines
2.4 KiB
JavaScript
45 lines
2.4 KiB
JavaScript
import {spawn,execFile} from 'node:child_process';
|
|
import {promisify} from 'node:util';
|
|
import fs from 'node:fs/promises';
|
|
const exec=promisify(execFile);
|
|
const delay=ms=>new Promise(r=>setTimeout(r,ms));
|
|
// Owned by the browser worker, which itself runs as the unprivileged browser UID.
|
|
export class AudioController {
|
|
constructor({managed=false,server='',spawnProcess=spawn,probe=()=>exec('/usr/bin/pactl',['info'],{timeout:500}),pause=delay,removeSocket=()=>fs.rm('/run/mars-browser-audio/pulse.sock',{force:true})}={}){
|
|
Object.assign(this,{managed,server,spawnProcess,probe,pause,removeSocket});this.child=null;this.ready=false;this.error='';
|
|
}
|
|
get available(){return this.managed?this.ready:!!this.server;}
|
|
get pid(){return this.child?.pid||0;}
|
|
async ensure(wanted){
|
|
if(!this.managed)return;
|
|
if(!wanted){await this.stop();this.error='';return;}
|
|
if(this.ready&&this.child)return;
|
|
if(this.child)await this.stop();
|
|
try{
|
|
if(!this.server)throw Error('PULSE_SERVER fehlt');
|
|
await this.removeSocket();
|
|
const child=this.spawnProcess('/usr/bin/pulseaudio',['-nF','/usr/local/libexec/mars-browser/pulse.pa','--daemonize=no','--exit-idle-time=-1','--log-target=stderr','--use-pid-file=no'],{stdio:['ignore','inherit','inherit'],env:{...process.env,XDG_RUNTIME_DIR:'/run/mars-browser-audio'}});
|
|
this.child=child;this.ready=false;
|
|
child.on('error',e=>{if(this.child===child){this.error=e.message;this.ready=false;}});
|
|
child.once('close',(code,signal)=>{if(this.child===child){this.child=null;this.ready=false;this.error=`PulseAudio beendet (${code??signal??'unbekannt'})`;}});
|
|
const until=Date.now()+4000;
|
|
do{
|
|
if(this.child!==child||child.exitCode!==null||child.signalCode!==null)break;
|
|
try{await this.probe();if(this.child===child&&child.exitCode===null&&child.signalCode===null){this.ready=true;this.error='';return;}}catch{}
|
|
await this.pause(100);
|
|
}while(Date.now()<until);
|
|
throw Error(this.error||'PulseAudio nicht bereit');
|
|
}catch(e){await this.stop();this.error=e.message;throw e;}
|
|
}
|
|
async stop(){
|
|
const child=this.child;this.ready=false;
|
|
if(!child)return;
|
|
this.child=null;
|
|
if(child.exitCode!==null||child.signalCode!==null||!child.pid)return;
|
|
await new Promise(resolve=>{
|
|
let timer,hard;const done=()=>{clearTimeout(timer);clearTimeout(hard);child.removeListener('close',done);resolve();};
|
|
child.once('close',done);timer=setTimeout(()=>child.kill('SIGKILL'),1000);hard=setTimeout(done,2000);child.kill('SIGTERM');
|
|
});
|
|
}
|
|
}
|