« get me outta code hell

loop-play.js « src - http-music - Command-line music player + utils (not a server!)
about summary refs log tree commit diff
path: root/src/loop-play.js
blob: b0bb4dd036f71620a42de6f928d8714d39e46dcc (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
// This isn't actually the code for the `play` command! That's in `play.js`.

'use strict'

const { spawn } = require('child_process')
const FIFO = require('fifo-js')
const EventEmitter = require('events')
const { getDownloaderFor, makeConverterDownloader } = require('./downloaders')
const { getItemPathString } = require('./playlist-utils')
const promisifyProcess = require('./promisify-process')

class DownloadController extends EventEmitter {
  waitForDownload() {
    // Returns a promise that resolves when a download is
    // completed.  Note that this isn't necessarily the download
    // that was initiated immediately before a call to
    // waitForDownload (if any), since that download may have
    // been canceled (see cancel).  You can also listen for the
    // 'downloaded' event instead.

    return new Promise(resolve => {
      this.once('downloaded', file => resolve(file))
    })
  }

  async download(downloader, arg) {
    // Downloads a file.  This doesn't return anything; use
    // waitForDownload to get the result of this.
    // (The reasoning is that it's possible for a download to
    // be canceled and replaced with a new download (see cancel)
    // which would void the result of the old download.)

    this.cleanupListeners()

    let canceled = false

    this._handleCanceled = () => {
      canceled = true
      this.cleanupListeners()
    }

    this.once('canceled', this._handleCanceled)

    const file = await downloader(arg)

    if (!canceled) {
      this.emit('downloaded', file)
    }
  }

  cleanupListeners() {
    if (this._handleCanceled) {
      this.removeListener('canceled', this._handleCanceled)
    }
  }

  cancel() {
    // Cancels the current download.  This doesn't cancel any
    // waitForDownload promises, though -- you'll need to start
    // a new download to resolve those.

    this.emit('canceled')
    this.cleanupListeners()
  }
}

class PlayController {
  constructor(picker, downloadController) {
    this.picker = picker
    this.downloadController = downloadController
    this.playOpts = []
    this.playerCommand = null
    this.currentTrack = null
    this.process = null
  }

  async loopPlay() {
    let nextFile

    // Null would imply there's NO up-next track, but really
    // we just haven't set it yet.
    this.nextTrack = undefined

    let downloadNext = () => {
      this.nextTrack = this.startNextDownload()
      if (this.nextTrack !== null) {
        return this.downloadController.waitForDownload().then(file => {
          nextFile = file
        })
      } else {
        nextFile = null
        return Promise.resolve()
      }
    }

    await downloadNext()

    while (this.nextTrack) {
      this.currentTrack = this.nextTrack

      await Promise.all([
        // If the downloader returns false, the file failed to download; that
        // means we'll just skip this track and wait for the next.
        nextFile !== false ? this.playFile(nextFile) : Promise.resolve(),
        downloadNext()
      ])
    }
  }

  startNextDownload() {
    // TODO: Handle/test null return from picker.
    const picked = this.picker()

    if (picked === null) {
      return null
    } else {
      let downloader = getDownloaderFor(picked.downloaderArg)
      downloader = makeConverterDownloader(downloader, 'wav')
      this.downloadController.download(downloader, picked.downloaderArg)
      return picked
    }
  }

  playFile(file) {
    if (this.playerCommand === 'sox' || this.playerCommand === 'play') {
      return this.playFileSoX(file)
    } else if (this.playerCommand === 'mpv') {
      return this.playFileMPV(file)
    } else {
      if (this.playerCommand) {
        console.warn('Invalid player command given?', this.playerCommand)
      } else {
        console.warn('No player command given?')
      }

      return Promise.resolve()
    }
  }

  playFileSoX(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', [
      ...this.playOpts,
      file
    ])

    return promisifyProcess(this.process)
  }

  playFileMPV(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.fifo = new FIFO()
    this.process = spawn('mpv', [
      '--input-file=' + this.fifo.path,
      '--no-audio-display',
      file,
      ...this.playOpts
    ])

    this.process.stderr.on('data', data => {
      const match = data.toString().match(
        /(..):(..):(..) \/ (..):(..):(..) \(([0-9]+)%\)/
      )

      if (match) {
        const [
          curHour, curMin, curSec, // ##:##:##
          lenHour, lenMin, lenSec, // ##:##:##
          percent // ###%
        ] = match.slice(1)

        let curStr, lenStr

        // We don't want to display hour counters if the total length is less
        // than an hour.
        if (parseInt(lenHour) > 0) {
          curStr = `${curHour}:${curMin}:${curSec}`
          lenStr = `${lenHour}:${lenMin}:${lenSec}`
        } else {
          curStr = `${curMin}:${curSec}`
          lenStr = `${lenMin}:${lenSec}`
        }

        // Multiplication casts to numbers; addition prioritizes strings.
        // Thanks, JavaScript!
        const curSecTotal = (3600 * curHour) + (60 * curMin) + (1 * curSec)
        const lenSecTotal = (3600 * lenHour) + (60 * lenMin) + (1 * lenSec)
        const percentVal = (100 / lenSecTotal) * curSecTotal
        const percentStr = (Math.trunc(percentVal * 100) / 100).toFixed(2)

        process.stdout.write(
          `\x1b[K~ (${percentStr}%) ${curStr} / ${lenStr}\r`
        )
      }
    })

    return new Promise(resolve => {
      this.process.once('close', resolve)
    })
  }

  skip() {
    this.kill()
  }

  seekAhead(secs) {
    this.sendCommand(`seek +${parseFloat(secs)}`)
  }

  seekBack(secs) {
    this.sendCommand(`seek -${parseFloat(secs)}`)
  }

  volUp(amount) {
    this.sendCommand(`add volume +${parseFloat(amount)}`)
  }

  volDown(amount) {
    this.sendCommand(`add volume -${parseFloat(amount)}`)
  }

  togglePause() {
    this.sendCommand('cycle pause')
  }

  sendCommand(command) {
    if (this.playerCommand === 'mpv' && this.fifo) {
      this.fifo.write(command)
    }
  }

  kill() {
    if (this.process) {
      this.process.kill()
    }

    if (this.fifo) {
      this.fifo.close()
      delete this.fifo
    }

    this.currentTrack = null
  }

  logTrackInfo() {
    const getMessage = t => {
      let path = getItemPathString(t)

      return (
        `\x1b[1m${t.name} \x1b[0m@ ${path} \x1b[2m${t.downloaderArg}\x1b[0m`
      )
    }

    if (this.currentTrack) {
      console.log(`Playing: ${getMessage(this.currentTrack)}`)
    } else {
      console.log("No song currently playing.")
    }

    if (this.nextTrack) {
      console.log(`Up next: ${getMessage(this.nextTrack)}`)
    } else {
      console.log("No song up next.")
    }
  }
}

module.exports = function loopPlay(
  picker, playerCommand = 'mpv', playOpts = []
) {
  // Looping play function. Takes one argument, the "picker" function,
  // which returns a track to play. Stops when the result of the picker
  // function is null (or similar). Optionally takes a second argument
  // used as arguments to the `play` process (before the file name).

  const downloadController = new DownloadController()

  const playController = new PlayController(picker, downloadController)

  Object.assign(playController, {playerCommand, playOpts})

  const promise = playController.loopPlay()

  return {
    promise,
    playController,
    downloadController
  }
}