-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathChuck.ts
1061 lines (999 loc) · 38 KB
/
Chuck.ts
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Here's a brief overview of the main components of the Chuck class:
* - Constructor: The constructor takes preloaded files, an AudioContext, and a WebAssembly (Wasm) binary as input. It initializes the AudioWorkletNode and sets up the necessary event listeners and error handlers.
* - init: A static method that initializes a new instance of the Chuck class. It loads the Wasm binary, creates an AudioContext, adds the AudioWorklet module, preloads files, and connects the instance to the audio context's destination.
* - AudioWorkletNode: Methods that expose the AudioWorkletNode, or properties of it.
* - Filesystem: Methods like createFile and preloadFiles help manage files within the ChucK environment.
* - Run/Replace Code: Methods like runCode, runCodeWithReplacementDac, replaceCode, and replaceCodeWithReplacementDac allow running and replacing ChucK code with or without a specified DAC (Digital-to-Analog Converter).
* - Run/Replace File: Methods like runFile, runFileWithReplacementDac, replaceFile, and replaceFileWithReplacementDac allow running and replacing ChucK files with or without a specified DAC.
* - Shred: Methods like removeShred and isShredActive allow managing ChucK shreds (concurrent threads of execution in ChucK).
* - Event: Methods like signalEvent, broadcastEvent, listenForEventOnce, startListeningForEvent, and stopListeningForEvent allow managing ChucK events.
* - Int, Float, String: Methods like setInt, getInt, setFloat, getFloat, setString, and getString allow setting and getting integer, float, and string variables in ChucK.
* - Int[], Float[]: Methods like setIntArray, getIntArray, setFloatArray, and getFloatArray allow managing integer and float arrays in ChucK.
* - Clear: Methods like clearChuckInstance and clearGlobals allow clearing the ChucK instance and its global state.
* - Private: Private methods like sendMessage and receiveMessage handle messaging between the Chuck class and the AudioWorklet.
*/
import DeferredPromise from "./DeferredPromise";
import { defer, isPlaintextFile, loadWasm, preloadFiles } from "./utils";
import type { File, Filename } from "./utils";
import { InMessage, OutMessage } from "./enums";
// Create a Record type for deferredPromises and eventCallbacks
type DeferredPromisesMap = Record<number, DeferredPromise<unknown>>;
type EventCallbacksMap = Record<number, () => void>;
/**
* WebChucK extends the Web Audio `AudioWorkletNode` and provides an interface
* to interact with the ChucK Virtual Machine.
*
* Get started with **{@link init | init()}** to create a ChucK instance.
*/
export default class Chuck extends window.AudioWorkletNode {
private deferredPromises: DeferredPromisesMap = {};
private deferredPromiseCounter: number = 0;
private eventCallbacks: EventCallbacksMap = {};
private eventCallbackCounter: number = 0;
private isReady: DeferredPromise<void> = defer();
/** @internal */
static chuckID: number = 1;
/** @internal */
static chuginsToLoad: Filename[] = [];
private chugins: string[] = [];
/**
* Private internal constructor for a ChucK AudioWorklet Web Audio Node.
* Use public **{@link init| Init}** to create a ChucK instance.
* @param preloadedFiles Array of Files to preload into ChucK's filesystem
* @param audioContext AudioContext to connect to
* @param wasm WebChucK WebAssembly binary
* @param numOutChannels Number of output channels
* @returns ChucK AudioWorklet Node
*/
private constructor(
preloadedFiles: File[],
audioContext: AudioContext,
wasm: ArrayBuffer,
numOutChannels: number = 2,
) {
super(audioContext, "chuck-node", {
numberOfInputs: 1,
numberOfOutputs: 1,
// important: "number of inputs / outputs" is like an aggregate source
// most of the time, you only want one input source and one output
// source, but each one has multiple channels
outputChannelCount: [numOutChannels],
processorOptions: {
chuckID: Chuck.chuckID,
srate: audioContext.sampleRate,
preloadedFiles,
wasm,
},
});
this.port.onmessage = this.receiveMessage.bind(this);
this.onprocessorerror = (e) => console.error(e);
Chuck.chuckID++;
}
/**
* Initialize a ChucK AudioWorkletNode. By default, a new AudioContext is
* created and ChucK is connected to the AudioContext destination.
* **Note:** init() is overloaded to allow for a custom AudioContext,
* custom number of output channels, and custom location of `whereIsChuck`.
* Skip an argument by passing in `undefined`.
*
* @example
* ```ts
* // default initialization
* theChuck = await Chuck.init([]);
* ```
* @example
* ```ts
* // Initialize ChucK with a list of files to preload
* theChuck = await Chuck.init([{serverFilename: "./path/filename.wav", virtualFilename: "filename.wav"}...]);
* ```
*
* @example
* ```ts
* // Initialize ChucK with a local audioContext, connect ChucK to the context destination
* var audioContext = new AudioContext();
* theChuck = await Chuck.init([], audioContext));
* theChuck.connect(audioContext.destination);
* ```
*
* @example
* ```ts
* // Initialize ChucK using local webchuck.js and webchuck.wasm files in "./src"
* theChuck = await Chuck.init([], undefined, undefined, "./src");
* ```
*
* @param filenamesToPreload Array of auxiliary files to preload into ChucK's filesystem. These can be .wav files, .ck files, .etc. `[{serverFilename: "./path/filename.wav", virtualFilename: "filename.wav"}...]`
* @param audioContext Optional parameter if you want to use your own AudioContext. **Note**: If an AudioContext is passed in, you will need to connect the ChucK instance to your own destination.
* @param numOutChannels Optional custom number of output channels. Default is 2 channel stereo and the Web Audio API supports up to 32 channels.
* @param whereIsChuck Optional custom url to your WebChucK `src` folder containing `webchuck.js` and `webchuck.wasm`. By default, `whereIsChuck` is {@link https://chuck.stanford.edu/webchuck/src | here}.
* @returns WebChucK ChucK instance
*/
public static async init(
filenamesToPreload: Filename[],
audioContext?: AudioContext,
numOutChannels: number = 2,
whereIsChuck: string = "https://chuck.stanford.edu/webchuck/src/", // default Chuck src location
): Promise<Chuck> {
const wasm = await loadWasm(whereIsChuck);
let defaultAudioContext: boolean = false;
// If an audioContext is not given, create a default one
if (audioContext === undefined) {
audioContext = new AudioContext();
defaultAudioContext = true;
}
await audioContext.audioWorklet.addModule(whereIsChuck + "webchuck.js");
// Add Chugins to filenamesToPreload
filenamesToPreload = filenamesToPreload.concat(Chuck.chuginsToLoad);
const preloadedFiles = await preloadFiles(filenamesToPreload);
const chuck = new Chuck(preloadedFiles, audioContext, wasm, numOutChannels);
// Remember the chugins that were loaded
chuck.chugins = Chuck.chuginsToLoad.map((chugin) => chugin.virtualFilename.split("/").pop()!);
Chuck.chuginsToLoad = []; // clear
// Connect node to default destination if using default audio context
if (defaultAudioContext) {
chuck.connect(audioContext.destination); // default connection source
}
audioContext.destination.channelCount = numOutChannels;
await chuck.isReady.promise;
return chuck;
}
/**
* Private function for ChucK to handle execution of tasks.
* Will create a Deferred promise that wraps a task for WebChucK to execute
* @returns callbackID to a an action for ChucK to perform
*/
private nextDeferID(): number {
const callbackID = this.deferredPromiseCounter++;
this.deferredPromises[callbackID] = defer();
return callbackID;
}
// ================== Filesystem ===================== //
/**
* Create a virtual file in ChucK's filesystem.
* You should first locally {@link https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch | fetch} the contents of your file, then pass the data to this method.
* Alternatively, you can use {@link loadFile} to automatically fetch and load a file from a URL.
* @param directory Virtual directory to create file in
* @param filename Name of file to create
* @param data Data to write to the file
*/
public createFile(directory: string, filename: string, data: string | ArrayBuffer) {
this.sendMessage(OutMessage.CREATE_FILE, {
directory,
filename,
data,
});
}
/**
* Create a virtual directory in ChucK's filesystem.
* @param parent Virtual directory to create the new directory in
* @param name Name of directory to create
*/
public createDirectory(parent: string, name: string) {
this.sendMessage(OutMessage.CREATE_DIRECTORY, {
parent,
name,
});
}
/**
* Automatically fetch and load in a file from a URL to ChucK's virtual filesystem
* @example
* ```ts
* theChuck.loadFile("./myFile.ck");
* ```
* @param url path or url to a file to fetch and load file
* @returns Promise of fetch request
*/
public async loadFile(url: string): Promise<void> {
const filename = url.split("/").pop()!;
const isText: boolean = isPlaintextFile(filename);
return fetch(url)
.then((response: Promise<string> | Promise<ArrayBuffer> | any) => {
if (isText) {
return response.text();
} else {
return response.arrayBuffer();
}
})
.then((data) => {
if (isText) {
this.createFile("", filename, data as string);
} else {
this.createFile("", filename, new Uint8Array(data as ArrayBuffer));
}
})
.catch((err) => {
throw new Error(err);
});
}
// ================== WebChugins ================== //
/**
* Load a single WebChugin (.chug.wasm) via url into WebChucK.
* A list of publicly available WebChugins to load can be found in the {@link https://chuck.stanford.edu/chugins/ | webchugins} folder.
* **Note:** WebChugins must be loaded before `theChuck` is initialized.
* @param url url to webchugin to load
* @example
* ```ts
* Chuck.loadChugin("https://url/to/myChugin.chug.wasm");
* theChuck = await Chuck.init([]);
* ```
*/
public static loadChugin(url: string): void {
Chuck.chuginsToLoad.push({
serverFilename: url,
virtualFilename: "/chugins/" + url.split("/").pop()!,
});
}
/**
* Return a list of loaded WebChugins.
* @returns String array of loaded WebChugin names
*/
public loadedChugins(): string[] {
return this.chugins;
}
// ================== Run/Replace Code ================== //
/**
* Run a string of ChucK code.
* @example theChuck.runCode("SinOsc osc => dac; 1::second => now;");
* @param code ChucK code string to be executed
* @returns Promise to shred ID
*/
public runCode(code: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.RUN_CODE, { callback: callbackID, code });
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* @hidden
* Run a string of ChucK code using a different dac (unsure of functionality)
* -tf (5/30/2023)
* @param code ChucK code string to be executed
* @param dacName dac for ChucK (??)
* @returns Promise to shred ID
*/
public runCodeWithReplacementDac(code: string, dacName: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.RUN_CODE_WITH_REPLACEMENT_DAC, {
callback: callbackID,
code,
dac_name: dacName,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Replace the last currently running shred with string of ChucK code to execute.
* @example theChuck.replaceCode("SinOsc osc => dac; 1::second => now;");
* @param code ChucK code string to run and replace last shred
* @returns Promise to shred ID that is replaced
*/
public replaceCode(code: string): Promise<{ oldShred: number; newShred: number }> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REPLACE_CODE, {
callback: callbackID,
code,
});
return this.deferredPromises[callbackID].value() as Promise<{
oldShred: number;
newShred: number;
}>;
}
/**
* @hidden
* Replace last running shred with string of ChucK code to execute, to another dac (??)
* @param code ChucK code string to replace last Shred
* @param dacName dac for ChucK (??)
* @returns Promise to shred ID
*/
public replaceCodeWithReplacementDac(
code: string,
dacName: string,
): Promise<{ oldShred: number; newShred: number }> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REPLACE_CODE_WITH_REPLACEMENT_DAC, {
callback: callbackID,
code,
dac_name: dacName,
});
return this.deferredPromises[callbackID].value() as Promise<{
oldShred: number;
newShred: number;
}>;
}
/**
* Remove the last running shred from Chuck Virtual Machine.
* @returns Promise to the shred ID that was removed
*/
public removeLastCode(): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REMOVE_LAST_CODE, { callback: callbackID });
return this.deferredPromises[callbackID].value() as Promise<number>;
}
// ================== Run/Replace File ================== //
/**
* Run a ChucK file that is already loaded in the WebChucK virtual file system.
* Note that the file must already have been loaded via {@link init | filenamesToPreload}, {@link createFile}, or {@link loadFile}
*
* @example
* ```ts
* await theChuck.loadFile("./myFile.ck"); // wait for file to load
* theChuck.runFile("myFile.ck");
* ```
*
* @param filename ChucK file to be run
* @returns Promise to running shred ID
*/
public runFile(filename: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.RUN_FILE, {
callback: callbackID,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* @hidden
* Run a ChucK file that is already in the WebChucK virtual file system, on separate dac (??).
* Note that the file must already have been loaded via {@link init | filenamesToPreload}, {@link createFile}, or {@link loadFile}
* @param filename ChucK file to be run
* @param dacName dac for ChucK (??)
* @returns Promise to shred ID
*/
public runFileWithReplacementDac(filename: string, dacName: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.RUN_FILE_WITH_REPLACEMENT_DAC, {
callback: callbackID,
dac_name: dacName,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Run a ChucK file already loaded in the WebChucK virtual file system and pass in arguments.
* e.g. Thie is the chuck command line equivalent of `chuck myFile:1:2:foo`
* @example theChuck.runFileWithArgs("myFile.ck", "1:2:foo");
* @param filename ChucK file to be run
* @param colonSeparatedArgs arguments to pass to the file separated by colons
* @returns Promise to running shred ID
*/
public runFileWithArgs(filename: string, colonSeparatedArgs: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.RUN_FILE_WITH_ARGS, {
callback: callbackID,
colon_separated_args: colonSeparatedArgs,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* @hidden
* Run a ChucK file that is already in the WebChucK virtual file system with arguments.
* e.g. native equivalent of `chuck myFile:arg`
* @param filename ChucK file to be run
* @param colonSeparatedArgs arguments to pass to the file
* @param dacName dac for ChucK (??)
* @returns Promise to shred ID
*/
public runFileWithArgsWithReplacementDac(
filename: string,
colonSeparatedArgs: string,
dacName: string,
): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.RUN_FILE_WITH_ARGS, {
callback: callbackID,
colon_separated_args: colonSeparatedArgs,
dac_name: dacName,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Replace the last currently running shred with a Chuck file to execute.
* Note that the file must already have been loaded via {@link init | filenamesToPreload}, {@link createFile}, or {@link loadFile}
* @param filename file to be replace last
* @returns Promise to replaced shred ID
*/
public replaceFile(filename: string): Promise<{ oldShred: number; newShred: number }> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REPLACE_FILE, {
callback: callbackID,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<{
oldShred: number;
newShred: number;
}>;
}
/**
* @hidden
* Replace the last running shred with a file to execute.
* Note that the file must already have been loaded via {@link init | filenamesToPreload}, {@link createFile}, or {@link loadFile}
* @param filename file to be replace last
* @param dacName dac for ChucK (??)
* @returns Promise to shred ID
*/
public replaceFileWithReplacementDac(
filename: string,
dacName: string,
): Promise<{ oldShred: number; newShred: number }> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REPLACE_FILE_WITH_REPLACEMENT_DAC, {
callback: callbackID,
dac_name: dacName,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<{
oldShred: number;
newShred: number;
}>;
}
/**
* Replace the last running shred with a file to execute, passing arguments.
* Note that the file must already have been loaded via {@link init | filenamesToPreload}, {@link createFile}, or {@link loadFile}
* @param filename file to be replace last running shred
* @param colonSeparatedArgs arguments to pass in to file
* @returns Promise to shred ID
*/
public replaceFileWithArgs(
filename: string,
colonSeparatedArgs: string,
): Promise<{ oldShred: number; newShred: number }> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REPLACE_FILE_WITH_ARGS, {
callback: callbackID,
colon_separated_args: colonSeparatedArgs,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<{
oldShred: number;
newShred: number;
}>;
}
/**
* @hidden
* Replace the last running shred with a file to execute, passing arguments, and dac.
* Note that the file must already have been loaded via {@link init | filenamesToPreload}, {@link createFile}, or {@link loadFile}
* @param filename file to be replace last running shred
* @param colonSeparatedArgs arguments to pass in to file
* @param dacName dac for ChucK (??)
* @returns Promise to shred ID
*/
public replaceFileWithArgsWithReplacementDac(
filename: string,
colonSeparatedArgs: string,
dacName: string,
): Promise<{ oldShred: number; newShred: number }> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REPLACE_FILE_WITH_ARGS, {
callback: callbackID,
colon_separated_args: colonSeparatedArgs,
dac_name: dacName,
filename,
});
return this.deferredPromises[callbackID].value() as Promise<{
oldShred: number;
newShred: number;
}>;
}
// ================== Shred =================== //
/**
* Remove a shred from ChucK VM by ID
* @param shred shred ID to be removed
* @returns Promise to shred ID if removed successfully, otherwise "removing code failed"
*/
public removeShred(shred: number | string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.REMOVE_SHRED, {
shred,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Check if shred with ID is running in the Chuck Virtual Machine.
* @param shred The shred ID to check
* @returns Promise to whether shred is running, 1 if running, 0 if not
*/
public isShredActive(shred: number | string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.IS_SHRED_ACTIVE, {
shred,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
// ================== Event =================== //
/**
* Signal a ChucK event global. This will wake the first waiting Shred.
* @param variable ChucK global event variable to be signaled
*/
public signalEvent(variable: string) {
this.sendMessage(OutMessage.SIGNAL_EVENT, { variable });
}
/**
* Broadcast a ChucK event to all waiting Shreds.
* @param variable ChucK global event variable to be signaled
*/
public broadcastEvent(variable: string) {
this.sendMessage(OutMessage.BROADCAST_EVENT, { variable });
}
/**
* Listen for a specific ChucK event to be signaled (through either signal()
* or broadcast()). Once signaled, the callback function is invoked. This can
* happen at most once per call.
* @param variable ChucK global event variable to be signaled
* @param callback javascript callback function
*/
public listenForEventOnce(variable: string, callback: () => void) {
const callbackID = this.eventCallbackCounter++;
this.eventCallbacks[callbackID] = callback;
this.sendMessage(OutMessage.LISTEN_FOR_EVENT_ONCE, {
variable,
callback: callbackID,
});
}
/**
* Listen for a specific ChucK event to be signaled (through either signal()
* or broadcast()). Each time the event is signaled, the callback function is
* invoked. This continues until {@link stopListeningForEvent} is called on the
* specific event.
* @param variable ChucK global event variable to be signaled
* @param callback javascript callback function
* @returns javascript callback ID
*/
public startListeningForEvent(variable: string, callback: () => void): number {
const callbackID = this.eventCallbackCounter++;
this.eventCallbacks[callbackID] = callback;
this.sendMessage(OutMessage.START_LISTENING_FOR_EVENT, {
variable,
callback: callbackID,
});
return callbackID;
}
/**
* Stop listening to a specific ChucK event, undoing the process started
* by {@link startListeningForEvent}.
* @param variable ChucK global event variable to be signaled
* @param callbackID callback ID returned by {@link startListeningForEvent}
*/
public stopListeningForEvent(variable: string, callbackID: number) {
this.sendMessage(OutMessage.STOP_LISTENING_FOR_EVENT, {
variable,
callback: callbackID,
});
}
// ================== Int, Float, String ============= //
/**
* Set the value of a global int variable in ChucK.
* @example theChuck.setInt("MY_GLOBAL_INT", 5);
* @param variable Name of int global variable
* @param value New int value to set
*/
public setInt(variable: string, value: number) {
this.sendMessage(OutMessage.SET_INT, { variable, value });
}
/**
* Get the value of a global int variable in ChucK.
* @example const myGlobalInt = await theChuck.getInt("MY_GLOBAL_INT");
* @param variable Name of int global variable
* @returns Promise with int value of the variable
*/
public getInt(variable: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_INT, {
variable,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Set the value of a global float variable in ChucK.
* @param variable Name of float global variable
* @param value New float value to set
*/
public setFloat(variable: string, value: number) {
this.sendMessage(OutMessage.SET_FLOAT, { variable, value });
}
/**
* Get the value of a global float variable in ChucK.
* @param variable Name of float global variable
* @returns Promise with float value of the variable
*/
public getFloat(variable: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_FLOAT, {
variable,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Set the value of a global string variable in ChucK.
* @param variable Name of string global variable
* @param value New string value to set
*/
public setString(variable: string, value: string) {
this.sendMessage(OutMessage.SET_STRING, { variable, value });
}
/**
* Get the value of a global string variable in ChucK.
* @param variable Name of string global variable
* @returns Promise with string value of the variable
*/
public getString(variable: string): Promise<string> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_STRING, {
variable,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<string>;
}
// ================== Int[] =================== //
/**
* Set the values of a global int array in ChucK.
* @param variable Name of global int array variable
* @param values Array of numbers to set
*/
public setIntArray(variable: string, values: number[]) {
this.sendMessage(OutMessage.SET_INT_ARRAY, { variable, values });
}
/**
* Get the values of a global int array in ChucK.
* @param variable Name of global int array variable
* @returns Promise to array of numbers
*/
public getIntArray(variable: string): Promise<number[]> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_INT_ARRAY, {
variable,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number[]>;
}
/**
* Set a single value (by index) in a global int array in ChucK.
* @param variable Name of int array variable
* @param index Array index to set
* @param value Value to set
*/
public setIntArrayValue(variable: string, index: number, value: number[]) {
this.sendMessage(OutMessage.SET_INT_ARRAY_VALUE, {
variable,
index,
value,
});
}
/**
* Get a single value (by index) in a global int array in ChucK.
* @param variable Name of int array variable
* @param index Array index to get
* @returns Promise to the value at the index
*/
public getIntArrayValue(variable: string, index: number): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_INT_ARRAY_VALUE, {
variable,
index,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Set the value (by key) of an associative int array in ChucK.
* Note that "associative array" is ChucK's version of a dictionary with string keys mapping to values (see ChucK documentation).
* @example theChucK.setAssociativeIntArrayValue("MY_INT_ASSOCIATIVE_ARRAY", "key", 5);
* @param variable Name of global associative int array to set
* @param key The key index (string) of the associative array
* @param value The new value
*/
public setAssociativeIntArrayValue(variable: string, key: string, value: number | string) {
this.sendMessage(OutMessage.SET_ASSOCIATIVE_INT_ARRAY_VALUE, {
variable,
key,
value,
});
}
/**
* Get the value (by key) of an associative int array in ChucK.
* e.g. theChucK.getAssociateIntArrayValue("MY_INT_ASSOCIATIVE_ARRAY", "key");
* @param variable Name of gobal associative int arry
* @param key The key index (string) to get
* @returns Promise with int array value
*/
public getAssociativeIntArrayValue(variable: string, key: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_ASSOCIATIVE_INT_ARRAY_VALUE, {
variable,
key,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
// ================== Float[] =================== //
/**
* Set the values of a global float array in ChucK.
* @param variable Name of global float array
* @param values Values to set
*/
public setFloatArray(variable: string, values: number[]) {
this.sendMessage(OutMessage.SET_FLOAT_ARRAY, { variable, values });
}
/**
* Get the values of a global float array in ChucK.
* @example theChucK.getFloatArray("MY_FLOAT_ARRAY");
* @param variable Name of float array
* @returns Promise of float values
*/
public getFloatArray(variable: string): Promise<number[]> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_FLOAT_ARRAY, {
variable,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number[]>;
}
/**
* Set the float value of a global float array at particular index.
* @param variable Name of global float array
* @param index Index of element
* @param value Value to set
*/
public setFloatArrayValue(variable: string, index: number, value: number) {
this.sendMessage(OutMessage.SET_FLOAT_ARRAY_VALUE, {
variable,
index,
value,
});
}
/**
* Get the float value of a global float arry at a particular index.
* @example theChucK.getFloatArray("MY_FLOAT_ARRAY", 1);
* @param variable Name of global float array
* @param index Index of element
* @returns Promise of float value at index
*/
public getFloatArrayValue(variable: string, index: number): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_FLOAT_ARRAY_VALUE, {
variable,
index,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Set the value (by key) of an associative float array in ChucK.
* Note that "associative array" is ChucK's version of a dictionary with string keys mapping to values (see ChucK documentation).
* @example theChucK.setAssociateFloatArrayValue("MY_FLOAT_ASSOCIATIVE_ARRAY", "key", 5);
* @param variable Name of global associative float array to set
* @param key The key index (string) of the associative array
* @param value Float value to set
*/
public setAssociativeFloatArrayValue(variable: string, key: string, value: number) {
this.sendMessage(OutMessage.SET_ASSOCIATIVE_FLOAT_ARRAY_VALUE, {
variable,
key,
value,
});
}
/**
* Get the value (by key) of an associative float array in ChucK.
* @example theChucK.getAssociateFloatArrayValue("MY_FLOAT_ASSOCIATIVE_ARRAY", "key");
* @param variable Name of gobal associative float array
* @param key The key index (string) to get
* @returns Promise with float array value
*/
public getAssociativeFloatArrayValue(variable: string, key: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_ASSOCIATIVE_FLOAT_ARRAY_VALUE, {
variable,
key,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
// ================== ChucK VM parameters =================== //
/**
* Set an internal ChucK VM integer parameter.
* e.g. "SAMPLE_RATE", "INPUT_CHANNELS", "OUTPUT_CHANNELS", "IS_REAL_TIME_AUDIO_HINT", "TTY_COLOR".
* @param name Name of VM int parameter to set
* @param value Value to set
*/
public setParamInt(name: string, value: number) {
this.sendMessage(OutMessage.SET_PARAM_INT, { name, value });
}
/**
* Get an internal ChucK VM integer parameter.
* e.g. "SAMPLE_RATE", "INPUT_CHANNELS", "OUTPUT_CHANNELS", "BUFFER_SIZE", "IS_REAL_TIME_AUDIO_HINT".
* @param name Name of VM int parameter to get
* @returns Promise with int value
*/
public getParamInt(name: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_PARAM_INT, {
name,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Set an internal ChucK VM float parameter.
* @param name Name of VM float parameter to set
* @param value Value to set
*/
public setParamFloat(name: string, value: number) {
this.sendMessage(OutMessage.SET_PARAM_FLOAT, { name, value });
}
/**
* Get an internal ChucK VM float parameter.
* @param name Name of VM float parameter to get
* @returns Promise with float value
*/
public getParamFloat(name: string): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_PARAM_FLOAT, {
name,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<number>;
}
/**
* Set an internal ChucK VM string parameter.
* @param name Name of VM string parameter to set
* @param value Value to set
*/
public setParamString(name: string, value: string) {
this.sendMessage(OutMessage.SET_PARAM_STRING, { name, value });
}
/**
* Get an internal ChucK VM string parameter.
* e.g. "VERSION".
* @param name Name of VM string parameter to get
* @returns Promise with string value
*/
public getParamString(name: string): Promise<string> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_PARAM_STRING, {
name,
callback: callbackID,
});
return this.deferredPromises[callbackID].value() as Promise<string>;
}
// ================== ChucK VM =================== //
/**
* Get the current time in samples of the ChucK VM.
* @returns Promise to current sample time in ChucK (int)
*/
public now(): Promise<number> {
const callbackID = this.nextDeferID();
this.sendMessage(OutMessage.GET_CHUCK_NOW, { callback: callbackID });
return this.deferredPromises[callbackID].value() as Promise<number>;
}
// ================= Clear ====================== //
/**
* Remove all shreds and reset the ChucK instance.
*/
public clearChuckInstance() {
this.sendMessage(OutMessage.CLEAR_INSTANCE);
}
/**
* Reset all global variables in ChucK.
*/
public clearGlobals() {
this.sendMessage(OutMessage.CLEAR_GLOBALS);
}
// ================== Print Output ================== //
/**
* Callback function for Chuck to print a message string to console.
* Override this method to redirect where ChucK console output goes. By default, Chuck prints to `console.log()`.
* Set your own method to display ChucK output or even use ChucK output as a message passing system.
* @example
* ```ts
* // Override the default print method with our own callback print method
* theChuck.chuckPrint = (message) => { console.log("ChucK says: " + message); }
*
* // Now when ChucK prints, it will print to our callback method
* theChuck.runCode(`<<< "Hello World!", "" >>>`);
*
* // Output: "ChucK says: Hello World!"
* ```
* @param message Message that ChucK will print to console
*/
public chuckPrint(message: string) {
// Default ChucK output destination
console.log(message);
}
//--------------------------------------------------------
// Internal Message Sending Communication
//--------------------------------------------------------
/**
* @hidden
* Internal: Message sending from JS to ChucK
*/
private sendMessage(type: OutMessage, body?: { [prop: string]: unknown }) {
const msgBody = body ? { type, ...body } : { type };
this.port.postMessage(msgBody);
}
/**
* @hidden
* Internal: Message receiving from ChucK to JS
*/
private receiveMessage(event: MessageEvent) {
const type: InMessage = event.data.type;
switch (type) {
case InMessage.INIT_DONE:
if (this.isReady && this.isReady.resolve) {
this.isReady.resolve();
}
break;
case InMessage.PRINT:
this.chuckPrint(event.data.message);
break;
case InMessage.EVENT:
if (event.data.callback in this.eventCallbacks) {
const callback = this.eventCallbacks[event.data.callback];
callback();
}
break;
case InMessage.INT:
case InMessage.FLOAT: