forked from feross/timidity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.old.js
404 lines (322 loc) · 11.3 KB
/
index.old.js
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*! timidity. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
const Debug = require('debug')
const EventEmitter = require('events').EventEmitter
const fs = require('fs')
const LibTimidity = require('./libtimidity')
const debug = Debug('timidity')
const debugVerbose = Debug('timidity:verbose')
// Inlined at build time by 'brfs' browserify transform
const TIMIDITY_CFG = fs.readFileSync(
__dirname + '/freepats.cfg', // eslint-disable-line node/no-path-concat
'utf8'
)
const SAMPLE_RATE = 44100
const AUDIO_FORMAT = 0x8010 // format of the rendered audio 's16'
const NUM_CHANNELS = 2 // stereo (2 channels)
const BYTES_PER_SAMPLE = 2 * NUM_CHANNELS
const BUFFER_SIZE = 16384 // buffer size for each render() call
const AudioContext = typeof window !== 'undefined' &&
(window.AudioContext || window.webkitAudioContext)
class Timidity extends EventEmitter {
constructor (baseUrl = '/') {
super()
this.destroyed = false
if (!baseUrl.endsWith('/')) baseUrl += '/'
this._baseUrl = new URL(baseUrl, window.location.origin).href
this._ready = false
this._playing = false
this._pendingFetches = {} // instrument -> fetch
this._songPtr = 0
this._bufferPtr = 0
this._array = new Int16Array(BUFFER_SIZE * 2)
this._currentUrlOrBuf = null // currently loading url or buf
this._interval = null
this._startInterval = this._startInterval.bind(this)
this._stopInterval = this._stopInterval.bind(this)
// If the Timidity constructor was not invoked inside a user-initiated event
// handler, then the AudioContext will be suspended. See:
// https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
this._audioContext = new AudioContext()
// Start the 'onaudioprocess' events flowing
this._node = this._audioContext.createScriptProcessor(
BUFFER_SIZE,
0,
NUM_CHANNELS
)
this._onAudioProcess = this._onAudioProcess.bind(this)
this._node.addEventListener('audioprocess', this._onAudioProcess)
this._node.connect(this._audioContext.destination)
LibTimidity({
locateFile: file => new URL(file, this._baseUrl).href
}).then((lib) => {
this._lib = lib
this._onLibReady()
})
}
_onLibReady () {
this._lib.FS.writeFile('/timidity.cfg', TIMIDITY_CFG)
const result = this._lib._mid_init('/timidity.cfg')
if (result !== 0) {
return this._destroy(new Error('Failed to initialize libtimidity'))
}
this._bufferPtr = this._lib._malloc(BUFFER_SIZE * BYTES_PER_SAMPLE)
debugVerbose('Initialized libtimidity')
this._ready = true
this.emit('_ready')
}
async load (urlOrBuf) {
debug('load %o', urlOrBuf)
if (this.destroyed) throw new Error('load() called after destroy()')
// If the Timidity constructor was not invoked inside a user-initiated event
// handler, then the AudioContext will be suspended. Attempt to resume it.
this._audioContext.resume()
// If a song already exists, destroy it before starting a new one
if (this._songPtr) this._destroySong()
this.emit('unstarted')
this._stopInterval()
if (!this._ready) return this.once('_ready', () => this.load(urlOrBuf))
this.emit('buffering')
// Save the url or buf to load. Allows detection of when a new interleaved
// load() starts so we can abort this load.
this._currentUrlOrBuf = urlOrBuf
let midiBuf
if (typeof urlOrBuf === 'string') {
midiBuf = await this._fetch(new URL(urlOrBuf, this._baseUrl))
// If another load() started while awaiting, abort this load
if (this._currentUrlOrBuf !== urlOrBuf) return
} else if (urlOrBuf instanceof Uint8Array) {
midiBuf = urlOrBuf
} else {
throw new Error('load() expects a `string` or `Uint8Array` argument')
}
let songPtr = this._loadSong(midiBuf)
// Are we missing instrument files?
let missingCount = this._lib._mid_get_load_request_count(songPtr)
if (missingCount > 0) {
let missingInstruments = this._getMissingInstruments(songPtr, missingCount)
debugVerbose('Fetching instruments: %o', missingInstruments)
// Wait for all instruments to load
await Promise.all(
missingInstruments.map(instrument => this._fetchInstrument(instrument))
)
// If another load() started while awaiting, abort this load
if (this._currentUrlOrBuf !== urlOrBuf) return
// Retry the song load, now that instruments have been loaded
this._lib._mid_song_free(songPtr)
songPtr = this._loadSong(midiBuf)
// Are we STILL missing instrument files? Then our General MIDI soundset
// is probably missing instrument files.
missingCount = this._lib._mid_get_load_request_count(songPtr)
// Print out missing instrument names
if (missingCount > 0) {
missingInstruments = this._getMissingInstruments(songPtr, missingCount)
debug('Playing with missing instruments: %o', missingInstruments)
}
}
this._songPtr = songPtr
this._lib._mid_song_start(this._songPtr)
debugVerbose('Song and instruments are loaded')
}
_getMissingInstruments (songPtr, missingCount) {
const missingInstruments = []
for (let i = 0; i < missingCount; i++) {
const instrumentPtr = this._lib._mid_get_load_request(songPtr, i)
const instrument = this._lib.UTF8ToString(instrumentPtr)
missingInstruments.push(instrument)
}
return missingInstruments
}
_loadSong (midiBuf) {
const optsPtr = this._lib._mid_alloc_options(
SAMPLE_RATE,
AUDIO_FORMAT,
NUM_CHANNELS,
BUFFER_SIZE
)
// Copy the MIDI buffer into the heap
const midiBufPtr = this._lib._malloc(midiBuf.byteLength)
this._lib.HEAPU8.set(midiBuf, midiBufPtr)
// Create a stream
const iStreamPtr = this._lib._mid_istream_open_mem(midiBufPtr, midiBuf.byteLength)
// Load the song
const songPtr = this._lib._mid_song_load(iStreamPtr, optsPtr)
// Free resources no longer needed
this._lib._mid_istream_close(iStreamPtr)
this._lib._free(optsPtr)
this._lib._free(midiBufPtr)
if (songPtr === 0) {
return this._destroy(new Error('Failed to load MIDI file'))
}
return songPtr
}
async _fetchInstrument (instrument) {
if (this._pendingFetches[instrument]) {
// If this instrument is already in the process of being fetched, return
// the existing promise to prevent duplicate fetches.
return this._pendingFetches[instrument]
}
const url = new URL(instrument, this._baseUrl)
const bufPromise = this._fetch(url)
this._pendingFetches[instrument] = bufPromise
const buf = await bufPromise
this._writeInstrumentFile(instrument, buf)
delete this._pendingFetches[instrument]
return buf
}
_writeInstrumentFile (instrument, buf) {
const folderPath = instrument
.split('/')
.slice(0, -1) // remove basename
.join('/')
this._mkdirp(folderPath)
this._lib.FS.writeFile(instrument, buf, { encoding: 'binary' })
}
_mkdirp (folderPath) {
const pathParts = folderPath.split('/')
let dirPath = '/'
for (let i = 0; i < pathParts.length; i++) {
const curPart = pathParts[i]
try {
this._lib.FS.mkdir(`${dirPath}${curPart}`)
} catch (err) {}
dirPath += `${curPart}/`
}
}
async _fetch (url) {
const opts = {
mode: 'cors',
credentials: 'same-origin'
}
const response = await window.fetch(url, opts)
if (response.status !== 200) throw new Error(`Could not load ${url}`)
const arrayBuffer = await response.arrayBuffer()
const buf = new Uint8Array(arrayBuffer)
return buf
}
play () {
debug('play')
if (this.destroyed) throw new Error('play() called after destroy()')
// If the Timidity constructor was not invoked inside a user-initiated event
// handler, then the AudioContext will be suspended. Attempt to resume it.
this._audioContext.resume()
this._playing = true
if (this._ready && !this._currentUrlOrBuf) {
this.emit('playing')
this._startInterval()
}
}
_onAudioProcess (event) {
const sampleCount = (this._songPtr && this._playing)
? this._readMidiData()
: 0
if (sampleCount > 0 && this._currentUrlOrBuf) {
this._currentUrlOrBuf = null
this.emit('playing')
this._startInterval()
}
const output0 = event.outputBuffer.getChannelData(0)
const output1 = event.outputBuffer.getChannelData(1)
for (let i = 0; i < sampleCount; i++) {
output0[i] = this._array[i * 2] / 0x7FFF
output1[i] = this._array[i * 2 + 1] / 0x7FFF
}
for (let i = sampleCount; i < BUFFER_SIZE; i++) {
output0[i] = 0
output1[i] = 0
}
if (this._songPtr && this._playing && sampleCount === 0) {
// Reached the end of the file
this.seek(0)
this.pause()
this._lib._mid_song_start(this._songPtr)
this.emit('ended')
}
}
_readMidiData () {
const byteCount = this._lib._mid_song_read_wave(
this._songPtr,
this._bufferPtr,
BUFFER_SIZE * BYTES_PER_SAMPLE
)
const sampleCount = byteCount / BYTES_PER_SAMPLE
// Was anything output? If not, don't bother copying anything
if (sampleCount === 0) {
return 0
}
this._array.set(
this._lib.HEAP16.subarray(this._bufferPtr / 2, (this._bufferPtr + byteCount) / 2)
)
return sampleCount
}
pause () {
debug('pause')
if (this.destroyed) throw new Error('pause() called after destroy()')
this._playing = false
this._stopInterval()
this.emit('paused')
}
seek (time) {
debug('seek %d', time)
if (this.destroyed) throw new Error('seek() called after destroy()')
if (!this._songPtr) return // ignore seek if there is no song loaded yet
const timeMs = Math.floor(time * 1000)
this._lib._mid_song_seek(this._songPtr, timeMs)
this._onTimeupdate()
}
get currentTime () {
if (this.destroyed || !this._songPtr) return 0
return this._lib._mid_song_get_time(this._songPtr) / 1000
}
get duration () {
if (this.destroyed || !this._songPtr) return 1
return this._lib._mid_song_get_total_time(this._songPtr) / 1000
}
/**
* This event fires when the time indicated by the `currentTime` property
* has been updated.
*/
_onTimeupdate () {
this.emit('timeupdate', this.currentTime)
}
_startInterval () {
this._onTimeupdate()
this._interval = setInterval(() => this._onTimeupdate(), 1000)
}
_stopInterval () {
this._onTimeupdate()
clearInterval(this._interval)
this._interval = null
}
destroy () {
debug('destroy')
if (this.destroyed) throw new Error('destroy() called after destroy()')
this._destroy()
}
_destroy (err) {
if (this.destroyed) return
this.destroyed = true
this._stopInterval()
this._array = null
if (this._songPtr) {
this._destroySong()
}
if (this._bufferPtr) {
this._lib._free(this._bufferPtr)
this._bufferPtr = 0
}
if (this._node) {
this._node.disconnect()
this._node.removeEventListener('audioprocess', this._onAudioProcess)
}
if (this._audioContext) {
this._audioContext.close()
}
if (err) this.emit('error', err)
debug('destroyed (err %o)', err)
}
_destroySong () {
this._lib._mid_song_free(this._songPtr)
this._songPtr = 0
}
}
module.exports = Timidity