@disjukr/execute 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +42 -2
  2. package/bin/copy-assets.js +15 -0
  3. package/dist/assets/gdi32.dll +0 -0
  4. package/dist/assets/i386-display.dll +0 -0
  5. package/dist/assets/i386-dsound.dll +0 -0
  6. package/dist/assets/i386-gdi32.dll +0 -0
  7. package/dist/assets/i386-kernel32.dll +0 -0
  8. package/dist/assets/i386-shell32.dll +0 -0
  9. package/dist/assets/i386-user32.dll +0 -0
  10. package/dist/assets/i386-winmm.dll +0 -0
  11. package/dist/assets/kernelbase-936.dll +0 -0
  12. package/dist/assets/kernelbase-949.dll +0 -0
  13. package/dist/assets/kernelbase-950.dll +0 -0
  14. package/dist/assets/kernelbase.dll +0 -0
  15. package/dist/assets/pe.js +6 -0
  16. package/dist/assets/process-server.wasm +0 -0
  17. package/dist/assets/process-services.js +45 -0
  18. package/dist/assets/process-worker.js +73 -0
  19. package/dist/assets/process.wasm +0 -0
  20. package/dist/assets/run.js +531 -0
  21. package/dist/assets/server-worker.js +397 -0
  22. package/dist/assets/shell32.dll +0 -0
  23. package/dist/assets/threads.js +60 -0
  24. package/dist/assets/user32.dll +0 -0
  25. package/dist/assets/webaudio-tinysynth.min.js +1 -0
  26. package/dist/assets/wow64host.exe +0 -0
  27. package/dist/index.js +1347 -0
  28. package/dist/licenses/GPL-3.0-only.txt +232 -0
  29. package/dist/licenses/LICENSE +44 -0
  30. package/dist/licenses/TinySynth +201 -0
  31. package/dist/licenses/Wine +17 -0
  32. package/dist/licenses/Wine-LGPL +502 -0
  33. package/dist/licenses/kwemu +340 -0
  34. package/dist/style.css +809 -0
  35. package/dist/types/demo.d.ts +1 -0
  36. package/dist/types/executable-icon.d.ts +1 -0
  37. package/dist/types/file-system.d.ts +13 -0
  38. package/dist/types/guest-files.d.ts +29 -0
  39. package/dist/types/index.d.ts +27 -0
  40. package/dist/types/launch.d.ts +91 -0
  41. package/dist/types/pe.d.ts +1 -0
  42. package/dist/types/process-group.d.ts +1 -0
  43. package/dist/types/window-thumbnail.d.ts +11 -0
  44. package/dist/types/windows-path.d.ts +1 -0
  45. package/package.json +44 -4
@@ -0,0 +1,397 @@
1
+ function windowsPath(input , directory ) {
2
+ let path = input.replaceAll("/", "\\");
3
+ if (path.startsWith("\\\\") || path.includes("\0"))
4
+ throw Error("Unsupported Windows path: " + input);
5
+ if (!/^[A-Za-z]:\\/.test(path)) {
6
+ if (!directory || path.includes(":"))
7
+ throw Error("Expected an absolute drive path: " + input);
8
+ path = path.startsWith("\\")
9
+ ? directory.slice(0, 2) + path
10
+ : directory + "\\" + path;
11
+ }
12
+ const parts = [];
13
+ for (const part of path.slice(3).split("\\")) {
14
+ if (part === "..") parts.pop();
15
+ else if (part && part !== ".") parts.push(part);
16
+ }
17
+ return path[0].toUpperCase() + ":\\" + parts.join("\\");
18
+ }
19
+ // The Wasm server owns Windows handles, IDs, wait queues and object lifetime.
20
+ // This worker owns only host endpoints, file bytes and pending transport replies.
21
+ importScripts('process-services.js');
22
+ async function serve(data) {
23
+ const endpoints = new Map(), pending = new Map(), files = new Map();
24
+ const pendingStatus = 0x103;
25
+ const rootDir = 'C:\\';
26
+ const rootPath = windowsPath(data.path,rootDir);
27
+ const libraries = {};
28
+ for (const [name, bytes] of Object.entries(data.files)) {
29
+ files.set(windowsPath(name,rootDir).toLowerCase(),bytes);
30
+ if (!/[\\/]/.test(name) && (/\.dll$/i.test(name) || name==='wow64host.exe')) libraries[name.toLowerCase()]=bytes;
31
+ }
32
+ let nextRead = 0;
33
+ const reads = new Map();
34
+ function readFile(path) {
35
+ const cached = files.get(path.toLowerCase());
36
+ if (cached) return Promise.resolve(cached);
37
+ return new Promise((resolve,reject)=>{
38
+ const id=++nextRead;
39
+ reads.set(id,{resolve,reject});
40
+ postMessage({kind:'readGuestFile',id,path});
41
+ });
42
+ }
43
+ const bytes = await (await fetch('process-server.wasm')).arrayBuffer();
44
+ const {instance} = await WebAssembly.instantiate(bytes, {transport: {
45
+ wake(tid,status) {
46
+ const continuation = pending.get(tid);
47
+ if (continuation) {
48
+ pending.delete(tid);
49
+ queueMicrotask(() => continuation(status));
50
+ }
51
+ }
52
+ }});
53
+ const server = instance.exports;
54
+ function values(count = 4) { return Array.from(new Uint32Array(server.memory.buffer, server.result(), count)); }
55
+ function respond(endpoint, status, values = []) {
56
+ const m = endpoint.mailbox;
57
+ m.fill(0, 2, 6);
58
+ m.set(values, 2);
59
+ m[1] = status;
60
+ Atomics.store(m, 0, 1);
61
+ Atomics.notify(m, 0);
62
+ }
63
+ const notifications=new Map(), popups=new Map();
64
+ const trayKey=(pid,hwnd,id)=>[pid,hwnd,id].join('/');
65
+ function clearShell(pid,hwnd) {
66
+ for(const [key,icon] of notifications) if(icon.pid===pid && (hwnd===undefined || icon.hwnd===hwnd)) {
67
+ notifications.delete(key);
68
+ postMessage({kind:'trayRemove',key});
69
+ }
70
+ for(const [tid,popup] of popups) if(popup.pid===pid && (hwnd===undefined || popup.hwnd===hwnd)) {
71
+ popups.delete(tid);
72
+ respond(popup.caller,0,[0]);
73
+ postMessage({kind:'popupClosed',tid});
74
+ }
75
+ }
76
+ let cursor=[0,0];
77
+ let timer;
78
+ function pollTimeouts() {
79
+ clearTimeout(timer);
80
+ const ticks = BigInt(Math.floor(performance.now()*10000));
81
+ const delay = server.pollTimeouts(BigInt(Date.now())*10000n + 116444736000000000n,ticks);
82
+ if (delay >= 0) timer = setTimeout(pollTimeouts,delay);
83
+ }
84
+ function wait(endpoint, status, complete) {
85
+ if (status === pendingStatus) pending.set(endpoint.tid,complete);
86
+ else complete(status);
87
+ pollTimeouts();
88
+ }
89
+ function finish(endpoint, code, error) {
90
+ if (endpoints.get(endpoint.pid) !== endpoint) return;
91
+ clearShell(endpoint.pid);
92
+ endpoints.delete(endpoint.pid);
93
+ postMessage({kind:'processClosed',pid:endpoint.pid});
94
+ for (const [tid,worker] of endpoint.workers) {
95
+ worker.terminate();
96
+ pending.delete(tid);
97
+ }
98
+ server.finishProcess(endpoint.pid, code);
99
+ if (endpoint.root) postMessage({kind:'root', code:code >>> 0, error});
100
+ if (!endpoints.size) postMessage({kind:'drained'});
101
+ }
102
+ function writeClassName(name) {
103
+ if (typeof name!=='string') return 0;
104
+ if (!name.length || name.length>255) return -1;
105
+ const buffer=new Uint16Array(server.memory.buffer,server.classNameBuffer(),name.length);
106
+ for (let i=0;i<name.length;i++) buffer[i]=name.charCodeAt(i);
107
+ return name.length;
108
+ }
109
+ onmessage=({data:event})=>{
110
+ if (event.kind==='guestFile') {
111
+ const read=reads.get(event.id);
112
+ reads.delete(event.id);
113
+ if(event.error) read?.reject(Error(event.error));
114
+ else read?.resolve(event.reply ?? event.bytes);
115
+ return;
116
+ }
117
+ pollTimeouts();
118
+ if (event.kind==='trayInput') {
119
+ cursor=[event.x,event.y];
120
+ const icon=notifications.get(event.key);
121
+ if(icon?.callback) {
122
+ const modern=icon.version>=4;
123
+ const message=event.context ? (modern ? 0x7b : 0x205) : (modern ? 0x400 : 0x202);
124
+ server.postWindowMessage(icon.tid,icon.hwnd,icon.callback,
125
+ modern ? (event.y<<16)|(event.x&65535) : icon.id, modern ? (icon.id<<16)|message : message);
126
+ }
127
+ }
128
+ if (event.kind==='popupResult') {
129
+ const popup=popups.get(event.tid);
130
+ if(popup) {
131
+ popups.delete(event.tid);
132
+ if(event.id && !(popup.flags&(0x100|0x80))) server.windowCommand(event.tid,popup.hwnd,GUI_MENU_COMMAND,event.id);
133
+ respond(popup.caller,0,[popup.flags&0x100 ? event.id : Number(!!event.id)]);
134
+ }
135
+ }
136
+ if(event.kind==='activate') server.windowCommand(event.tid,event.hwnd,GUI_HOST_ACTIVATE,0);
137
+ if(event.kind==='deactivate') server.windowCommand(event.tid,event.hwnd,GUI_HOST_DEACTIVATE,0);
138
+ if (event.kind==='pointer') server.pointerInput(event.tid,event.hwnd,event.x,event.y,event.down);
139
+ if (event.kind==='keyboard') server.keyboardInput(event.vk,event.scan,event.flags);
140
+ if (event.kind==='menu') server.windowCommand(event.tid,event.hwnd,GUI_MENU_COMMAND,event.id);
141
+ if (event.kind==='resize') server.windowCommand(event.tid,event.hwnd,event.maximized ? GUI_REQUEST_MAXIMIZE : GUI_REQUEST_RESIZE,(event.height<<16)|event.width);
142
+ if (event.kind==='close') server.windowCommand(event.tid,event.hwnd,GUI_CLOSE,0);
143
+ };
144
+ async function spawn(parent, path, command) {
145
+ const file = await readFile(path);
146
+ if (parent && !server.liveThread(parent.owner.pid,parent.tid)) return;
147
+ if (!file) {
148
+ if (parent) return respond(parent,0xc0000034);
149
+ throw Error('Missing root executable: '+path);
150
+ }
151
+ const directory = path.slice(0,path.lastIndexOf('\\')+1);
152
+ const openFiles = new Map();
153
+ let nextHandle = 0x40000001;
154
+ const status = server.create(parent?.tid ?? 0);
155
+ if (status) {
156
+ if (parent) respond(parent, status);
157
+ else throw Error('Could not allocate root process');
158
+ return;
159
+ }
160
+ const [ph, th, pid, tid, info] = values(5);
161
+ const endpoint = {pid, tid, root:!parent, workers:new Map()};
162
+ endpoints.set(pid,endpoint);
163
+ postMessage({kind:'processStarted',pid,path});
164
+ if (parent) {
165
+ wait(parent, server.waitStartup(parent.tid, info), waitStatus => {
166
+ if (!server.liveThread(parent.owner.pid,parent.tid)) return;
167
+ const status = server.collectStartup(parent.tid,info,ph,th) || waitStatus;
168
+ respond(parent,status,status ? [] : [ph,th,pid,tid]);
169
+ });
170
+ }
171
+ const images=new Map(), classAtoms=new Map(), classIcons=new Map();
172
+ const jitCache = new Map();
173
+ function broadcastJit(update) {
174
+ for (const worker of endpoint.workers.values()) {
175
+ Atomics.add(worker.jitNotifications,0,1);
176
+ worker.postMessage(update);
177
+ }
178
+ }
179
+ function updateJit(msg) {
180
+ const {slot,generation} = msg;
181
+ const old = jitCache.get(slot);
182
+ if (old && (generation < old.generation || (generation === old.generation && msg.kind !== 'jitRetire'))) return;
183
+ const record = {slot,generation,module:null};
184
+ jitCache.set(slot,record);
185
+ if (msg.kind === 'jitRetire') {
186
+ broadcastJit(record);
187
+ return;
188
+ }
189
+ WebAssembly.compile(msg.bytes).then(module => {
190
+ if (endpoints.get(pid) !== endpoint || jitCache.get(slot) !== record) return;
191
+ record.module = module;
192
+ broadcastJit(record);
193
+ }).catch(error => console.error('kwemu JIT compilation failed',error));
194
+ }
195
+ function launch(tid, thread) {
196
+ const worker = new Worker('process-worker.js');
197
+ worker.jitNotifications = new Int32Array(new SharedArrayBuffer(4));
198
+ const caller = {tid,owner:endpoint,mailbox:new Int32Array(new SharedArrayBuffer(24+256))};
199
+ function snapshotKeys() {
200
+ const ptr=server.inputKeyState(tid);
201
+ if(ptr) {
202
+ const state=new Uint8Array(caller.mailbox.buffer,24,256);
203
+ const source=new Uint8Array(server.memory.buffer,ptr,256);
204
+ for(let key=0;key<256;key++) state[key]=source[key]&0x81;
205
+ }
206
+ }
207
+ endpoint.workers.set(tid,worker);
208
+ worker.onerror = event => { event.preventDefault(); finish(endpoint, 0xc0000142, event.message); };
209
+ worker.onmessage = async ({data:msg}) => {
210
+ if (endpoints.get(pid) !== endpoint || endpoint.workers.get(tid) !== worker) return;
211
+ if (msg.kind === 'jitCompile' || msg.kind === 'jitRetire') { updateJit(msg); return; }
212
+ if (msg.kind === 'spawnThread') {
213
+ if (!server.liveThread(pid,msg.thread.tid)) return;
214
+ try { launch(msg.thread.tid,msg.thread); }
215
+ catch (error) { finish(endpoint,0xc0000142,String(error)); }
216
+ return;
217
+ }
218
+ if (msg.kind === 'audio') postMessage({...msg,pid},msg.bytes ? [msg.bytes.buffer] : []);
219
+ if (msg.kind === 'menuState') postMessage({...msg,pid});
220
+ if (msg.kind === 'dialogControl') postMessage(msg);
221
+ if (msg.kind === 'surfaceFrame') postMessage({...msg,pid,tid},[msg.pixels.buffer]);
222
+ if (msg.kind === 'threadDone') endpoint.workers.delete(tid);
223
+ if (msg.kind === 'output') postMessage(msg);
224
+ if (msg.kind === 'exit') finish(endpoint, msg.code, msg.error);
225
+ if (msg.kind !== 'request') return;
226
+ if (!server.liveThread(endpoint.pid,caller.tid)) { respond(caller,0xc000004b); return; }
227
+ pollTimeouts();
228
+ const q = msg.message;
229
+ if(data.hostFiles && ['fileOpen','fileBeginRead','fileWrite','fileClose'].includes(q.op)) {
230
+ try {
231
+ if(q.op==='fileOpen') {
232
+ q.path=windowsPath(q.path,directory);
233
+ q.access ??= 0x80000000;
234
+ q.share ??= 3;
235
+ q.mode ??= 3;
236
+ }
237
+ const reply=await new Promise((resolve,reject)=>{
238
+ const id=++nextRead;
239
+ reads.set(id,{resolve,reject});
240
+ postMessage({kind:'fileOperation',pid,id,request:q},q.bytes ? [q.bytes.buffer] : []);
241
+ });
242
+ if(reply.bytes) {
243
+ caller.readBytes=reply.bytes;
244
+ respond(caller,0,[0,reply.bytes.length]);
245
+ } else respond(caller,reply.status,reply.values);
246
+ } catch {respond(caller,5);}
247
+ return;
248
+ }
249
+ if(data.hostFiles && q.op==='fileRead') {
250
+ new Uint8Array(q.buffer).set(caller.readBytes.subarray(q.offset,q.offset+q.count));
251
+ if(q.offset+q.count>=caller.readBytes.length) caller.readBytes=undefined;
252
+ respond(caller,0,[q.count]);return;
253
+ }
254
+ if(q.op==='fileWrite' || (q.op==='fileOpen' &&
255
+ ((q.access & 0x50000006) || (q.mode !== undefined && q.mode !== 3)))) {
256
+ respond(caller,5);return;
257
+ }
258
+ if(q.op==='fileOpen' || q.op===RPC_IMAGE_EXISTS || q.op===RPC_PROCESS_CREATE) {
259
+ try {
260
+ const fullPath=windowsPath(q.path,directory);
261
+ if(q.op===RPC_PROCESS_CREATE) await spawn(caller,fullPath,q.command);
262
+ else {
263
+ const bytes=await readFile(fullPath);
264
+ if(q.op===RPC_IMAGE_EXISTS) respond(caller,bytes ? 0 : 0xc0000034);
265
+ else if(!bytes) respond(caller,2);
266
+ else {
267
+ const handle=nextHandle;
268
+ nextHandle+=4;
269
+ openFiles.set(handle,{bytes,offset:0});
270
+ respond(caller,0,[handle,bytes.length]);
271
+ }
272
+ }
273
+ } catch(error) {
274
+ respond(caller,q.op==='fileOpen' ? 5 : 0xc0000022);
275
+ }
276
+ return;
277
+ }
278
+ if(q.op==='fileBeginRead') {
279
+ const f=openFiles.get(q.handle);
280
+ if(!f) respond(caller,6);
281
+ else {
282
+ const start=f.offset;
283
+ const length=Math.min(q.count,f.bytes.length-start);
284
+ f.offset+=length;
285
+ respond(caller,0,[start,length]);
286
+ }
287
+ return;
288
+ }
289
+ if(q.op==='fileRead') {
290
+ const f=openFiles.get(q.handle);
291
+ if(!f) respond(caller,6);
292
+ else {
293
+ const chunk=f.bytes.subarray(q.offset,q.offset+q.count);
294
+ new Uint8Array(q.buffer).set(chunk);
295
+ respond(caller,0,[chunk.length]);
296
+ }
297
+ return;
298
+ }
299
+ if(q.op==='fileClose') { respond(caller,openFiles.delete(q.handle)?0:6);return; }
300
+ if(q.op==='classIcon') {
301
+ classIcons.set(q.atom,images.get(q.small) ?? images.get(q.large));
302
+ respond(caller,0,[1]);
303
+ } else if(q.op==='iconImage') {
304
+ images.set(q.handle,q.ico);respond(caller,0,[1]);
305
+ } else if(q.op==='windowRequest' && q.command===GUI_CURSOR_POSITION) {
306
+ respond(caller,0,cursor);
307
+ } else if (q.op==='tray') {
308
+ const key=trayKey(pid,q.hwnd,q.id);
309
+ let icon=notifications.get(key);
310
+ let ok=false;
311
+ if(q.action===0 && !icon) {
312
+ icon={key,pid,tid,hwnd:q.hwnd,id:q.id,version:0,tip:'',callback:0};
313
+ notifications.set(key,icon); ok=true;
314
+ } else if(icon && [1,2,4].includes(q.action)) ok=true;
315
+ if(ok && q.action===2) {
316
+ notifications.delete(key);postMessage({kind:'trayRemove',key});
317
+ } else if(ok) {
318
+ if(q.action===4) icon.version=q.version;
319
+ else {
320
+ if(q.flags&1) icon.callback=q.callback;
321
+ if(q.flags&4) icon.tip=q.tip;
322
+ if(q.flags&2) icon.image=images.get(q.handle);
323
+ }
324
+ postMessage({kind:'trayIcon',...icon});
325
+ }
326
+ respond(caller,0,[Number(ok)]);
327
+ } else if(q.op==='popup') {
328
+ popups.set(tid,{pid,caller,hwnd:q.hwnd,flags:q.flags});
329
+ postMessage({kind:'popup',tid,items:q.items,x:q.x,y:q.y});
330
+ } else if (q.op === 'registerClass') {
331
+ const atom=server.registerClass(tid,writeClassName(q.name),q.proc);
332
+ if(atom) classAtoms.set(q.name.toLowerCase(),atom);
333
+ respond(caller,atom ? 0 : 1,[atom]);
334
+ } else if (q.op === 'windowOpen') {
335
+ const hwnd=server.openWindow(tid,q.width,q.height,writeClassName(q.name),typeof q.name==='number' ? q.name : 0,q.style,q.exStyle,q.owner===0xfffffffd ? 0 : q.owner);
336
+ const atom=typeof q.name==='string' ? classAtoms.get(q.name.toLowerCase()) : q.name;
337
+ if (hwnd) postMessage({kind:'surfaceOpen',pid,tid,hwnd,x:q.x,y:q.y,style:q.style,exStyle:q.exStyle,owner:q.owner,dialog:q.name==='#32770' || q.name===32770,icon:classIcons.get(atom),title:q.title,menu:q.menu,width:q.width,height:q.height});
338
+ respond(caller,hwnd ? 0 : 1,[hwnd]);
339
+ } else if (q.op === 'windowRequest') {
340
+ if(q.command===GUI_PEEK_MESSAGE) {
341
+ const ok=server.peekMessage(tid,q.arg);
342
+ if(ok && q.arg&1) snapshotKeys();
343
+ respond(caller,ok?0:1,ok?values():[]);
344
+ } else if (q.command===GUI_GET_MESSAGE) {
345
+ const receive=()=>{
346
+ if (server.nextMessage(tid)) {snapshotKeys();respond(caller,0,values());}
347
+ else wait(caller,server.waitMessage(tid),status=>{
348
+ if (status) respond(caller,status);
349
+ else receive();
350
+ });
351
+ };
352
+ receive();
353
+ } else {
354
+ const ok=server.windowCommand(tid,q.hwnd,q.command,q.arg);
355
+ if (ok && q.command===GUI_WINDOW_STYLE && q.arg)
356
+ postMessage({kind:'windowStyle',tid,hwnd:q.hwnd,style:q.arg>>>0});
357
+ if (ok && q.command===GUI_RESIZE) postMessage({kind:'surfaceResize',hwnd:q.hwnd,width:q.arg&65535,height:q.arg>>>16});
358
+ if(ok && q.command===GUI_SHOW) postMessage({kind:'surfaceShown',hwnd:q.hwnd});
359
+ if (ok && (q.command===GUI_HIDE || (q.command===GUI_WINDOW_STYLE && q.arg && !(q.arg&0x10000000)))) {
360
+ server.windowCommand(tid,q.hwnd,GUI_GET_OWNER,0);
361
+ postMessage({kind:'surfaceHidden',hwnd:q.hwnd,owner:values()[0]});
362
+ }
363
+ if (ok && q.command===GUI_RELEASE_WINDOW) {clearShell(pid,q.hwnd);postMessage({kind:'surfaceClosed',pid,hwnd:q.hwnd});}
364
+ respond(caller,ok ? 0 : 1,values());
365
+ }
366
+ } else if (q.op === 'ready') {
367
+ wait(caller, server.ready(caller.tid), status => respond(caller,status));
368
+ } else {
369
+ const status = server.call(caller.tid,q.op,q.handle,q.timeout);
370
+ const result = values();
371
+ if (!status && q.op === RPC_PROCESS_TERMINATE) {
372
+ for (const tid of endpoint.workers.keys()) if (tid !== caller.tid) {
373
+ pending.delete(tid);
374
+ }
375
+ }
376
+ wait(caller,status,s => respond(caller,s,result));
377
+ }
378
+ };
379
+ worker.postMessage({module:data.module, screenSize:data.screenSize, file:thread ? null : file, libraries:thread ? undefined : libraries, mailbox:caller.mailbox.buffer,
380
+ thread, jitNotifications:worker.jitNotifications.buffer, jitModules:Array.from(jitCache.values()).filter(record => record.module), imagePath:path, encoding:data.encoding, commandLine:command, pid, tid});
381
+ }
382
+ try { launch(tid); } catch (error) { finish(endpoint,0xc0000142,String(error)); }
383
+ }
384
+ try {
385
+ await spawn(null,rootPath,data.command);
386
+ } catch (error) {
387
+ postMessage({kind:'root', error:String(error)});
388
+ postMessage({kind:'drained'});
389
+ }
390
+ }
391
+
392
+ onmessage = ({data}) => {
393
+ serve(data).catch(error => {
394
+ postMessage({kind:'root', error:String(error)});
395
+ postMessage({kind:'drained'});
396
+ });
397
+ };
Binary file
@@ -0,0 +1,60 @@
1
+ // Readers can execute Wine or guest instructions concurrently. A mapping writer
2
+ // waits for readers to finish or reach a point with no translated pointer in use.
3
+ class ProcessExecution {
4
+ constructor(tid) {
5
+ this.tid = tid;
6
+ this.mappingDepth = 0;
7
+ }
8
+ attach(core) {
9
+ this.state = new Int32Array(core.memory.buffer,Number(core.mappingControl()),3);
10
+ this.acquire();
11
+ }
12
+ acquire() {
13
+ const state = this.state;
14
+ for (;;) {
15
+ const writers = Atomics.load(state,1);
16
+ if (writers) { Atomics.wait(state,1,writers); continue; }
17
+ const readers = Atomics.load(state,0);
18
+ if (readers < 0) { Atomics.wait(state,0,readers); continue; }
19
+ if (Atomics.compareExchange(state,0,readers,readers+1) === readers) break;
20
+ }
21
+ this.checkTermination();
22
+ }
23
+ release() {
24
+ if (Atomics.sub(this.state,0,1) === 1) Atomics.notify(this.state,0);
25
+ }
26
+ checkTermination() {
27
+ const exiting = Atomics.load(this.state,2);
28
+ if (exiting && exiting !== this.tid) {
29
+ this.release();
30
+ throw ProcessExecution.peerStopped;
31
+ }
32
+ }
33
+ checkpoint() {
34
+ this.checkTermination();
35
+ if (Atomics.load(this.state,1)) {
36
+ this.release();
37
+ this.acquire();
38
+ }
39
+ }
40
+ beginMapping() {
41
+ if (this.mappingDepth++) return;
42
+ const state = this.state;
43
+ Atomics.add(state,1,1);
44
+ this.release();
45
+ for (;;) {
46
+ const busy = Atomics.compareExchange(state,0,0,-1);
47
+ if (!busy) break;
48
+ Atomics.wait(state,0,busy);
49
+ }
50
+ Atomics.sub(state,1,1);
51
+ Atomics.notify(state,1);
52
+ }
53
+ endMapping() {
54
+ if (--this.mappingDepth) return;
55
+ Atomics.store(this.state,0,1);
56
+ Atomics.notify(this.state,0);
57
+ this.checkpoint();
58
+ }
59
+ static peerStopped = Symbol('peer terminated');
60
+ }
Binary file
@@ -0,0 +1 @@
1
+ !function(window){"use strict";function WebAudioTinySynthCore(target){Object.assign(target,{properties:{masterVol:{type:Number,value:.5,observer:"setMasterVol"},reverbLev:{type:Number,value:.3,observer:"setReverbLev"},quality:{type:Number,value:1,observer:"setQuality"},debug:{type:Number,value:0},src:{type:String,value:null,observer:"loadMIDIfromSrc"},loop:{type:Number,value:0},internalcontext:{type:Number,value:1},tsmode:{type:Number,value:0},voices:{type:Number,value:64},useReverb:{type:Number,value:1},width:{type:String,value:"300px",observer:"layout"},height:{type:String,value:"32px",observer:"layout"},graph:{type:Number,value:1},disabledrop:{type:Number,value:0},perfmon:{type:Number,value:0}},layout:()=>{this.canvas.style.width=this.width,this.canvas.style.height=this.height},program:[{name:"Acoustic Grand Piano"},{name:"Bright Acoustic Piano"},{name:"Electric Grand Piano"},{name:"Honky-tonk Piano"},{name:"Electric Piano 1"},{name:"Electric Piano 2"},{name:"Harpsichord"},{name:"Clavi"},{name:"Celesta"},{name:"Glockenspiel"},{name:"Music Box"},{name:"Vibraphone"},{name:"Marimba"},{name:"Xylophone"},{name:"Tubular Bells"},{name:"Dulcimer"},{name:"Drawbar Organ"},{name:"Percussive Organ"},{name:"Rock Organ"},{name:"Church Organ"},{name:"Reed Organ"},{name:"Accordion"},{name:"Harmonica"},{name:"Tango Accordion"},{name:"Acoustic Guitar (nylon)"},{name:"Acoustic Guitar (steel)"},{name:"Electric Guitar (jazz)"},{name:"Electric Guitar (clean)"},{name:"Electric Guitar (muted)"},{name:"Overdriven Guitar"},{name:"Distortion Guitar"},{name:"Guitar harmonics"},{name:"Acoustic Bass"},{name:"Electric Bass (finger)"},{name:"Electric Bass (pick)"},{name:"Fretless Bass"},{name:"Slap Bass 1"},{name:"Slap Bass 2"},{name:"Synth Bass 1"},{name:"Synth Bass 2"},{name:"Violin"},{name:"Viola"},{name:"Cello"},{name:"Contrabass"},{name:"Tremolo Strings"},{name:"Pizzicato Strings"},{name:"Orchestral Harp"},{name:"Timpani"},{name:"String Ensemble 1"},{name:"String Ensemble 2"},{name:"SynthStrings 1"},{name:"SynthStrings 2"},{name:"Choir Aahs"},{name:"Voice Oohs"},{name:"Synth Voice"},{name:"Orchestra Hit"},{name:"Trumpet"},{name:"Trombone"},{name:"Tuba"},{name:"Muted Trumpet"},{name:"French Horn"},{name:"Brass Section"},{name:"SynthBrass 1"},{name:"SynthBrass 2"},{name:"Soprano Sax"},{name:"Alto Sax"},{name:"Tenor Sax"},{name:"Baritone Sax"},{name:"Oboe"},{name:"English Horn"},{name:"Bassoon"},{name:"Clarinet"},{name:"Piccolo"},{name:"Flute"},{name:"Recorder"},{name:"Pan Flute"},{name:"Blown Bottle"},{name:"Shakuhachi"},{name:"Whistle"},{name:"Ocarina"},{name:"Lead 1 (square)"},{name:"Lead 2 (sawtooth)"},{name:"Lead 3 (calliope)"},{name:"Lead 4 (chiff)"},{name:"Lead 5 (charang)"},{name:"Lead 6 (voice)"},{name:"Lead 7 (fifths)"},{name:"Lead 8 (bass + lead)"},{name:"Pad 1 (new age)"},{name:"Pad 2 (warm)"},{name:"Pad 3 (polysynth)"},{name:"Pad 4 (choir)"},{name:"Pad 5 (bowed)"},{name:"Pad 6 (metallic)"},{name:"Pad 7 (halo)"},{name:"Pad 8 (sweep)"},{name:"FX 1 (rain)"},{name:"FX 2 (soundtrack)"},{name:"FX 3 (crystal)"},{name:"FX 4 (atmosphere)"},{name:"FX 5 (brightness)"},{name:"FX 6 (goblins)"},{name:"FX 7 (echoes)"},{name:"FX 8 (sci-fi)"},{name:"Sitar"},{name:"Banjo"},{name:"Shamisen"},{name:"Koto"},{name:"Kalimba"},{name:"Bag pipe"},{name:"Fiddle"},{name:"Shanai"},{name:"Tinkle Bell"},{name:"Agogo"},{name:"Steel Drums"},{name:"Woodblock"},{name:"Taiko Drum"},{name:"Melodic Tom"},{name:"Synth Drum"},{name:"Reverse Cymbal"},{name:"Guitar Fret Noise"},{name:"Breath Noise"},{name:"Seashore"},{name:"Bird Tweet"},{name:"Telephone Ring"},{name:"Helicopter"},{name:"Applause"},{name:"Gunshot"}],drummap:[{name:"Acoustic Bass Drum"},{name:"Bass Drum 1"},{name:"Side Stick"},{name:"Acoustic Snare"},{name:"Hand Clap"},{name:"Electric Snare"},{name:"Low Floor Tom"},{name:"Closed Hi Hat"},{name:"High Floor Tom"},{name:"Pedal Hi-Hat"},{name:"Low Tom"},{name:"Open Hi-Hat"},{name:"Low-Mid Tom"},{name:"Hi-Mid Tom"},{name:"Crash Cymbal 1"},{name:"High Tom"},{name:"Ride Cymbal 1"},{name:"Chinese Cymbal"},{name:"Ride Bell"},{name:"Tambourine"},{name:"Splash Cymbal"},{name:"Cowbell"},{name:"Crash Cymbal 2"},{name:"Vibraslap"},{name:"Ride Cymbal 2"},{name:"Hi Bongo"},{name:"Low Bongo"},{name:"Mute Hi Conga"},{name:"Open Hi Conga"},{name:"Low Conga"},{name:"High Timbale"},{name:"Low Timbale"},{name:"High Agogo"},{name:"Low Agogo"},{name:"Cabasa"},{name:"Maracas"},{name:"Short Whistle"},{name:"Long Whistle"},{name:"Short Guiro"},{name:"Long Guiro"},{name:"Claves"},{name:"Hi Wood Block"},{name:"Low Wood Block"},{name:"Mute Cuica"},{name:"Open Cuica"},{name:"Mute Triangle"},{name:"Open Triangle"}],program1:[[{w:"sine",v:.4,d:.7,r:.1},{w:"triangle",v:3,d:.7,s:.1,g:1,a:.01,k:-1.2}],[{w:"triangle",v:.4,d:.7,r:.1},{w:"triangle",v:4,t:3,d:.4,s:.1,g:1,k:-1,a:.01}],[{w:"sine",d:.7,r:.1},{w:"triangle",v:4,f:2,d:.5,s:.5,g:1,k:-1}],[{w:"sine",d:.7,v:.2},{w:"triangle",v:4,t:3,f:2,d:.3,g:1,k:-1,a:.01,s:.5}],[{w:"sine",v:.35,d:.7},{w:"sine",v:3,t:7,f:1,d:1,s:1,g:1,k:-.7}],[{w:"sine",v:.35,d:.7},{w:"sine",v:8,t:7,f:1,d:.5,s:1,g:1,k:-.7}],[{w:"sawtooth",v:.34,d:2},{w:"sine",v:8,f:.1,d:2,s:1,r:2,g:1}],[{w:"triangle",v:.34,d:1.5},{w:"square",v:6,f:.1,d:1.5,s:.5,r:2,g:1}],[{w:"sine",d:.3,r:.3},{w:"sine",v:7,t:11,d:.03,g:1}],[{w:"sine",d:.3,r:.3},{w:"sine",v:11,t:6,d:.2,s:.4,g:1}],[{w:"sine",v:.2,d:.3,r:.3},{w:"sine",v:11,t:5,d:.1,s:.4,g:1}],[{w:"sine",v:.2,d:.6,r:.6},{w:"triangle",v:11,t:5,f:1,s:.5,g:1}],[{w:"sine",v:.3,d:.2,r:.2},{w:"sine",v:6,t:5,d:.02,g:1}],[{w:"sine",v:.3,d:.2,r:.2},{w:"sine",v:7,t:11,d:.03,g:1}],[{w:"sine",v:.2,d:1,r:1},{w:"sine",v:11,t:3.5,d:1,r:1,g:1}],[{w:"triangle",v:.2,d:.5,r:.2},{w:"sine",v:6,t:2.5,d:.2,s:.1,r:.2,g:1}],[{w:"w9999",v:.22,s:.9},{w:"w9999",v:.22,t:2,f:2,s:.9}],[{w:"w9999",v:.2,s:1},{w:"sine",v:11,t:6,f:2,s:.1,g:1,h:.006,r:.002,d:.002},{w:"w9999",v:.2,t:2,f:1,h:0,s:1}],[{w:"w9999",v:.2,d:.1,s:.9},{w:"w9999",v:.25,t:4,f:2,s:.5}],[{w:"w9999",v:.3,a:.04,s:.9},{w:"w9999",v:.2,t:8,f:2,a:.04,s:.9}],[{w:"sine",v:.2,a:.02,d:.05,s:1},{w:"sine",v:6,t:3,f:1,a:.02,d:.05,s:1,g:1}],[{w:"triangle",v:.2,a:.02,d:.05,s:.8},{w:"square",v:7,t:3,f:1,d:.05,s:1.5,g:1}],[{w:"square",v:.2,a:.02,d:.2,s:.5},{w:"square",v:1,d:.03,s:2,g:1}],[{w:"square",v:.2,a:.02,d:.1,s:.8},{w:"square",v:1,a:.3,d:.1,s:2,g:1}],[{w:"sine",v:.3,d:.5,f:1},{w:"triangle",v:5,t:3,f:-1,d:1,s:.1,g:1}],[{w:"sine",v:.4,d:.6,f:1},{w:"triangle",v:12,t:3,d:.6,s:.1,g:1,f:-1}],[{w:"triangle",v:.3,d:1,f:1},{w:"triangle",v:6,f:-1,d:.4,s:.5,g:1,t:3}],[{w:"sine",v:.3,d:1,f:-1},{w:"triangle",v:11,f:1,d:.4,s:.5,g:1,t:3}],[{w:"sine",v:.4,d:.1,r:.01},{w:"sine",v:7,g:1}],[{w:"triangle",v:.4,d:1,f:1},{w:"square",v:4,f:-1,d:1,s:.7,g:1}],[{w:"triangle",v:.35,d:1,f:1},{w:"square",v:7,f:-1,d:.3,s:.5,g:1}],[{w:"sine",v:.2,t:1.5,a:.005,h:.2,d:.6},{w:"sine",v:11,t:5,f:2,d:1,s:.5,g:1}],[{w:"sine",d:.3},{w:"sine",v:4,t:3,d:1,s:1,g:1}],[{w:"sine",d:.3},{w:"sine",v:4,t:3,d:1,s:1,g:1}],[{w:"w9999",d:.3,v:.7,s:.5},{w:"sawtooth",v:1.2,d:.02,s:.5,g:1,h:0,r:.02}],[{w:"sine",d:.3},{w:"sine",v:4,t:3,d:1,s:1,g:1}],[{w:"triangle",v:.3,t:2,d:1},{w:"triangle",v:15,t:2.5,d:.04,s:.1,g:1}],[{w:"triangle",v:.3,t:2,d:1},{w:"triangle",v:15,t:2.5,d:.04,s:.1,g:1}],[{w:"triangle",d:.7},{w:"square",v:.4,t:.5,f:1,d:.2,s:10,g:1}],[{w:"triangle",d:.7},{w:"square",v:.4,t:.5,f:1,d:.2,s:10,g:1}],[{w:"sawtooth",v:.4,a:.1,d:11},{w:"sine",v:5,d:11,s:.2,g:1}],[{w:"sawtooth",v:.4,a:.1,d:11},{w:"sine",v:5,d:11,s:.2,g:1}],[{w:"sawtooth",v:.4,a:.1,d:11},{w:"sine",v:5,t:.5,d:11,s:.2,g:1}],[{w:"sawtooth",v:.4,a:.1,d:11},{w:"sine",v:5,t:.5,d:11,s:.2,g:1}],[{w:"sine",v:.4,a:.1,d:11},{w:"sine",v:6,f:2.5,d:.05,s:1.1,g:1}],[{w:"sine",v:.3,d:.1,r:.1},{w:"square",v:4,t:3,d:1,s:.2,g:1}],[{w:"sine",v:.3,d:.5,r:.5},{w:"sine",v:7,t:2,f:2,d:1,r:1,g:1}],[{w:"triangle",v:.6,h:.03,d:.3,r:.3,t:.5},{w:"n0",v:8,t:1.5,d:.08,r:.08,g:1}],[{w:"sawtooth",v:.3,a:.03,s:.5},{w:"sawtooth",v:.2,t:2,f:2,d:1,s:2}],[{w:"sawtooth",v:.3,f:-2,a:.03,s:.5},{w:"sawtooth",v:.2,t:2,f:2,d:1,s:2}],[{w:"sawtooth",v:.2,a:.02,s:1},{w:"sawtooth",v:.2,t:2,f:2,a:1,d:1,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1},{w:"sawtooth",v:.2,f:2,a:.02,d:1,s:1}],[{w:"triangle",v:.3,a:.03,s:1},{w:"sine",v:3,t:5,f:1,d:1,s:1,g:1}],[{w:"sine",v:.4,a:.03,s:.9},{w:"sine",v:1,t:2,f:3,d:.03,s:.2,g:1}],[{w:"triangle",v:.6,a:.05,s:.5},{w:"sine",v:1,f:.8,d:.2,s:.2,g:1}],[{w:"square",v:.15,a:.01,d:.2,r:.2,t:.5,h:.03},{w:"square",v:4,f:.5,d:.2,r:11,a:.01,g:1,h:.02},{w:"square",v:.15,t:4,f:1,a:.02,d:.15,r:.15,h:.03},{g:3,w:"square",v:4,f:-.5,a:.01,h:.02,d:.15,r:11}],[{w:"square",v:.2,a:.01,d:1,s:.6,r:.04},{w:"sine",v:1,d:.1,s:4,g:1}],[{w:"square",v:.2,a:.02,d:1,s:.5,r:.08},{w:"sine",v:1,d:.1,s:4,g:1}],[{w:"square",v:.2,a:.04,d:1,s:.4,r:.08},{w:"sine",v:1,d:.1,s:4,g:1}],[{w:"square",v:.15,a:.04,s:1},{w:"sine",v:2,d:.1,g:1}],[{w:"square",v:.2,a:.02,d:1,s:.5,r:.08},{w:"sine",v:1,d:.1,s:4,g:1}],[{w:"square",v:.2,a:.02,d:1,s:.6,r:.08},{w:"sine",v:1,f:.2,d:.1,s:4,g:1}],[{w:"square",v:.2,a:.02,d:.5,s:.7,r:.08},{w:"sine",v:1,d:.1,s:4,g:1}],[{w:"square",v:.2,a:.02,d:1,s:.5,r:.08},{w:"sine",v:1,d:.1,s:4,g:1}],[{w:"square",v:.2,a:.02,d:2,s:.6},{w:"sine",v:2,d:1,g:1}],[{w:"square",v:.2,a:.02,d:2,s:.6},{w:"sine",v:2,d:1,g:1}],[{w:"square",v:.2,a:.02,d:1,s:.6},{w:"sine",v:2,d:1,g:1}],[{w:"square",v:.2,a:.02,d:1,s:.6},{w:"sine",v:2,d:1,g:1}],[{w:"sine",v:.4,a:.02,d:.7,s:.5},{w:"square",v:5,t:2,d:.2,s:.5,g:1}],[{w:"sine",v:.3,a:.05,d:.2,s:.8},{w:"sawtooth",v:6,f:.1,d:.1,s:.3,g:1}],[{w:"sine",v:.3,a:.03,d:.2,s:.4},{w:"square",v:7,f:.2,d:1,s:.1,g:1}],[{w:"square",v:.2,a:.05,d:.1,s:.8},{w:"square",v:4,d:.1,s:1.1,g:1}],[{w:"sine",a:.02,d:2},{w:"sine",v:6,t:2,d:.04,g:1}],[{w:"sine",v:.7,a:.03,d:.4,s:.4},{w:"sine",v:4,t:2,f:.2,d:.4,g:1}],[{w:"sine",v:.7,a:.02,d:.4,s:.6},{w:"sine",v:3,t:2,d:0,s:1,g:1}],[{w:"sine",v:.4,a:.06,d:.3,s:.3},{w:"sine",v:7,t:2,d:.2,s:.2,g:1}],[{w:"sine",a:.02,d:.3,s:.3},{w:"sawtooth",v:3,t:2,d:.3,g:1}],[{w:"sine",v:.4,a:.02,d:2,s:.1},{w:"sawtooth",v:8,t:2,f:1,d:.5,g:1}],[{w:"sine",v:.7,a:.03,d:.5,s:.3},{w:"sine",v:.003,t:0,f:4,d:.1,s:.002,g:1}],[{w:"sine",v:.7,a:.02,d:2},{w:"sine",v:1,t:2,f:1,d:.02,g:1}],[{w:"square",v:.3,d:1,s:.5},{w:"square",v:1,f:.2,d:1,s:.5,g:1}],[{w:"sawtooth",v:.3,d:2,s:.5},{w:"square",v:2,f:.1,s:.5,g:1}],[{w:"triangle",v:.5,a:.05,d:2,s:.6},{w:"sine",v:4,t:2,g:1}],[{w:"triangle",v:.3,a:.01,d:2,s:.3},{w:"sine",v:22,t:2,f:1,d:.03,s:.2,g:1}],[{w:"sawtooth",v:.3,d:1,s:.5},{w:"sine",v:11,t:11,a:.2,d:.05,s:.3,g:1}],[{w:"sine",v:.3,a:.06,d:1,s:.5},{w:"sine",v:7,f:1,d:1,s:.2,g:1}],[{w:"sawtooth",v:.3,a:.03,d:.7,s:.3,r:.2},{w:"sawtooth",v:.3,t:.75,d:.7,a:.1,s:.3,r:.2}],[{w:"triangle",v:.3,a:.01,d:.7,s:.5},{w:"square",v:5,t:.5,d:.7,s:.5,g:1}],[{w:"triangle",v:.3,a:.02,d:.3,s:.3,r:.3},{w:"square",v:3,t:4,f:1,a:.02,d:.1,s:1,g:1},{w:"triangle",v:.08,t:.5,a:.1,h:0,d:.1,s:.5,r:.1,b:0,c:0}],[{w:"sine",v:.3,a:.05,d:1,s:.7,r:.3},{w:"sine",v:2,f:1,d:.3,s:1,g:1}],[{w:"square",v:.3,a:.03,d:.5,s:.3,r:.1},{w:"square",v:4,f:1,a:.03,d:.1,g:1}],[{w:"triangle",v:.3,a:.08,d:1,s:.3,r:.1},{w:"square",v:2,f:1,d:.3,s:.3,g:1,t:4,a:.08}],[{w:"sine",v:.3,a:.05,d:1,s:.3,r:.1},{w:"sine",v:.1,t:2.001,f:1,d:1,s:50,g:1}],[{w:"triangle",v:.3,a:.03,d:.7,s:.3,r:.2},{w:"sine",v:12,t:7,f:1,d:.5,s:1.7,g:1}],[{w:"sine",v:.3,a:.05,d:1,s:.3,r:.1},{w:"sawtooth",v:22,t:6,d:.06,s:.3,g:1}],[{w:"triangle",v:.3,a:.05,d:11,r:.3},{w:"triangle",v:1,d:1,s:8,g:1}],[{w:"sawtooth",v:.3,d:4,s:.8,r:.1},{w:"square",v:1,t:2,f:8,a:1,d:1,s:1,r:.1,g:1}],[{w:"triangle",v:.3,d:1,s:.5,t:.8,a:.2,p:1.25,q:.2},{w:"sawtooth",v:.2,a:.2,d:.3,s:1,t:1.2,p:1.25,q:.2}],[{w:"sine",v:.3,d:1,s:.3},{w:"square",v:22,t:11,d:.5,s:.1,g:1}],[{w:"sawtooth",v:.3,a:.04,d:1,s:.8,r:.1},{w:"square",v:1,t:.5,d:1,s:2,g:1}],[{w:"triangle",v:.3,d:1,s:.3},{w:"sine",v:22,t:6,d:.6,s:.05,g:1}],[{w:"sine",v:.6,a:.1,d:.05,s:.4},{w:"sine",v:5,t:5,f:1,d:.05,s:.3,g:1}],[{w:"sine",a:.1,d:.05,s:.4,v:.8},{w:"sine",v:5,t:5,f:1,d:.05,s:.3,g:1}],[{w:"square",v:.3,a:.1,d:.1,s:.4},{w:"square",v:1,f:1,d:.3,s:.1,g:1}],[{w:"sawtooth",v:.3,d:.5,r:.5},{w:"sawtooth",v:11,t:5,d:.05,g:1}],[{w:"square",v:.3,d:.2,r:.2},{w:"square",v:7,t:3,d:.05,g:1}],[{w:"triangle",d:.2,r:.2},{w:"square",v:9,t:3,d:.1,r:.1,g:1}],[{w:"triangle",d:.3,r:.3},{w:"square",v:6,t:3,d:1,r:1,g:1}],[{w:"triangle",v:.4,d:.2,r:.2},{w:"square",v:22,t:12,d:.1,r:.1,g:1}],[{w:"sine",v:.25,a:.02,d:.05,s:.8},{w:"square",v:1,t:2,d:.03,s:11,g:1}],[{w:"sine",v:.3,a:.05,d:11},{w:"square",v:7,t:3,f:1,s:.7,g:1}],[{w:"square",v:.3,a:.05,d:.1,s:.8},{w:"square",v:4,d:.1,s:1.1,g:1}],[{w:"sine",v:.4,d:.3,r:.3},{w:"sine",v:7,t:9,d:.1,r:.1,g:1}],[{w:"sine",v:.7,d:.1,r:.1},{w:"sine",v:22,t:7,d:.05,g:1}],[{w:"sine",v:.6,d:.15,r:.15},{w:"square",v:11,t:3.2,d:.1,r:.1,g:1}],[{w:"sine",v:.8,d:.07,r:.07},{w:"square",v:11,t:7,r:.01,g:1}],[{w:"triangle",v:.7,t:.5,d:.2,r:.2,p:.95},{w:"n0",v:9,g:1,d:.2,r:.2}],[{w:"sine",v:.7,d:.1,r:.1,p:.9},{w:"square",v:14,t:2,d:.005,r:.005,g:1}],[{w:"square",d:.15,r:.15,p:.5},{w:"square",v:4,t:5,d:.001,r:.001,g:1}],[{w:"n1",v:.3,a:1,s:1,d:.15,r:0,t:.5}],[{w:"sine",t:12.5,d:0,r:0,p:.5,v:.3,h:.2,q:.5},{g:1,w:"sine",v:1,t:2,d:0,r:0,s:1},{g:1,w:"n0",v:.2,t:2,a:.6,h:0,d:.1,r:.1,b:0,c:0}],[{w:"n0",v:.2,a:.05,h:.02,d:.02,r:.02}],[{w:"n0",v:.4,a:1,d:1,t:.25}],[{w:"sine",v:.3,a:.1,d:1,s:.5},{w:"sine",v:4,t:0,f:1.5,d:1,s:1,r:.1,g:1},{g:1,w:"sine",v:4,t:0,f:2,a:.6,h:0,d:.1,s:1,r:.1,b:0,c:0}],[{w:"square",v:.3,t:.25,d:11,s:1},{w:"square",v:12,t:0,f:8,d:1,s:1,r:11,g:1}],[{w:"n0",v:.4,t:.5,a:1,d:11,s:1,r:.5},{w:"square",v:1,t:0,f:14,d:1,s:1,r:11,g:1}],[{w:"sine",t:0,f:1221,a:.2,d:1,r:.25,s:1},{g:1,w:"n0",v:3,t:.5,d:1,s:1,r:1}],[{w:"sine",d:.4,r:.4,p:.1,t:2.5,v:1},{w:"n0",v:12,t:2,d:1,r:1,g:1}]],program0:[[{w:"triangle",v:.5,d:.7}],[{w:"triangle",v:.5,d:.7}],[{w:"triangle",v:.5,d:.7}],[{w:"triangle",v:.5,d:.7}],[{w:"triangle",v:.5,d:.7}],[{w:"triangle",v:.5,d:.7}],[{w:"sawtooth",v:.3,d:.7}],[{w:"sawtooth",v:.3,d:.7}],[{w:"sine",v:.5,d:.3,r:.3}],[{w:"triangle",v:.5,d:.3,r:.3}],[{w:"square",v:.2,d:.3,r:.3}],[{w:"square",v:.2,d:.3,r:.3}],[{w:"sine",v:.5,d:.1,r:.1}],[{w:"sine",v:.5,d:.1,r:.1}],[{w:"square",v:.2,d:1,r:1}],[{w:"sawtooth",v:.3,d:.7,r:.7}],[{w:"sine",v:.5,a:.01,s:1}],[{w:"sine",v:.7,d:.02,s:.7}],[{w:"square",v:.2,s:1}],[{w:"triangle",v:.5,a:.01,s:1}],[{w:"square",v:.2,a:.02,s:1}],[{w:"square",v:.2,a:.02,s:1}],[{w:"square",v:.2,a:.02,s:1}],[{w:"square",v:.2,a:.05,s:1}],[{w:"triangle",v:.5,d:.5}],[{w:"square",v:.2,d:.6}],[{w:"square",v:.2,d:.6}],[{w:"triangle",v:.8,d:.6}],[{w:"triangle",v:.4,d:.05}],[{w:"square",v:.2,d:1}],[{w:"square",v:.2,d:1}],[{w:"sine",v:.4,d:.6}],[{w:"triangle",v:.7,d:.4}],[{w:"triangle",v:.7,d:.7}],[{w:"triangle",v:.7,d:.7}],[{w:"triangle",v:.7,d:.7}],[{w:"square",v:.3,d:.2}],[{w:"square",v:.3,d:.2}],[{w:"square",v:.3,d:.1,s:.2}],[{w:"sawtooth",v:.4,d:.1,s:.2}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.3,d:.1}],[{w:"sawtooth",v:.3,d:.5,r:.5}],[{w:"triangle",v:.6,d:.1,r:.1,h:.03,p:.8}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"sawtooth",v:.2,a:.02,s:1}],[{w:"triangle",v:.3,a:.03,s:1}],[{w:"sine",v:.3,a:.03,s:1}],[{w:"triangle",v:.3,a:.05,s:1}],[{w:"sawtooth",v:.5,a:.01,d:.1}],[{w:"square",v:.3,a:.05,d:.2,s:.6}],[{w:"square",v:.3,a:.05,d:.2,s:.6}],[{w:"square",v:.3,a:.05,d:.2,s:.6}],[{w:"square",v:.2,a:.05,d:.01,s:1}],[{w:"square",v:.3,a:.05,s:1}],[{w:"square",v:.3,s:.7}],[{w:"square",v:.3,s:.7}],[{w:"square",v:.3,s:.7}],[{w:"square",v:.3,a:.02,d:2}],[{w:"square",v:.3,a:.02,d:2}],[{w:"square",v:.3,a:.03,d:2}],[{w:"square",v:.3,a:.04,d:2}],[{w:"square",v:.3,a:.02,d:2}],[{w:"square",v:.3,a:.05,d:2}],[{w:"square",v:.3,a:.03,d:2}],[{w:"square",v:.3,a:.03,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"sine",v:.7,a:.02,d:2}],[{w:"square",v:.3,s:.7}],[{w:"sawtooth",v:.4,s:.7}],[{w:"triangle",v:.5,s:.7}],[{w:"sawtooth",v:.4,s:.7}],[{w:"sawtooth",v:.4,d:12}],[{w:"sine",v:.4,a:.06,d:12}],[{w:"sawtooth",v:.4,d:12}],[{w:"sawtooth",v:.4,d:12}],[{w:"sawtooth",v:.3,d:12}],[{w:"triangle",v:.5,d:12}],[{w:"square",v:.3,d:12}],[{w:"triangle",v:.5,a:.08,d:11}],[{w:"sawtooth",v:.5,a:.05,d:11}],[{w:"sawtooth",v:.5,d:11}],[{w:"triangle",v:.5,d:11}],[{w:"triangle",v:.5,d:11}],[{w:"triangle",v:.5,d:11}],[{w:"triangle",v:.5,d:11}],[{w:"square",v:.3,d:11}],[{w:"sawtooth",v:.5,a:.04,d:11}],[{w:"sawtooth",v:.5,d:11}],[{w:"triangle",v:.5,a:.8,d:11}],[{w:"triangle",v:.5,d:11}],[{w:"square",v:.3,d:11}],[{w:"sawtooth",v:.3,d:1,r:1}],[{w:"sawtooth",v:.5,d:.3}],[{w:"sawtooth",v:.5,d:.3,r:.3}],[{w:"sawtooth",v:.5,d:.3,r:.3}],[{w:"square",v:.3,d:.2,r:.2}],[{w:"square",v:.3,a:.02,d:2}],[{w:"sawtooth",v:.2,a:.02,d:.7}],[{w:"triangle",v:.5,d:1}],[{w:"sawtooth",v:.3,d:.3,r:.3}],[{w:"sine",v:.8,d:.1,r:.1}],[{w:"square",v:.2,d:.1,r:.1,p:1.05}],[{w:"sine",v:.8,d:.05,r:.05}],[{w:"triangle",v:.5,d:.1,r:.1,p:.96}],[{w:"triangle",v:.5,d:.1,r:.1,p:.97}],[{w:"square",v:.3,d:.1,r:.1}],[{w:"n1",v:.3,a:1,s:1,d:.15,r:0,t:.5}],[{w:"triangle",v:.5,d:.03,t:0,f:1332,r:.001,p:1.1}],[{w:"n0",v:.2,t:.1,d:.02,a:.05,h:.02,r:.02}],[{w:"n0",v:.4,a:1,d:1,t:.25}],[{w:"sine",v:.3,a:.8,d:1,t:0,f:1832}],[{w:"triangle",d:.5,t:0,f:444,s:1}],[{w:"n0",v:.4,d:1,t:0,f:22,s:1}],[{w:"n0",v:.5,a:.2,d:11,t:0,f:44}],[{w:"n0",v:.5,t:.25,d:.4,r:.4}]],drummap1:[[{w:"triangle",t:0,f:70,v:1,d:.05,h:.03,p:.9,q:.1},{w:"n0",g:1,t:6,v:17,r:.01,h:0,p:0}],[{w:"triangle",t:0,f:88,v:1,d:.05,h:.03,p:.5,q:.1},{w:"n0",g:1,t:5,v:42,r:.01,h:0,p:0}],[{w:"n0",f:222,p:0,t:0,r:.01,h:0}],[{w:"triangle",v:.3,f:180,d:.05,t:0,h:.03,p:.9,q:.1},{w:"n0",v:.6,t:0,f:70,h:.02,r:.01,p:0},{g:1,w:"square",v:2,t:0,f:360,r:.01,b:0,c:0}],[{w:"square",f:1150,v:.34,t:0,r:.03,h:.025,d:.03},{g:1,w:"n0",t:0,f:13,h:.025,d:.1,s:1,r:.1,v:1}],[{w:"triangle",f:200,v:1,d:.06,t:0,r:.06},{w:"n0",g:1,t:0,f:400,v:12,r:.02,d:.02}],[{w:"triangle",f:100,v:.9,d:.12,h:.02,p:.5,t:0,r:.12},{g:1,w:"n0",v:5,t:.4,h:.015,d:.005,r:.005}],[{w:"n1",f:390,v:.25,r:.01,t:0}],[{w:"triangle",f:120,v:.9,d:.12,h:.02,p:.5,t:0,r:.12},{g:1,w:"n0",v:5,t:.5,h:.015,d:.005,r:.005}],[{w:"n1",v:.25,f:390,r:.03,t:0,h:.005,d:.03}],[{w:"triangle",f:140,v:.9,d:.12,h:.02,p:.5,t:0,r:.12},{g:1,w:"n0",v:5,t:.3,h:.015,d:.005,r:.005}],[{w:"n1",v:.25,f:390,t:0,d:.2,r:.2},{w:"n0",v:.3,t:0,c:0,f:440,h:.005,d:.05}],[{w:"triangle",f:155,v:.9,d:.12,h:.02,p:.5,t:0,r:.12},{g:1,w:"n0",v:5,t:.3,h:.015,d:.005,r:.005}],[{w:"triangle",f:180,v:.9,d:.12,h:.02,p:.5,t:0,r:.12},{g:1,w:"n0",v:5,t:.3,h:.015,d:.005,r:.005}],[{w:"n1",v:.3,f:1200,d:.2,r:.2,h:.05,t:0},{w:"n1",t:0,v:1,d:.1,r:.1,p:1.2,f:440}],[{w:"triangle",f:220,v:.9,d:.12,h:.02,p:.5,t:0,r:.12},{g:1,w:"n0",v:5,t:.3,h:.015,d:.005,r:.005}],[{w:"n1",f:500,v:.15,d:.4,r:.4,h:0,t:0},{w:"n0",v:.1,t:0,r:.01,f:440}],[{w:"n1",v:.3,f:800,d:.2,r:.2,h:.05,t:0},{w:"square",t:0,v:1,d:.1,r:.1,p:.1,f:220,g:1}],[{w:"sine",f:1651,v:.15,d:.2,r:.2,h:0,t:0},{w:"sawtooth",g:1,t:1.21,v:7.2,d:.1,r:11,h:1},{g:1,w:"n0",v:3.1,t:.152,d:.002,r:.002}],null,[{w:"n1",v:.3,f:1200,d:.2,r:.2,h:.05,t:0},{w:"n1",t:0,v:1,d:.1,r:.1,p:1.2,f:440}],null,[{w:"n1",v:.3,f:555,d:.25,r:.25,h:.05,t:0},{w:"n1",t:0,v:1,d:.1,r:.1,f:440,a:.005,h:.02}],[{w:"sawtooth",f:776,v:.2,d:.3,t:0,r:.3},{g:1,w:"n0",v:2,t:0,f:776,a:.005,h:.02,d:.1,s:1,r:.1,c:0},{g:11,w:"sine",v:.1,t:0,f:22,d:.3,r:.3,b:0,c:0}],[{w:"n1",f:440,v:.15,d:.4,r:.4,h:0,t:0},{w:"n0",v:.4,t:0,r:.01,f:440}],null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,[{w:"sine",f:1720,v:.3,d:.02,t:0,r:.02},{w:"square",g:1,t:0,f:2876,v:6,d:.2,s:1,r:.2}],[{w:"sine",f:1720,v:.3,d:.25,t:0,r:.25},{w:"square",g:1,t:0,f:2876,v:6,d:.2,s:1,r:.2}]],drummap0:[[{w:"triangle",t:0,f:110,v:1,d:.05,h:.02,p:.1}],[{w:"triangle",t:0,f:150,v:.8,d:.1,p:.1,h:.02,r:.01}],[{w:"n0",f:392,v:.5,d:.01,p:0,t:0,r:.05}],[{w:"n0",f:33,d:.05,t:0}],[{w:"n0",f:100,v:.7,d:.03,t:0,r:.03,h:.02}],[{w:"n0",f:44,v:.7,d:.02,p:.1,t:0,h:.02}],[{w:"triangle",f:240,v:.9,d:.1,h:.02,p:.1,t:0}],[{w:"n0",f:440,v:.2,r:.01,t:0}],[{w:"triangle",f:270,v:.9,d:.1,h:.02,p:.1,t:0}],[{w:"n0",f:440,v:.2,d:.04,r:.04,t:0}],[{w:"triangle",f:300,v:.9,d:.1,h:.02,p:.1,t:0}],[{w:"n0",f:440,v:.2,d:.1,r:.1,h:.02,t:0}],[{w:"triangle",f:320,v:.9,d:.1,h:.02,p:.1,t:0}],[{w:"triangle",f:360,v:.9,d:.1,h:.02,p:.1,t:0}],[{w:"n0",f:150,v:.2,d:.1,r:.1,h:.05,t:0,p:.1}],[{w:"triangle",f:400,v:.9,d:.1,h:.02,p:.1,t:0}],[{w:"n0",f:150,v:.2,d:.1,r:.01,h:.05,t:0,p:.1}],[{w:"n0",f:150,v:.2,d:.1,r:.01,h:.05,t:0,p:.1}],[{w:"n0",f:440,v:.3,d:.1,p:.9,t:0,r:.1}],[{w:"n0",f:200,v:.2,d:.05,p:.9,t:0}],[{w:"n0",f:440,v:.3,d:.12,p:.9,t:0}],[{w:"sine",f:800,v:.4,d:.06,t:0}],[{w:"n0",f:150,v:.2,d:.1,r:.01,h:.05,t:0,p:.1}],[{w:"n0",f:33,v:.3,d:.2,p:.9,t:0}],[{w:"n0",f:300,v:.3,d:.14,p:.9,t:0}],[{w:"sine",f:200,d:.06,t:0}],[{w:"sine",f:150,d:.06,t:0}],[{w:"sine",f:300,t:0}],[{w:"sine",f:300,d:.06,t:0}],[{w:"sine",f:250,d:.06,t:0}],[{w:"square",f:300,v:.3,d:.06,p:.8,t:0}],[{w:"square",f:260,v:.3,d:.06,p:.8,t:0}],[{w:"sine",f:850,v:.5,d:.07,t:0}],[{w:"sine",f:790,v:.5,d:.07,t:0}],[{w:"n0",f:440,v:.3,a:.05,t:0}],[{w:"n0",f:440,v:.3,a:.05,t:0}],[{w:"triangle",f:1800,v:.4,p:.9,t:0,h:.03}],[{w:"triangle",f:1800,v:.3,p:.9,t:0,h:.13}],[{w:"n0",f:330,v:.3,a:.02,t:0,r:.01}],[{w:"n0",f:330,v:.3,a:.02,t:0,h:.04,r:.01}],[{w:"n0",f:440,v:.3,t:0}],[{w:"sine",f:800,t:0}],[{w:"sine",f:700,t:0}],[{w:"n0",f:330,v:.3,t:0}],[{w:"n0",f:330,v:.3,t:0,h:.1,r:.01,p:.7}],[{w:"sine",t:0,f:1200,v:.3,r:.01}],[{w:"sine",t:0,f:1200,v:.3,d:.2,r:.2}]],_guiInit:()=>{this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.ctx.fillStyle="#000",this.ctx.fillRect(0,0,300,32),this.canvas.addEventListener("dragover",this.dragOver.bind(this),!1),this.canvas.addEventListener("dragleave",this.dragLeave.bind(this),!1),this.canvas.addEventListener("drop",this.execDrop.bind(this),!1),this.canvas.addEventListener("click",this.click.bind(this),!1),this.canvas.addEventListener("mousedown",this.pointerdown.bind(this),!1),this.canvas.addEventListener("mousemove",this.pointermove.bind(this),!1),this.canvas.addEventListener("touchstart",this.pointerdown.bind(this),!1),this.canvas.addEventListener("touchend",this.pointerup.bind(this),!1),this.canvas.addEventListener("touchcancel",this.pointerup.bind(this),!1),this.canvas.addEventListener("touchmove",this.pointermove.bind(this),!1))},_guiUpdate:()=>{if(this.canvas){this.ctx.fillStyle="#000",this.ctx.fillRect(0,0,300,32);var row1=8,row2=20;if(this.song?(row1=4,row2=24):(this.ctx.fillStyle="#fff",this.ctx.fillText("TinySynth",8,20)),this.graph){this.ctx.fillStyle="#800",this.ctx.fillRect(80,row1,132,4),this.ctx.fillRect(80,row2,132,4),this.ctx.fillStyle="#f00";for(let i=this.notetab.length-1;i>=0;--i){const nt=this.notetab[i];nt.f&&!this.rhythm[nt.ch]||(this.ctx.fillRect(80+nt.n,row1,4,4),this.ctx.fillRect(80+8*nt.ch,row2,6,4))}}this.perfmon&&(this.ctx.fillStyle="#fff",this.ctx.fillRect(180,30,28,-12),this.ctx.fillStyle="#000",this.ctx.fillText(this.notetab.length,185,28)),this.ctx.fillStyle="#fff",this.ctx.fillRect(250,15,32,2),this.ctx.fillStyle="#fff",this.ctx.strokeStyle="#000",this.ctx.beginPath(),this.ctx.arc(250+32*this.masterVol,16,6,0,6.28,0),this.ctx.moveTo(220,12),this.ctx.lineTo(224,12),this.ctx.lineTo(230,6),this.ctx.lineTo(230,26),this.ctx.lineTo(224,20),this.ctx.lineTo(220,20),this.ctx.fill(),this.ctx.stroke(),this.ctx.strokeStyle="#fff",this.ctx.lineWidth=2,this.ctx.beginPath(),this.ctx.arc(230,16,4,-1,1,!1),this.ctx.stroke(),this.ctx.beginPath(),this.ctx.arc(230,16,8,-1,1,!1),this.ctx.stroke(),0==this.masterVol&&(this.ctx.strokeStyle="#000",this.ctx.lineWidth=4,this.ctx.beginPath(),this.ctx.moveTo(220,7),this.ctx.lineTo(238,25),this.ctx.stroke(),this.ctx.strokeStyle="#fff",this.ctx.lineWidth=2,this.ctx.stroke()),this.song&&(this.ctx.fillStyle="#fff",this.ctx.fillRect(4,2,28,28),this.ctx.fillRect(80,15,128,2),this.ctx.fillStyle="#000",this.playing?(this.ctx.fillRect(12,10,4,12),this.ctx.fillRect(22,10,4,12)):(this.ctx.beginPath(),this.ctx.moveTo(12,9),this.ctx.lineTo(25,16),this.ctx.lineTo(12,23),this.ctx.fill()),this.ctx.fillStyle="#fff",this.ctx.fillText(this.toTime(this.playTick),38,14),this.ctx.fillText(this.toTime(this.maxTick),38,28),this.ctx.strokeStyle="#000",this.ctx.beginPath(),this.ctx.arc(80+this.playTick/this.maxTick*128,16,6,0,6.28,0),this.ctx.fill(),this.ctx.stroke()),this.waitdrop&&(this.ctx.fillStyle="rgba(0,0,0,0.7)",this.ctx.fillRect(0,0,300,32),this.ctx.fillStyle="#fff",this.ctx.fillText("Drop MIDI File Here",100,20))}},toTime:ti=>{const s=(ti=4*ti*60/this.song.timebase/this.song.tempo|0)%60;return("00"+(ti/60|0)).substr(-2)+":"+("00"+s).substr(-2)},preventScroll:e=>{e.preventDefault()},pointerup:ev=>{document.body.removeEventListener("touchstart",this.preventScroll,!1)},getPos:e=>{var p=e.target.getBoundingClientRect();return p.right!=p.left?{x:300*(e.clientX-p.left)/(p.right-p.left),y:e.clientY-p.top}:{x:0,y:0}},pointerdown:ev=>{let e=ev;if(ev.touches&&(e=ev.touches[0]),this.downpos=this.getPos(e),ev.touches||1&e.buttons){if(this.song&&this.downpos.x>=80&&this.downpos.x<=208){const p=(this.downpos.x-80)/128*this.maxTick;this.locateMIDI(p),document.body.addEventListener("touchstart",this.preventScroll,!1)}if(this.downpos.x>=250&&this.downpos.x<282){const p=(this.downpos.x-250)/32;this.setMasterVol(p),document.body.addEventListener("touchstart",this.preventScroll,!1)}}},pointermove:ev=>{let e=ev;if(ev.touches&&(e=ev.touches[0]),ev.touches||1&e.buttons){const pos=this.getPos(e);if(this.song&&pos.x>=70&&pos.x<=208){pos.x<80&&(pos.x=80);const p=(pos.x-80)/128*this.maxTick;this.locateMIDI(p)}if(pos.x>=250&&pos.x<282){const p=(pos.x-250)/32;this.setMasterVol(p)}}},click:e=>{const pos=this.getPos(e);pos.x<40&&this.song&&(this.playing?this.stopMIDI():this.song&&this.playMIDI()),pos.x>=215&&pos.x<243&&this.downpos.x>=215&&this.downpos.x<243&&(this.masterVol>0?(this.lastMasterVol=this.masterVol,this.masterVol=0):this.masterVol=this.lastMasterVol)},dragLeave:e=>{this.waitdrop=0},dragOver:e=>{this.waitdrop=1,e.stopPropagation(),e.preventDefault(),e.dataTransfer.dropEffect="copy"},execDrop:e=>{this.waitdrop=0;const f=e.dataTransfer.files;if(0==this.disabledrop){var reader=new FileReader;reader.onload=function(e){this.loadMIDI(reader.result)}.bind(this),reader.readAsArrayBuffer(f[0])}e.stopPropagation(),e.preventDefault()},ready:()=>new Promise((resolv=>{const timerid=setInterval((()=>{this.isReady&&(clearInterval(timerid),console.log("Initialized"),resolv())}),100)})),init:()=>{this.pg=[],this.vol=[],this.ex=[],this.bend=[],this.rpnidx=[],this.brange=[],this.sustain=[],this.notetab=[],this.rhythm=[],this.masterTuningC=0,this.masterTuningF=0,this.tuningC=[],this.tuningF=[],this.maxTick=0,this.playTick=0,this.playing=0,this.releaseRatio=3.5;for(let i=0;i<16;++i)this.pg[i]=0,this.vol[i]=3e4/16129,this.bend[i]=0,this.brange[i]=256,this.tuningC[i]=0,this.tuningF[i]=0,this.rhythm[i]=0;this.rhythm[9]=1,this.preroll=.2,this.relcnt=0,setInterval(function(){if(++this.relcnt>=3){this.relcnt=0;for(let i=this.notetab.length-1;i>=0;--i){var nt=this.notetab[i];this.actx.currentTime>nt.e&&(this._pruneNote(nt),this.notetab.splice(i,1))}}if(this.playing&&this.song.ev.length>0){let e=this.song.ev[this.playIndex];for(;this.actx.currentTime+this.preroll>this.playTime;)if(65361==e.m[0]?(this.song.tempo=e.m[1],this.tick2Time=240/this.song.tempo/this.song.timebase):this.send(e.m,this.playTime),++this.playIndex,this.playIndex>=this.song.ev.length){if(!this.loop){this.playTick=this.maxTick,this.playing=0;break}e=this.song.ev[this.playIndex=0],this.playTick=e.t}else e=this.song.ev[this.playIndex],this.playTime+=(e.t-this.playTick)*this.tick2Time,this.playTick=e.t}}.bind(this),60),console.log("internalcontext:"+this.internalcontext),this.internalcontext&&(window.AudioContext=window.AudioContext||window.webkitAudioContext,this.setAudioContext(new AudioContext)),this.isReady=1},setMasterVol:v=>{null!=v&&(this.masterVol=v),this.out&&(this.out.gain.value=this.masterVol)},setReverbLev:v=>{null!=v&&(this.reverbLev=v);var r=parseFloat(this.reverbLev);this.rev&&!isNaN(r)&&(this.rev.gain.value=8*r)},setLoop:f=>{this.loop=f},setVoices:v=>{this.voices=v},getPlayStatus:()=>({play:this.playing,maxTick:this.maxTick,curTick:this.playTick}),locateMIDI:tick=>{let i,p=this.playing;for(this.stopMIDI(),i=0;i<this.song.ev.length&&tick>this.song.ev[i].t;++i){var m=this.song.ev[i],ch=15&m.m[0];switch(240&m.m[0]){case 176:switch(m.m[1]){case 1:this.setModulation(ch,m.m[2]);break;case 7:this.setChVol(ch,m.m[2]);break;case 10:this.setPan(ch,m.m[2]);break;case 11:this.setExpression(ch,m.m[2]);break;case 64:this.setSustain(ch,m.m[2])}break;case 192:this.pg[15&m.m[0]]=m.m[1]}65361==m.m[0]&&(this.song.tempo=m.m[1])}this.song.ev[i]?(this.playIndex=i,this.playTick=this.song.ev[i].t):(this.playIndex=0,this.playTick=this.maxTick),p&&this.playMIDI()},getTimbreName:(m,n)=>0==m?this.program[n].name:this.drummap[n-35].name,loadMIDIfromSrc:()=>{this.loadMIDIUrl(this.src)},loadMIDIUrl:url=>{if(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,!0),xhr.responseType="arraybuffer",xhr.loadMIDI=this.loadMIDI.bind(this),xhr.onload=function(e){200==this.status&&this.loadMIDI(this.response)},xhr.send()}},reset:()=>{for(let i=0;i<16;++i)this.setProgram(i,0),this.setBendRange(i,256),this.setModulation(i,0),this.setChVol(i,100),this.setPan(i,64),this.resetAllControllers(i),this.allSoundOff(i),this.rhythm[i]=0,this.tuningC[i]=0,this.tuningF[i]=0;this.masterTuningC=0,this.masterTuningF=0,this.rhythm[9]=1},stopMIDI:()=>{this.playing=0;for(var i=0;i<16;++i)this.allSoundOff(i)},playMIDI:()=>{if(!this.song)return;const dummy=this.actx.createOscillator();dummy.connect(this.actx.destination),dummy.frequency.value=0,dummy.start(0),dummy.stop(this.actx.currentTime+.001),this.playTick>=this.maxTick&&(this.playTick=0,this.playIndex=0),this.playTime=this.actx.currentTime+.1,this.tick2Time=240/this.song.tempo/this.song.timebase,this.playing=1},loadMIDI:data=>{function Get2(s,i){return(s[i]<<8)+s[i+1]}function Get4(s,i){return(s[i]<<24)+(s[i+1]<<16)+(s[i+2]<<8)+s[i+3]}function GetStr(s,i,len){return String.fromCharCode.apply(null,s.slice(i,i+len))}function Delta(s,i){var v,d;for(v=0,datalen=1;128&(d=s[i]);)v=(v<<7)+(127&d),++datalen,++i;return(v<<7)+d}function Msg(song,tick,s,i){var v=s[i];switch(datalen=1,0==(128&v)&&(v=runst,datalen=0),runst=v,240&v){case 192:case 208:song.ev.push({t:tick,m:[v,s[i+datalen]]}),datalen+=1;break;case 240:switch(v){case 240:case 247:var len=Delta(s,i+1);datastart=1+datalen;var exd=Array.from(s.slice(i+datastart,i+datastart+len));exd.unshift(240),song.ev.push({t:tick,m:exd}),datalen+=len+1;break;case 255:len=Delta(s,i+2);switch(datastart=2+datalen,datalen=len+datalen+2,s[i+1]){case 2:song.copyright+=GetStr(s,i+datastart,datalen-3);break;case 1:case 3:case 4:case 9:song.text=GetStr(s,i+datastart,datalen-datastart);break;case 47:return 1;case 81:var val=Math.floor(6e7/function(s,i){return(s[i]<<16)+(s[i+1]<<8)+s[i+2]}(s,i+3));song.ev.push({t:tick,m:[65361,val]})}}break;default:song.ev.push({t:tick,m:[v,s[i+datalen],s[i+datalen+1]]}),datalen+=2}return 0}this.stopMIDI();var s=new Uint8Array(data),datalen=0,datastart=0,runst=144,idx=0,hd=s.slice(0,4);if("77,84,104,100"==hd.toString()){var len=Get4(s,4),numtrk=(Get2(s,8),Get2(s,10));this.maxTick=0;var tb=4*Get2(s,12);idx=len+8,this.song={copyright:"",text:"",tempo:120,timebase:tb,ev:[]};for(let tr=0;tr<numtrk;++tr){if(hd=s.slice(idx,idx+4),len=Get4(s,idx+4),"77,84,114,107"==hd.toString()){var tick=0,j=0;for(this.notetab.length=0;;){tick+=Delta(s,idx+8+j),j+=datalen;var e=Msg(this.song,tick,s,idx+8+j);if(j+=datalen,e)break}tick>this.maxTick&&(this.maxTick=tick)}idx+=len+8}this.song.ev.sort((function(x,y){return x.t-y.t})),this.reset(),this.locateMIDI(0)}},setQuality:q=>{null!=q&&(this.quality=q);for(let i=0;i<128;++i)this.setTimbre(0,i,this.program0[i]);for(let i=0;i<this.drummap0.length;++i)this.setTimbre(1,i+35,this.drummap0[i]);if(this.quality){for(let i=0;i<this.program1.length;++i)this.setTimbre(0,i,this.program1[i]);for(let i=0;i<this.drummap.length;++i)this.drummap1[i]&&this.setTimbre(1,i+35,this.drummap1[i])}},setTimbre:(m,n,p)=>{const defp={g:0,w:"sine",t:1,f:0,v:.5,a:0,h:.01,d:.01,s:0,r:.05,p:1,q:1,k:0};function filldef(p){for(n=0;n<p.length;++n)for(let k in defp)p[n].hasOwnProperty(k)&&void 0!==p[n][k]||(p[n][k]=defp[k]);return p}m&&n>=35&&n<=81&&(this.drummap[n-35].p=filldef(p)),0==m&&n>=0&&n<=127&&(this.program[n].p=filldef(p))},_pruneNote:nt=>{for(let k=nt.o.length-1;k>=0;--k){if(nt.o[k].frequency?nt.o[k].frequency.cancelScheduledValues(0):nt.o[k].playbackRate.cancelScheduledValues(0),nt.g[k].gain.cancelScheduledValues(0),nt.o[k].stop(),nt.o[k].detune)try{this.chmod[nt.ch].disconnect(nt.o[k].detune)}catch(e){}nt.g[k].gain.value=0}},_limitVoices:(ch,n)=>{this.notetab.sort((function(n1,n2){return n1.f!=n2.f?n1.f-n2.f:n1.e!=n2.e?n2.e-n1.e:n2.t-n1.t}));for(let i=this.notetab.length-1;i>=0;--i){var nt=this.notetab[i];(this.actx.currentTime>nt.e||i>=this.voices-1)&&(this._pruneNote(nt),this.notetab.splice(i,1))}},_note:(t,ch,n,v,p)=>{let out,sc,pn;const o=[],g=[],vp=[],fp=[],r=[],f=440*Math.pow(2,(n-69+this.masterTuningC+this.tuningC[ch]+(this.masterTuningF+this.tuningF[ch])/8192)/12);this._limitVoices(ch,n);for(let i=0;i<p.length;++i){pn=p[i];const dt=t+pn.a+pn.h;switch(0==pn.g?(out=this.chvol[ch],sc=v*v/16384,fp[i]=f*pn.t+pn.f):pn.g>10?(out=g[pn.g-11].gain,sc=1,fp[i]=fp[pn.g-11]*pn.t+pn.f):o[pn.g-1].frequency?(out=o[pn.g-1].frequency,sc=fp[pn.g-1],fp[i]=fp[pn.g-1]*pn.t+pn.f):(out=o[pn.g-1].playbackRate,sc=fp[pn.g-1]/440,fp[i]=fp[pn.g-1]*pn.t+pn.f),pn.w[0]){case"n":o[i]=this.actx.createBufferSource(),o[i].buffer=this.noiseBuf[pn.w],o[i].loop=!0,o[i].playbackRate.value=fp[i]/440,1!=pn.p&&this._setParamTarget(o[i].playbackRate,fp[i]/440*pn.p,t,pn.q),o[i].detune&&(this.chmod[ch].connect(o[i].detune),o[i].detune.value=this.bend[ch]);break;default:o[i]=this.actx.createOscillator(),o[i].frequency.value=fp[i],1!=pn.p&&this._setParamTarget(o[i].frequency,fp[i]*pn.p,t,pn.q),"w"==pn.w[0]?o[i].setPeriodicWave(this.wave[pn.w]):o[i].type=pn.w,o[i].detune&&(this.chmod[ch].connect(o[i].detune),o[i].detune.value=this.bend[ch])}g[i]=this.actx.createGain(),r[i]=pn.r,o[i].connect(g[i]),g[i].connect(out),vp[i]=sc*pn.v,pn.k&&(vp[i]*=Math.pow(2,(n-60)/12*pn.k)),pn.a?(g[i].gain.value=0,g[i].gain.setValueAtTime(0,t),g[i].gain.linearRampToValueAtTime(vp[i],t+pn.a)):g[i].gain.setValueAtTime(vp[i],t),this._setParamTarget(g[i].gain,pn.s*vp[i],dt,pn.d),o[i].start(t),this.rhythm[ch]&&(o[i].onended=()=>{try{o[i].detune&&this.chmod[ch].disconnect(o[i].detune)}catch(e){}},o[i].stop(t+p[0].d*this.releaseRatio))}this.rhythm[ch]||this.notetab.push({t:t,e:99999,ch:ch,n:n,o:o,g:g,t2:t+pn.a,v:vp,r:r,f:0})},_setParamTarget:(p,v,t,d)=>{0!=d?p.setTargetAtTime(v,t,d):p.setValueAtTime(v,t)},_releaseNote:(nt,t)=>{if(9!=nt.ch)for(let k=nt.g.length-1;k>=0;--k)nt.g[k].gain.cancelScheduledValues(t),t==nt.t2?nt.g[k].gain.setValueAtTime(nt.v[k],t):t<nt.t2&&nt.g[k].gain.setValueAtTime(nt.v[k]*(t-nt.t)/(nt.t2-nt.t),t),this._setParamTarget(nt.g[k].gain,0,t,nt.r[k]);nt.e=t+nt.r[0]*this.releaseRatio,nt.f=1},setModulation:(ch,v,t)=>{this.chmod[ch].gain.setValueAtTime(100*v/127,this._tsConv(t))},setChVol:(ch,v,t)=>{this.vol[ch]=3*v*v/16129,this.chvol[ch].gain.setValueAtTime(this.vol[ch]*this.ex[ch],this._tsConv(t))},setPan:(ch,v,t)=>{this.chpan[ch]&&this.chpan[ch].pan.setValueAtTime((v-64)/64,this._tsConv(t))},setExpression:(ch,v,t)=>{this.ex[ch]=v*v/16129,this.chvol[ch].gain.setValueAtTime(this.vol[ch]*this.ex[ch],this._tsConv(t))},setSustain:(ch,v,t)=>{if(this.sustain[ch]=v,t=this._tsConv(t),v<64)for(let i=this.notetab.length-1;i>=0;--i){const nt=this.notetab[i];t>=nt.t&&nt.ch==ch&&1==nt.f&&this._releaseNote(nt,t)}},allSoundOff:ch=>{for(let i=this.notetab.length-1;i>=0;--i){const nt=this.notetab[i];nt.ch==ch&&(this._pruneNote(nt),this.notetab.splice(i,1))}},resetAllControllers:ch=>{this.bend[ch]=0,this.ex[ch]=1,this.rpnidx[ch]=16383,this.sustain[ch]=0,this.chvol[ch]&&(this.chvol[ch].gain.value=this.vol[ch]*this.ex[ch],this.chmod[ch].gain.value=0)},setBendRange:(ch,v)=>{this.brange[ch]=v},setProgram:(ch,v)=>{this.debug&&console.log("Pg("+ch+")="+v),this.pg[ch]=v},_tsConv:t=>(null==t||t<=0?(t=0,this.actx&&(t=this.actx.currentTime)):this.tsmode&&(t=.001*t-this.tsdiff),t),setBend:(ch,v,t)=>{t=this._tsConv(t);const br=100*this.brange[ch]/127;this.bend[ch]=(v-8192)*br/8192;for(let i=this.notetab.length-1;i>=0;--i){const nt=this.notetab[i];if(nt.ch==ch)for(let k=nt.o.length-1;k>=0;--k)nt.o[k].frequency&&nt.o[k].detune&&nt.o[k].detune.setValueAtTime(this.bend[ch],t)}},noteOff:(ch,n,t)=>{if(!this.rhythm[ch]){t=this._tsConv(t);for(let i=this.notetab.length-1;i>=0;--i){const nt=this.notetab[i];t>=nt.t&&nt.ch==ch&&nt.n==n&&0==nt.f&&(nt.f=1,this.sustain[ch]<64&&this._releaseNote(nt,t))}}},noteOn:(ch,n,v,t)=>{0!=v?(t=this._tsConv(t),this.rhythm[ch]?n>=35&&n<=81&&this._note(t,ch,n,v,this.drummap[n-35].p):this._note(t,ch,n,v,this.program[this.pg[ch]].p)):this.noteOff(ch,n,t)},setTsMode:tsmode=>{this.tsmode=tsmode},send:(msg,t)=>{const ch=15&msg[0],cmd=-16&msg[0];if(!(cmd<128||cmd>=256))switch("suspended"==this.audioContext.state&&this.audioContext.resume(),cmd){case 176:switch(msg[1]){case 1:this.setModulation(ch,msg[2],t);break;case 7:this.setChVol(ch,msg[2],t);break;case 10:this.setPan(ch,msg[2],t);break;case 11:this.setExpression(ch,msg[2],t);break;case 64:this.setSustain(ch,msg[2],t);break;case 98:case 99:this.rpnidx[ch]=16383;break;case 100:this.rpnidx[ch]=16256&this.rpnidx[ch]|msg[2];break;case 101:this.rpnidx[ch]=127&this.rpnidx[ch]|msg[2]<<7;break;case 6:switch(this.rpnidx[ch]){case 0:this.brange[ch]=(msg[2]<<7)+(127&this.brange[ch]);break;case 1:this.tuningF[ch]=(msg[2]<<7)+(this.tuningF[ch]+8192&127)-8192;break;case 2:this.tuningC[ch]=msg[2]-64}break;case 38:switch(this.rpnidx[ch]){case 0:this.brange[ch]=16256&this.brange[ch]|msg[2];break;case 1:this.tuningF[ch]=this.tuningF[ch]+8192&16256|msg[2]-8192}break;case 120:case 123:case 124:case 125:case 126:case 127:this.allSoundOff(ch);break;case 121:this.resetAllControllers(ch)}break;case 192:this.setProgram(ch,msg[1]);break;case 224:this.setBend(ch,msg[1]+(msg[2]<<7),t);break;case 144:this.noteOn(ch,msg[1],msg[2],t);break;case 128:this.noteOff(ch,msg[1],t);break;case 240:if(255==msg[0]){this.reset();break}if(254!=msg[0]&&this.debug){var ds=[];for(let ii=0;ii<msg.length;++ii)ds.push(msg[ii].toString(16))}if(240==msg[0]&&(127==msg[1]&&4==msg[3]&&(3==msg[4]&&msg.length>=8&&(this.masterTuningF=128*msg[6]+msg[5]-8192),4==msg[4]&&msg.length>=8&&(this.masterTuningC=msg[6]-64)),65==msg[1]&&66==msg[3]&&18==msg[4]&&64==msg[5]&&16==(240&msg[6])&&21==msg[7])){const c=[9,0,1,2,3,4,5,6,7,8,10,11,12,13,14,15][15&msg[6]];this.rhythm[c]=msg[8]}}},_createWave:w=>{const imag=new Float32Array(w.length),real=new Float32Array(w.length);for(let i=1;i<w.length;++i)imag[i]=w[i];return this.actx.createPeriodicWave(real,imag)},getAudioContext:()=>this.actx,setAudioContext:(actx,dest)=>{this.audioContext=this.actx=actx,this.dest=dest,dest||(this.dest=actx.destination),this.tsdiff=.001*performance.now()-this.actx.currentTime,console.log("TSDiff:"+this.tsdiff),this.out=this.actx.createGain(),this.comp=this.actx.createDynamicsCompressor();var blen=.5*this.actx.sampleRate|0;this.convBuf=this.actx.createBuffer(2,blen,this.actx.sampleRate),this.noiseBuf={},this.noiseBuf.n0=this.actx.createBuffer(1,blen,this.actx.sampleRate),this.noiseBuf.n1=this.actx.createBuffer(1,blen,this.actx.sampleRate);var d1=this.convBuf.getChannelData(0),d2=this.convBuf.getChannelData(1),dn=this.noiseBuf.n0.getChannelData(0),dr=this.noiseBuf.n1.getChannelData(0);for(let i=0;i<blen;++i)i/blen<Math.random()&&(d1[i]=Math.exp(-3*i/blen)*(Math.random()-.5)*.5,d2[i]=Math.exp(-3*i/blen)*(Math.random()-.5)*.5),dn[i]=2*Math.random()-1;for(let jj=0;jj<64;++jj){const r1=10*Math.random()+1,r2=10*Math.random()+1;for(let i=0;i<blen;++i){var dd=Math.sin(i/blen*2*Math.PI*440*r1)*Math.sin(i/blen*2*Math.PI*440*r2);dr[i]+=dd/8}}this.useReverb&&(this.conv=this.actx.createConvolver(),this.conv.buffer=this.convBuf,this.rev=this.actx.createGain(),this.rev.gain.value=this.reverbLev,this.out.connect(this.conv),this.conv.connect(this.rev),this.rev.connect(this.comp)),this.setMasterVol(),this.out.connect(this.comp),this.comp.connect(this.dest),this.chvol=[],this.chmod=[],this.chpan=[],this.wave={w9999:this._createWave("w9999")},this.lfo=this.actx.createOscillator(),this.lfo.frequency.value=5,this.lfo.start(0);for(let i=0;i<16;++i)this.chvol[i]=this.actx.createGain(),this.actx.createStereoPanner?(this.chpan[i]=this.actx.createStereoPanner(),this.chvol[i].connect(this.chpan[i]),this.chpan[i].connect(this.out)):(this.chpan[i]=null,this.chvol[i].connect(this.out)),this.chmod[i]=this.actx.createGain(),this.lfo.connect(this.chmod[i]),this.pg[i]=0,this.resetAllControllers(i);this.setReverbLev(),this.reset(),this.send([144,60,1]),this.send([144,60,0])}})}if(window&&window.customElements){class WebAudioTinySynthElement extends HTMLElement{constructor(){super()}connectedCallback(){const div=document.createElement("div");div.innerHTML="<canvas\n id='wa-canvas' width='300' height='32'\n touch-action='none' tabindex='0'\n style='\n position:relative;\n margin:0;\n border:none;\n width:300px;\n height:32px;\n '\n ></canvas>\n <div id='wa-logo'\n style='\n display:none;\n position:absolute;\n top:5px;\n left:5px;\n color:#fff;\n font-size:8px;\n background:rgba(0,0,0,0.5);\n '\n >TinySynth</div>",this.getAttr=(n,def)=>{let v=this.getAttribute(n);if(""==v||null==v)return def;switch(typeof def){case"number":return"true"==v?1:(v=+v,isNaN(v)?0:v)}return v},this.canvas=div.children[0],this.appendChild(div),WebAudioTinySynthCore.bind(this)(this);const plist=this.properties;for(let k in plist){const v=plist[k];v.observer?(this["_"+k]=v.value,Object.defineProperty(this,k,{get:()=>this["_"+k],set:val=>{this["_"+k]=val,this[v.observer]()}})):this[k]=v}for(let k in plist){const v=plist[k];this[k]=this.getAttr(k,v.value)}this.setQuality(1),this.init(),this._guiInit.bind(this)(),setInterval(this._guiUpdate.bind(this),100)}}window.customElements.define("webaudio-tinysynth",WebAudioTinySynthElement)}class WebAudioTinySynth{constructor(opt){WebAudioTinySynthCore.bind(this)(this);for(let k in this.properties)this[k]=this.properties[k].value;this.setQuality(1),opt&&(null!=opt.useReverb&&(this.useReverb=opt.useReverb),null!=opt.quality&&this.setQuality(opt.quality),null!=opt.voices&&this.setVoices(opt.voices)),this.init()}}"object"==typeof exports&&"undefined"!=typeof module?module.exports=WebAudioTinySynth:"function"==typeof define&&define.amd?define((function(){return WebAudioTinySynth})):window.WebAudioTinySynth=WebAudioTinySynth}(this);
Binary file