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

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

class DownloadController {
  constructor(picker, downloader) {
    this.process = null
    this.requestingSkipUpNext = false
    this.isDownloading = false

    this.picker = picker
    this.downloader = downloader
  }

  async downloadNext() {
    this.requestingSkipUpNext = false
    this.isDownloading = 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
    }

    // 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

    console.log(`Downloading ${title}..\nDownloader arg: ${downloaderArg}`)

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

    // 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 to = 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', from, to
    ])

    // It's handy to store the output WAV file (the "to" file) and the `avconv`
    // process; the WAV file is used later to be played, and the convert
    // process is stored so it can be killed before it finishes.
    this.wavFile = to
    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) {
      console.warn("Failed to convert " + title)
      console.warn("Selecting a new track\n")

      // 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.)
      return await this.downloadNext()
    }

    // If we were requested to skip the up-next track that's currently being
    // downloaded (probably by the user), we'll have to do that now.
    if (this.requestingSkipUpNext) return await this.downloadNext()

    // We successfully downloaded something, and so the downloadNext function
    // is done. We mark that here, so that skipUpNext will know that it'll need
    // to start a whole new downloadNext to have any effect.
    this.isDownloading = false
  }

  skipUpNext() {
    // If we're already in the process of downloading the up-next track, we'll
    // set the requestingSkipUpNext flag to true. downloadNext will use this to
    // cancel its current download and begin new.
    if (this.isDownloading) {
      this.requestingSkipUpNext = true
      this.killProcess()
    }

    // If we aren't currently downloading a track, downloadNext won't
    // automatically be called from the start again, so we need to do that
    // here.
    if (!this.isDownloading) {
      this.downloadNext()
    }
  }

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

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

    this.downloadController = downloadController
  }

  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) {
      const nextPromise = this.downloadController.downloadNext()

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

      try {
        await playPromise
      } catch(err) {
        console.warn(err)
      }

      await nextPromise
    }
  }

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

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()
    }
  }
}