« get me outta code hell

players.js - mtui - Music Text User Interface - user-friendly command line music player
about summary refs log tree commit diff
path: root/players.js
blob: dde1fbf71561ec53a53232ceb15b7195ef4170f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
// 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) {
    if (!!val !== this.isPaused) {
      this.togglePause()
    }
  }

  setLoop(val) {
    if (!!val !== this.isLooping) {
      this.toggleLoop()
    }
  }

  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
}