-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.min.js
4539 lines (4058 loc) · 164 KB
/
index.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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
(function(l, r) { if (!l || l.getElementById('livereloadscript')) return; r = l.createElement('script'); r.async = 1; r.src = '//' + (self.location.host || 'localhost').split(':')[0] + ':35729/livereload.js?snipver=1'; r.id = 'livereloadscript'; r.crossOrigin='anonymous'; l.getElementsByTagName('head')[0].appendChild(r) })(self.document);
var version = (function (exports) {
'use strict';
// Send audio interleaved audio frames between threads, wait-free.
// A Single Producer - Single Consumer thread-safe wait-free ring buffer.
//
// The producer and the consumer can be separate thread, but cannot change role,
// except with external synchronization.
class RingBuffer {
static getStorageForCapacity(capacity, type) {
if (!type.BYTES_PER_ELEMENT) {
throw "Pass in a ArrayBuffer subclass";
}
var bytes = 8 + (capacity + 1) * type.BYTES_PER_ELEMENT;
return new SharedArrayBuffer(bytes);
}
// `sab` is a SharedArrayBuffer with a capacity calculated by calling
// `getStorageForCapacity` with the desired capacity.
constructor(sab, type) {
if (!ArrayBuffer.__proto__.isPrototypeOf(type) &&
type.BYTES_PER_ELEMENT !== undefined) {
throw "Pass a concrete typed array class as second argument";
}
// Maximum usable size is 1<<32 - type.BYTES_PER_ELEMENT bytes in the ring
// buffer for this version, easily changeable.
// -4 for the write ptr (uint32_t offsets)
// -4 for the read ptr (uint32_t offsets)
// capacity counts the empty slot to distinguish between full and empty.
this._type = type;
this.capacity = (sab.byteLength - 8) / type.BYTES_PER_ELEMENT;
this.buf = sab;
this.write_ptr = new Uint32Array(this.buf, 0, 1);
this.read_ptr = new Uint32Array(this.buf, 4, 1);
this.storage = new type(this.buf, 8, this.capacity);
}
// Returns the type of the underlying ArrayBuffer for this RingBuffer. This
// allows implementing crude type checking.
type() {
return this._type.name;
}
// Push bytes to the ring buffer. `bytes` is an typed array of the same type
// as passed in the ctor, to be written to the queue.
// Returns the number of elements written to the queue.
push(elements) {
var rd = Atomics.load(this.read_ptr, 0);
var wr = Atomics.load(this.write_ptr, 0);
if ((wr + 1) % this._storage_capacity() == rd) {
// full
return 0;
}
let to_write = Math.min(this._available_write(rd, wr), elements.length);
let first_part = Math.min(this._storage_capacity() - wr, to_write);
let second_part = to_write - first_part;
this._copy(elements, 0, this.storage, wr, first_part);
this._copy(elements, first_part, this.storage, 0, second_part);
// publish the enqueued data to the other side
Atomics.store(
this.write_ptr,
0,
(wr + to_write) % this._storage_capacity()
);
return to_write;
}
// Read `elements.length` elements from the ring buffer. `elements` is a typed
// array of the same type as passed in the ctor.
// Returns the number of elements read from the queue, they are placed at the
// beginning of the array passed as parameter.
pop(elements) {
var rd = Atomics.load(this.read_ptr, 0);
var wr = Atomics.load(this.write_ptr, 0);
if (wr == rd) {
return 0;
}
let to_read = Math.min(this._available_read(rd, wr), elements.length);
let first_part = Math.min(this._storage_capacity() - rd, elements.length);
let second_part = to_read - first_part;
this._copy(this.storage, rd, elements, 0, first_part);
this._copy(this.storage, 0, elements, first_part, second_part);
Atomics.store(this.read_ptr, 0, (rd + to_read) % this._storage_capacity());
return to_read;
}
// True if the ring buffer is empty false otherwise. This can be late on the
// reader side: it can return true even if something has just been pushed.
empty() {
var rd = Atomics.load(this.read_ptr, 0);
var wr = Atomics.load(this.write_ptr, 0);
return wr == rd;
}
// True if the ring buffer is full, false otherwise. This can be late on the
// write side: it can return true when something has just been poped.
full() {
var rd = Atomics.load(this.read_ptr, 0);
var wr = Atomics.load(this.write_ptr, 0);
return (wr + 1) % this.capacity != rd;
}
// The usable capacity for the ring buffer: the number of elements that can be
// stored.
capacity() {
return this.capacity - 1;
}
// Number of elements available for reading. This can be late, and report less
// elements that is actually in the queue, when something has just been
// enqueued.
available_read() {
var rd = Atomics.load(this.read_ptr, 0);
var wr = Atomics.load(this.write_ptr, 0);
return this._available_read(rd, wr);
}
// Number of elements available for writing. This can be late, and report less
// elemtns that is actually available for writing, when something has just
// been dequeued.
available_write() {
var rd = Atomics.load(this.read_ptr, 0);
var wr = Atomics.load(this.write_ptr, 0);
return this._available_write(rd, wr);
}
// private methods //
// Number of elements available for reading, given a read and write pointer..
_available_read(rd, wr) {
if (wr > rd) {
return wr - rd;
} else {
return wr + this._storage_capacity() - rd;
}
}
// Number of elements available from writing, given a read and write pointer.
_available_write(rd, wr) {
let rv = rd - wr - 1;
if (wr >= rd) {
rv += this._storage_capacity();
}
return rv;
}
// The size of the storage for elements not accounting the space for the index.
_storage_capacity() {
return this.capacity;
}
// Copy `size` elements from `input`, starting at offset `offset_input`, to
// `output`, starting at offset `offset_output`.
_copy(input, offset_input, output, offset_output, size) {
for (var i = 0; i < size; i++) {
output[offset_output + i] = input[offset_input + i];
}
}
}
const getBase64 = (str) => {
//check if the string is a data URI
if (str.indexOf(';base64,') !== -1) {
//see where the actual data begins
var dataStart = str.indexOf(';base64,') + 8;
//check if the data is base64-encoded, if yes, return it
// taken from
// http://stackoverflow.com/a/8571649
return str.slice(dataStart).match(/^([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==)$/) ? str.slice(dataStart) : false;
} else return false;
};
const _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
const removePaddingFromBase64 = (input) => {
var lkey = Module.maxiTools._keyStr.indexOf(input.charAt(input.length - 1));
if (lkey === 64) {
return input.substring(0, input.length - 1);
}
return input;
};
const loadSampleToArray = (audioContext, sampleObjectName, url, audioWorkletNode) => {
var data = [];
//check if url is actually a base64-encoded string
var b64 = getBase64(url);
if (b64) {
//convert to arraybuffer
//modified version of this:
// https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js
var ab_bytes = (b64.length / 4) * 3;
var arrayBuffer = new ArrayBuffer(ab_bytes);
b64 = removePaddingFromBase64(removePaddingFromBase64(b64));
var bytes = parseInt((b64.length / 4) * 3, 10);
var uarray;
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
var j = 0;
uarray = new Uint8Array(arrayBuffer);
b64 = b64.replace(/[^A-Za-z0-9\+\/\=]/g, "");
for (i = 0; i < bytes; i += 3) {
//get the 3 octects in 4 ascii chars
enc1 = _keyStr.indexOf(b64.charAt(j++));
enc2 = _keyStr.indexOf(b64.charAt(j++));
enc3 = _keyStr.indexOf(b64.charAt(j++));
enc4 = _keyStr.indexOf(b64.charAt(j++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
uarray[i] = chr1;
if (enc3 !== 64) {
uarray[i + 1] = chr2;
}
if (enc4 !== 64) {
uarray[i + 2] = chr3;
}
}
// https://webaudio.github.io/web-audio-api/#dom-baseaudiocontext-decodeaudiodata
// Asynchronously decodes the audio file data contained in the ArrayBuffer.
audioContext.decodeAudioData(
arrayBuffer, // has its content-type determined by sniffing
function (buffer) { // successCallback, argument is an AudioBuffer representing the decoded PCM audio data.
// source.buffer = buffer;
// source.loop = true;
// source.start(0);
let float32ArrayBuffer = buffer.getChannelData(0);
if (data !== undefined && audioWorkletNode !== undefined) {
// console.log('f32array: ' + float32Array);
audioWorkletNode.port.postMessage({
"sample":sampleObjectName,
"buffer": float32ArrayBuffer,
});
}
},
function (buffer) { // errorCallback
console.log("Error decoding source!");
}
);
} else {
// Load asynchronously
// NOTE: This is giving me an error
// Uncaught ReferenceError: XMLHttpRequest is not defined (index):97 MaxiProcessor Error detected: undefined
// NOTE: followed the trail to the wasmmodule.js
// when loading on if (typeof XMLHttpRequest !== 'undefined') {
// throw new Error("Lazy loading should have been performed (contents set) in createLazyFile, but it was not. Lazy loading only works in web workers.
// Use --embed-file or --preload-file in emcc on the main thread.");
var request = new XMLHttpRequest();
request.addEventListener("load", () =>
console.info(`loading sample '${sampleObjectName}'`)
);
request.open("GET", url, true);
request.responseType = "arraybuffer";
request.onload = function () {
audioContext.decodeAudioData(
request.response,
function (buffer) {
let float32ArrayBuffer = buffer.getChannelData(0);
if (data !== undefined && audioWorkletNode !== undefined) {
// console.log('f32array: ' + float32Array);
audioWorkletNode.port.postMessage({
"sample":sampleObjectName,
"buffer": float32ArrayBuffer,
});
}
},
function (buffer) {
console.log("Error decoding source!");
}
);
};
request.send();
}
return "Loading module";
};
class Event {
constructor(eventName) {
this.eventName = eventName;
this.callbacks = [];
}
registerCallback(callback) {
this.callbacks.push(callback);
}
unregisterCallback(callback) {
const index = this.callbacks.indexOf(callback);
if (index > -1) {
this.callbacks.splice(index, 1);
}
}
emit(data) {
const callbacks = this.callbacks.slice(0);
callbacks.forEach( callback => {
callback(data);
});
}
}
class Dispatcher {
constructor() {
this.events = {};
}
dispatch(eventName, data) {
// console.log("dispatch is getting called.");
const event = this.events[eventName];
//let event = Event()
// console.log("event", this.events, "data", data);
// console.log("data", data, event);
if (event) {
// console.log("data being emitted", data)
event.emit(data);
}
}
addEventListener(eventName, callback) {
let event = this.events[eventName];
if (!event) {
event = new Event(eventName);
this.events[eventName] = event;
}
event.registerCallback(callback);
}
removeEventListener(eventName, callback) {
const event = this.events[eventName];
if (event && event.callbacks.indexOf(callback) > -1) {
event.unregisterCallback(callback);
if (event.callbacks.length === 0) {
delete this.events[eventName];
}
}
}
}
// var cl, ci, cw, ce;
class Logger {
/**
* @constructor
*/
constructor() {
if (Logger.instance) {
return Logger.instance; // Singleton pattern
}
Logger.instance = this;
this.log = [];
this.rawLog = ""; //raw log of string data
this.dispatcher = new Dispatcher();
}
//pass in svelte store, of log
// setStore(storeLog){
// storeLog.set = this.rawLog;
// }
addEventListener(event, callback) {
// console.log("registering", event, callback);
if (this.dispatcher && event && callback) {
this.dispatcher.addEventListener(event, callback);
// console.log("registered");
} else throw new Error("Error adding event listener to Logger");
}
push(data) {
this.log.push(data);
this.rawLog =
this.rawLog + "\n" + data.type + " " + [...data.payload].join();
this.dispatcher.dispatch("onLog");
//console.log("getting dispatched", this.rawLog);
//this.dispatcher.dispatch("onConsoleLogsUpdate", {test:10});
}
//console.log = overrideConsoleLog();
takeOverConsole() {
if (window.console) {
// this.onMessageHandler.bind(this);
let cl, ci, cw, ce;
if (window.console.log) cl = console.log;
if (window.console.info) ci = console.info;
if (window.console.warn) cw = console.warn;
if (window.console.error) ce = console.error;
if (cl && ci && cw && ce) {
cw("taking over MAIN console");
console.log = function (text) {
this.push({
func: "logs",
payload: [...arguments],
type: "[MAIN]",
});
cl.apply(this, arguments);
}.bind(this);
console.info = function (text) {
this.push({
func: "logs",
payload: [...arguments],
type: "[MAIN]",
});
ci.apply(this, arguments);
}.bind(this);
console.warn = function (text) {
// window.postMessage({
this.push({
func: "logs",
payload: [...arguments],
type: "[MAIN]",
});
cw.apply(this, arguments);
}.bind(this);
console.error = function (text) {
// window.postMessage({
this.push({
func: "logs",
payload: [...arguments],
type: "[MAIN]",
});
ce.apply(this, arguments);
}.bind(this);
ce("MAIN console taken over");
}
}
}
// takeOverConsole(f) {
// if (f) {
// try {
// var original = window.console;
// function handle(method, args) {
// var message = Array.prototype.slice.apply(args).join(" ");
// if (original) original[method]("> " + message);
// }
// window.console = {
// log: function () {
// handle("log", arguments);
// },
// warn: function () {
// handle("warn", arguments);
// },
// error: function () {
// handle("error", arguments);
// },
// info: function () {
// handle("info", arguments);
// },
// };
// } catch (error) {
// console.error(error);
// }
// }
// }
}
// NOTE: this imports RingBuffer directly from node_modules
// }
/**
* The Engine is a singleton class that encapsulates the AudioContext
* and all WASM and Maximilian -powered Audio Worklet Processor
* @class AudioEngine
* TODO more error handling
* TODO more checking of arguments passed to methods
* TODO optimise performance, especially on analysers which are pumping data continuously
*/
class Engine {
/**
* @constructor
*/
constructor() {
if (Engine.instance) {
return Engine.instance; // Singleton pattern
}
Engine.instance = this;
this.origin = "";
this.learners = {};
// Hash of on-demand analysers (e.g. spectrogram, oscilloscope)
// NOTE: analysers serialized to localStorage are de-serialized
// and loaded from localStorage before user-triggered audioContext init
this.analysers = {};
this.mediaStreamSource = {};
this.mediaStream = {};
// Shared array buffers for sharing client side data to the audio engine- e.g. mouse coords
this.sharedArrayBuffers = {};
// Event emitter that should be subscribed by SAB receivers
this.dispatcher = new Dispatcher();
this.logger = new Logger();
this.samplesLoaded = false;
this.isHushed = false;
}
/**
* Add learner instance
*/
async addLearner(id, learner) {
if (learner) {
try {
// `this` is the scope that will
await learner.init(this.origin);
this.addEventListener("onSharedBuffer", (e) =>
learner.addSharedBuffer(e)
); // Engine's SAB emissions subscribed by Learner
learner.addEventListener("onSharedBuffer", (e) =>
this.addSharedBuffer(e)
); // Learner's SAB emissions subscribed by Engine
this.learners[id] = learner;
} catch (error) {
console.error("Error adding Learner to Engine: ", error);
}
} else throw new Error("Error adding Learner instance to Engine");
}
removeLearner(id) {
if (id){
if (this.learners && ( id in this.learners ) ) {
let learner = this.learners[id];
learner.removeEventListener("onSharedBuffer", (e) =>
this.addSharedBuffer(e)
);
learner = null;
delete this.learners[id];
}
// else throw new Error("Error removing Learner from Engine: ");
} else throw new Error("Error with learner ID when removing Learner from Engine");
}
/**
* Engine's event subscription
* @addEventListener
* @param {*} event
* @param {*} callback
*/
addEventListener(event, callback) {
if (this.dispatcher && event && callback)
this.dispatcher.addEventListener(event, callback);
else throw new Error("Error adding event listener to Engine");
}
/* #region SharedBuffers */
/**
* Create a shared array buffer for communicating with the audio engine
* @param channelId
* @param ttype
* @param blocksize
*/
createSharedBuffer(channelId, ttype, blocksize) {
let sab = RingBuffer.getStorageForCapacity(32 * blocksize, Float64Array);
let ringbuf = new RingBuffer(sab, Float64Array);
this.audioWorkletNode.port.postMessage({
func: "sab",
value: sab,
ttype: ttype,
channelID: channelId,
blocksize: blocksize,
});
this.sharedArrayBuffers[channelId] = {
sab: sab, // TODO: this is redundant, you can access the sab from the rb,
// TODO change hashmap name it is confusing and induces error
rb: ringbuf,
};
return sab;
}
/**
* Push data to shared array buffer for communicating with the audio engine and ML worker
* @param {*} e
*/
addSharedBuffer(e) {
if (e) {
if (e.value && e.value instanceof SharedArrayBuffer) {
try {
let ringbuf = new RingBuffer(e.value, Float64Array);
this.audioWorkletNode.port.postMessage({
func: "sab",
value: e.value,
ttype: e.ttype,
channelID: e.channelID,
blocksize: e.blocksize,
});
this.sharedArrayBuffers[e.channelID] = {
sab: e.value, // TODO this is redundant, you can access the sab from the rb,
// TODO also change hashmap name it is confusing and induces error
rb: ringbuf,
};
} catch (err) {
console.error("Error pushing SharedBuffer to engine");
}
} else if (e.name && e.data) {
this.audioWorkletNode.port.postMessage({
func: "sendbuf",
name: e.name,
data: e.data,
});
}
} else throw new Error("Error with onSharedBuffer event");
}
/**
* Push data to shared array buffer for communicating with the audio engine and ML worker
* @param {*} e
* @param {*} channelId
*/
pushDataToSharedBuffer(channelId, data) {
if (channelId && data && typeof Array.isArray(data)) {
if (this.sharedArrayBuffers && this.sharedArrayBuffers[channelId]) {
this.sharedArrayBuffers[channelId].rb.push(data);
}
} else throw new Error("Error in function parameters");
}
/* #region Analysers */
/**
* Polls data from connected WAAPI analyser return structured object with data and time data in arrays
* @param {*} analyser
*/
pollAnalyserData(analyser) {
if (analyser !== undefined) {
const timeDataArray = new Uint8Array(analyser.fftSize); // Uint8Array should be the same length as the fftSize
const frequencyDataArray = new Uint8Array(analyser.fftSize);
analyser.getByteTimeDomainData(timeDataArray);
analyser.getByteFrequencyData(frequencyDataArray);
return {
smoothingTimeConstant: analyser.smoothingTimeConstant,
fftSize: analyser.fftSize,
frequencyDataArray: frequencyDataArray,
timeDataArray: timeDataArray,
};
}
}
/**
* Creates a WAAPI analyser node
* @todo configuration object as argumen
* @createAnalyser
*/
createAnalyser(analyserID, callback) {
// If Analyser creation happens after AudioContext intialization, create and connect WAAPI analyser
if (analyserID && callback){
if(this.audioContext && this.audioWorkletNode ) {
let analyser = this.audioContext.createAnalyser();
analyser.smoothingTimeConstant = 0.25;
analyser.fftSize = 256; // default 2048;
analyser.minDecibels = -90; // default
analyser.maxDecibels = -0; // default -10; max 0
this.audioWorkletNode.connect(analyser);
let analyserFrameId = -1,
analyserData = {};
this.analysers[analyserID] = {
analyser,
analyserFrameId,
callback,
};
/**
* Creates requestAnimationFrame loop for polling data and publishing
* Returns Analyser Frame ID for adding to Analysers hash
* and cancelling animation frame
*/
const analyserPollingLoop = () => {
analyserData = this.pollAnalyserData(
this.analysers[analyserID].analyser
);
this.analysers[analyserID].callback(analyserData); // Invoke callback that carries
// This will guarantee feeding poll request at steady animation framerate
this.analysers[analyserID].analyserFrameId = requestAnimationFrame(
analyserPollingLoop
);
return analyserFrameId;
};
console.info("Created analyser");
analyserPollingLoop();
// Other if AudioContext is NOT created yet (after app load, before splashScreen click)
} else {
this.analysers[analyserID] = { callback };
}
} else throw new Error('Parameters to createAnalyser incorrect')
}
/**
* Connects WAAPI analyser nodes to the main audio worklet for visualisation.
* @connectAnalysers
*/
connectAnalysers() {
Object.keys(this.analysers).map((id) =>
this.createAnalyser(id, this.analysers[id].callback)
);
}
/**
* Removes a WAAPI analyser node, disconnects graph, cancels animation frame, deletes from hash
* @removeAnalyser
*/
removeAnalyser(event) {
if ( this.audioContext && this.audioWorkletNode ) {
let analyser = this.analysers[event.id];
if (analyser !== undefined) {
cancelAnimationFrame(this.analysers[event.id].analyserFrameId);
delete this.analysers[event.id];
// this.audioWorkletNode.disconnect(analyser);
}
}
}
/* #endregion */
/**
* Initialises audio context and sets worklet processor code
* @play
*/
async init(origin) {
if (origin && new URL(origin)) {
let isWorkletProcessorLoaded;
try{
// AudioContext needs lazy loading to workaround the Chrome warning
// Audio Engine first play() call, triggered by user, prevents the warning
// by setting this.audioContext = new AudioContext();
this.audioContext;
this.origin = origin;
this.audioWorkletName = "maxi-processor";
this.audioWorkletUrl = origin + "/" + this.audioWorkletName + ".js";
if (this.audioContext === undefined) {
this.audioContext = new AudioContext({
// create audio context with latency optimally configured for playback
latencyHint: "playback",
// latencyHint: 32/44100, //this doesn't work below 512 on chrome (?)
// sampleRate: 48000
});
}
isWorkletProcessorLoaded = await this.loadWorkletProcessorCode();
console.log("Processor loaded");
}
catch(err){
return false;
}
if (isWorkletProcessorLoaded) {
this.connectWorkletNode();
return true;
} else return false;
// No need to inject the callback here, messaging is built in KuraClock
// this.kuraClock = new kuramotoNetClock((phase, idx) => {
// // console.log( `DEBUG:AudioEngine:sendPeersMyClockPhase:phase:${phase}:id:${idx}`);
// // This requires an initialised audio worklet
// this.audioWorkletNode.port.postMessage({ phase: phase, i: idx });
// });
// if (this.kuraClock.connected()) {
// this.kuraClock.queryPeers(async numClockPeers => {
// console.log(`DEBUG:AudioEngine:init:numClockPeers: ${numClockPeers}`);
// });
// }
} else {
throw new Error("Name and valid URL required for AudioWorklet processor");
}
}
/**
* Initialises audio context and sets worklet processor code
* or re-starts audio playback by stopping and running the latest Audio Worklet Processor code
* @play
*/
play() {
if (this.audioContext !== undefined) {
if (this.audioContext.state === "suspended") {
this.audioContext.resume();
return true;
} else {
this.hush();
// this.stop();
return false;
}
}
}
/**
* Suspends AudioContext (Pause)
* @stop
*/
stop() {
if (this.audioWorkletNode !== undefined) {
this.hush();
// this.audioContext.suspend();
}
}
/**
* Stops audio by disconnecting AudioNode with AudioWorkletProcessor code
* from Web Audio graph TODO Investigate when it is best to just STOP the graph exectution
* @stop
*/
stopAndRelease() {
if (this.audioWorkletNode !== undefined) {
this.audioWorkletNode.disconnect(this.audioContext.destination);
this.audioWorkletNode = undefined;
}
}
setGain(gain) {
if (this.audioWorkletNode !== undefined && gain >= 0 && gain <= 1) {
const gainParam = this.audioWorkletNode.parameters.get("gain");
gainParam.value = gain;
console.log(gainParam.value); // DEBUG
return true;
} else return false;
}
more() {
if (this.audioWorkletNode !== undefined) {
const gainParam = this.audioWorkletNode.parameters.get("gain");
gainParam.value += 0.05;
console.info(gainParam.value); // DEBUG
return gainParam.value;
} else throw new Error("error increasing sound level");
}
less() {
if (this.audioWorkletNode !== undefined) {
const gainParam = this.audioWorkletNode.parameters.get("gain");
gainParam.value -= 0.05;
console.info(gainParam.value); // DEBUG
return gainParam.value;
} else throw new Error("error decreasing sound level");
}
hush() {
if (this.audioWorkletNode !== undefined) {
this.audioWorkletNode.port.postMessage({
hush: 1,
});
this.isHushed = true;
return true;
} else return false;
}
unHush() {
if (this.audioWorkletNode !== undefined) {
this.audioWorkletNode.port.postMessage({
unhush: 1,
});
this.isHushed = false;
return true;
} else return false;
}
eval(dspFunction) {
if (this.audioWorkletNode && this.audioWorkletNode.port) {
if (this.audioContext.state === "suspended") {
this.audioContext.resume();
}
this.audioWorkletNode.port.postMessage({
eval: 1,
setup: dspFunction.setup,
loop: dspFunction.loop,
});
this.isHushed = false;
return true;
} else return false;
}
/**
* Handler of the Pub/Sub message events
* whose topics are subscribed to in the audio engine constructor
* @asyncPostToProcessor
* @param {*} event
*/
asyncPostToProcessor(event) {
if (event && this.audioWorkletNode && this.audioWorkletNode.port) {
// Receive notification from 'model-output-data' topic
console.log("DEBUG:AudioEngine:onMessagingEventHandler:");
console.log(event);
this.audioWorkletNode.port.postMessage(event);
} else throw new Error("Error async posting to processor");
}
sendClockPhase(phase, idx) {
if (this.audioWorkletNode !== undefined) {
this.audioWorkletNode.port.postMessage({
phase: phase,
i: idx,
});
}
}
onAudioInputInit(stream) {
try {
this.mediaStreamSource = this.audioContext.createMediaStreamSource(stream);
this.mediaStreamSource.connect(this.audioWorkletNode);
this.mediaStream = stream;
this.mediaStreamSourceConnected = true;
} catch (error) {
console.error(error);
}
}
onAudioInputFail(error) {
this.mediaStreamSourceConnected = false;
console.error(
`ERROR:Engine:AudioInputFail: ${error.message} ${error.name}`
);
}
onAudioInputDisconnect() {
}
/**
* Sets up an AudioIn WAAPI sub-graph
* @connectMediaStreamSourceInput
*/
async connectMediaStream() {
const constraints = ( window.constraints = {
audio: {
latency: 0.02,
echoCancellation: false,
mozNoiseSuppression: false,
mozAutoGainControl: false
},
video: false,
});
// onAudioInputDisconnect();
await navigator.mediaDevices
.getUserMedia(constraints)
.then( s => this.onAudioInputInit(s) )
.catch(this.onAudioInputFail);
return this.mediaStreamSourceConnected;