--- /dev/null
+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) {
+
+/**
+ * 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) {
+
+var _Blob, _BlobBuilder, _URL, _btoa;
+
+void function (prefixes, urlPrefixes) {
+ function find (name, prefixes) {
+ var b, a = prefixes.slice();
+
+ for (b=a.shift(); typeof b !== 'undefined'; b=a.shift()) {
+ b = Function('return typeof ' + b + name +
+ '=== "undefined" ? undefined : ' +
+ b + name)();
+
+ if (b) return b;
+ }
+ }
+
+ _Blob = find('Blob', prefixes);
+ _BlobBuilder = find('BlobBuilder', prefixes);
+ _URL = find('URL', urlPrefixes);
+ _btoa = find('btoa', ['']);
+}([
+ '',
+ 'Moz',
+ 'WebKit',
+ 'MS'
+], [
+ '',
+ 'webkit'
+]);
+
+var createBlob = _Blob && _URL && function (content, type) {
+ return _URL.createObjectURL(new _Blob([content], { type: type }));
+};
+
+var createBlobBuilder = _BlobBuilder && _URL && function (content, type) {
+ var bb = new _BlobBuilder();
+ bb.append(content);
+
+ return _URL.createObjectURL(bb.getBlob(type));
+};
+
+var createData = _btoa && function (content, type) {
+ return 'data:' + type + ';base64,' + _btoa(content);
+};
+
+var createDynURL =
+ createBlob ||
+ createBlobBuilder ||
+ createData;
+
+if (!createDynURL) return;
+
+if (createBlob) createDynURL.createBlob = createBlob;
+if (createBlobBuilder) createDynURL.createBlobBuilder = createBlobBuilder;
+if (createData) createDynURL.createData = createData;
+
+if (_Blob) createDynURL.Blob = _Blob;
+if (_BlobBuilder) createDynURL.BlobBuilder = _BlobBuilder;
+if (_URL) createDynURL.URL = _URL;
+
+Sink.createDynURL = createDynURL;
+
+Sink.revokeDynURL = function (url) {
+ if (typeof url === 'string' && url.indexOf('data:') === 0) {
+ return false;
+ } else {
+ return _URL.revokeObjectURL(url);
+ }
+};
+
+}(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) {
+
+/**
+ * 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.
+*/
+
+var define = Object.defineProperty ? function (obj, name, value) {
+ Object.defineProperty(obj, name, {
+ value: value,
+ configurable: true,
+ writable: true
+ });
+} : function (obj, name, value) {
+ obj[name] = value;
+};
+
+function terminate () {
+ define(this, 'terminate', this._terminate);
+
+ Sink.revokeDynURL(this._url);
+
+ delete this._url;
+ delete this._terminate;
+ return this.terminate();
+}
+
+function inlineWorker (script) {
+ function wrap (type, content, typeName) {
+ try {
+ var url = type(content, 'text/javascript');
+ var worker = new Worker(url);
+
+ define(worker, '_url', url);
+ define(worker, '_terminate', worker.terminate);
+ define(worker, 'terminate', terminate);
+
+ if (inlineWorker.type) return worker;
+
+ inlineWorker.type = typeName;
+ inlineWorker.createURL = type;
+
+ return worker;
+ } catch (e) {
+ return null;
+ }
+ }
+
+ var createDynURL = Sink.createDynURL;
+
+ if (!createDynURL) return null;
+
+ var worker;
+
+ if (inlineWorker.createURL) {
+ return wrap(inlineWorker.createURL, script, inlineWorker.type);
+ }
+
+ worker = wrap(createDynURL.createBlob, script, 'blob');
+ if (worker) return worker;
+
+ worker = wrap(createDynURL.createBlobBuilder, script, 'blobbuilder');
+ if (worker) return worker;
+
+ worker = wrap(createDynURL.createData, script, 'data');
+
+ return worker;
+}
+
+Sink.EventEmitter.call(inlineWorker);
+
+inlineWorker.test = function () {
+ inlineWorker.ready = inlineWorker.working = false;
+ inlineWorker.type = '';
+ inlineWorker.createURL = null;
+
+ var worker = inlineWorker('this.onmessage=function(e){postMessage(e.data)}');
+ var data = 'inlineWorker';
+
+ 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) {
+ setTimeout(function () {
+ ready(false);
+ }, 0);
+ } 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) {
+
+/**
+ * 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);
+void function (Sink) {
+
+var cubeb;
+
+try {
+ cubeb = require('cubeb');
+} catch (e) {
+ return;
+}
+
+var getContext = function () {
+ var ctx;
+
+ return function () {
+ ctx = new cubeb.Context(
+ "sink.js " + process.pid + ' ' + new Date()
+ );
+
+ getContext = function () { return ctx; };
+
+ return ctx;
+ };
+}();
+
+var streamCount = 0;
+
+Sink.sinks('cubeb', function () {
+ var self = this;
+
+ self.start.apply(self, arguments);
+
+ self._ctx = getContext();
+ self._stream = new cubeb.Stream(
+ self._ctx,
+ self._ctx.name + ' ' + streamCount++,
+ cubeb.SAMPLE_FLOAT32LE,
+ self.channelCount,
+ self.sampleRate,
+ self.bufferSize,
+ self._latency,
+ function (frameCount) {
+ var buffer = new Buffer(
+ 4 * frameCount * self.channelCount);
+ var soundData = new Float32Array(buffer);
+
+ self.process(soundData, self.channelCount);
+
+ self._stream.write(buffer);
+ self._stream.release();
+ },
+ function (state) {}
+ );
+
+ self._stream.start();
+}, {
+ _ctx: null,
+ _stream: null,
+ _latency: 250,
+ bufferSize: 4096,
+
+ kill: function () {
+ this._stream.stop();
+ this.emit('kill');
+ },
+
+ getPlaybackTime: function () {
+ return this._stream.position;
+ }
+});
+
+}(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 (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));
+ (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 = null,
+ soundData = null,
+ zeroBuffer = null;
+ self.start.apply(self, arguments);
+ node = context.createJavaScriptNode(self.bufferSize, self.channelCount, self.channelCount);
+
+ 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) {
+
+/**
+ * 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.
+ *
+ * @return {Buffer} The interleaved buffer created.
+*/
+
+Sink.interleave = function (buffers, channelCount, buffer) {
+ channelCount = channelCount || buffers.length;
+ var l = buffers[0].length,
+ bufferCount = buffers.length,
+ i, n;
+ buffer = buffer || new Float32Array(l * channelCount);
+ for (i=0; i<bufferCount; i++) {
+ for (n=0; n<l; n++) {
+ buffer[i + n * channelCount] = buffers[i][n];
+ }
+ }
+ return buffer;
+};
+
+/**
+ * Mixes two or more buffers down to one.
+ *
+ * @static Sink
+ * @name mix
+ *
+ * @arg {Buffer} buffer The buffer to append the others to.
+ * @arg {Buffer} bufferX The buffers to append from.
+ *
+ * @return {Buffer} The mixed buffer.
+*/
+
+Sink.mix = function (buffer) {
+ var buffers = [].slice.call(arguments, 1),
+ l, i, c;
+ for (c=0; c<buffers.length; c++){
+ l = Math.max(buffer.length, buffers[c].length);
+ for (i=0; i<l; i++){
+ buffer[i] += buffers[c][i];
+ }
+ }
+ return buffer;
+};
+
+/**
+ * Resets a buffer to all zeroes.
+ *
+ * @static Sink
+ * @name resetBuffer
+ *
+ * @arg {Buffer} buffer The buffer to reset.
+ *
+ * @return {Buffer} The 0-reset buffer.
+*/
+
+Sink.resetBuffer = function (buffer) {
+ var l = buffer.length,
+ i;
+ for (i=0; i<l; i++){
+ buffer[i] = 0;
+ }
+ return buffer;
+};
+
+/**
+ * Copies the content of a buffer to another buffer.
+ *
+ * @static Sink
+ * @name clone
+ *
+ * @arg {Buffer} buffer The buffer to copy from.
+ * @arg {Buffer} !result The buffer to copy to.
+ *
+ * @return {Buffer} A clone of the buffer.
+*/
+
+Sink.clone = function (buffer, result) {
+ var l = buffer.length,
+ i;
+ result = result || new Float32Array(l);
+ for (i=0; i<l; i++){
+ result[i] = buffer[i];
+ }
+ return result;
+};
+
+/**
+ * Creates an array of buffers of the specified length and the specified count.
+ *
+ * @static Sink
+ * @name createDeinterleaved
+ *
+ * @arg {Number} length The length of a single channel.
+ * @arg {Number} channelCount The number of channels.
+ * @return {Array} The array of buffers.
+*/
+
+Sink.createDeinterleaved = function (length, channelCount) {
+ var result = new Array(channelCount),
+ i;
+ for (i=0; i<channelCount; i++){
+ result[i] = new Float32Array(length);
+ }
+ return result;
+};
+
+Sink.memcpy = function (src, srcOffset, dst, dstOffset, length) {
+ src = src.subarray || src.slice ? src : src.buffer;
+ dst = dst.subarray || dst.slice ? dst : dst.buffer;
+
+ src = srcOffset ? src.subarray ?
+ src.subarray(srcOffset, length && srcOffset + length) :
+ src.slice(srcOffset, length && srcOffset + length) : src;
+
+ if (dst.set) {
+ dst.set(src, dstOffset);
+ } else {
+ for (var i=0; i<src.length; i++) {
+ dst[i + dstOffset] = src[i];
+ }
+ }
+
+ return dst;
+};
+
+Sink.memslice = function (buffer, offset, length) {
+ return buffer.subarray ? buffer.subarray(offset, length) : buffer.slice(offset, length);
+};
+
+Sink.mempad = function (buffer, out, offset) {
+ out = out.length ? out : new (buffer.constructor)(out);
+ Sink.memcpy(buffer, 0, out, offset);
+ return out;
+};
+
+Sink.linspace = function (start, end, out) {
+ var l, i, n, step;
+ out = out.length ? (l=out.length) && out : Array(l=out);
+ step = (end - start) / --l;
+ for (n=start+step, i=1; i<l; i++, n+=step) {
+ out[i] = n;
+ }
+ out[0] = start;
+ out[l] = end;
+ return out;
+};
+
+Sink.ftoi = function (input, bitCount, output) {
+ var i, mask = Math.pow(2, bitCount - 1);
+
+ output = output || new (input.constructor)(input.length);
+
+ for (i=0; i<input.length; i++) {
+ output[i] = ~~(mask * input[i]);
+ }
+
+ return output;
+};
+
+}(this.Sink));
+(function (Sink) {
+
+function Proxy (bufferSize, channelCount) {
+ Sink.EventEmitter.call(this);
+
+ this.bufferSize = isNaN(bufferSize) || bufferSize === null ? this.bufferSize : bufferSize;
+ this.channelCount = isNaN(channelCount) || channelCount === null ? this.channelCount : channelCount;
+
+ var self = this;
+ this.callback = function () {
+ return self.process.apply(self, arguments);
+ };
+
+ this.resetBuffer();
+}
+
+Proxy.prototype = {
+ buffer: null,
+ zeroBuffer: null,
+ parentSink: null,
+ bufferSize: 4096,
+ channelCount: 2,
+ offset: null,
+
+ resetBuffer: function () {
+ this.buffer = new Float32Array(this.bufferSize);
+ this.zeroBuffer = new Float32Array(this.bufferSize);
+ },
+
+ process: function (buffer, channelCount) {
+ if (this.offset === null) {
+ this.loadBuffer();
+ }
+
+ for (var i=0; i<buffer.length; i++) {
+ if (this.offset >= this.buffer.length) {
+ this.loadBuffer();
+ }
+
+ buffer[i] = this.buffer[this.offset++];
+ }
+ },
+
+ loadBuffer: function () {
+ this.offset = 0;
+ Sink.memcpy(this.zeroBuffer, 0, this.buffer, 0);
+ this.emit('audioprocess', [this.buffer, this.channelCount]);
+ }
+};
+
+Sink.Proxy = Proxy;
+
+/**
+ * Creates a proxy callback system for the sink instance.
+ * Requires Sink utils.
+ *
+ * @method Sink
+ * @method createProxy
+ *
+ * @arg {Number} !bufferSize The buffer size for the proxy.
+*/
+Sink.prototype.createProxy = function (bufferSize) {
+ var proxy = new Sink.Proxy(bufferSize, this.channelCount);
+ proxy.parentSink = this;
+
+ this.on('audioprocess', proxy.callback);
+
+ return proxy;
+};
+
+}(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));
+void function (Sink) {
+
+Sink.on('init', function (sink) {
+ sink.activeRecordings = [];
+ sink.on('postprocess', sink.recordData);
+});
+
+Sink.prototype.activeRecordings = null;
+
+/**
+ * Starts recording the sink output.
+ *
+ * @method Sink
+ * @name record
+ *
+ * @return {Recording} The recording object for the recording started.
+*/
+Sink.prototype.record = function () {
+ var recording = new Sink.Recording(this);
+ this.emit('record', [recording]);
+ return recording;
+};
+/**
+ * Private method that handles the adding the buffers to all the current recordings.
+ *
+ * @method Sink
+ * @method recordData
+ *
+ * @arg {Array} buffer The buffer to record.
+*/
+Sink.prototype.recordData = function (buffer) {
+ var activeRecs = this.activeRecordings,
+ i, l = activeRecs.length;
+ for (i=0; i<l; i++) {
+ activeRecs[i].add(buffer);
+ }
+};
+
+/**
+ * A Recording class for recording sink output.
+ *
+ * @class
+ * @static Sink
+ * @arg {Object} bindTo The sink to bind the recording to.
+*/
+
+function Recording (bindTo) {
+ this.boundTo = bindTo;
+ this.buffers = [];
+ bindTo.activeRecordings.push(this);
+}
+
+Recording.prototype = {
+/**
+ * Adds a new buffer to the recording.
+ *
+ * @arg {Array} buffer The buffer to add.
+ *
+ * @method Recording
+*/
+ add: function (buffer) {
+ this.buffers.push(buffer);
+ },
+/**
+ * Empties the recording.
+ *
+ * @method Recording
+*/
+ clear: function () {
+ this.buffers = [];
+ },
+/**
+ * Stops the recording and unbinds it from it's host sink.
+ *
+ * @method Recording
+*/
+ stop: function () {
+ var recordings = this.boundTo.activeRecordings,
+ i;
+ for (i=0; i<recordings.length; i++) {
+ if (recordings[i] === this) {
+ recordings.splice(i--, 1);
+ }
+ }
+ },
+/**
+ * Joins the recorded buffers into a single buffer.
+ *
+ * @method Recording
+*/
+ join: function () {
+ var bufferLength = 0,
+ bufPos = 0,
+ buffers = this.buffers,
+ newArray,
+ n, i, l = buffers.length;
+
+ for (i=0; i<l; i++) {
+ bufferLength += buffers[i].length;
+ }
+ newArray = new Float32Array(bufferLength);
+ for (i=0; i<l; i++) {
+ for (n=0; n<buffers[i].length; n++) {
+ newArray[bufPos + n] = buffers[i][n];
+ }
+ bufPos += buffers[i].length;
+ }
+ return newArray;
+ }
+};
+
+Sink.Recording = Recording;
+
+}(this.Sink);
+void function (Sink) {
+
+function processRingBuffer () {
+ if (this.ringBuffer) {
+ (this.channelMode === 'interleaved' ? this.ringSpin : this.ringSpinInterleaved).apply(this, arguments);
+ }
+}
+
+Sink.on('init', function (sink) {
+ sink.on('preprocess', processRingBuffer);
+});
+
+Sink.prototype.ringBuffer = null;
+
+/**
+ * A private method that applies the ring buffer contents to the specified buffer, while in interleaved mode.
+ *
+ * @method Sink
+ * @name ringSpin
+ *
+ * @arg {Array} buffer The buffer to write to.
+*/
+Sink.prototype.ringSpin = function (buffer) {
+ var ring = this.ringBuffer,
+ l = buffer.length,
+ m = ring.length,
+ off = this.ringOffset,
+ i;
+ for (i=0; i<l; i++){
+ buffer[i] += ring[off];
+ off = (off + 1) % m;
+ }
+ this.ringOffset = off;
+};
+
+/**
+ * A private method that applies the ring buffer contents to the specified buffer, while in deinterleaved mode.
+ *
+ * @method Sink
+ * @name ringSpinDeinterleaved
+ *
+ * @param {Array} buffer The buffers to write to.
+*/
+Sink.prototype.ringSpinDeinterleaved = function (buffer) {
+ var ring = this.ringBuffer,
+ l = buffer.length,
+ ch = ring.length,
+ m = ring[0].length,
+ len = ch * m,
+ off = this.ringOffset,
+ i, n;
+ for (i=0; i<l; i+=ch){
+ for (n=0; n<ch; n++){
+ buffer[i + n] += ring[n][off];
+ }
+ off = (off + 1) % m;
+ }
+ this.ringOffset = n;
+};
+
+}(this.Sink);
+void function (Sink, proto) {
+
+proto = Sink.prototype;
+
+Sink.on('init', function (sink) {
+ sink.asyncBuffers = [];
+ sink.syncBuffers = [];
+ sink.on('preprocess', sink.writeBuffersSync);
+ sink.on('postprocess', sink.writeBuffersAsync);
+});
+
+proto.writeMode = 'async';
+proto.asyncBuffers = proto.syncBuffers = null;
+
+/**
+ * Private method that handles the mixing of asynchronously written buffers.
+ *
+ * @method Sink
+ * @name writeBuffersAsync
+ *
+ * @arg {Array} buffer The buffer to write to.
+*/
+proto.writeBuffersAsync = function (buffer) {
+ var buffers = this.asyncBuffers,
+ l = buffer.length,
+ buf,
+ bufLength,
+ i, n, offset;
+ if (buffers) {
+ for (i=0; i<buffers.length; i++) {
+ buf = buffers[i];
+ bufLength = buf.b.length;
+ offset = buf.d;
+ buf.d -= Math.min(offset, l);
+
+ for (n=0; n + offset < l && n < bufLength; n++) {
+ buffer[n + offset] += buf.b[n];
+ }
+ buf.b = buf.b.subarray(n + offset);
+ if (i >= bufLength) {
+ buffers.splice(i--, 1);
+ }
+ }
+ }
+};
+
+/**
+ * A private method that handles mixing synchronously written buffers.
+ *
+ * @method Sink
+ * @name writeBuffersSync
+ *
+ * @arg {Array} buffer The buffer to write to.
+*/
+proto.writeBuffersSync = function (buffer) {
+ var buffers = this.syncBuffers,
+ l = buffer.length,
+ i = 0,
+ soff = 0;
+ for (;i<l && buffers.length; i++) {
+ buffer[i] += buffers[0][soff];
+ if (buffers[0].length <= soff){
+ buffers.splice(0, 1);
+ soff = 0;
+ continue;
+ }
+ soff++;
+ }
+ if (buffers.length) {
+ buffers[0] = buffers[0].subarray(soff);
+ }
+};
+
+/**
+ * Writes a buffer asynchronously on top of the existing signal, after a specified delay.
+ *
+ * @method Sink
+ * @name writeBufferAsync
+ *
+ * @arg {Array} buffer The buffer to write.
+ * @arg {Number} delay The delay to write after. If not specified, the Sink will calculate a delay to compensate the latency.
+ * @return {Number} The number of currently stored asynchronous buffers.
+*/
+proto.writeBufferAsync = function (buffer, delay) {
+ buffer = this.mode === 'deinterleaved' ? Sink.interleave(buffer, this.channelCount) : buffer;
+ var buffers = this.asyncBuffers;
+ buffers.push({
+ b: buffer,
+ d: isNaN(delay) ? ~~((+new Date() - this.previousHit) / 1000 * this.sampleRate) : delay
+ });
+ return buffers.length;
+};
+
+/**
+ * Writes a buffer synchronously to the output.
+ *
+ * @method Sink
+ * @name writeBufferSync
+ *
+ * @param {Array} buffer The buffer to write.
+ * @return {Number} The number of currently stored synchronous buffers.
+*/
+proto.writeBufferSync = function (buffer) {
+ buffer = this.mode === 'deinterleaved' ? Sink.interleave(buffer, this.channelCount) : buffer;
+ var buffers = this.syncBuffers;
+ buffers.push(buffer);
+ return buffers.length;
+};
+
+/**
+ * Writes a buffer, according to the write mode specified.
+ *
+ * @method Sink
+ * @name writeBuffer
+ *
+ * @arg {Array} buffer The buffer to write.
+ * @arg {Number} delay The delay to write after. If not specified, the Sink will calculate a delay to compensate the latency. (only applicable in asynchronous write mode)
+ * @return {Number} The number of currently stored (a)synchronous buffers.
+*/
+proto.writeBuffer = function () {
+ return this[this.writeMode === 'async' ? 'writeBufferAsync' : 'writeBufferSync'].apply(this, arguments);
+};
+
+/**
+ * Gets the total amount of yet unwritten samples in the synchronous buffers.
+ *
+ * @method Sink
+ * @name getSyncWriteOffset
+ *
+ * @return {Number} The total amount of yet unwritten samples in the synchronous buffers.
+*/
+proto.getSyncWriteOffset = function () {
+ var buffers = this.syncBuffers,
+ offset = 0,
+ i;
+ for (i=0; i<buffers.length; i++) {
+ offset += buffers[i].length;
+ }
+ return offset;
+};
+
+} (this.Sink);