« 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: d22d55dad4c7244423502cb24cfcae168d734a99 (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
'use strict'

const { spawn } = require('child_process')
const promisifyProcess = require('./promisify-process')
const sanitize = require('sanitize-filename')
const tempy = require('tempy')

const EventEmitter = require('events')

class DownloadController extends EventEmitter {
  constructor(picker, downloader) {
    super()

    this.pickedTrack = null
    this.process = null
    this.isDownloading = false

    this.picker = picker
    this.downloader = downloader

    this._downloadNext = null
  }

  downloadNext() {
    this.downloadNextHelper()

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

  async downloadNextHelper() {
    this.isDownloading = true

    let wasDestroyed = false

    this._destroyDownload = () => {
      wasDestroyed = true
    }

    // We need to actually pick something to download; we'll use the picker
    // (given in the DownloadController constructor) for that.
    // (See pickers.js.)
    const picked = this.picker()

    // If the picker returns null, nothing was picked; that means that we
    // should stop now. No point in trying to play nothing!
    if (picked == null) {
      this.wavFile = null
      return false
    }

    // Having the picked song being available is handy, for UI stuff (i.e. for
    // being displayed to the user through the console).
    this.pickedTrack = picked
    this.emit('trackPicked', picked)

    // The picked result is an array containing the title of the track (only
    // really used to display to the user) and an argument to be passed to the
    // downloader. The downloader argument doesn't have to be anything in
    // particular; but typically it's a string containing a URL or file path.
    // It's up to the downloader to decide what to do with it.
    const [ title, downloaderArg ] = picked

    // The "from" file is downloaded by the downloader (given in the
    // DownloadController constructor) using the downloader argument we just
    // got.
    const fromFile = await this.downloader(downloaderArg)

    // Before we convert the file, we'll check if it's already an audio file.
    // This goes on the assumption that if avprobe understands a file, play
    // also does; which is probably true almost all the time.
    let probeCode

    try {
      // Well, lovely. avprobe ALWAYS outputs "# avprobe output" - even if
      // its loglevel is set to silent! Blasphemy, but whatever. We're forced
      // to not pipe to stdout (which we do by passing false to
      // promisifyProcess).
      await promisifyProcess(spawn('avprobe', [fromFile]), false)
    } catch(errorCode) {
      probeCode = errorCode
    }

    // We'll use this wav file later, to actually play the track.
    if (probeCode > 0) {
      this.wavFile = await this.convert(picked, fromFile)
    } else {
      this.wavFile = fromFile
    }

    // If this download was destroyed, we quit now; we don't want to emit that
    // the download was finished if the finished download was the destroyed
    // one!
    if (wasDestroyed) {
      return
    }

    this.emit('downloadFinished')
  }

  async convert(picked, fromFile) {
    // The "to" file is simply a WAV file. We give this WAV file a specific
    // name - the title of the track we got earlier, sanitized to be file-safe
    // - so that when `play` outputs the name of the song, it's obvious to the
    // user what's being played.
    const tempDir = tempy.directory()
    const toFile = tempDir + `/.${sanitize(title)}.wav`

    // Now that we've got the `to` and `from` file names, we can actually do
    // the convertion. We don't want any output from `avconv` at all, since the
    // output of `play` will usually be displayed while `avconv` is running,
    // so we pass `-loglevel quiet` into `avconv`.
    const convertProcess = spawn('avconv', [
      '-loglevel', 'quiet', '-i', fromFile, toFile
    ])

    // We store the convert process so that we can kill it before it finishes,
    // if that's most convenient (e.g. if skipping the current song or quitting
    // the entire program).
    this.process = convertProcess

    // Now it's only a matter of time before the process is finished.
    // Literally; we need to await the promisified version of our convertion
    // child process.
    try {
      await promisifyProcess(convertProcess)
    } catch(err) {
      // There's a chance we'll fail, though. That could happen if the passed
      // "from" file doesn't actually contain audio data. In that case, we
      // have to attempt this whole process over again, so that we get a
      // different file. (Technically, the picker might always pick the same
      // file; if that's the case, and the convert process is failing on it,
      // we could end up in an infinite loop. That would be bad, since there
      // isn't any guarding against a situation like that here.)

      // Usually we'll log a warning message saying that the convertion failed,
      // but if this download was destroyed, it's expected for the avconv
      // process to fail; so in that case we don't bother warning the user.
      if (!wasDestroyed) {
        console.warn("Failed to convert " + title)
        console.warn("Selecting a new track")

        return await this.downloadNext()
      }
    }

    return to
  }

  skipUpNext() {
    if (this._destroyDownload) {
      this._destroyDownload()
    }

    this.downloadNextHelper()
  }

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

class PlayController {
  constructor(downloadController) {
    this.currentTrack = null
    this.upNextTrack = null
    this.playArgs = []
    this.process = null

    this.downloadController = downloadController

    this.downloadController.on('trackPicked', track => {
      this.upNextTrack = track
    })
  }

  async loopPlay() {
    // Playing music in a loop isn't particularly complicated; essentially, we
    // just want to keep downloading and playing tracks until none is picked.

    await this.downloadController.downloadNext()

    while (this.downloadController.wavFile) {
      this.currentTrack = this.downloadController.pickedTrack


      const file = this.downloadController.wavFile
      const playProcess = spawn('play', [...this.playArgs, file])
      const playPromise = promisifyProcess(playProcess)
      this.process = playProcess

      const nextPromise = this.downloadController.downloadNext()

      try {
        await playPromise
      } catch(err) {
        console.warn(err + '\n')
      }

      await nextPromise
    }
  }

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

    this.currentTrack = null
  }
}

module.exports = function loopPlay(picker, downloader, playArgs = []) {
  // Looping play function. Takes one argument, the "pick" function,
  // which returns a track to play. Preemptively downloads the next
  // track while the current one is playing for seamless continuation
  // from one song to the next. Stops when the result of the pick
  // 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(picker, downloader)

  const playController = new PlayController(downloadController)
  playController.playArgs = playArgs

  const promise = playController.loopPlay()

  return {
    promise,

    skipCurrent: function() {
      playController.killProcess()
    },

    skipUpNext: function() {
      downloadController.skipUpNext()
    },

    kill: function() {
      playController.killProcess()
      downloadController.killProcess()
    },

    logTrackInfo: function() {
      if (playController.currentTrack) {
        const [ curTitle, curArg ] = playController.currentTrack
        console.log(`Playing: \x1b[1m${curTitle} \x1b[2m${curArg}\x1b[0m`)
      } else {
        console.log("No song currently playing.")
      }

      if (playController.upNextTrack) {
        const [ nextTitle, nextArg ] = playController.upNextTrack
        console.log(`Up next: \x1b[1m${nextTitle} \x1b[2m${nextArg}\x1b[0m`)
      } else {
        console.log("No song up next.")
      }
    }
  }
}