kannon-client/classes/Player.js

178 lines
No EOL
4.9 KiB
JavaScript

const NodeSpeaker = require('../libs/speaker/index.js');
const EventEmitter = require('events');
const { spawn } = require('child_process');
const createWriteStream = require('fs').createWriteStream;
const unlink = require('fs/promises').unlink;
const resolve = require('path').resolve;
const AudioBuffer = require('./AudioBuffer.js');
const { STATE_PLAYING } = require('../libs/constants.js');
class Player extends EventEmitter {
constructor() {
super();
this.timestamp = Date.now();
this.position = 0;
this.events = [];
this.tmp = {
file: resolve(global.config?.tmp || '/tmp/kannon.tmp')
};
this.buffer = {
size: 0,
elements: []
};
}
async prepare(threshold, stream) {
logger.debug('preparing audio player...');
await this.#reset();
this.speaker = new NodeSpeaker({
channels: 2,
bitDepth: 16,
sampleRate: 44100
});
this.audiobuffer = new AudioBuffer(threshold, stream, this.speaker);
this.audiobuffer.on(constants.BUFFER_THRESHOLD, () => {
this.#setState(constants.STATE_READY);
});
}
play() {
this.#setState(STATE_PLAYING);
this.audiobuffer.resume();
}
async pause() {
await this.#reset(true);
this.#setState(constants.STATE_PAUSED);
}
async stop() {
await this.#reset();
this.#setState(constants.STATE_STOPPED);
}
isReady() {
return this.state === constants.STATE_READY;
}
isPlaying() {
return this.state === constants.STATE_PLAYING;
}
isPaused() {
return this.state === constants.STATE_PAUSED;
}
isFinished() {
return this.state === constants.STATE_STOPPED;
}
hasError() {
return this.state === constants.STATE_ERROR;
}
getPosition() {
return this.position;
}
async #spawnProcess(position) {
return new Promise((resolve, reject) => {
const args = [
'-vn',
'-nodisp'
];
if (this.isPaused() && !isNaN(position)) {
args.unshift('-ss', position);
}
args.push(this.tmp.file);
this.process = spawn("ffplay", args);
this.process.on('error', (error) => {
this.#reset();
// TODO: try/catch error
reject('error spawning process \'ffplay\': ' + error);
});
this.process.on('spawn', () => {
logger.info('spawned process \'ffplay\' (pid: ' + this.process.pid + ')...');
this.#setState(constants.STATE_PLAYING);
resolve();
});
});
}
#setState(state, data) {
if (this.state === state) {
return;
}
this.state = state;
logger.debug('setting state of audio player to \'' + state + '\'...');
if (this.events.includes(state)) {
return;
}
logger.debug('emitting state \'' + state + '\' of audio player...');
this.emit(this.state, { data: data });
this.emit('statechange', { state: this.state });
this.events.push(state);
}
async #killProcess() {
if (this.process === undefined) {
return;
}
const pid = this.process.pid;
this.#closeStdIO();
if (this.process?.killed === false) {
this.process.kill('SIGTERM');
}
await new Promise((resolve, reject) => {
this.process.on('close', (code, signal) => {
let msg = 'process \'ffplay\' (pid: ' + pid + ') closed with';
if (code !== undefined) {
msg += ' code \'' + code + '\'';
} else {
msg += ' signal \'' + signal + '\'';
}
logger.debug(msg);
this.process = undefined;
resolve();
});
});
}
#closeStdIO() {
if (this.process?.stdio === undefined) {
return;
}
logger.debug('closing all stdio streams of process \'ffplay\' (pid: ' + this.process.pid + ')...');
for (let index = 0; index < this.process.stdio.length; index++) {
this.process.stdio[index].destroy();
}
}
async #removeTemporaryFile() {
try {
await unlink(this.tmp.file);
} catch (error) {
if (error?.code === 'ENOENT') {
return;
}
logger.error('error removing temporary file \'' + this.tmp.file + '\': ' + error);
}
}
async #reset(paused) {
await this.#killProcess();
this.timestamp = Date.now();
this.events = [];
if (paused === true) {
return;
}
this.position = 0;
}
}
module.exports = Player;