players.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. if (!!val !== this.isPaused) {
  206. this.togglePause()
  207. }
  208. }
  209. setLoop(val) {
  210. if (!!val !== this.isLooping) {
  211. this.toggleLoop()
  212. }
  213. }
  214. async kill() {
  215. const path = this.socketPath
  216. delete this.socketPath
  217. if (this.socat) {
  218. await this.socat.dispose()
  219. await this.socat.stop()
  220. }
  221. await super.kill()
  222. await this.removeSocket(path)
  223. }
  224. async removeSocket(path) {
  225. if (path) {
  226. await unlink(path).catch(() => {})
  227. }
  228. }
  229. }
  230. export class SoXPlayer extends Player {
  231. playFile(file, startTime) {
  232. // SoX's play command is useful for systems that don't have MPV. SoX is
  233. // much easier to install (and probably more commonly installed, as well).
  234. // You don't get keyboard controls such as seeking or volume adjusting
  235. // with SoX, though.
  236. this._file = file
  237. this.process = spawn('play', [file].concat(
  238. this.processOptions,
  239. startTime ? ['trim', startTime] : []
  240. ))
  241. this.process.stdout.on('data', data => {
  242. process.stdout.write(data.toString())
  243. })
  244. // Most output from SoX is given to stderr, for some reason!
  245. this.process.stderr.on('data', data => {
  246. // The status line starts with "In:".
  247. if (data.toString().trim().startsWith('In:')) {
  248. if (this.disablePlaybackStatus) {
  249. return
  250. }
  251. const timeRegex = String.raw`([0-9]*):([0-9]*):([0-9]*)\.([0-9]*)`
  252. const match = data.toString().trim().match(new RegExp(
  253. `^In:([0-9.]+%)\\s*${timeRegex}\\s*\\[${timeRegex}\\]`
  254. ))
  255. if (match) {
  256. // SoX takes a loooooot of math in order to actually figure out the
  257. // duration, since it outputs the current time and the remaining time
  258. // (but not the duration).
  259. const [
  260. curHour, curMin, curSec, curSecFrac, // ##:##:##.##
  261. remHour, remMin, remSec, remSecFrac // ##:##:##.##
  262. ] = match.slice(2).map(n => parseInt(n))
  263. const duration = Math.round(
  264. (curHour + remHour) * 3600 +
  265. (curMin + remMin) * 60 +
  266. (curSec + remSec) * 1 +
  267. (curSecFrac + remSecFrac) / 100
  268. )
  269. const lenHour = Math.floor(duration / 3600)
  270. const lenMin = Math.floor((duration - lenHour * 3600) / 60)
  271. const lenSec = Math.floor(duration - lenHour * 3600 - lenMin * 60)
  272. this.printStatusLine(getTimeStrings({curHour, curMin, curSec, lenHour, lenMin, lenSec}))
  273. }
  274. }
  275. })
  276. return new Promise(resolve => {
  277. this.process.on('close', () => resolve())
  278. }).then(() => {
  279. if (this._restartPromise) {
  280. const p = this._restartPromise
  281. this._restartPromise = null
  282. return p
  283. }
  284. })
  285. }
  286. async seekToStart() {
  287. // SoX doesn't support a command interface to interact while playback is
  288. // ongoing. However, we can simulate seeking to the start by restarting
  289. // playback altogether. We just need to be careful not to resolve the
  290. // original playback promise before the new one is complete!
  291. if (!this._file) {
  292. return
  293. }
  294. let resolve = null
  295. let reject = null
  296. // The original call of playFile() will yield control to this promise, which
  297. // we bind to the resolve/reject of a new call to playFile().
  298. this._restartPromise = new Promise((res, rej) => {
  299. resolve = res
  300. reject = rej
  301. })
  302. await this.kill()
  303. this.playFile(this._file).then(resolve, reject)
  304. }
  305. }
  306. export class GhostPlayer extends Player {
  307. // The music player which makes believe! This player doesn't actually process
  308. // any files nor interface with an underlying binary or API to provide real
  309. // sound playback. It just provides all the usual interfaces as best as it
  310. // can - simulating playback time by accounting for pause/resume, seeking,
  311. // and so on, for example.
  312. statusInterval = 250
  313. // This is always a number if a track is "loaded", whether or not paused.
  314. // It's null if no track is loaded (aka "stopped"). It's used as the base
  315. // for the playback time, if resumed, or directly as the current playback
  316. // time, if paused. (Note: time is internally tracked in milliseconds.)
  317. #playingFrom = null
  318. // This is null if no track is "loaded" (aka "stopped") or if paused.
  319. // It's used to calculate the current playback time when resumed.
  320. #resumedSince = null
  321. // These are interval/timer identifiers and are null if no track is loaded
  322. // or if paused.
  323. #statusInterval = null
  324. #doneTimeout = null
  325. #loopTimeout = null
  326. // This is a callback which resolves the playFile promise. It exists at the
  327. // same time as playingFrom, i.e. while a track is "loaded", whether or not
  328. // paused.
  329. #resolvePlayFilePromise = null
  330. // This is reset to null every time a track is started. It can be provided
  331. // externally with setDuration(). It's used to control emitting a "done"
  332. // event.
  333. #duration = null
  334. setDuration(duration) {
  335. // This is a unique interface on GhostPlayer, not found on other players.
  336. // Most players inherently know when to resolve playFile thanks to the
  337. // child process exiting (or outputting a message) when the input file is
  338. // done. GhostPlayer is intended not to operate on actual files at all, so
  339. // we couldn't even read duration metadata if we wanted to. So, this extra
  340. // interface can be used to provide that data instead!
  341. if (this.#playingFrom === null) {
  342. return
  343. }
  344. if (duration !== null) {
  345. if (this.#getPlaybackTime() >= duration * 1000) {
  346. // No need to do anything else if we're already done playing according
  347. // to the provided duration.
  348. this.#donePlaying()
  349. return
  350. }
  351. }
  352. this.#affectTimeRemaining(() => {
  353. this.#duration = duration
  354. })
  355. }
  356. playFile(file, startTime = 0) {
  357. // This function is public, and might be called without any advance notice,
  358. // so clear existing playback info. This also resolves a prior playFile
  359. // promise.
  360. if (this.#playingFrom !== null) {
  361. this.#donePlaying()
  362. }
  363. const promise = new Promise(resolve => {
  364. this.#resolvePlayFilePromise = resolve
  365. })
  366. this.#playingFrom = 1000 * startTime
  367. // It's possible to have paused the player before the next track came up,
  368. // in which case playback begins paused.
  369. if (!this.isPaused) {
  370. this.#resumedSince = Date.now()
  371. }
  372. this.#status()
  373. this.#startStatusInterval()
  374. // We can't start any end-of-track timeouts here because we don't have a
  375. // duration yet - we'll instate the appropriate timeout once it's been
  376. // provided externally (with setDuration()).
  377. return promise
  378. }
  379. setPause(paused) {
  380. if (!paused && this.isPaused) {
  381. this.#resumedSince = Date.now()
  382. this.#status()
  383. this.#startStatusInterval()
  384. if (this.#duration !== null) {
  385. if (this.isLooping) {
  386. this.#startLoopTimeout()
  387. } else {
  388. this.#startDoneTimeout()
  389. }
  390. }
  391. }
  392. if (paused && !this.isPaused) {
  393. this.#playingFrom = this.#getPlaybackTime()
  394. this.#resumedSince = null
  395. this.#status()
  396. this.#clearStatusInterval()
  397. if (this.#duration !== null) {
  398. if (this.isLooping) {
  399. this.#clearLoopTimeout()
  400. } else {
  401. this.#clearDoneTimeout()
  402. }
  403. }
  404. }
  405. this.isPaused = paused
  406. }
  407. togglePause() {
  408. this.setPause(!this.isPaused)
  409. }
  410. setLoop(looping) {
  411. if (!looping && this.isLooping) {
  412. if (this.#duration !== null) {
  413. this.#clearLoopTimeout()
  414. this.#startDoneTimeout()
  415. }
  416. }
  417. if (looping && !this.isLooping) {
  418. if (this.#duration !== null) {
  419. this.#clearDoneTimeout()
  420. this.#startLoopTimeout()
  421. }
  422. }
  423. this.isLooping = looping
  424. }
  425. toggleLoop() {
  426. this.setLoop(!this.isLooping)
  427. }
  428. seekToStart() {
  429. if (this.#playingFrom === null) {
  430. return
  431. }
  432. this.seekTo(0)
  433. }
  434. seekAhead(secs) {
  435. if (this.#playingFrom === null) {
  436. return
  437. }
  438. this.seekTo(this.#getPlaybackTime() / 1000 + secs)
  439. }
  440. seekBack(secs) {
  441. if (this.#playingFrom === null) {
  442. return
  443. }
  444. this.seekTo(this.#getPlaybackTime() / 1000 - secs)
  445. }
  446. seekTo(timeInSecs) {
  447. if (this.#playingFrom === null) {
  448. return
  449. }
  450. let seekTime = null
  451. if (this.#duration !== null && timeInSecs > this.#duration) {
  452. // Seeking past the duration of the track either loops it or ends it.
  453. if (this.isLooping) {
  454. seekTime = 0
  455. } else {
  456. this.#donePlaying()
  457. return
  458. }
  459. } else if (timeInSecs < 0) {
  460. // You can't seek before the beginning of a track!
  461. seekTime = 0
  462. } else {
  463. // Otherwise, just seek to the specified time.
  464. seekTime = timeInSecs
  465. }
  466. this.#affectTimeRemaining(() => {
  467. if (this.#resumedSince !== null) {
  468. // Seeking doesn't pause, but it does functionally reset where we're
  469. // measuring playback time from.
  470. this.#resumedSince = Date.now()
  471. }
  472. this.#playingFrom = seekTime * 1000
  473. })
  474. }
  475. async kill() {
  476. if (this.#playingFrom === null) {
  477. return
  478. }
  479. this.#donePlaying()
  480. }
  481. #affectTimeRemaining(callback) {
  482. // Changing the time remaining (i.e. the delta between current playback
  483. // time and duration) means any timeouts which run when the track ends
  484. // need to be reset with the new delta. This function also handily creates
  485. // those timeouts in the first place if a duration hadn't been set before.
  486. if (this.#resumedSince !== null && this.#duration !== null) {
  487. // If there was an existing timeout for the end of the track, clear it.
  488. // We're going to instate a new one in a moment.
  489. if (this.isLooping) {
  490. this.#clearLoopTimeout()
  491. } else {
  492. this.#clearDoneTimeout()
  493. }
  494. }
  495. // Do something which will affect the time remaining.
  496. callback()
  497. this.#status()
  498. if (this.#resumedSince !== null && this.#duration !== null) {
  499. // Start a timeout for the (possibly new) end of the track, but only if
  500. // we're actually playing!
  501. if (this.isLooping) {
  502. this.#startLoopTimeout()
  503. } else {
  504. this.#startDoneTimeout()
  505. }
  506. }
  507. }
  508. #startStatusInterval() {
  509. if (this.#statusInterval !== null) {
  510. throw new Error(`Status interval already set (this code shouldn't be reachable!)`)
  511. }
  512. this.#statusInterval = setInterval(() => this.#status(), this.statusInterval)
  513. }
  514. #startDoneTimeout() {
  515. if (this.#doneTimeout !== null) {
  516. throw new Error(`Done timeout already set (this code shouldn't be reachable!)`)
  517. }
  518. const timeoutInMilliseconds = this.#duration * 1000 - this.#getPlaybackTime()
  519. this.#doneTimeout = setTimeout(() => this.#donePlaying(), timeoutInMilliseconds)
  520. }
  521. #startLoopTimeout() {
  522. if (this.#loopTimeout !== null) {
  523. throw new Error(`Loop timeout already set (this code shouldn't be reachable!)`)
  524. }
  525. const timeoutInMilliseconds = this.#duration * 1000 - this.#getPlaybackTime()
  526. this.#loopTimeout = setTimeout(() => this.#loopAtEnd(), timeoutInMilliseconds)
  527. }
  528. #clearStatusInterval() {
  529. if (this.#statusInterval === null) {
  530. throw new Error(`Status interval not set yet (this code shouldn't be reachable!)`)
  531. }
  532. clearInterval(this.#statusInterval)
  533. this.#statusInterval = null
  534. }
  535. #clearDoneTimeout() {
  536. if (this.#doneTimeout === null) {
  537. throw new Error(`Done timeout not set yet (this code shouldn't be reachable!)`)
  538. }
  539. clearTimeout(this.#doneTimeout)
  540. this.#doneTimeout = null
  541. }
  542. #clearLoopTimeout() {
  543. if (this.#loopTimeout === null) {
  544. throw new Error(`Loop timeout nout set yet (this code shouldn't be reachable!)`)
  545. }
  546. clearTimeout(this.#loopTimeout)
  547. this.#loopTimeout = null
  548. }
  549. #status() {
  550. // getTimeStringsFromSec supports null duration, so we don't need to
  551. // perform a specific check here.
  552. const timeInSecs = this.#getPlaybackTime() / 1000
  553. this.printStatusLine(getTimeStringsFromSec(timeInSecs, this.#duration))
  554. }
  555. #donePlaying() {
  556. if (this.#resumedSince !== null) {
  557. this.#clearStatusInterval()
  558. }
  559. // Run this first, while we still have a track "loaded". This ensures the
  560. // end-of-track timeouts get cleared appropriately (if they've been set).
  561. this.setDuration(null)
  562. this.#playingFrom = null
  563. this.#resumedSince = null
  564. // No, this doesn't have any spooky tick order errors - resolved promises
  565. // always continue on a later tick of the event loop, not the current one.
  566. // So the second line here will always happen before any potential future
  567. // calls to playFile().
  568. this.#resolvePlayFilePromise()
  569. this.#resolvePlayFilePromise = null
  570. }
  571. #loopAtEnd() {
  572. // Looping is just seeking back to the start! This will also cause the
  573. // loop timer to be reinstated (via #affectTimeRemaining).
  574. this.seekToStart()
  575. }
  576. #getPlaybackTime() {
  577. if (this.#resumedSince === null) {
  578. return this.#playingFrom
  579. } else {
  580. return this.#playingFrom + Date.now() - this.#resumedSince
  581. }
  582. }
  583. }
  584. export async function getPlayer(name = null, options = []) {
  585. if (name === 'ghost') {
  586. return new GhostPlayer(options)
  587. }
  588. if (await commandExists('mpv') && (name === null || name === 'mpv')) {
  589. return new ControllableMPVPlayer(options)
  590. } else if (name === 'mpv') {
  591. return null
  592. }
  593. if (await commandExists('play') && (name === null || name === 'sox')) {
  594. return new SoXPlayer(options)
  595. } else if (name === 'sox') {
  596. return null
  597. }
  598. return null
  599. }