forked from bbloomf/jgabc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sink.js
1545 lines (1308 loc) · 36.5 KB
/
sink.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
var Sink = this.Sink = function (global) {
/**
* Creates a Sink according to specified parameters, if possible.
*
* @class
*
* @arg =!readFn
* @arg =!channelCount
* @arg =!bufferSize
* @arg =!sampleRate
*
* @param {Function} readFn A callback to handle the buffer fills.
* @param {Number} channelCount Channel count.
* @param {Number} bufferSize (Optional) Specifies a pre-buffer size to control the amount of latency.
* @param {Number} sampleRate Sample rate (ms).
* @param {Number} default=0 writePosition Write position of the sink, as in how many samples have been written per channel.
* @param {String} default=async writeMode The default mode of writing to the sink.
* @param {String} default=interleaved channelMode The mode in which the sink asks the sample buffers to be channeled in.
* @param {Number} default=0 previousHit The previous time of a callback.
* @param {Buffer} default=null ringBuffer The ring buffer array of the sink. If null, ring buffering will not be applied.
* @param {Number} default=0 ringOffset The current position of the ring buffer.
*/
function Sink (readFn, channelCount, bufferSize, sampleRate) {
var sinks = Sink.sinks.list,
i;
for (i=0; i<sinks.length; i++) {
if (sinks[i].enabled) {
try {
return new sinks[i](readFn, channelCount, bufferSize, sampleRate);
} catch(e1){}
}
}
throw Sink.Error(0x02);
}
function SinkClass () {
}
Sink.SinkClass = SinkClass;
SinkClass.prototype = Sink.prototype = {
sampleRate: 44100,
channelCount: 2,
bufferSize: 4096,
writePosition: 0,
previousHit: 0,
ringOffset: 0,
channelMode: 'interleaved',
isReady: false,
/**
* Does the initialization of the sink.
* @method Sink
*/
start: function (readFn, channelCount, bufferSize, sampleRate) {
this.channelCount = isNaN(channelCount) || channelCount === null ? this.channelCount: channelCount;
this.bufferSize = isNaN(bufferSize) || bufferSize === null ? this.bufferSize : bufferSize;
this.sampleRate = isNaN(sampleRate) || sampleRate === null ? this.sampleRate : sampleRate;
this.readFn = readFn;
this.activeRecordings = [];
this.previousHit = +new Date();
Sink.EventEmitter.call(this);
Sink.emit('init', [this].concat([].slice.call(arguments)));
},
/**
* The method which will handle all the different types of processing applied on a callback.
* @method Sink
*/
process: function (soundData, channelCount) {
this.emit('preprocess', arguments);
if (this.ringBuffer) {
(this.channelMode === 'interleaved' ? this.ringSpin : this.ringSpinInterleaved).apply(this, arguments);
}
if (this.channelMode === 'interleaved') {
this.emit('audioprocess', arguments);
if (this.readFn) {
this.readFn.apply(this, arguments);
}
} else {
var soundDataSplit = Sink.deinterleave(soundData, this.channelCount),
args = [soundDataSplit].concat([].slice.call(arguments, 1));
this.emit('audioprocess', args);
if (this.readFn) {
this.readFn.apply(this, args);
}
Sink.interleave(soundDataSplit, this.channelCount, soundData);
}
this.emit('postprocess', arguments);
this.previousHit = +new Date();
this.writePosition += soundData.length / channelCount;
},
/**
* Get the current output position, defaults to writePosition - bufferSize.
*
* @method Sink
*
* @return {Number} The position of the write head, in samples, per channel.
*/
getPlaybackTime: function () {
return this.writePosition - this.bufferSize;
},
/**
* Internal method to send the ready signal if not ready yet.
* @method Sink
*/
ready: function () {
if (this.isReady) return;
this.isReady = true;
this.emit('ready', []);
}
};
/**
* The container for all the available sinks. Also a decorator function for creating a new Sink class and binding it.
*
* @method Sink
* @static
*
* @arg {String} type The name / type of the Sink.
* @arg {Function} constructor The constructor function for the Sink.
* @arg {Object} prototype The prototype of the Sink. (optional)
* @arg {Boolean} disabled Whether the Sink should be disabled at first.
*/
function sinks (type, constructor, prototype, disabled, priority) {
prototype = prototype || constructor.prototype;
constructor.prototype = new Sink.SinkClass();
constructor.prototype.type = type;
constructor.enabled = !disabled;
var k;
for (k in prototype) {
if (prototype.hasOwnProperty(k)) {
constructor.prototype[k] = prototype[k];
}
}
sinks[type] = constructor;
sinks.list[priority ? 'unshift' : 'push'](constructor);
}
Sink.sinks = Sink.devices = sinks;
Sink.sinks.list = [];
Sink.singleton = function () {
var sink = Sink.apply(null, arguments);
Sink.singleton = function () {
return sink;
};
return sink;
};
global.Sink = Sink;
return Sink;
}(function (){ return this; }());
void function (Sink) {
/**
* A light event emitter.
*
* @class
* @static Sink
*/
function EventEmitter () {
var k;
for (k in EventEmitter.prototype) {
if (EventEmitter.prototype.hasOwnProperty(k)) {
this[k] = EventEmitter.prototype[k];
}
}
this._listeners = {};
}
EventEmitter.prototype = {
_listeners: null,
/**
* Emits an event.
*
* @method EventEmitter
*
* @arg {String} name The name of the event to emit.
* @arg {Array} args The arguments to pass to the event handlers.
*/
emit: function (name, args) {
if (this._listeners[name]) {
for (var i=0; i<this._listeners[name].length; i++) {
this._listeners[name][i].apply(this, args);
}
}
return this;
},
/**
* Adds an event listener to an event.
*
* @method EventEmitter
*
* @arg {String} name The name of the event.
* @arg {Function} listener The event listener to attach to the event.
*/
on: function (name, listener) {
this._listeners[name] = this._listeners[name] || [];
this._listeners[name].push(listener);
return this;
},
/**
* Adds an event listener to an event.
*
* @method EventEmitter
*
* @arg {String} name The name of the event.
* @arg {Function} !listener The event listener to remove from the event. If not specified, will delete all.
*/
off: function (name, listener) {
if (this._listeners[name]) {
if (!listener) {
delete this._listeners[name];
return this;
}
for (var i=0; i<this._listeners[name].length; i++) {
if (this._listeners[name][i] === listener) {
this._listeners[name].splice(i--, 1);
}
}
if (!this._listeners[name].length) {
delete this._listeners[name];
}
}
return this;
}
};
Sink.EventEmitter = EventEmitter;
EventEmitter.call(Sink);
}(this.Sink);
void function (Sink) {
/*
* A Sink-specific error class.
*
* @class
* @static Sink
* @name Error
*
* @arg =code
*
* @param {Number} code The error code.
* @param {String} message A brief description of the error.
* @param {String} explanation A more verbose explanation of why the error occured and how to fix.
*/
function SinkError(code) {
if (!SinkError.hasOwnProperty(code)) throw SinkError(1);
if (!(this instanceof SinkError)) return new SinkError(code);
var k;
for (k in SinkError[code]) {
if (SinkError[code].hasOwnProperty(k)) {
this[k] = SinkError[code][k];
}
}
this.code = code;
}
SinkError.prototype = new Error();
SinkError.prototype.toString = function () {
return 'SinkError 0x' + this.code.toString(16) + ': ' + this.message;
};
SinkError[0x01] = {
message: 'No such error code.',
explanation: 'The error code does not exist.'
};
SinkError[0x02] = {
message: 'No audio sink available.',
explanation: 'The audio device may be busy, or no supported output API is available for this browser.'
};
SinkError[0x10] = {
message: 'Buffer underflow.',
explanation: 'Trying to recover...'
};
SinkError[0x11] = {
message: 'Critical recovery fail.',
explanation: 'The buffer underflow has reached a critical point, trying to recover, but will probably fail anyway.'
};
SinkError[0x12] = {
message: 'Buffer size too large.',
explanation: 'Unable to allocate the buffer due to excessive length, please try a smaller buffer. Buffer size should probably be smaller than the sample rate.'
};
Sink.Error = SinkError;
}(this.Sink);
void function (Sink) {
var BlobBuilder = typeof window === 'undefined' ? undefined :
window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder || window.OBlobBuilder,
URL = typeof window === 'undefined' ? undefined : (window.URL || window.MozURL || window.webkitURL || window.MSURL || window.OURL);
/**
* Creates an inline worker using a data/blob URL, if possible.
*
* @static Sink
*
* @arg {String} script
*
* @return {Worker} A web worker, or null if impossible to create.
*/
function inlineWorker (script) {
var worker = null,
url, bb;
try {
bb = new BlobBuilder();
bb.append(script);
url = URL.createObjectURL(bb.getBlob());
worker = new Worker(url);
worker._terminate = worker.terminate;
worker._url = url;
bb = null;
worker.terminate = function () {
this._terminate();
URL.revokeObjectURL(this._url);
};
inlineWorker.type = 'blob';
return worker;
} catch (e) {}
try {
worker = new Worker('data:text/javascript;base64,' + btoa(script));
inlineWorker.type = 'data';
return worker;
} catch (e) {}
return worker;
}
inlineWorker.ready = inlineWorker.working = false;
Sink.EventEmitter.call(inlineWorker);
inlineWorker.test = function () {
var worker = inlineWorker('this.onmessage=function (e){postMessage(e.data)}'),
data = 'inlineWorker';
inlineWorker.ready = inlineWorker.working = false;
function ready (success) {
if (inlineWorker.ready) return;
inlineWorker.ready = true;
inlineWorker.working = success;
inlineWorker.emit('ready', [success]);
inlineWorker.off('ready');
if (success && worker) {
worker.terminate();
}
worker = null;
}
if (!worker) {
ready(false);
} else {
worker.onmessage = function (e) {
ready(e.data === data);
};
worker.postMessage(data);
setTimeout(function () {
ready(false);
}, 1000);
}
};
Sink.inlineWorker = inlineWorker;
inlineWorker.test();
}(this.Sink);
void function (Sink) {
/**
* Creates a timer with consistent (ie. not clamped) intervals even in background tabs.
* Uses inline workers to achieve this. If not available, will revert to regular timers.
*
* @static Sink
* @name doInterval
*
* @arg {Function} callback The callback to trigger on timer hit.
* @arg {Number} timeout The interval between timer hits.
*
* @return {Function} A function to cancel the timer.
*/
Sink.doInterval = function (callback, timeout) {
var timer, kill;
function create (noWorker) {
if (Sink.inlineWorker.working && !noWorker) {
timer = Sink.inlineWorker('setInterval(function (){ postMessage("tic"); }, ' + timeout + ');');
timer.onmessage = function (){
callback();
};
kill = function () {
timer.terminate();
};
} else {
timer = setInterval(callback, timeout);
kill = function (){
clearInterval(timer);
};
}
}
if (Sink.inlineWorker.ready) {
create();
} else {
Sink.inlineWorker.on('ready', function () {
create();
});
}
return function () {
if (!kill) {
if (!Sink.inlineWorker.ready) {
Sink.inlineWorker.on('ready', function () {
if (kill) kill();
});
}
} else {
kill();
}
};
};
}(this.Sink);
void function (Sink) {
/**
* A Sink class for the Mozilla Audio Data API.
*/
Sink.sinks('audiodata', function () {
var self = this,
currentWritePosition = 0,
tail = null,
audioDevice = new Audio(),
written, currentPosition, available, soundData, prevPos,
timer; // Fix for https://bugzilla.mozilla.org/show_bug.cgi?id=630117
self.start.apply(self, arguments);
self.preBufferSize = isNaN(arguments[4]) || arguments[4] === null ? this.preBufferSize : arguments[4];
function bufferFill() {
if (tail) {
written = audioDevice.mozWriteAudio(tail);
currentWritePosition += written;
if (written < tail.length){
tail = tail.subarray(written);
return tail;
}
tail = null;
}
currentPosition = audioDevice.mozCurrentSampleOffset();
available = Number(currentPosition + (prevPos !== currentPosition ? self.bufferSize : self.preBufferSize) * self.channelCount - currentWritePosition);
if (currentPosition === prevPos) {
self.emit('error', [Sink.Error(0x10)]);
}
if (available > 0 || prevPos === currentPosition){
self.ready();
try {
soundData = new Float32Array(prevPos === currentPosition ? self.preBufferSize * self.channelCount :
self.forceBufferSize ? available < self.bufferSize * 2 ? self.bufferSize * 2 : available : available);
} catch(e) {
self.emit('error', [Sink.Error(0x12)]);
self.kill();
return;
}
self.process(soundData, self.channelCount);
written = self._audio.mozWriteAudio(soundData);
if (written < soundData.length){
tail = soundData.subarray(written);
}
currentWritePosition += written;
}
prevPos = currentPosition;
}
audioDevice.mozSetup(self.channelCount, self.sampleRate);
this._timers = [];
this._timers.push(Sink.doInterval(function () {
// Check for complete death of the output
if (+new Date() - self.previousHit > 2000) {
self._audio = audioDevice = new Audio();
audioDevice.mozSetup(self.channelCount, self.sampleRate);
currentWritePosition = 0;
self.emit('error', [Sink.Error(0x11)]);
}
}, 1000));
this._timers.push(Sink.doInterval(bufferFill, self.interval));
self._bufferFill = bufferFill;
self._audio = audioDevice;
}, {
// These are somewhat safe values...
bufferSize: 24576,
preBufferSize: 24576,
forceBufferSize: false,
interval: 100,
kill: function () {
while (this._timers.length) {
this._timers.shift()();
}
this.emit('kill');
},
getPlaybackTime: function () {
return this._audio.mozCurrentSampleOffset() / this.channelCount;
}
}, false, true);
Sink.sinks.moz = Sink.sinks.audiodata;
}(this.Sink);
(function (Sink, sinks) {
sinks = Sink.sinks;
function newAudio (src) {
var audio = document.createElement('audio');
if (src) {
audio.src = src;
}
return audio;
}
/* TODO: Implement a <BGSOUND> hack for IE8. */
/**
* A sink class for WAV data URLs
* Relies on pcmdata.js and utils to be present.
* Thanks to grantgalitz and others for the idea.
*/
sinks('wav', function () {
var self = this,
audio = new sinks.wav.wavAudio(),
PCMData = typeof PCMData === 'undefined' ? audioLib.PCMData : PCMData;
self.start.apply(self, arguments);
var soundData = new Float32Array(self.bufferSize * self.channelCount),
zeroData = new Float32Array(self.bufferSize * self.channelCount);
if (!newAudio().canPlayType('audio/wav; codecs=1') || !btoa) throw 0;
function bufferFill () {
if (self._audio.hasNextFrame) return;
self.ready();
Sink.memcpy(zeroData, 0, soundData, 0);
self.process(soundData, self.channelCount);
self._audio.setSource('data:audio/wav;base64,' + btoa(
audioLib.PCMData.encode({
data: soundData,
sampleRate: self.sampleRate,
channelCount: self.channelCount,
bytesPerSample: self.quality
})
));
if (!self._audio.currentFrame.src) self._audio.nextClip();
}
self.kill = Sink.doInterval(bufferFill, 40);
self._bufferFill = bufferFill;
self._audio = audio;
}, {
quality: 1,
bufferSize: 22050,
getPlaybackTime: function () {
var audio = this._audio;
return (audio.currentFrame ? audio.currentFrame.currentTime * this.sampleRate : 0) + audio.samples;
}
});
function wavAudio () {
var self = this;
self.currentFrame = newAudio();
self.nextFrame = newAudio();
self._onended = function () {
self.samples += self.bufferSize;
self.nextClip();
};
}
wavAudio.prototype = {
samples: 0,
nextFrame: null,
currentFrame: null,
_onended: null,
hasNextFrame: false,
nextClip: function () {
var curFrame = this.currentFrame;
this.currentFrame = this.nextFrame;
this.nextFrame = curFrame;
this.hasNextFrame = false;
this.currentFrame.play();
},
setSource: function (src) {
this.nextFrame.src = src;
this.nextFrame.addEventListener('ended', this._onended, true);
this.hasNextFrame = true;
}
};
sinks.wav.wavAudio = wavAudio;
}(this.Sink));
void function (Sink) {
/**
* A dummy Sink. (No output)
*/
Sink.sinks('dummy', function () {
var self = this;
self.start.apply(self, arguments);
function bufferFill () {
var soundData = new Float32Array(self.bufferSize * self.channelCount);
self.process(soundData, self.channelCount);
}
self._kill = Sink.doInterval(bufferFill, self.bufferSize / self.sampleRate * 1000);
self._callback = bufferFill;
}, {
kill: function () {
this._kill();
this.emit('kill');
}
}, true);
}(this.Sink);
(function (sinks, fixChrome82795) {
var AudioContext = typeof window === 'undefined' ? null : window.webkitAudioContext || window.AudioContext;
/**
* A sink class for the Web Audio API
*/
sinks('webaudio', function (readFn, channelCount, bufferSize, sampleRate) {
var self = this,
context = sinks.webaudio.getContext(),
node = context.createJavaScriptNode(bufferSize, 0, channelCount),
soundData = null,
zeroBuffer = null;
self.start.apply(self, arguments);
function bufferFill(e) {
var outputBuffer = e.outputBuffer,
channelCount = outputBuffer.numberOfChannels,
i, n, l = outputBuffer.length,
size = outputBuffer.size,
channels = new Array(channelCount),
tail;
self.ready();
soundData = soundData && soundData.length === l * channelCount ? soundData : new Float32Array(l * channelCount);
zeroBuffer = zeroBuffer && zeroBuffer.length === soundData.length ? zeroBuffer : new Float32Array(l * channelCount);
soundData.set(zeroBuffer);
for (i=0; i<channelCount; i++) {
channels[i] = outputBuffer.getChannelData(i);
}
self.process(soundData, self.channelCount);
for (i=0; i<l; i++) {
for (n=0; n < channelCount; n++) {
channels[n][i] = soundData[i * self.channelCount + n];
}
}
}
self.sampleRate = context.sampleRate;
node.onaudioprocess = bufferFill;
node.connect(context.destination);
self._context = context;
self._node = node;
self._callback = bufferFill;
/* Keep references in order to avoid garbage collection removing the listeners, working around http://code.google.com/p/chromium/issues/detail?id=82795 */
// Thanks to @baffo32
fixChrome82795.push(node);
}, {
kill: function () {
this._node.disconnect(0);
for (var i=0; i<fixChrome82795.length; i++) {
if (fixChrome82795[i] === this._node) {
fixChrome82795.splice(i--, 1);
}
}
this._node = this._context = null;
this.emit('kill');
},
getPlaybackTime: function () {
return this._context.currentTime * this.sampleRate;
}
}, false, true);
sinks.webkit = sinks.webaudio;
sinks.webaudio.fix82795 = fixChrome82795;
sinks.webaudio.getContext = function () {
// For now, we have to accept that the AudioContext is at 48000Hz, or whatever it decides.
var context = new AudioContext(/*sampleRate*/);
sinks.webaudio.getContext = function () {
return context;
};
return context;
};
}(this.Sink.sinks, []));
(function (Sink) {
/**
* A Sink class for the Media Streams Processing API and/or Web Audio API in a Web Worker.
*/
Sink.sinks('worker', function () {
var self = this,
global = (function(){ return this; }()),
soundData = null,
outBuffer = null,
zeroBuffer = null;
self.start.apply(self, arguments);
// Let's see if we're in a worker.
importScripts();
function mspBufferFill (e) {
if (!self.isReady) {
self.initMSP(e);
}
self.ready();
var channelCount = self.channelCount,
l = e.audioLength,
n, i;
soundData = soundData && soundData.length === l * channelCount ? soundData : new Float32Array(l * channelCount);
outBuffer = outBuffer && outBuffer.length === soundData.length ? outBuffer : new Float32Array(l * channelCount);
zeroBuffer = zeroBuffer && zeroBuffer.length === soundData.length ? zeroBuffer : new Float32Array(l * channelCount);
soundData.set(zeroBuffer);
outBuffer.set(zeroBuffer);
self.process(soundData, self.channelCount);
for (n=0; n<channelCount; n++) {
for (i=0; i<l; i++) {
outBuffer[n * e.audioLength + i] = soundData[n + i * channelCount];
}
}
e.writeAudio(outBuffer);
}
function waBufferFill(e) {
if (!self.isReady) {
self.initWA(e);
}
self.ready();
var outputBuffer = e.outputBuffer,
channelCount = outputBuffer.numberOfChannels,
i, n, l = outputBuffer.length,
size = outputBuffer.size,
channels = new Array(channelCount),
tail;
soundData = soundData && soundData.length === l * channelCount ? soundData : new Float32Array(l * channelCount);
zeroBuffer = zeroBuffer && zeroBuffer.length === soundData.length ? zeroBuffer : new Float32Array(l * channelCount);
soundData.set(zeroBuffer);
for (i=0; i<channelCount; i++) {
channels[i] = outputBuffer.getChannelData(i);
}
self.process(soundData, self.channelCount);
for (i=0; i<l; i++) {
for (n=0; n < channelCount; n++) {
channels[n][i] = soundData[i * self.channelCount + n];
}
}
}
global.onprocessmedia = mspBufferFill;
global.onaudioprocess = waBufferFill;
self._mspBufferFill = mspBufferFill;
self._waBufferFill = waBufferFill;
}, {
ready: false,
initMSP: function (e) {
this.channelCount = e.audioChannels;
this.sampleRate = e.audioSampleRate;
this.bufferSize = e.audioLength * this.channelCount;
this.ready = true;
this.emit('ready', []);
},
initWA: function (e) {
var b = e.outputBuffer;
this.channelCount = b.numberOfChannels;
this.sampleRate = b.sampleRate;
this.bufferSize = b.length * this.channelCount;
this.ready = true;
this.emit('ready', []);
}
});
}(this.Sink));
(function (Sink) {
(function(){
/**
* If method is supplied, adds a new interpolation method to Sink.interpolation, otherwise sets the default interpolation method (Sink.interpolate) to the specified property of Sink.interpolate.
*
* @arg {String} name The name of the interpolation method to get / set.
* @arg {Function} !method The interpolation method.
*/
function interpolation(name, method) {
if (name && method) {
interpolation[name] = method;
} else if (name && interpolation[name] instanceof Function) {
Sink.interpolate = interpolation[name];
}
return interpolation[name];
}
Sink.interpolation = interpolation;
/**
* Interpolates a fractal part position in an array to a sample. (Linear interpolation)
*
* @param {Array} arr The sample buffer.
* @param {number} pos The position to interpolate from.
* @return {Float32} The interpolated sample.
*/
interpolation('linear', function (arr, pos) {
var first = Math.floor(pos),
second = first + 1,
frac = pos - first;
second = second < arr.length ? second : 0;
return arr[first] * (1 - frac) + arr[second] * frac;
});
/**
* Interpolates a fractal part position in an array to a sample. (Nearest neighbour interpolation)
*
* @param {Array} arr The sample buffer.
* @param {number} pos The position to interpolate from.
* @return {Float32} The interpolated sample.
*/
interpolation('nearest', function (arr, pos) {
return pos >= arr.length - 0.5 ? arr[0] : arr[Math.round(pos)];
});
interpolation('linear');
}());
/**
* Resamples a sample buffer from a frequency to a frequency and / or from a sample rate to a sample rate.
*
* @static Sink
* @name resample
*
* @arg {Buffer} buffer The sample buffer to resample.
* @arg {Number} fromRate The original sample rate of the buffer, or if the last argument, the speed ratio to convert with.
* @arg {Number} fromFrequency The original frequency of the buffer, or if the last argument, used as toRate and the secondary comparison will not be made.
* @arg {Number} toRate The sample rate of the created buffer.
* @arg {Number} toFrequency The frequency of the created buffer.
*
* @return The new resampled buffer.
*/
Sink.resample = function (buffer, fromRate /* or speed */, fromFrequency /* or toRate */, toRate, toFrequency) {
var
argc = arguments.length,
speed = argc === 2 ? fromRate : argc === 3 ? fromRate / fromFrequency : toRate / fromRate * toFrequency / fromFrequency,
l = buffer.length,
length = Math.ceil(l / speed),
newBuffer = new Float32Array(length),
i, n;
for (i=0, n=0; i<l; i += speed) {
newBuffer[n++] = Sink.interpolate(buffer, i);
}
return newBuffer;
};
}(this.Sink));
(function (Sink) {
/**
* Splits a sample buffer into those of different channels.
*
* @static Sink
* @name deinterleave
*
* @arg {Buffer} buffer The sample buffer to split.
* @arg {Number} channelCount The number of channels to split to.
*
* @return {Array} An array containing the resulting sample buffers.
*/
Sink.deinterleave = function (buffer, channelCount) {
var l = buffer.length,
size = l / channelCount,
ret = [],
i, n;
for (i=0; i<channelCount; i++){
ret[i] = new Float32Array(size);
for (n=0; n<size; n++){
ret[i][n] = buffer[n * channelCount + i];
}
}
return ret;
};
/**
* Joins an array of sample buffers into a single buffer.
*
* @static Sink
* @name resample
*
* @arg {Array} buffers The buffers to join.
* @arg {Number} !channelCount The number of channels. Defaults to buffers.length
* @arg {Buffer} !buffer The output buffer.
*