From: karim hamidou Date: Wed, 29 May 2013 14:13:32 +0000 (+0200) Subject: porting to sink.js, for portability X-Git-Url: http://git.khamidou.com/?a=commitdiff_plain;h=f9e652a44f344adea1f6074a53e0efd83bddbb8e;p=minisynth.git porting to sink.js, for portability --- diff --git a/sink.js b/sink.js new file mode 100644 index 0000000..98e07d1 --- /dev/null +++ b/sink.js @@ -0,0 +1,1718 @@ +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 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 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= 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= 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 dynamicaudio demo + - - - - - - + +