123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329 |
- // stolen from http-music
- const { spawn } = require('child_process')
- const { commandExists, killProcess, getTimeStrings } = require('./general-util')
- const EventEmitter = require('events')
- const Socat = require('./socat')
- const fs = require('fs')
- const util = require('util')
- const unlink = util.promisify(fs.unlink)
- class Player extends EventEmitter {
- constructor(processOptions = []) {
- super()
- this.processOptions = processOptions
- this.disablePlaybackStatus = false
- this.isLooping = false
- this.isPaused = false
- this.volume = 100
- this.volumeMultiplier = 1.0
- }
- set process(newProcess) {
- this._process = newProcess
- this._process.on('exit', code => {
- if (code !== 0 && !this._killed) {
- this.emit('crashed', code)
- }
- this._killed = false
- })
- }
- get process() {
- return this._process
- }
- playFile(file) {}
- seekAhead(secs) {}
- seekBack(secs) {}
- seekTo(timeInSecs) {}
- volUp(amount) {}
- volDown(amount) {}
- setVolume(value) {}
- updateVolume() {}
- togglePause() {}
- toggleLoop() {}
- setPause() {}
- setLoop() {}
- async kill() {
- if (this.process) {
- this._killed = true
- await killProcess(this.process)
- }
- }
- printStatusLine(data) {
- // Quick sanity check - we don't want to print the status line if it's
- // disabled! Hopefully printStatusLine won't be called in that case, but
- // if it is, we should be careful.
- if (!this.disablePlaybackStatus) {
- this.emit('printStatusLine', data)
- }
- }
- setVolumeMultiplier(value) {
- this.volumeMultiplier = value
- this.updateVolume()
- }
- fadeIn() {
- const interval = 50
- const duration = 1000
- const delta = 1.0 - this.volumeMultiplier
- const id = setInterval(() => {
- this.volumeMultiplier += delta * interval / duration
- if (this.volumeMultiplier >= 1.0) {
- this.volumeMultiplier = 1.0
- clearInterval(id)
- }
- this.updateVolume()
- }, interval)
- }
- }
- module.exports.MPVPlayer = class extends Player {
- getMPVOptions(file) {
- const opts = ['--no-video', file]
- if (this.isLooping) {
- opts.unshift('--loop')
- }
- if (this.isPaused) {
- opts.unshift('--pause')
- }
- opts.unshift('--volume=' + this.volume * this.volumeMultiplier)
- return opts
- }
- playFile(file) {
- // The more powerful MPV player. MPV is virtually impossible for a human
- // being to install; if you're having trouble with it, try the SoX player.
- this.process = spawn('mpv', this.getMPVOptions(file).concat(this.processOptions))
- let lastPercent = 0
- this.process.stderr.on('data', data => {
- if (this.disablePlaybackStatus) {
- return
- }
- const match = data.toString().match(
- /(..):(..):(..) \/ (..):(..):(..) \(([0-9]+)%\)/
- )
- if (match) {
- const [
- curHour, curMin, curSec, // ##:##:##
- lenHour, lenMin, lenSec, // ##:##:##
- percent // ###%
- ] = match.slice(1)
- if (parseInt(percent) < lastPercent) {
- // mpv forgets commands you sent it whenever it loops, so you
- // have to specify them every time it loops. We do that whenever the
- // position in the track decreases, since that means it may have
- // looped.
- this.setLoop(this.isLooping)
- }
- lastPercent = parseInt(percent)
- this.printStatusLine(getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}))
- }
- this.updateVolume();
- })
- return new Promise(resolve => {
- this.process.once('close', resolve)
- })
- }
- }
- module.exports.ControllableMPVPlayer = class extends module.exports.MPVPlayer {
- getMPVOptions(file) {
- return ['--input-ipc-server=' + this.socat.path, ...super.getMPVOptions(file)]
- }
- playFile(file) {
- this.removeSocket(this.socketPath)
- do {
- // this.socketPathpath = '/tmp/mtui-socket-' + Math.floor(Math.random() * 10000)
- this.socketPath = __dirname + '/mtui-socket-' + Math.floor(Math.random() * 10000)
- } while (this.existsSync(this.socketPath))
- this.socat = new Socat(this.socketPath)
- const mpv = super.playFile(file)
- mpv.then(() => this.removeSocket(this.socketPath))
- return mpv
- }
- existsSync(path) {
- try {
- fs.statSync(path)
- return true
- } catch (error) {
- return false
- }
- }
- sendCommand(...command) {
- if (this.socat) {
- this.socat.send(JSON.stringify({command}))
- }
- }
- seekAhead(secs) {
- this.sendCommand('seek', secs)
- }
- seekBack(secs) {
- this.sendCommand('seek', -secs)
- }
- seekTo(timeInSecs) {
- this.sendCommand('seek', timeInSecs, 'absolute')
- }
- volUp(amount) {
- this.setVolume(this.volume + amount)
- }
- volDown(amount) {
- this.setVolume(this.volume - amount)
- }
- setVolume(value) {
- this.volume = value
- this.volume = Math.max(0, this.volume)
- this.volume = Math.min(100, this.volume)
- this.updateVolume()
- }
- updateVolume() {
- this.sendCommand('set_property', 'volume', this.volume * this.volumeMultiplier)
- }
- togglePause() {
- this.isPaused = !this.isPaused
- this.sendCommand('cycle', 'pause')
- }
- toggleLoop() {
- this.isLooping = !this.isLooping
- this.sendCommand('cycle', 'loop')
- }
- setPause(val) {
- this.isPaused = !!val
- this.sendCommand('set', 'pause', this.isPaused)
- }
- setLoop(val) {
- this.isLooping = !!val
- this.sendCommand('set', 'loop', this.isLooping)
- }
- async kill() {
- const path = this.socketPath
- delete this.socketPath
- if (this.socat) {
- await this.socat.dispose()
- await this.socat.stop()
- }
- await super.kill()
- await this.removeSocket(path)
- }
- async removeSocket(path) {
- if (path) {
- await unlink(path).catch(() => {})
- }
- }
- }
- module.exports.SoXPlayer = class extends Player {
- playFile(file) {
- // SoX's play command is useful for systems that don't have MPV. SoX is
- // much easier to install (and probably more commonly installed, as well).
- // You don't get keyboard controls such as seeking or volume adjusting
- // with SoX, though.
- this.process = spawn('play', [file].concat(this.processOptions))
- this.process.stdout.on('data', data => {
- process.stdout.write(data.toString())
- })
- // Most output from SoX is given to stderr, for some reason!
- this.process.stderr.on('data', data => {
- // The status line starts with "In:".
- if (data.toString().trim().startsWith('In:')) {
- if (this.disablePlaybackStatus) {
- return
- }
- const timeRegex = '([0-9]*):([0-9]*):([0-9]*)\.([0-9]*)'
- const match = data.toString().trim().match(new RegExp(
- `^In:([0-9.]+%)\\s*${timeRegex}\\s*\\[${timeRegex}\\]`
- ))
- if (match) {
- const percentStr = match[1]
- // SoX takes a loooooot of math in order to actually figure out the
- // duration, since it outputs the current time and the remaining time
- // (but not the duration).
- const [
- curHour, curMin, curSec, curSecFrac, // ##:##:##.##
- remHour, remMin, remSec, remSecFrac // ##:##:##.##
- ] = match.slice(2).map(n => parseInt(n))
- const duration = Math.round(
- (curHour + remHour) * 3600 +
- (curMin + remMin) * 60 +
- (curSec + remSec) * 1 +
- (curSecFrac + remSecFrac) / 100
- )
- const lenHour = Math.floor(duration / 3600)
- const lenMin = Math.floor((duration - lenHour * 3600) / 60)
- const lenSec = Math.floor(duration - lenHour * 3600 - lenMin * 60)
- this.printStatusLine(getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}))
- }
- }
- })
- return new Promise(resolve => {
- this.process.on('close', () => resolve())
- })
- }
- }
- module.exports.getPlayer = async function(name = null, options = []) {
- if (await commandExists('mpv') && (name === null || name === 'mpv')) {
- return new module.exports.ControllableMPVPlayer(options)
- } else if (name === 'mpv') {
- return null
- }
- if (await commandExists('play') && (name === null || name === 'sox')) {
- return new module.exports.SoXPlayer(options)
- } else if (name === 'sox') {
- return null
- }
- return null
- }
|