Debian Codegraph @

src/host-web/chucknode-postjs.js

raw symbols SCIP
1 //-----------------------------------------------------------------------------
2 // name: chucknode-post.js
3 // desc: emscripten binding agent for web assembly compilation / js code
4 //
5 // author: Jack Atherton
6 // date: created 4/19/17
7 //-------------------------- wasm-audio-helper.js -----------------------------
8 /**
9 * Copyright 2018 Google LLC
10 *
11 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
12 * use this file except in compliance with the License. You may obtain a copy of
13 * the License at
14 *
15 * http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
19 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
20 * License for the specific language governing permissions and limitations under
21 * the License.
22 */
23 //-----------------------------------------------------------------------------
24
25 // Basic byte unit of WASM heap. (16 bit = 2 bytes)
26 const BYTES_PER_UNIT = Uint16Array.BYTES_PER_ELEMENT;
27
28 // Byte per audio sample. (32 bit float)
29 const BYTES_PER_SAMPLE = Float32Array.BYTES_PER_ELEMENT;
30
31 // The max audio channel on Chrome is 32.
32 const MAX_CHANNEL_COUNT = 32;
33
34 // WebAudio's render quantum size.
35 const RENDER_QUANTUM_FRAMES = 128;
36
37
38 /**
39 * A WASM HEAP wrapper for AudioBuffer class. This breaks down the AudioBuffer
40 * into an Array of Float32Array for the convinient WASM opearion.
41 *
42 * @class
43 * @dependency Module A WASM module generated by the emscripten glue code.
44 */
45 class HeapAudioBuffer {
46 /**
47 * @constructor
48 * @param {object} wasmModule WASM module generated by Emscripten.
49 * @param {number} length Buffer frame length.
50 * @param {number} channelCount Number of channels.
51 * @param {number=} maxChannelCount Maximum number of channels.
52 */
53 constructor(wasmModule, length, channelCount, maxChannelCount) {
54 // The |channelCount| must be greater than 0, and less than or equal to
55 // the maximum channel count.
56 this._isInitialized = false;
57 this._module = wasmModule;
58 this._length = length;
59 this._maxChannelCount = maxChannelCount
60 ? Math.min(maxChannelCount, MAX_CHANNEL_COUNT)
61 : channelCount;
62 this._channelCount = channelCount;
63 this._allocateHeap();
64 this._isInitialized = true;
65 }
66
67 /**
68 * Allocates memory in the WASM heap and set up Float32Array views for the
69 * channel data.
70 *
71 * @private
72 */
73 _allocateHeap() {
74 const channelByteSize = this._length * BYTES_PER_SAMPLE;
75 const dataByteSize = this._channelCount * channelByteSize;
76 this._dataPtr = this._module._malloc(dataByteSize);
77 this._channelData = [];
78 for (let i = 0; i < this._channelCount; ++i) {
79 let startByteOffset = this._dataPtr + i * channelByteSize;
80 let endByteOffset = startByteOffset + channelByteSize;
81 // Get the actual array index by dividing the byte offset by 2 bytes.
82 this._channelData[i] =
83 this._module.HEAPF32.subarray(startByteOffset >> BYTES_PER_UNIT,
84 endByteOffset >> BYTES_PER_UNIT);
85 }
86 }
87
88 /**
89 * Adapt the current channel count to the new input buffer.
90 *
91 * @param {number} newChannelCount The new channel count.
92 */
93 adaptChannel(newChannelCount) {
94 if (newChannelCount < this._maxChannelCount) {
95 this._channelCount = newChannelCount;
96 }
97 // reform subArrays just in case memory has grown since we last did this
98 const channelByteSize = this._length * BYTES_PER_SAMPLE;
99 for (let i = 0; i < this._channelCount; ++i)
100 {
101 let startByteOffset = this._dataPtr + i * channelByteSize;
102 let endByteOffset = startByteOffset + channelByteSize;
103 // Get the actual array index by dividing the byte offset by 2 bytes.
104 this._channelData[i] =
105 this._module.HEAPF32.subarray(startByteOffset >> BYTES_PER_UNIT,
106 endByteOffset >> BYTES_PER_UNIT);
107 }
108 }
109
110 /**
111 * Getter for the buffer length in frames.
112 *
113 * @return {?number} Buffer length in frames.
114 */
115 get length() {
116 return this._isInitialized ? this._length : null;
117 }
118
119 /**
120 * Getter for the number of channels.
121 *
122 * @return {?number} Buffer length in frames.
123 */
124 get numberOfChannels() {
125 return this._isInitialized ? this._channelCount : null;
126 }
127
128 /**
129 * Getter for the maxixmum number of channels allowed for the instance.
130 *
131 * @return {?number} Buffer length in frames.
132 */
133 get maxChannelCount() {
134 return this._isInitialized ? this._maxChannelCount : null;
135 }
136
137 /**
138 * Returns a Float32Array object for a given channel index. If the channel
139 * index is undefined, it returns the reference to the entire array of channel
140 * data.
141 *
142 * @param {number|undefined} channelIndex Channel index.
143 * @return {?Array} a channel data array or an
144 * array of channel data.
145 */
146 getChannelData(channelIndex) {
147 if (channelIndex >= this._channelCount) {
148 return null;
149 }
150 return typeof channelIndex === 'undefined'
151 ? this._channelData : this._channelData[channelIndex];
152 }
153
154 /**
155 * Returns the base address of the allocated memory space in the WASM heap.
156 *
157 * @return {number} WASM Heap address.
158 */
159 getHeapAddress() {
160 return this._dataPtr;
161 }
162
163 /**
164 * Frees the allocated memory space in the WASM heap.
165 */
166 free() {
167 this._isInitialized = false;
168 this._module._free(this._dataPtr);
169 this._module._free(this._pointerArrayPtr);
170 this._channelData = null;
171 }
172 } // class HeapAudioBuffer
173
174
175 /**
176 * A JS FIFO implementation for the AudioWorklet. 3 assumptions for the
177 * simpler operation:
178 * 1. the push and the pull operation are done by 128 frames. (Web Audio
179 * API's render quantum size in the speficiation)
180 * 2. the channel count of input/output cannot be changed dynamically.
181 * The AudioWorkletNode should be configured with the `.channelCount = k`
182 * (where k is the channel count you want) and
183 * `.channelCountMode = explicit`.
184 * 3. This is for the single-thread operation. (obviously)
185 *
186 * @class
187 */
188 class RingBuffer {
189 /**
190 * @constructor
191 * @param {number} length Buffer length in frames.
192 * @param {number} channelCount Buffer channel count.
193 */
194 constructor(length, channelCount) {
195 this._readIndex = 0;
196 this._writeIndex = 0;
197 this._framesAvailable = 0;
198
199 this._channelCount = channelCount;
200 this._length = length;
201 this._channelData = [];
202 for (let i = 0; i < this._channelCount; ++i) {
203 this._channelData[i] = new Float32Array(length);
204 }
205 }
206
207 /**
208 * Getter for Available frames in buffer.
209 *
210 * @return {number} Available frames in buffer.
211 */
212 get framesAvailable() {
213 return this._framesAvailable;
214 }
215
216 /**
217 * Push a sequence of Float32Arrays to buffer.
218 *
219 * @param {array} arraySequence A sequence of Float32Arrays.
220 */
221 push(arraySequence) {
222 // The channel count of arraySequence and the length of each channel must
223 // match with this buffer obejct.
224
225 // Transfer data from the |arraySequence| storage to the internal buffer.
226 let sourceLength = arraySequence[0].length;
227 for (let i = 0; i < sourceLength; ++i) {
228 let writeIndex = (this._writeIndex + i) % this._length;
229 for (let channel = 0; channel < this._channelCount; ++channel) {
230 this._channelData[channel][writeIndex] = arraySequence[channel][i];
231 }
232 }
233
234 this._writeIndex += sourceLength;
235 if (this._writeIndex >= this._length) {
236 this._writeIndex = 0;
237 }
238
239 // For excessive frames, the buffer will be overwritten.
240 this._framesAvailable += sourceLength;
241 if (this._framesAvailable > this._length) {
242 this._framesAvailable = this._length;
243 }
244 }
245
246 /**
247 * Pull data out of buffer and fill a given sequence of Float32Arrays.
248 *
249 * @param {array} arraySequence An array of Float32Arrays.
250 */
251 pull(arraySequence) {
252 // The channel count of arraySequence and the length of each channel must
253 // match with this buffer obejct.
254
255 // If the FIFO is completely empty, do nothing.
256 if (this._framesAvailable === 0) {
257 return;
258 }
259
260 let destinationLength = arraySequence[0].length;
261
262 // Transfer data from the internal buffer to the |arraySequence| storage.
263 for (let i = 0; i < destinationLength; ++i) {
264 let readIndex = (this._readIndex + i) % this._length;
265 for (let channel = 0; channel < this._channelCount; ++channel) {
266 arraySequence[channel][i] = this._channelData[channel][readIndex];
267 }
268 }
269
270 this._readIndex += destinationLength;
271 if (this._readIndex >= this._length) {
272 this._readIndex = 0;
273 }
274
275 this._framesAvailable -= destinationLength;
276 if (this._framesAvailable < 0) {
277 this._framesAvailable = 0;
278 }
279 }
280 } // class RingBuffer
281
282 // ------------------------------------------------------------------------ //
283 // ------------------------------------------------------------------------ //
284 // ------------------------------------------------------------------------ //
285 // ------------------------------------------------------------------------ //
286
287
288
289
290 // ------------------------------------------------------------------------ //
291 // ------------------------------------------------------------------------ //
292 // ------------------------------------------------------------------------ //
293 // ------------------------------------------------------------------------ //
294 // --------------------------- chucknode.js ------------------------------- //
295
296 var globalInit = false;
297 var globalPromise = undefined;
298 var chucks = {};
299
300 var setDataDir, setLogLevel, initChuckInstance, clearChuckInstance,
301 clearGlobals, cleanupChuckInstance, cleanRegisteredChucks,
302
303 runChuckCode, runChuckCodeWithReplacementDac, runChuckFile,
304 runChuckFileWithReplacementDac, runChuckFileWithArgs,
305 runChuckFileWithArgsWithReplacementDac,
306
307 replaceChuckCode, replaceChuckCodeWithReplacementDac,
308 replaceChuckFile, replaceChuckFileWithReplacementDac,
309 replaceChuckFileWithArgs, replaceChuckFileWithArgsWithReplacementDac,
310
311 isShredActive,
312 removeShred,
313
314 // don't care about these because emscripten has another mechanism
315 // for rerouting print statements
316 // setChoutCallback =
317 // setCherrCallback =
318 // setStdoutCallback =
319 // setStderrCallback =
320
321 // set/get global int, float, string
322 setChuckInt, getChuckInt, setChuckFloat, getChuckFloat,
323 setChuckString, getChuckString,
324
325 // global Events
326 signalChuckEvent, broadcastChuckEvent, listenForChuckEventOnce,
327 startListeningForChuckEvent, stopListeningForChuckEvent,
328
329 // note: array is SAMPLE == Float32
330 // NOTE ALSO anything using arrays cannot use cwrap; use in similar manner to Module._chuckManualAudioCallback
331 // TODO
332 // getGlobalUGenSamples = Module.cwrap( 'getGlobalUGenSamples', 'number', ['number', 'string', 'array', 'number'] );
333
334 // set/get global int arrays
335 // note: anything using arrays cannot use cwrap (since 'array' is an Int64Array)
336 // called manually with heap manipulation below
337 // setGlobalIntArray = Module.cwrap( 'setGlobalIntArray', 'number', ['number', 'string', 'array', 'number'] );
338 getGlobalIntArray, setGlobalIntArrayValue, getGlobalIntArrayValue,
339 setGlobalAssociativeIntArrayValue, getGlobalAssociativeIntArrayValue,
340
341 // set/get global float arrays
342 // note: anything using arrays cannot use cwrap. called manually with heap manipulation below
343 // setGlobalFloatArray = Module.cwrap( 'setGlobalFloatArray', 'number', ['number', 'string', 'array', 'number'] );
344 getGlobalFloatArray, setGlobalFloatArrayValue, getGlobalFloatArrayValue,
345 setGlobalAssociativeFloatArrayValue, getGlobalAssociativeFloatArrayValue,
346
347 // set chuck VM parameters (do not confuse these with chuck globals)
348 // 1.5.0.8 (ge) added | see core/chuck.h for parameters names
349 setParamInt, setParamFloat, setParamString,
350 getParamInt, getParamFloat, getParamString,
351
352 // get current time | 1.5.0.8 (ge) added
353 getChuckNow;
354
355
356 var initGlobals = function( Module )
357 {
358 // metaproperties (e.g. setDataDir must be called before init_chuck
359 setDataDir = Module.cwrap( 'setDataDir', 'number', ['string'] );
360 setLogLevel = Module.cwrap( 'setLogLevel', 'number', ['number'] );
361
362 // initialize a VM
363 initChuckInstance = Module.cwrap( 'initChuckInstance', 'number', ['number', 'number', 'number', 'number'] );
364
365 // cleanup
366 clearChuckInstance = Module.cwrap( 'clearChuckInstance', 'number', ['number'] );
367 clearGlobals = Module.cwrap( 'clearGlobals', 'number', ['number'] );
368 cleanupChuckInstance = Module.cwrap( 'cleanupChuckInstance', 'number', ['number'] );
369 cleanRegisteredChucks = Module.cwrap( 'cleanRegisteredChucks', null );
370
371 // running code
372 runChuckCode = Module.cwrap( 'runChuckCode', 'number', ['number', 'string'] );
373 runChuckCodeWithReplacementDac = Module.cwrap( 'runChuckCodeWithReplacementDac', 'number', ['number', 'string', 'string'] );
374 runChuckFile = Module.cwrap( 'runChuckFile', 'number', ['number', 'string'] );
375 runChuckFileWithReplacementDac = Module.cwrap( 'runChuckFileWithReplacementDac', 'number', ['number', 'string', 'string'] );
376 runChuckFileWithArgs = Module.cwrap( 'runChuckFileWithArgs', 'number', ['number', 'string', 'string'] );
377 runChuckFileWithArgsWithReplacementDac = Module.cwrap( 'runChuckFileWithArgsWithReplacementDac', 'number', ['number', 'string', 'string', 'string'] );
378
379 replaceChuckCode = Module.cwrap( 'replaceChuckCode', 'number', ['number', 'number', 'string'] );
380 replaceChuckCodeWithReplacementDac = Module.cwrap( 'replaceChuckCodeWithReplacementDac', 'number', ['number', 'number', 'string', 'string'] );
381 replaceChuckFile = Module.cwrap( 'replaceChuckFile', 'number', ['number', 'number', 'string'] );
382 replaceChuckFileWithReplacementDac = Module.cwrap( 'replaceChuckFileWithReplacementDac', 'number', ['number', 'number', 'string', 'string'] );
383 replaceChuckFileWithArgs = Module.cwrap( 'replaceChuckFileWithArgs', 'number', ['number', 'number', 'string', 'string'] );
384 replaceChuckFileWithArgsWithReplacementDac = Module.cwrap( 'replaceChuckFileWithArgsWithReplacementDac', 'number', ['number', 'number', 'string', 'string', 'string'] );
385
386
387 isShredActive = Module.cwrap( 'isShredActive', 'number', ['number', 'number'] );
388 removeShred = Module.cwrap( 'removeShred', 'number', ['number', 'number'] );
389
390 // don't care about these because emscripten has another mechanism
391 // for rerouting print statements
392 // setChoutCallback =
393 // setCherrCallback =
394 // setStdoutCallback =
395 // setStderrCallback =
396
397 // set/get global int, float, string
398 setChuckInt = Module.cwrap( 'setChuckInt', 'number', ['number', 'string', 'number'] );
399 getChuckInt = Module.cwrap( 'getChuckInt', 'number', ['number', 'string'] );
400 setChuckFloat = Module.cwrap( 'setChuckFloat', 'number', ['number', 'string', 'number'] );
401 getChuckFloat = Module.cwrap( 'getChuckFloat', 'number', ['number', 'string'] );
402 setChuckString = Module.cwrap( 'setChuckString', 'number', ['number', 'string', 'string'] );
403 getChuckString = Module.cwrap( 'getChuckString', 'number', ['number', 'string', 'number'] );
404
405 // global Events
406 signalChuckEvent = Module.cwrap( 'signalChuckEvent', 'number', ['number', 'string'] );
407 broadcastChuckEvent = Module.cwrap( 'broadcastChuckEvent', 'number', ['number', 'string'] );
408 listenForChuckEventOnce = Module.cwrap( 'listenForChuckEventOnce', 'number', ['number', 'string', 'number'] );
409 startListeningForChuckEvent = Module.cwrap( 'startListeningForChuckEvent', 'number', ['number', 'string', 'number']);
410 stopListeningForChuckEvent = Module.cwrap( 'stopListeningForChuckEvent', 'number', ['number', 'string', 'number']);
411
412 // note: array is SAMPLE == Float32
413 // NOTE ALSO anything using arrays cannot use cwrap; use in similar manner to Module._chuckManualAudioCallback
414 // TODO
415 // getGlobalUGenSamples = Module.cwrap( 'getGlobalUGenSamples', 'number', ['number', 'string', 'array', 'number'] );
416
417 // set/get global int arrays
418 // note: anything using arrays cannot use cwrap (since 'array' is an Int64Array)
419 // called manually with heap manipulation below
420 // setGlobalIntArray = Module.cwrap( 'setGlobalIntArray', 'number', ['number', 'string', 'array', 'number'] );
421 getGlobalIntArray = Module.cwrap( 'getGlobalIntArray', 'number', ['number', 'string', 'number'] );
422 setGlobalIntArrayValue = Module.cwrap( 'setGlobalIntArrayValue', 'number', ['number', 'string', 'number', 'number'] );
423 getGlobalIntArrayValue = Module.cwrap( 'getGlobalIntArrayValue', 'number', ['number', 'string', 'number'] );
424 setGlobalAssociativeIntArrayValue = Module.cwrap( 'setGlobalAssociativeIntArrayValue', 'number', ['number', 'string', 'string', 'number'] );
425 getGlobalAssociativeIntArrayValue = Module.cwrap( 'getGlobalAssociativeIntArrayValue', 'number', ['number', 'string', 'string'] );
426
427 // set/get global float arrays
428 // note: anything using arrays cannot use cwrap. called manually with heap manipulation below
429 // setGlobalFloatArray = Module.cwrap( 'setGlobalFloatArray', 'number', ['number', 'string', 'array', 'number'] );
430 getGlobalFloatArray = Module.cwrap( 'getGlobalFloatArray', 'number', ['number', 'string', 'number'] );
431 setGlobalFloatArrayValue = Module.cwrap( 'setGlobalFloatArrayValue', 'number', ['number', 'string', 'number', 'number'] );
432 getGlobalFloatArrayValue = Module.cwrap( 'getGlobalFloatArrayValue', 'number', ['number', 'string', 'number'] );
433 setGlobalAssociativeFloatArrayValue = Module.cwrap( 'setGlobalAssociativeFloatArrayValue', 'number', ['number', 'string', 'string', 'number'] );
434 getGlobalAssociativeFloatArrayValue = Module.cwrap( 'getGlobalAssociativeFloatArrayValue', 'number', ['number', 'string', 'string'] );
435
436 // set and get VM params | 1.5.0.8 (ge) added
437 setParamInt = Module.cwrap( 'setParamInt', 'number', ['number', 'string', 'number'] );
438 setParamFloat = Module.cwrap( 'setParamFloat', 'number', ['number', 'string', 'number'] );
439 setParamString = Module.cwrap( 'setParamString', 'number', ['number', 'string', 'string'] );
440 getParamInt = Module.cwrap( 'getParamInt', 'number', ['number', 'string'] );
441 getParamFloat = Module.cwrap( 'getParamFloat', 'number', ['number', 'string'] );
442 getParamString = Module.cwrap( 'getParamString', 'string', ['number', 'string'] );
443
444 // get current time | 1.5.0.8
445 getChuckNow = Module.cwrap( 'getChuckNow', 'number', ['number'] );
446
447 // set data dir to "/" for embedded files
448 setDataDir( "/" );
449 }
450
451 class ChuckNode extends AudioWorkletProcessor
452 {
453 constructor( options )
454 {
455 super();
456
457 // Extract constructor options
458 this.srate = options.processorOptions.srate;
459 this.inChannels = options.outputChannelCount[0];
460 this.outChannels = options.outputChannelCount[0];
461 this.myID = options.processorOptions.chuckID;
462
463 chucks[this.myID] = this;
464
465 // Set up a message handler to respond to incoming messages
466 this.port.onmessage = this.handle_message.bind(this);
467
468 // Initialize properties for this ChuckNode instance
469 this.myPointers = {}
470 this.myActiveShreds = [];
471 this.haveInit = false;
472
473 // Initialize the Chuck AudioWorkletProcessor
474 this.init( options.processorOptions.preloadedFiles,
475 options.processorOptions.wasm );
476 }
477
478 /**
479 * Initialize the Chuck as an AudioWorkletProcessor.
480 */
481 init( preloadedFiles, wasm )
482 {
483 if( !globalInit )
484 {
485 var PreModule = {
486 wasmBinary: wasm,
487 print: (function( self )
488 {
489 return function( text )
490 {
491 self.port.postMessage( { type: "console print", message: text } );
492 }
493 })( this ),
494 printErr: (function( self )
495 {
496 return function( text )
497 {
498 self.port.postMessage( { type: "console print", message: text } );
499 }
500 })( this ),
501 // don't try to decode audio files; I'm really truly trying to copy the binaries only I promise
502 noAudioDecoding: true,
503 // don't try to decode images either, just so it will stop printing warnings it can't do it
504 noImageDecoding: true
505 };
506
507 PreModule[ "preRun" ] = [
508 (function( filesToPreload, Module )
509 {
510 return function()
511 {
512 // Create directories required to load filesToPreload
513 const dirs = filesToPreload.map((f) => {
514 const path = f.filename.split("/");
515 return path.slice(0, path.length - 1);
516 });
517
518 dirs.forEach((dir) =>
519 dir.reduce((parent, name) => {
520 Module["FS_createPath"](parent, name, true, true);
521 return parent + "/" + name;
522 }, '/')
523 );
524
525 // Preload files into the file system
526 for( var i = 0; i < filesToPreload.length; i++ )
527 {
528 Module["FS_createPreloadedFile"]( "/",
529 filesToPreload[i].filename,
530 filesToPreload[i].data, true, true );
531 }
532 }
533 })( preloadedFiles, PreModule )
534 ]
535
536 globalPromise = ChucK( PreModule );
537 globalInit = true;
538 }
539 globalPromise.then( (function( self )
540 {
541 return function( Module )
542 {
543 self.Module = Module;
544
545 initGlobals( Module );
546
547 // Allocate the buffer for the heap access. Start with stereo, but it can
548 // be expanded up to 32 channels.
549 self._heapInputBuffer = new HeapAudioBuffer(Module, RENDER_QUANTUM_FRAMES,
550 self.inChannels, MAX_CHANNEL_COUNT);
551 self._heapOutputBuffer = new HeapAudioBuffer(Module, RENDER_QUANTUM_FRAMES,
552 self.outChannels, MAX_CHANNEL_COUNT);
553
554 // log
555 //setLogLevel( 3 );
556
557 // initialize chuck instance
558 // FYI this invokes `new ChucK()` + instance initialization on the C++ side
559 initChuckInstance( self.myID, self.srate, self.inChannels, self.outChannels );
560
561 // flag
562 self.haveInit = true;
563
564 // invoke init callback
565 self.port.postMessage( { type: 'initCallback' } );
566 }
567 })( this ) );
568 }
569
570 handleNewShredID( newShredID, shredCallback )
571 {
572 if( newShredID > 0 )
573 {
574 // keep track for myself
575 this.myActiveShreds.push( newShredID );
576 }
577 else
578 {
579 // compilation failed
580 }
581 // tell the host
582 this.port.postMessage( {
583 type: "newShredCallback",
584 callback: shredCallback,
585 shred: newShredID
586 } );
587 }
588
589 handleReplacedShredID( oldShredID, newShredID, shredCallback )
590 {
591 if( newShredID > 0 )
592 {
593 // keep track for myself
594 this.myActiveShreds.push( newShredID );
595 }
596 else
597 {
598 // compilation failed --> we did not actually remove oldShredID
599 this.myActiveShreds.push( oldShredID );
600 }
601 // tell the host
602 this.port.postMessage( {
603 type: "replacedShredCallback",
604 callback: shredCallback,
605 newShred: newShredID,
606 oldShred: oldShredID
607 } );
608 }
609
610 handleRemoveShred( shredID, callback )
611 {
612 if( removeShred( this.myID, shredID ) )
613 {
614 this.handleRemovedShredID( shredID, callback );
615 }
616 else
617 {
618 this.handleRemovedShredID( 0, callback );
619 }
620 }
621
622 handleRemovedShredID( shredID, shredCallback )
623 {
624 this.port.postMessage( {
625 type: "removedShredCallback",
626 callback: shredCallback,
627 shred: shredID
628 } );
629 }
630
631 findMostRecentActiveShred()
632 {
633 // find the most recent shred that is still active,
634 // and forget about all the more recently shredded ones
635 // that are no longer active
636 var shredID = this.myActiveShreds.pop();
637 while( shredID && !isShredActive( this.myID, shredID ) )
638 {
639 shredID = this.myActiveShreds.pop();
640 }
641 return shredID;
642 }
643
644 findShredToReplace()
645 {
646 var shredToReplace = this.findMostRecentActiveShred();
647 if( !shredToReplace )
648 {
649 this.port.postMessage( {
650 type: "console print",
651 message: "[chuck](VM): no shreds to replace..."
652 } );
653 }
654 return shredToReplace;
655 }
656
657 handle_message( event )
658 {
659 switch( event.data.type )
660 {
661 // ================== Filesystem ===================== //
662 case 'createFile':
663 this.Module.FS_createDataFile( '/' + event.data.directory,
664 event.data.filename, event.data.data, true, true, true );
665 break;
666 case 'createDirectory':
667 this.Module.FS_createPath( '/' + event.data.parent,
668 event.data.name, true, true );
669 break;
670 // ================== Run / Compile ================== //
671 case 'runChuckCode':
672 var shredID = runChuckCode( this.myID, event.data.code );
673 this.handleNewShredID( shredID, event.data.callback );
674 break;
675 case 'runChuckCodeWithReplacementDac':
676 var shredID = runChuckCodeWithReplacementDac( this.myID, event.data.code, event.data.dac_name );
677 this.handleNewShredID( shredID, event.data.callback );
678 break;
679 case 'runChuckFile':
680 var shredID = runChuckFile( this.myID, event.data.filename );
681 this.handleNewShredID( shredID, event.data.callback );
682 break;
683 case 'runChuckFileWithReplacementDac':
684 var shredID = runChuckFileWithReplacementDac( this.myID, event.data.filename, event.data.dac_name );
685 this.handleNewShredID( shredID, event.data.callback );
686 break;
687 case 'runChuckFileWithArgs':
688 var shredID = runChuckFileWithArgs( this.myID, event.data.filename, event.data.colon_separated_args );
689 this.handleNewShredID( shredID, event.data.callback );
690 break;
691 case 'runChuckFileWithArgsWithReplacementDac':
692 var shredID = runChuckFileWithArgsWithReplacementDac( this.myID, event.data.filename, event.data.colon_separated_args, event.data.dac_name );
693 this.handleNewShredID( shredID, event.data.callback );
694 break;
695 case 'replaceChuckCode':
696 var shredToReplace = this.findShredToReplace();
697 if( shredToReplace )
698 {
699 var shredID = replaceChuckCode( this.myID, shredToReplace, event.data.code );
700 this.handleReplacedShredID( shredToReplace, shredID, event.data.callback );
701 }
702 break;
703 case 'replaceChuckCodeWithReplacementDac':
704 var shredToReplace = this.findShredToReplace();
705 if( shredToReplace )
706 {
707 var shredID = replaceChuckCodeWithReplacementDac( this.myID, shredToReplace, event.data.code, event.data.dac_name );
708 this.handleReplacedShredID( shredToReplace, shredID, event.data.callback );
709 }
710 break;
711 case 'replaceChuckFile':
712 var shredToReplace = this.findShredToReplace();
713 if( shredToReplace )
714 {
715 var shredID = replaceChuckFile( this.myID, shredToReplace, event.data.filename );
716 this.handleReplacedShredID( shredToReplace, shredID, event.data.callback );
717 }
718 break;
719 case 'replaceChuckFileWithReplacementDac':
720 var shredToReplace = this.findShredToReplace();
721 if( shredToReplace )
722 {
723 var shredID = replaceChuckFileWithReplacementDac( this.myID, shredToReplace, event.data.filename, event.data.dac_name );
724 this.handleReplacedShredID( shredToReplace, shredID, event.data.callback );
725 }
726 break;
727 case 'replaceChuckFileWithArgs':
728 var shredToReplace = this.findShredToReplace();
729 if( shredToReplace )
730 {
731 var shredID = replaceChuckFileWithArgs( this.myID, shredToReplace, event.data.filename, event.data.colon_separated_args );
732 this.handleReplacedShredID( shredToReplace, shredID, event.data.callback );
733 }
734 break;
735 case 'replaceChuckFileWithArgsWithReplacementDac':
736 var shredToReplace = this.findShredToReplace();
737 if( shredToReplace )
738 {
739 var shredID = replaceChuckFileWithArgsWithReplacementDac( this.myID, shredToReplace, event.data.filename, event.data.colon_separated_args, event.data.dac_name );
740 this.handleReplacedShredID( shredToReplace, shredID, event.data.callback );
741 }
742 break;
743 case 'removeLastCode':
744 var shredID = this.findMostRecentActiveShred();
745 // if we found a shred, remove it, otherwise,
746 // there are no shreds left to remove
747 if( shredID )
748 {
749 this.handleRemoveShred( shredID, event.data.callback );
750 }
751 else
752 {
753 this.port.postMessage( {
754 type: "console print",
755 message: "[chuck](VM): no shreds to remove..."
756 } );
757 }
758 break;
759 case 'removeShred':
760 this.handleRemoveShred( event.data.shred, event.data.callback );
761 break;
762 case 'isShredActive':
763 this.port.postMessage({
764 type: "intCallback",
765 callback: event.data.callback,
766 result: isShredActive( this.myID, event.data.shred )
767 });
768 break;
769 // ================== Int, Float, String ============= //
770 case 'setChuckInt':
771 setChuckInt( this.myID, event.data.variable, event.data.value );
772 break;
773 case 'getChuckInt':
774 var result = getChuckInt( this.myID, event.data.variable );
775 this.port.postMessage( { type: "intCallback", callback: event.data.callback, result: result } );
776 break;
777 case 'setChuckFloat':
778 setChuckFloat( this.myID, event.data.variable, event.data.value );
779 break;
780 case 'getChuckFloat':
781 var result = getChuckFloat( this.myID, event.data.variable );
782 this.port.postMessage( { type: "floatCallback", callback: event.data.callback, result: result } );
783 break;
784 case 'setChuckString':
785 setChuckString( this.myID, event.data.variable, event.data.value );
786 break;
787 case 'getChuckString':
788 (function( thePort, theCallback, theVariable, theID, Module )
789 {
790 var pointer = Module.addFunction( (function(thePort, theCallback)
791 {
792 return function( string_ptr )
793 {
794 thePort.postMessage( {
795 type: "stringCallback",
796 callback: theCallback,
797 result: Module.UTF8ToString( string_ptr )
798 } );
799 Module.removeFunction( pointer );
800 }
801 })(thePort, theCallback), 'vi' );
802 getChuckString( theID, theVariable, pointer );
803 })(this.port, event.data.callback, event.data.variable, this.myID, this.Module);
804 break;
805 // ================== Event =================== //
806 case 'signalChuckEvent':
807 signalChuckEvent( this.myID, event.data.variable );
808 break;
809 case 'broadcastChuckEvent':
810 broadcastChuckEvent( this.myID, event.data.variable );
811 break;
812 case 'listenForChuckEventOnce':
813 (function( thePort, theCallback, theVariable, theID, Module )
814 {
815 var pointer = Module.addFunction( (function(thePort, theCallback)
816 {
817 return function()
818 {
819 thePort.postMessage( { type: "eventCallback", callback: theCallback } );
820 Module.removeFunction( pointer );
821 }
822 })(thePort, theCallback), 'v' );
823 listenForChuckEventOnce( theID, theVariable, pointer );
824 })(this.port, event.data.callback, event.data.variable, this.myID, this.Module);
825 break;
826 case 'startListeningForChuckEvent':
827 this.myPointers[event.data.callback] = this.Module.addFunction( (function(thePort, theCallback)
828 {
829 return function()
830 {
831 thePort.postMessage( { type: "eventCallback", callback: theCallback } );
832 }
833 })(this.port, event.data.callback), 'v' );
834 startListeningForChuckEvent( this.myID, event.data.variable, this.myPointers[event.data.callback] );
835 break;
836 case 'stopListeningForChuckEvent':
837 stopListeningForChuckEvent( this.myID, event.data.variable, this.myPointers[event.data.callback] );
838 this.Module.removeFunction( this.myPointers[event.data.callback] );
839 break;
840 // ================== Int[] =================== //
841 case 'setGlobalIntArray':
842 // convert to Int32Array
843 var values = new Int32Array( event.data.values );
844 // put onto heap
845 var valuesPtr = this.Module._malloc( values.length * values.BYTES_PER_ELEMENT );
846 var heapview = this.Module.HEAP32.subarray( (valuesPtr >> 2), (valuesPtr >> 2) + values.length );
847 heapview.set( values );
848
849 // put variable name on heap as well
850 var stringBytes = event.data.variable.length << 2 + 1;
851 var stringPtr = this.Module._malloc( stringBytes );
852 this.Module.stringToUTF8( event.data.variable, stringPtr, stringBytes );
853
854 // call
855 this.Module._setGlobalIntArray( this.myID, stringPtr, valuesPtr, values.length );
856
857 // free
858 this.Module._free( valuesPtr );
859 this.Module._free( stringPtr );
860 break;
861 case 'getGlobalIntArray':
862 (function( thePort, theCallback, theVariable, theID, Module )
863 {
864 var pointer = Module.addFunction( (function(thePort, theCallback)
865 {
866 return function( int32_ptr, len )
867 {
868 var result = new Int32Array(
869 Module.HEAPU8.buffer,
870 int32_ptr,
871 len
872 );
873 thePort.postMessage( {
874 type: "intArrayCallback",
875 callback: theCallback,
876 result: Array.from(result)
877 } );
878 Module.removeFunction( pointer );
879 }
880 })(thePort, theCallback), 'vii' );
881 getGlobalIntArray( theID, theVariable, pointer );
882 })(this.port, event.data.callback, event.data.variable, this.myID, this.Module);
883 break;
884 case 'setGlobalIntArrayValue':
885 setGlobalIntArrayValue( this.myID, event.data.variable, event.data.index, event.data.value );
886 break;
887 case 'getGlobalIntArrayValue':
888 var result = getGlobalIntArrayValue( this.myID, event.data.variable, event.data.index );
889 this.port.postMessage( { type: "intCallback", callback: event.data.callback, result: result } );
890 break;
891 case 'setGlobalAssociativeIntArrayValue':
892 setGlobalAssociativeIntArrayValue( this.myID, event.data.variable, event.data.key, event.data.value );
893 break;
894 case 'getGlobalAssociativeIntArrayValue':
895 var result = getGlobalAssociativeIntArrayValue( this.myID, event.data.variable, event.data.key );
896 this.port.postMessage( { type: "intCallback", callback: event.data.callback, result: result } );
897 break;
898 // ================== Float[] =================== //
899 case 'setGlobalFloatArray':
900 // convert to Float64Array
901 var values = new Float64Array( event.data.values );
902 // put onto heap
903 var valuesPtr = this.Module._malloc( values.length * values.BYTES_PER_ELEMENT );
904 var heapview = this.Module.HEAPF64.subarray( (valuesPtr >> 3), (valuesPtr >> 3) + values.length );
905 heapview.set( values );
906
907 // put variable name on heap as well
908 var stringBytes = event.data.variable.length << 2 + 1;
909 var stringPtr = this.Module._malloc( stringBytes );
910 this.Module.stringToUTF8( event.data.variable, stringPtr, stringBytes );
911
912 // call
913 this.Module._setGlobalFloatArray( this.myID, stringPtr, valuesPtr, values.length );
914
915 // free
916 this.Module._free( valuesPtr );
917 this.Module._free( stringPtr );
918 break;
919 case 'getGlobalFloatArray':
920 (function( thePort, theCallback, theVariable, theID, Module )
921 {
922 var pointer = Module.addFunction( (function(thePort, theCallback)
923 {
924 return function( float64_ptr, len )
925 {
926 var result = new Float64Array(
927 Module.HEAPU8.buffer,
928 float64_ptr,
929 len
930 );
931 thePort.postMessage( {
932 type: "floatArrayCallback",
933 callback: theCallback,
934 result: Array.from(result)
935 } );
936 Module.removeFunction( pointer );
937 }
938 })(thePort, theCallback), 'vii' );
939 getGlobalFloatArray( theID, theVariable, pointer );
940 })(this.port, event.data.callback, event.data.variable, this.myID, this.Module);
941 break;
942 case 'setGlobalFloatArrayValue':
943 setGlobalFloatArrayValue( this.myID, event.data.variable, event.data.index, event.data.value );
944 break;
945 case 'getGlobalFloatArrayValue':
946 var result = getGlobalFloatArrayValue( this.myID, event.data.variable, event.data.index );
947 this.port.postMessage( { type: "floatCallback", callback: event.data.callback, result: result } );
948 break;
949 case 'setGlobalAssociativeFloatArrayValue':
950 setGlobalAssociativeFloatArrayValue( this.myID, event.data.variable, event.data.key, event.data.value );
951 break;
952 case 'getGlobalAssociativeFloatArrayValue':
953 var result = getGlobalAssociativeFloatArrayValue( this.myID, event.data.variable, event.data.key );
954 this.port.postMessage( { type: "floatCallback", callback: event.data.callback, result: result } );
955 break;
956 // ==================== VM Param Functions ======================
957 // 1.5.0.8 (ge) added
958 case 'setParamInt':
959 setParamInt( this.myID, event.data.name, event.data.value );
960 break;
961 case 'getParamInt':
962 var result = getParamInt( this.myID, event.data.name );
963 this.port.postMessage( { type: "intCallback", callback: event.data.callback, result: result } );
964 break;
965 case 'setParamFloat':
966 setParamFloat( this.myID, event.data.name, event.data.value );
967 break;
968 case 'getParamFloat':
969 var result = getParamFloat( this.myID, event.data.name );
970 this.port.postMessage( { type: "floatCallback", callback: event.data.callback, result: result } );
971 break;
972 case 'setParamString':
973 setParamString( this.myID, event.data.name, event.data.value );
974 break;
975 case 'getParamString':
976 var result = getParamString( this.myID, event.data.name );
977 this.port.postMessage( { type: "stringCallback", callback: event.data.callback, result: result } );
978 break;
979 // ==================== VM Functions ====================== //
980 case 'now': // can use either name
981 case 'getChuckNow':
982 var result = getChuckNow( this.myID );
983 this.port.postMessage( { type: "floatCallback", callback: event.data.callback, result: result } );
984 break;
985 case 'clearChuckInstance':
986 clearChuckInstance( this.myID );
987 break;
988 case 'clearGlobals':
989 clearGlobals( this.myID );
990 this.port.postMessage( {
991 type: "console print",
992 message: "[chuck](VM): resetting all global variables"
993 } );
994 break;
995 default:
996 break;
997 }
998
999 }
1000
1001 process(inputs, outputs, parameters)
1002 {
1003 if( !this.haveInit ) { return true; }
1004 // structure for two-channel audio is [[Float32Array,Float32Array]]
1005 // since it's ONE output (outer array) with TWO channels (inner array of arrays)
1006 let input = inputs[0];
1007 let output = outputs[0];
1008 // recompute subarray views just in case memory has grown recently
1009 this._heapInputBuffer.adaptChannel( input.length );
1010
1011 // copy input
1012 for (let channel = 0; channel < input.length; channel++)
1013 {
1014 // ... but only if they actually gave us something
1015 if( input[channel].length > 0 )
1016 {
1017 this._heapInputBuffer.getChannelData(channel).set(input[channel]);
1018 }
1019 }
1020
1021 // process
1022 // for multichannel, WebAudio uses planar buffers.
1023 // this version of ChucK has been specially compiled to do the same
1024 // (ordinarily, ChucK uses interleaved buffers since it processes
1025 // sample by sample)
1026 this.Module._chuckManualAudioCallback(
1027 this.myID, // chuck ID
1028 this._heapInputBuffer.getHeapAddress(),
1029 this._heapOutputBuffer.getHeapAddress(),
1030 output[0].length, // frame size (probably 128)
1031 this.inChannels, // in channels
1032 this.outChannels // out channels
1033 );
1034
1035 // recompute subarray views just in case memory grew while we
1036 // were calling chuck audio callback
1037 this._heapOutputBuffer.adaptChannel( output.length );
1038
1039 // copy output
1040 for (let channel = 0; channel < output.length; channel++)
1041 {
1042 output[channel].set(this._heapOutputBuffer.getChannelData(channel));
1043 }
1044
1045 return true;
1046 }
1047
1048 }
1049
1050 class ChuckSubNode extends AudioWorkletProcessor
1051 {
1052 constructor( options )
1053 {
1054 super();
1055
1056 this.inChannels = 0;
1057 // SHOULD BE 1
1058 this.outChannels = options.outputChannelCount[0];
1059
1060
1061 this.myID = options.processorOptions.chuckID;
1062 this.myDac = options.processorOptions.dac;
1063
1064 // do this in response to an incoming message
1065 this.port.onmessage = this.handle_message.bind(this);
1066
1067 console.assert( globalInit && this.myID in chucks, "ChuckSubNode can't find its ChuckNode with ID " + this.myID );
1068 this.myChuck = chucks[ this.myID ];
1069
1070 this.haveInit = false;
1071 this.init();
1072 }
1073
1074 init()
1075 {
1076 globalPromise.then( (function( self )
1077 {
1078 return function( Module )
1079 {
1080 self.Module = Module;
1081
1082 // Allocate the buffer for the heap access. Start with however many channels we have
1083 // (should be 1)
1084 self._heapOutputBuffer = new HeapAudioBuffer(Module, RENDER_QUANTUM_FRAMES,
1085 self.outChannels, MAX_CHANNEL_COUNT);
1086
1087 var stringBytes = self.myDac.length << 2 + 1;
1088 self.myDacCString = self.Module._malloc( stringBytes );
1089 self.Module.stringToUTF8( self.myDac, self.myDacCString, stringBytes );
1090
1091 self.haveInit = true;
1092
1093 self.port.postMessage( { type: 'initCallback' } );
1094 }
1095 })( this ) );
1096 }
1097
1098 handle_message( event )
1099 {
1100 switch( event.data.type )
1101 {
1102 default:
1103 break;
1104 }
1105
1106 }
1107
1108 process( inputs, outputs, parameters )
1109 {
1110 if( !this.haveInit ) { return true; }
1111
1112 let output = outputs[0];
1113
1114 // fetch
1115 this.Module._getGlobalUGenSamples(
1116 this.myID,
1117 this.myDacCString,
1118 this._heapOutputBuffer.getHeapAddress(),
1119 output[0].length // frame size (probably 128)
1120 );
1121
1122 // recompute subarray views just in case memory grew recently
1123 this._heapOutputBuffer.adaptChannel( output.length );
1124
1125 // copy output
1126 for (let channel = 0; channel < output.length; channel++)
1127 {
1128 output[channel].set(this._heapOutputBuffer.getChannelData(channel));
1129 }
1130
1131 return true;
1132 }
1133
1134 }
1135
1136 registerProcessor( 'chuck-node', ChuckNode );
1137 registerProcessor( 'chuck-sub-node', ChuckSubNode );
1138
1139 // ------------------------------------------------------------------------ //
1140 // ------------------------------------------------------------------------ //
1141 // ------------------------------------------------------------------------ //
1142 // ------------------------------------------------------------------------ //