players.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // stolen from http-music
  2. const { spawn } = require('child_process')
  3. const { commandExists, killProcess, getTimeStrings } = require('./general-util')
  4. const EventEmitter = require('events')
  5. const Socat = require('./socat')
  6. const fs = require('fs')
  7. const util = require('util')
  8. const unlink = util.promisify(fs.unlink)
  9. class Player extends EventEmitter {
  10. constructor(processOptions = []) {
  11. super()
  12. this.processOptions = processOptions
  13. this.disablePlaybackStatus = false
  14. this.isLooping = false
  15. this.isPaused = false
  16. this.volume = 100
  17. this.volumeMultiplier = 1.0
  18. }
  19. set process(newProcess) {
  20. this._process = newProcess
  21. this._process.on('exit', code => {
  22. if (code !== 0 && !this._killed) {
  23. this.emit('crashed', code)
  24. }
  25. this._killed = false
  26. })
  27. }
  28. get process() {
  29. return this._process
  30. }
  31. playFile(file) {}
  32. seekAhead(secs) {}
  33. seekBack(secs) {}
  34. seekTo(timeInSecs) {}
  35. volUp(amount) {}
  36. volDown(amount) {}
  37. setVolume(value) {}
  38. updateVolume() {}
  39. togglePause() {}
  40. toggleLoop() {}
  41. setPause() {}
  42. setLoop() {}
  43. async kill() {
  44. if (this.process) {
  45. this._killed = true
  46. await killProcess(this.process)
  47. }
  48. }
  49. printStatusLine(data) {
  50. // Quick sanity check - we don't want to print the status line if it's
  51. // disabled! Hopefully printStatusLine won't be called in that case, but
  52. // if it is, we should be careful.
  53. if (!this.disablePlaybackStatus) {
  54. this.emit('printStatusLine', data)
  55. }
  56. }
  57. setVolumeMultiplier(value) {
  58. this.volumeMultiplier = value
  59. this.updateVolume()
  60. }
  61. fadeIn() {
  62. const interval = 50
  63. const duration = 1000
  64. const delta = 1.0 - this.volumeMultiplier
  65. const id = setInterval(() => {
  66. this.volumeMultiplier += delta * interval / duration
  67. if (this.volumeMultiplier >= 1.0) {
  68. this.volumeMultiplier = 1.0
  69. clearInterval(id)
  70. }
  71. this.updateVolume()
  72. }, interval)
  73. }
  74. }
  75. module.exports.MPVPlayer = class extends Player {
  76. getMPVOptions(file) {
  77. const opts = ['--no-video', file]
  78. if (this.isLooping) {
  79. opts.unshift('--loop')
  80. }
  81. if (this.isPaused) {
  82. opts.unshift('--pause')
  83. }
  84. opts.unshift('--volume=' + this.volume * this.volumeMultiplier)
  85. return opts
  86. }
  87. playFile(file) {
  88. // The more powerful MPV player. MPV is virtually impossible for a human
  89. // being to install; if you're having trouble with it, try the SoX player.
  90. this.process = spawn('mpv', this.getMPVOptions(file).concat(this.processOptions))
  91. let lastPercent = 0
  92. this.process.stderr.on('data', data => {
  93. if (this.disablePlaybackStatus) {
  94. return
  95. }
  96. const match = data.toString().match(
  97. /(..):(..):(..) \/ (..):(..):(..) \(([0-9]+)%\)/
  98. )
  99. if (match) {
  100. const [
  101. curHour, curMin, curSec, // ##:##:##
  102. lenHour, lenMin, lenSec, // ##:##:##
  103. percent // ###%
  104. ] = match.slice(1)
  105. if (parseInt(percent) < lastPercent) {
  106. // mpv forgets commands you sent it whenever it loops, so you
  107. // have to specify them every time it loops. We do that whenever the
  108. // position in the track decreases, since that means it may have
  109. // looped.
  110. this.setLoop(this.isLooping)
  111. }
  112. lastPercent = parseInt(percent)
  113. this.printStatusLine(getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}))
  114. }
  115. this.updateVolume();
  116. })
  117. return new Promise(resolve => {
  118. this.process.once('close', resolve)
  119. })
  120. }
  121. }
  122. module.exports.ControllableMPVPlayer = class extends module.exports.MPVPlayer {
  123. getMPVOptions(file) {
  124. return ['--input-ipc-server=' + this.socat.path, ...super.getMPVOptions(file)]
  125. }
  126. playFile(file) {
  127. this.removeSocket(this.socketPath)
  128. do {
  129. // this.socketPathpath = '/tmp/mtui-socket-' + Math.floor(Math.random() * 10000)
  130. this.socketPath = __dirname + '/mtui-socket-' + Math.floor(Math.random() * 10000)
  131. } while (this.existsSync(this.socketPath))
  132. this.socat = new Socat(this.socketPath)
  133. const mpv = super.playFile(file)
  134. mpv.then(() => this.removeSocket(this.socketPath))
  135. return mpv
  136. }
  137. existsSync(path) {
  138. try {
  139. fs.statSync(path)
  140. return true
  141. } catch (error) {
  142. return false
  143. }
  144. }
  145. sendCommand(...command) {
  146. if (this.socat) {
  147. this.socat.send(JSON.stringify({command}))
  148. }
  149. }
  150. seekAhead(secs) {
  151. this.sendCommand('seek', secs)
  152. }
  153. seekBack(secs) {
  154. this.sendCommand('seek', -secs)
  155. }
  156. seekTo(timeInSecs) {
  157. this.sendCommand('seek', timeInSecs, 'absolute')
  158. }
  159. volUp(amount) {
  160. this.setVolume(this.volume + amount)
  161. }
  162. volDown(amount) {
  163. this.setVolume(this.volume - amount)
  164. }
  165. setVolume(value) {
  166. this.volume = value
  167. this.volume = Math.max(0, this.volume)
  168. this.volume = Math.min(100, this.volume)
  169. this.updateVolume()
  170. }
  171. updateVolume() {
  172. this.sendCommand('set_property', 'volume', this.volume * this.volumeMultiplier)
  173. }
  174. togglePause() {
  175. this.isPaused = !this.isPaused
  176. this.sendCommand('cycle', 'pause')
  177. }
  178. toggleLoop() {
  179. this.isLooping = !this.isLooping
  180. this.sendCommand('cycle', 'loop')
  181. }
  182. setPause(val) {
  183. this.isPaused = !!val
  184. this.sendCommand('set', 'pause', this.isPaused)
  185. }
  186. setLoop(val) {
  187. this.isLooping = !!val
  188. this.sendCommand('set', 'loop', this.isLooping)
  189. }
  190. async kill() {
  191. const path = this.socketPath
  192. delete this.socketPath
  193. if (this.socat) {
  194. await this.socat.dispose()
  195. await this.socat.stop()
  196. }
  197. await super.kill()
  198. await this.removeSocket(path)
  199. }
  200. async removeSocket(path) {
  201. if (path) {
  202. await unlink(path).catch(() => {})
  203. }
  204. }
  205. }
  206. module.exports.SoXPlayer = class extends Player {
  207. playFile(file) {
  208. // SoX's play command is useful for systems that don't have MPV. SoX is
  209. // much easier to install (and probably more commonly installed, as well).
  210. // You don't get keyboard controls such as seeking or volume adjusting
  211. // with SoX, though.
  212. this.process = spawn('play', [file].concat(this.processOptions))
  213. this.process.stdout.on('data', data => {
  214. process.stdout.write(data.toString())
  215. })
  216. // Most output from SoX is given to stderr, for some reason!
  217. this.process.stderr.on('data', data => {
  218. // The status line starts with "In:".
  219. if (data.toString().trim().startsWith('In:')) {
  220. if (this.disablePlaybackStatus) {
  221. return
  222. }
  223. const timeRegex = '([0-9]*):([0-9]*):([0-9]*)\.([0-9]*)'
  224. const match = data.toString().trim().match(new RegExp(
  225. `^In:([0-9.]+%)\\s*${timeRegex}\\s*\\[${timeRegex}\\]`
  226. ))
  227. if (match) {
  228. const percentStr = match[1]
  229. // SoX takes a loooooot of math in order to actually figure out the
  230. // duration, since it outputs the current time and the remaining time
  231. // (but not the duration).
  232. const [
  233. curHour, curMin, curSec, curSecFrac, // ##:##:##.##
  234. remHour, remMin, remSec, remSecFrac // ##:##:##.##
  235. ] = match.slice(2).map(n => parseInt(n))
  236. const duration = Math.round(
  237. (curHour + remHour) * 3600 +
  238. (curMin + remMin) * 60 +
  239. (curSec + remSec) * 1 +
  240. (curSecFrac + remSecFrac) / 100
  241. )
  242. const lenHour = Math.floor(duration / 3600)
  243. const lenMin = Math.floor((duration - lenHour * 3600) / 60)
  244. const lenSec = Math.floor(duration - lenHour * 3600 - lenMin * 60)
  245. this.printStatusLine(getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}))
  246. }
  247. }
  248. })
  249. return new Promise(resolve => {
  250. this.process.on('close', () => resolve())
  251. })
  252. }
  253. }
  254. module.exports.getPlayer = async function(name = null, options = []) {
  255. if (await commandExists('mpv') && (name === null || name === 'mpv')) {
  256. return new module.exports.ControllableMPVPlayer(options)
  257. } else if (name === 'mpv') {
  258. return null
  259. }
  260. if (await commandExists('play') && (name === null || name === 'sox')) {
  261. return new module.exports.SoXPlayer(options)
  262. } else if (name === 'sox') {
  263. return null
  264. }
  265. return null
  266. }