Repository navigation
Expand file tree
/
Copy pathworklet.js
More file actions
460 lines (349 loc) · 12.3 KB
/
Copy pathworklet.js
File metadata and controls
460 lines (349 loc) · 12.3 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
let glue = null;
function encodeUTF8(str) {
return encodeURIComponent(s).replace(/%([\dA-Fa-f]{2})/g, m, code => {
return String.fromCharCode(parseInt(code, 16));
});
}
function decodeUTF8(str) {
if (/[\u0100-\uffff]/.test(str)) {
throw new Error("UTF8 decoding works on bytes only.");
}
let escaped = '';
for(let t=0; t<str.length; t++) {
escaped += '%'+('0'+str.charCodeAt(t).toString(16)).slice(-2);
}
return decodeURIComponent(escaped);
}
function readCString(heapOrArray, idx, maxBytesToRead) {
var endIdx = idx + maxBytesToRead;
var endPtr = idx;
// node endIdx will be NaN if the argument is not supplied
while (heapOrArray[endPtr] && !(endPtr >= endIdx)) ++endPtr;
var str = '';
while (idx < endPtr) {
str += String.fromCharCode(heapOrArray[idx++]);
}
return str;
}
function writeCString(str, heap, outIdx) {
var startIdx = outIdx;
for (var i = 0; i < str.length; ++i) {
var u = str.charCodeAt(i);
heap[outIdx++] = u & 0xff;
}
heap[outIdx] = 0;
return outIdx - startIdx;
}
class Glue {
constructor() {
this.instance = null;
this.memoryBuffer = null;
this.heapu8 = null;
this.importObject = {
env: {
emscripten_notify_memory_growth: () => {
console.log('growing memory');
this.loadHeap();
},
log_msg: (ptr, len) => {
// prob not available.. maybe use bootstrap broker
console.log('msg', this.readStringAt(ptr, len))
}
}
};
}
async init(module) {
const result = await WebAssembly.instantiate(module, this.importObject);
this.instance = result;
this.instance.exports._initialize();
this.exports = this.instance.exports;
this.loadHeap();
}
loadHeap() {
this.memoryBuffer = this.exports.memory.buffer;
this.heapu8 = new Uint8Array(this.memoryBuffer);
}
malloc(size) {
return this.instance.exports.malloc(size);
}
free(ptr) {
return this.instance.exports.free(ptr);
}
writeInto(ptr, src) {
this.heapu8.set(new Uint8Array(src), ptr);
}
readStringAt(ptr, maxLen) {
if (!ptr) return '';
return readCString(this.heapu8, ptr, maxLen);
}
allocString(str) {
// only ascii strings!
const ptr = this.malloc(str.length+1);
writeCString(str, this.heapu8, ptr);
return ptr;
}
// for utf8 strings, encode before writing, decode after reading
}
// once we can send a message to the module directly, this bootstrap processor will be obsolete
class Bootstrap extends AudioWorkletProcessor {
constructor(options) {
super(options);
this.init(options.processorOptions.module);
}
process() {}
async init(module) {
glue = new Glue();
await glue.init(module);
this.port.postMessage({ok: true});
}
}
registerProcessor('bootstrap', Bootstrap);
function createMsgHandler(port, cmdHandler, otherHandler) {
port.onmessage = async (event) => {
const data = event.data;
if (data && data.cmd && data.msgId) {
const { cmd, msgId } = data;
if (cmdHandler) {
try {
const result = await cmdHandler(cmd, data);
port.postMessage({ replyFor: msgId, value: result });
} catch (error) {
port.postMessage({ replyFor: msgId, error: error.toString() });
}
}
} else if (otherHandler) {
otherHandler(event);
}
}
}
class MidiPlayerProcessor extends AudioWorkletProcessor {
// this player must be explicitly closed (via delete) to free resources
// it can be used with multiple sequences
constructor(...args) {
super(...args);
this.alive = true; // basically duplicates truthiness of this.ps
this.hasPlayer = false;
this.playingFrameOffset = -1;
this.initBuffers(1024);
createMsgHandler(this.port, (cmd, data) => {
if (cmd == 'setSequence') {
return this.setSequence(data.buffer);
} else if (cmd == 'stop') {
this.stop();
} else if (cmd == 'play') {
this.play();
} else if (cmd == 'loop') {
this.loop(data.times);
} else if (cmd == 'getPosition') {
return this.getPosition();
} else if (cmd == 'seek') {
return this.seek(data.pos);
} else if (cmd == 'shortEvent') {
return this.shortEvent(data.status, data.data1, data.data2);
} else if (cmd == 'delete') {
this.delete();
}
}, e => {
// other messages
});
this.ps = glue.exports.midiplayer_create(globalThis.sampleRate);
this.hasPlayer = true;
this.isPlaying = false; // to track end of media
}
initBuffers(size) {
if (this.leftBuf) {
glue.free(this.leftBuf);
glue.free(this.rightBuf);
}
this.bufSize = size;
this.leftBuf = glue.malloc(size);
this.rightBuf = glue.malloc(size);
}
play() {
this.playingFrameOffset = -1;
glue.exports.midiplayer_play(this.ps);
this.isPlaying = true;
}
loop(times) {
glue.exports.midiplayer_loop(this.ps, times);
}
stop() {
glue.exports.midiplayer_stop(this.ps);
this.isPlaying = false;
}
getPosition() {
return glue.exports.midiplayer_get_position(this.ps);
}
seek(pos) {
glue.exports.midiplayer_seek(pos);
}
setSequence(bytes) {
const len = bytes.length || bytes.byteLength;
const ptr = glue.malloc(len);
glue.writeInto(ptr, bytes);
const ticks = glue.exports.midiplayer_set_sequence(this.ps, ptr, len);
glue.free(ptr);
// it's not playing anymore, player was reset
this.isPlaying = false;
// ticks are not really duration.. see api again
return { duration: ticks };
}
shortEvent(status, data1, data2) {
return glue.exports.midiplayer_short_event(this.ps, status, data1, data2);
}
// always called, even if the node not connected
// returning false causes the node to become permanently defunct
process(inputs, outputs) {
if (this.hasPlayer) {
const missedFrames = this.playingFrameOffset === -1 ? 0 : ((currentFrame - this.playingFrameOffset) | 0);
const samples = outputs[0][0].length;
if (samples > this.bufSize/4) {
this.initBuffers(samples*4);
}
const playing = glue.exports.midiplayer_write_data(this.ps, this.leftBuf, this.rightBuf, samples, missedFrames);
outputs[0][0].set(new Float32Array(glue.memoryBuffer, this.leftBuf, samples));
outputs[0][1].set(new Float32Array(glue.memoryBuffer, this.rightBuf, samples));
// eom is only reported after reverb. but loops work properly
if (this.isPlaying && !playing) { // refers to audio output, not to the sequencer
this.port.postMessage("end-of-media");
this.isPlaying = false;
}
}
this.playingFrameOffset = (currentFrame + outputs[0][0].length) | 0;
return this.alive;
}
delete() {
glue.midiplayer_delete(this.ps);
this.ps = null;
this.alive = false;
}
}
registerProcessor('midi-player', MidiPlayerProcessor);
class FFAudioPlayerProcessor extends AudioWorkletProcessor {
// this player must be explicitly closed (via delete) to free resources
// it can only be used with one sequence
constructor(...args) {
super(...args);
this.alive = true; // until closed
this.ps = null;
this.playing = false;
this.initBuffers(1024);
createMsgHandler(this.port, (cmd, data) => {
if (cmd == 'load') {
return this.load(data.buffer, data.contentType);
} else if (cmd == 'stop') {
this.stop();
} else if (cmd == 'play') {
this.play();
} else if (cmd == 'loop') {
this.loop(data.times);
} else if (cmd == 'seek') {
this.seek(data.pos);
} else if (cmd == 'getPosition') {
return this.getPosition();
} else if (cmd == 'close') {
this.close();
}
}, e => {
// other messages
});
this.loops = 0;
this.loopsLeft = 0;
this.playingFrameOffset = -1;
this.inputPtr = 0;
}
load(bytes, contentType) {
if (this.ps) {
throw new Error("player was already loaded");
}
const len = bytes.length || bytes.byteLength;
const ptr = glue.malloc(len); // player is responsible for freeing
glue.writeInto(ptr, bytes);
let contentTypePtr = contentType ? glue.allocString(contentType) : 0;
this.ps = glue.exports.ffplayer_open(ptr, len, globalThis.sampleRate, contentTypePtr);
if (contentTypePtr) {
glue.free(contentTypePtr);
}
if (!this.ps) {
glue.free(ptr);
throw new Error("failed to initialize player");
}
this.inputPtr = ptr;
return glue.exports.ffplayer_get_duration_ms(this.ps);
}
initBuffers(size) {
if (this.leftBuf) {
glue.free(this.leftBuf);
glue.free(this.rightBuf);
}
this.bufSize = size;
this.leftBuf = glue.malloc(size);
this.rightBuf = glue.malloc(size);
}
play() {
this.playingFrameOffset = -1;
this.isPlaying = true;
this.loopsLeft = this.loops;
}
loop(times) {
this.loops = times;
this.loopsLeft = times;
}
stop() {
this.isPlaying = false;
}
getPosition() {
return glue.exports.ffplayer_get_current_time_ms(this.ps);
}
seek(pos) {
glue.exports.ffplayer_seek(this.ps, pos);
}
process(inputs, outputs) {
if (this.ps && this.isPlaying) {
let missedFrames = this.playingFrameOffset === -1 ? 0 : ((currentFrame - this.playingFrameOffset) | 0);
const samples = outputs[0][0].length;
if (samples > this.bufSize/4) {
this.initBuffers(samples*4); // 4 is for 32bit
}
let samplesWritten = 0;
while(samplesWritten < samples) {
const samplesLeft = samples - samplesWritten;
const framesToWrite = (missedFrames > 0) ? Math.min(missedFrames, samples) : samplesLeft;
const off = (missedFrames > 0) ? 0 : samplesWritten;
const nowWritten = glue.exports.ffplayer_read(this.ps, this.leftBuf + off*4, this.rightBuf + off*4, framesToWrite);
if (missedFrames > 0) {
missedFrames -= nowWritten;
} else {
samplesWritten += nowWritten;
}
if (nowWritten < framesToWrite) {
this.seek(0);
// loop-or-eom
if (this.loopsLeft == -1 || this.loopsLeft > 0) {
this.loopsLeft = this.loopsLeft == -1 ? -1 : this.loopsLeft - 1;
} else {
this.port.postMessage("end-of-media");
this.isPlaying = false;
break;
}
}
}
outputs[0][0].set(new Float32Array(glue.memoryBuffer, this.leftBuf, samplesWritten));
outputs[0][1].set(new Float32Array(glue.memoryBuffer, this.rightBuf, samplesWritten));
this.playingFrameOffset = (currentFrame + samples) | 0;
}
return this.alive;
}
close() {
if (this.ps) {
glue.exports.ffplayer_close(this.ps);
this.ps = null;
}
if (this.inputPtr) {
glue.free(this.inputPtr);
this.inputPtr = 0;
}
this.alive = false;
}
}
registerProcessor('ff-player', FFAudioPlayerProcessor);