kannon-client/classes/Player.js

210 lines
6.1 KiB
JavaScript
Raw Normal View History

2022-04-14 14:25:48 +02:00
const EventEmitter = require('events');
const { sleep } = require('../libs/util.js');
const { spawn } = require('child_process');
2022-04-14 15:26:46 +02:00
const createWriteStream = require('fs').createWriteStream;
const unlink = require('fs/promises').unlink;
const resolve = require('path').resolve;
2022-04-14 14:25:48 +02:00
const STATE_READY = 'ready';
const STATE_PLAYING = 'playing';
const STATE_PAUSED = 'paused';
2022-04-14 15:26:46 +02:00
const STATE_STOPPED = 'stopped';
2022-04-14 14:25:48 +02:00
const STATE_ERROR = 'error';
class Player extends EventEmitter {
constructor() {
super();
this.position = 0;
this.events = [];
this.buffer = [];
2022-04-14 15:26:46 +02:00
this.tmp = {
2022-04-20 16:15:51 +02:00
file: resolve(global.config?.tmp || '/tmp/kannon.tmp')
};
2022-04-14 14:25:48 +02:00
this.buffersize = 0;
}
async prepare(size, threshold) {
logger.debug('preparing audio player...');
2022-04-20 16:15:51 +02:00
await this.#reset();
await this.#removeTemporaryFile();
2022-04-14 14:25:48 +02:00
this.size = size;
this.threshold = threshold;
2022-04-14 15:26:46 +02:00
this.tmp.stream = createWriteStream(this.tmp.file);
2022-04-20 16:15:51 +02:00
this.tmp.stream.on('ready', async () => {
const timestamp = Date.now();
while (this.tmp.stream.bytesWritten !== this.size) {
if (this.buffer.length === 0) {
await sleep(1);
continue;
}
const tmp = this.buffer[0];
this.buffer.shift();
this.tmp.stream.write(tmp);
if (this.tmp.announced !== true && this.tmp.stream.bytesWritten >= this.threshold) {
this.#setState(STATE_READY);
logger.debug('threshold of ' + this.threshold + ' bytes reached after ' + (Date.now() - timestamp) + 'ms');
this.tmp.announced = true;
}
}
this.tmp.stream.end();
this.tmp.stream.close();
logger.debug('finished writing of ' + this.size + ' bytes after ' + (Date.now() - timestamp) + 'ms');
});
2022-04-14 14:25:48 +02:00
}
feed(buffer) {
this.buffer.push(buffer);
}
2022-04-20 16:15:51 +02:00
async play(position) {
2022-04-14 14:25:48 +02:00
if (this.isPlaying()) {
this.stop();
}
2022-04-20 16:15:51 +02:00
await this.#spawnProcess(position);
2022-04-14 14:25:48 +02:00
this.process.stderr.on('data', (data) => {
data = data.toString();
const position = data.toString().trim().split(' ')[0];
if (position.length === 0 || isNaN(position)) {
return;
}
this.position = position;
});
this.process.stdin.on('error', (error) => {
this.#setState(STATE_ERROR, error);
});
}
async pause() {
2022-04-20 16:15:51 +02:00
await this.#reset(true);
2022-04-14 15:26:46 +02:00
this.#setState(STATE_PAUSED);
2022-04-14 14:25:48 +02:00
}
async stop() {
2022-04-20 16:15:51 +02:00
await this.#reset();
2022-04-14 15:26:46 +02:00
this.#setState(STATE_STOPPED);
2022-04-14 14:25:48 +02:00
}
isReady() {
return this.state === STATE_READY;
}
isPlaying() {
return this.state === STATE_PLAYING;
}
isPaused() {
return this.state === STATE_PAUSED;
}
isFinished() {
2022-04-14 15:26:46 +02:00
return this.state === STATE_STOPPED;
2022-04-14 14:25:48 +02:00
}
hasError() {
return this.state === STATE_ERROR;
}
2022-04-20 16:15:51 +02:00
getPosition() {
return this.position;
}
async #spawnProcess(position) {
2022-04-14 14:25:48 +02:00
return new Promise((resolve, reject) => {
2022-04-14 15:26:46 +02:00
const args = [
'-vn',
'-nodisp'
];
2022-04-20 16:15:51 +02:00
if (this.isPaused() && !isNaN(position)) {
args.unshift('-ss', position);
2022-04-14 14:25:48 +02:00
}
2022-04-20 16:15:51 +02:00
args.push(this.tmp.file);
2022-04-14 15:26:46 +02:00
this.process = spawn("ffplay", args);
2022-04-14 14:25:48 +02:00
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 + ')...');
2022-04-20 16:15:51 +02:00
this.#setState(STATE_PLAYING);
2022-04-14 14:25:48 +02:00
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;
}
2022-04-14 15:26:46 +02:00
logger.debug('emitting state \'' + state + '\' of audio player...');
2022-04-20 16:15:51 +02:00
this.emit(this.state, { data: data });
this.emit('statechange', { state: this.state });
2022-04-14 14:25:48 +02:00
this.events.push(state);
}
2022-04-20 16:15:51 +02:00
async #killProcess() {
if (this.process === undefined) {
return;
}
const pid = this.process.pid;
2022-04-14 14:25:48 +02:00
this.#closeStdIO();
if (this.process?.killed === false) {
this.process.kill('SIGTERM');
}
2022-04-20 16:15:51 +02:00
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();
});
});
2022-04-14 14:25:48 +02:00
}
#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();
}
}
2022-04-20 16:15:51 +02:00
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();
2022-04-14 14:25:48 +02:00
this.events = [];
2022-04-14 15:26:46 +02:00
this.buffer = [];
2022-04-20 16:15:51 +02:00
if (paused === true) {
return;
2022-04-14 14:25:48 +02:00
}
2022-04-20 16:15:51 +02:00
this.position = 0;
2022-04-14 14:25:48 +02:00
}
}
module.exports = Player;