players.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // stolen from http-music
  2. import {
  3. commandExists,
  4. killProcess,
  5. getTimeStrings,
  6. getTimeStringsFromSec,
  7. } from './general-util.js'
  8. import {spawn} from 'node:child_process'
  9. import {statSync} from 'node:fs'
  10. import {unlink} from 'node:fs/promises'
  11. import EventEmitter from 'node:events'
  12. import path from 'node:path'
  13. import url from 'node:url'
  14. import Socat from './socat.js'
  15. export class Player extends EventEmitter {
  16. constructor(processOptions = []) {
  17. super()
  18. this.processOptions = processOptions
  19. this.disablePlaybackStatus = false
  20. this.isLooping = false
  21. this.isPaused = false
  22. this.volume = 100
  23. this.volumeMultiplier = 1.0
  24. }
  25. set process(newProcess) {
  26. this._process = newProcess
  27. this._process.on('exit', code => {
  28. if (code !== 0 && !this._killed) {
  29. this.emit('crashed', code)
  30. }
  31. this._killed = false
  32. })
  33. }
  34. get process() {
  35. return this._process
  36. }
  37. playFile(_file, _startTime) {}
  38. seekAhead(_secs) {}
  39. seekBack(_secs) {}
  40. seekTo(_timeInSecs) {}
  41. seekToStart() {}
  42. volUp(_amount) {}
  43. volDown(_amount) {}
  44. setVolume(_value) {}
  45. updateVolume() {}
  46. togglePause() {}
  47. toggleLoop() {}
  48. setPause() {}
  49. setLoop() {}
  50. async kill() {
  51. if (this.process) {
  52. this._killed = true
  53. await killProcess(this.process)
  54. }
  55. }
  56. printStatusLine(data) {
  57. // Quick sanity check - we don't want to print the status line if it's
  58. // disabled! Hopefully printStatusLine won't be called in that case, but
  59. // if it is, we should be careful.
  60. if (!this.disablePlaybackStatus) {
  61. this.emit('printStatusLine', data)
  62. }
  63. }
  64. setVolumeMultiplier(value) {
  65. this.volumeMultiplier = value
  66. this.updateVolume()
  67. }
  68. fadeIn() {
  69. const interval = 50
  70. const duration = 1000
  71. const delta = 1.0 - this.volumeMultiplier
  72. const id = setInterval(() => {
  73. this.volumeMultiplier += delta * interval / duration
  74. if (this.volumeMultiplier >= 1.0) {
  75. this.volumeMultiplier = 1.0
  76. clearInterval(id)
  77. }
  78. this.updateVolume()
  79. }, interval)
  80. }
  81. }
  82. export class MPVPlayer extends Player {
  83. // The more powerful MPV player. MPV is virtually impossible for a human
  84. // being to install; if you're having trouble with it, try the SoX player.
  85. getMPVOptions(file, startTime) {
  86. const opts = [
  87. `--term-status-msg='${this.getMPVStatusMessage()}'`,
  88. '--no-video',
  89. file
  90. ]
  91. if (this.isLooping) {
  92. opts.unshift('--loop')
  93. }
  94. if (this.isPaused) {
  95. opts.unshift('--pause')
  96. }
  97. if (startTime) {
  98. opts.unshift('--start=' + startTime)
  99. }
  100. opts.unshift('--volume=' + this.volume * this.volumeMultiplier)
  101. return opts
  102. }
  103. getMPVStatusMessage() {
  104. // Note: This function shouldn't include any single-quotes! It probably
  105. // (NOTE: PROBABLY) wouldn't cause any security issues, but it will break
  106. // --term-status-msg parsing and might keep mpv from starting at all.
  107. return '${=time-pos} ${=duration} ${=percent-pos}'
  108. }
  109. playFile(file, startTime) {
  110. this.process = spawn('mpv', this.getMPVOptions(file, startTime).concat(this.processOptions))
  111. let lastPercent = 0
  112. this.process.stderr.on('data', data => {
  113. if (this.disablePlaybackStatus) {
  114. return
  115. }
  116. const match = data.toString().match(
  117. /([0-9.]+) ([0-9.]+) ([0-9.]+)/
  118. )
  119. if (match) {
  120. const [
  121. curSecTotal,
  122. lenSecTotal,
  123. percent
  124. ] = match.slice(1)
  125. if (parseInt(percent) < lastPercent) {
  126. // mpv forgets commands you sent it whenever it loops, so you
  127. // have to specify them every time it loops. We do that whenever the
  128. // position in the track decreases, since that means it may have
  129. // looped.
  130. this.setLoop(this.isLooping)
  131. }
  132. lastPercent = parseInt(percent)
  133. this.printStatusLine(getTimeStringsFromSec(curSecTotal, lenSecTotal))
  134. }
  135. this.updateVolume();
  136. })
  137. return new Promise(resolve => {
  138. this.process.once('close', resolve)
  139. })
  140. }
  141. }
  142. export class ControllableMPVPlayer extends MPVPlayer {
  143. getMPVOptions(...args) {
  144. return ['--input-ipc-server=' + this.socat.path, ...super.getMPVOptions(...args)]
  145. }
  146. playFile(file, startTime) {
  147. this.removeSocket(this.socketPath)
  148. do {
  149. this.socketPath = path.join(path.dirname(url.fileURLToPath(import.meta.url)), 'mtui-socket-' + Math.floor(Math.random() * 10000))
  150. } while (this.existsSync(this.socketPath))
  151. this.socat = new Socat(this.socketPath)
  152. const mpv = super.playFile(file, startTime)
  153. mpv.then(() => this.removeSocket(this.socketPath))
  154. return mpv
  155. }
  156. existsSync(path) {
  157. try {
  158. statSync(path)
  159. return true
  160. } catch (error) {
  161. return false
  162. }
  163. }
  164. sendCommand(...command) {
  165. if (this.socat) {
  166. this.socat.send(JSON.stringify({command}))
  167. }
  168. }
  169. seekAhead(secs) {
  170. this.sendCommand('seek', secs)
  171. }
  172. seekBack(secs) {
  173. this.sendCommand('seek', -secs)
  174. }
  175. seekTo(timeInSecs) {
  176. this.sendCommand('seek', timeInSecs, 'absolute')
  177. }
  178. seekToStart() {
  179. this.seekTo(0)
  180. }
  181. volUp(amount) {
  182. this.setVolume(this.volume + amount)
  183. }
  184. volDown(amount) {
  185. this.setVolume(this.volume - amount)
  186. }
  187. setVolume(value) {
  188. this.volume = value
  189. this.volume = Math.max(0, this.volume)
  190. this.volume = Math.min(100, this.volume)
  191. this.updateVolume()
  192. }
  193. updateVolume() {
  194. this.sendCommand('set_property', 'volume', this.volume * this.volumeMultiplier)
  195. }
  196. togglePause() {
  197. this.isPaused = !this.isPaused
  198. this.sendCommand('cycle', 'pause')
  199. }
  200. toggleLoop() {
  201. this.isLooping = !this.isLooping
  202. this.sendCommand('cycle', 'loop')
  203. }
  204. setPause(val) {
  205. const wasPaused = this.isPaused
  206. this.isPaused = !!val
  207. if (this.isPaused !== wasPaused) {
  208. this.sendCommand('cycle', 'pause')
  209. }
  210. // For some reason "set pause" doesn't seem to be working anymore:
  211. // this.sendCommand('set', 'pause', this.isPaused)
  212. }
  213. setLoop(val) {
  214. this.isLooping = !!val
  215. this.sendCommand('set', 'loop', this.isLooping)
  216. }
  217. async kill() {
  218. const path = this.socketPath
  219. delete this.socketPath
  220. if (this.socat) {
  221. await this.socat.dispose()
  222. await this.socat.stop()
  223. }
  224. await super.kill()
  225. await this.removeSocket(path)
  226. }
  227. async removeSocket(path) {
  228. if (path) {
  229. await unlink(path).catch(() => {})
  230. }
  231. }
  232. }
  233. export class SoXPlayer extends Player {
  234. playFile(file, startTime) {
  235. // SoX's play command is useful for systems that don't have MPV. SoX is
  236. // much easier to install (and probably more commonly installed, as well).
  237. // You don't get keyboard controls such as seeking or volume adjusting
  238. // with SoX, though.
  239. this._file = file
  240. this.process = spawn('play', [file].concat(
  241. this.processOptions,
  242. startTime ? ['trim', startTime] : []
  243. ))
  244. this.process.stdout.on('data', data => {
  245. process.stdout.write(data.toString())
  246. })
  247. // Most output from SoX is given to stderr, for some reason!
  248. this.process.stderr.on('data', data => {
  249. // The status line starts with "In:".
  250. if (data.toString().trim().startsWith('In:')) {
  251. if (this.disablePlaybackStatus) {
  252. return
  253. }
  254. const timeRegex = String.raw`([0-9]*):([0-9]*):([0-9]*)\.([0-9]*)`
  255. const match = data.toString().trim().match(new RegExp(
  256. `^In:([0-9.]+%)\\s*${timeRegex}\\s*\\[${timeRegex}\\]`
  257. ))
  258. if (match) {
  259. // SoX takes a loooooot of math in order to actually figure out the
  260. // duration, since it outputs the current time and the remaining time
  261. // (but not the duration).
  262. const [
  263. curHour, curMin, curSec, curSecFrac, // ##:##:##.##
  264. remHour, remMin, remSec, remSecFrac // ##:##:##.##
  265. ] = match.slice(2).map(n => parseInt(n))
  266. const duration = Math.round(
  267. (curHour + remHour) * 3600 +
  268. (curMin + remMin) * 60 +
  269. (curSec + remSec) * 1 +
  270. (curSecFrac + remSecFrac) / 100
  271. )
  272. const lenHour = Math.floor(duration / 3600)
  273. const lenMin = Math.floor((duration - lenHour * 3600) / 60)
  274. const lenSec = Math.floor(duration - lenHour * 3600 - lenMin * 60)
  275. this.printStatusLine(getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}))
  276. }
  277. }
  278. })
  279. return new Promise(resolve => {
  280. this.process.on('close', () => resolve())
  281. }).then(() => {
  282. if (this._restartPromise) {
  283. const p = this._restartPromise
  284. this._restartPromise = null
  285. return p
  286. }
  287. })
  288. }
  289. async seekToStart() {
  290. // SoX doesn't support a command interface to interact while playback is
  291. // ongoing. However, we can simulate seeking to the start by restarting
  292. // playback altogether. We just need to be careful not to resolve the
  293. // original playback promise before the new one is complete!
  294. if (!this._file) {
  295. return
  296. }
  297. let resolve = null
  298. let reject = null
  299. // The original call of playFile() will yield control to this promise, which
  300. // we bind to the resolve/reject of a new call to playFile().
  301. this._restartPromise = new Promise((res, rej) => {
  302. resolve = res
  303. reject = rej
  304. })
  305. await this.kill()
  306. this.playFile(this._file).then(resolve, reject)
  307. }
  308. }
  309. export async function getPlayer(name = null, options = []) {
  310. if (await commandExists('mpv') && (name === null || name === 'mpv')) {
  311. return new ControllableMPVPlayer(options)
  312. } else if (name === 'mpv') {
  313. return null
  314. }
  315. if (await commandExists('play') && (name === null || name === 'sox')) {
  316. return new SoXPlayer(options)
  317. } else if (name === 'sox') {
  318. return null
  319. }
  320. return null
  321. }