merge
This commit is contained in:
commit
688e275e0c
396 changed files with 41550 additions and 30663 deletions
488
packages/superdough/fft.js
Normal file
488
packages/superdough/fft.js
Normal file
|
|
@ -0,0 +1,488 @@
|
|||
'use strict';
|
||||
// sourced from https://github.com/indutny/fft.js/
|
||||
// LICENSE
|
||||
// This software is licensed under the MIT License.
|
||||
// Copyright Fedor Indutny, 2017.
|
||||
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software
|
||||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
export default class FFT {
|
||||
constructor(size) {
|
||||
this.size = size | 0;
|
||||
if (this.size <= 1 || (this.size & (this.size - 1)) !== 0)
|
||||
throw new Error('FFT size must be a power of two and bigger than 1');
|
||||
|
||||
this._csize = size << 1;
|
||||
|
||||
// NOTE: Use of `var` is intentional for old V8 versions
|
||||
var table = new Array(this.size * 2);
|
||||
for (var i = 0; i < table.length; i += 2) {
|
||||
const angle = (Math.PI * i) / this.size;
|
||||
table[i] = Math.cos(angle);
|
||||
table[i + 1] = -Math.sin(angle);
|
||||
}
|
||||
this.table = table;
|
||||
|
||||
// Find size's power of two
|
||||
var power = 0;
|
||||
for (var t = 1; this.size > t; t <<= 1) power++;
|
||||
|
||||
// Calculate initial step's width:
|
||||
// * If we are full radix-4 - it is 2x smaller to give inital len=8
|
||||
// * Otherwise it is the same as `power` to give len=4
|
||||
this._width = power % 2 === 0 ? power - 1 : power;
|
||||
|
||||
// Pre-compute bit-reversal patterns
|
||||
this._bitrev = new Array(1 << this._width);
|
||||
for (var j = 0; j < this._bitrev.length; j++) {
|
||||
this._bitrev[j] = 0;
|
||||
for (var shift = 0; shift < this._width; shift += 2) {
|
||||
var revShift = this._width - shift - 2;
|
||||
this._bitrev[j] |= ((j >>> shift) & 3) << revShift;
|
||||
}
|
||||
}
|
||||
|
||||
this._out = null;
|
||||
this._data = null;
|
||||
this._inv = 0;
|
||||
}
|
||||
fromComplexArray(complex, storage) {
|
||||
var res = storage || new Array(complex.length >>> 1);
|
||||
for (var i = 0; i < complex.length; i += 2) res[i >>> 1] = complex[i];
|
||||
return res;
|
||||
}
|
||||
createComplexArray() {
|
||||
const res = new Array(this._csize);
|
||||
for (var i = 0; i < res.length; i++) res[i] = 0;
|
||||
return res;
|
||||
}
|
||||
toComplexArray(input, storage) {
|
||||
var res = storage || this.createComplexArray();
|
||||
for (var i = 0; i < res.length; i += 2) {
|
||||
res[i] = input[i >>> 1];
|
||||
res[i + 1] = 0;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
completeSpectrum(spectrum) {
|
||||
var size = this._csize;
|
||||
var half = size >>> 1;
|
||||
for (var i = 2; i < half; i += 2) {
|
||||
spectrum[size - i] = spectrum[i];
|
||||
spectrum[size - i + 1] = -spectrum[i + 1];
|
||||
}
|
||||
}
|
||||
transform(out, data) {
|
||||
if (out === data) throw new Error('Input and output buffers must be different');
|
||||
|
||||
this._out = out;
|
||||
this._data = data;
|
||||
this._inv = 0;
|
||||
this._transform4();
|
||||
this._out = null;
|
||||
this._data = null;
|
||||
}
|
||||
realTransform(out, data) {
|
||||
if (out === data) throw new Error('Input and output buffers must be different');
|
||||
|
||||
this._out = out;
|
||||
this._data = data;
|
||||
this._inv = 0;
|
||||
this._realTransform4();
|
||||
this._out = null;
|
||||
this._data = null;
|
||||
}
|
||||
inverseTransform(out, data) {
|
||||
if (out === data) throw new Error('Input and output buffers must be different');
|
||||
|
||||
this._out = out;
|
||||
this._data = data;
|
||||
this._inv = 1;
|
||||
this._transform4();
|
||||
for (var i = 0; i < out.length; i++) out[i] /= this.size;
|
||||
this._out = null;
|
||||
this._data = null;
|
||||
}
|
||||
// radix-4 implementation
|
||||
//
|
||||
// NOTE: Uses of `var` are intentional for older V8 version that do not
|
||||
// support both `let compound assignments` and `const phi`
|
||||
_transform4() {
|
||||
var out = this._out;
|
||||
var size = this._csize;
|
||||
|
||||
// Initial step (permute and transform)
|
||||
var width = this._width;
|
||||
var step = 1 << width;
|
||||
var len = (size / step) << 1;
|
||||
|
||||
var outOff;
|
||||
var t;
|
||||
var bitrev = this._bitrev;
|
||||
if (len === 4) {
|
||||
for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
|
||||
const off = bitrev[t];
|
||||
this._singleTransform2(outOff, off, step);
|
||||
}
|
||||
} else {
|
||||
// len === 8
|
||||
for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
|
||||
const off = bitrev[t];
|
||||
this._singleTransform4(outOff, off, step);
|
||||
}
|
||||
}
|
||||
|
||||
// Loop through steps in decreasing order
|
||||
var inv = this._inv ? -1 : 1;
|
||||
var table = this.table;
|
||||
for (step >>= 2; step >= 2; step >>= 2) {
|
||||
len = (size / step) << 1;
|
||||
var quarterLen = len >>> 2;
|
||||
|
||||
// Loop through offsets in the data
|
||||
for (outOff = 0; outOff < size; outOff += len) {
|
||||
// Full case
|
||||
var limit = outOff + quarterLen;
|
||||
for (var i = outOff, k = 0; i < limit; i += 2, k += step) {
|
||||
const A = i;
|
||||
const B = A + quarterLen;
|
||||
const C = B + quarterLen;
|
||||
const D = C + quarterLen;
|
||||
|
||||
// Original values
|
||||
const Ar = out[A];
|
||||
const Ai = out[A + 1];
|
||||
const Br = out[B];
|
||||
const Bi = out[B + 1];
|
||||
const Cr = out[C];
|
||||
const Ci = out[C + 1];
|
||||
const Dr = out[D];
|
||||
const Di = out[D + 1];
|
||||
|
||||
// Middle values
|
||||
const MAr = Ar;
|
||||
const MAi = Ai;
|
||||
|
||||
const tableBr = table[k];
|
||||
const tableBi = inv * table[k + 1];
|
||||
const MBr = Br * tableBr - Bi * tableBi;
|
||||
const MBi = Br * tableBi + Bi * tableBr;
|
||||
|
||||
const tableCr = table[2 * k];
|
||||
const tableCi = inv * table[2 * k + 1];
|
||||
const MCr = Cr * tableCr - Ci * tableCi;
|
||||
const MCi = Cr * tableCi + Ci * tableCr;
|
||||
|
||||
const tableDr = table[3 * k];
|
||||
const tableDi = inv * table[3 * k + 1];
|
||||
const MDr = Dr * tableDr - Di * tableDi;
|
||||
const MDi = Dr * tableDi + Di * tableDr;
|
||||
|
||||
// Pre-Final values
|
||||
const T0r = MAr + MCr;
|
||||
const T0i = MAi + MCi;
|
||||
const T1r = MAr - MCr;
|
||||
const T1i = MAi - MCi;
|
||||
const T2r = MBr + MDr;
|
||||
const T2i = MBi + MDi;
|
||||
const T3r = inv * (MBr - MDr);
|
||||
const T3i = inv * (MBi - MDi);
|
||||
|
||||
// Final values
|
||||
const FAr = T0r + T2r;
|
||||
const FAi = T0i + T2i;
|
||||
|
||||
const FCr = T0r - T2r;
|
||||
const FCi = T0i - T2i;
|
||||
|
||||
const FBr = T1r + T3i;
|
||||
const FBi = T1i - T3r;
|
||||
|
||||
const FDr = T1r - T3i;
|
||||
const FDi = T1i + T3r;
|
||||
|
||||
out[A] = FAr;
|
||||
out[A + 1] = FAi;
|
||||
out[B] = FBr;
|
||||
out[B + 1] = FBi;
|
||||
out[C] = FCr;
|
||||
out[C + 1] = FCi;
|
||||
out[D] = FDr;
|
||||
out[D + 1] = FDi;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// radix-2 implementation
|
||||
//
|
||||
// NOTE: Only called for len=4
|
||||
_singleTransform2(outOff, off, step) {
|
||||
const out = this._out;
|
||||
const data = this._data;
|
||||
|
||||
const evenR = data[off];
|
||||
const evenI = data[off + 1];
|
||||
const oddR = data[off + step];
|
||||
const oddI = data[off + step + 1];
|
||||
|
||||
const leftR = evenR + oddR;
|
||||
const leftI = evenI + oddI;
|
||||
const rightR = evenR - oddR;
|
||||
const rightI = evenI - oddI;
|
||||
|
||||
out[outOff] = leftR;
|
||||
out[outOff + 1] = leftI;
|
||||
out[outOff + 2] = rightR;
|
||||
out[outOff + 3] = rightI;
|
||||
}
|
||||
// radix-4
|
||||
//
|
||||
// NOTE: Only called for len=8
|
||||
_singleTransform4(outOff, off, step) {
|
||||
const out = this._out;
|
||||
const data = this._data;
|
||||
const inv = this._inv ? -1 : 1;
|
||||
const step2 = step * 2;
|
||||
const step3 = step * 3;
|
||||
|
||||
// Original values
|
||||
const Ar = data[off];
|
||||
const Ai = data[off + 1];
|
||||
const Br = data[off + step];
|
||||
const Bi = data[off + step + 1];
|
||||
const Cr = data[off + step2];
|
||||
const Ci = data[off + step2 + 1];
|
||||
const Dr = data[off + step3];
|
||||
const Di = data[off + step3 + 1];
|
||||
|
||||
// Pre-Final values
|
||||
const T0r = Ar + Cr;
|
||||
const T0i = Ai + Ci;
|
||||
const T1r = Ar - Cr;
|
||||
const T1i = Ai - Ci;
|
||||
const T2r = Br + Dr;
|
||||
const T2i = Bi + Di;
|
||||
const T3r = inv * (Br - Dr);
|
||||
const T3i = inv * (Bi - Di);
|
||||
|
||||
// Final values
|
||||
const FAr = T0r + T2r;
|
||||
const FAi = T0i + T2i;
|
||||
|
||||
const FBr = T1r + T3i;
|
||||
const FBi = T1i - T3r;
|
||||
|
||||
const FCr = T0r - T2r;
|
||||
const FCi = T0i - T2i;
|
||||
|
||||
const FDr = T1r - T3i;
|
||||
const FDi = T1i + T3r;
|
||||
|
||||
out[outOff] = FAr;
|
||||
out[outOff + 1] = FAi;
|
||||
out[outOff + 2] = FBr;
|
||||
out[outOff + 3] = FBi;
|
||||
out[outOff + 4] = FCr;
|
||||
out[outOff + 5] = FCi;
|
||||
out[outOff + 6] = FDr;
|
||||
out[outOff + 7] = FDi;
|
||||
}
|
||||
// Real input radix-4 implementation
|
||||
_realTransform4() {
|
||||
var out = this._out;
|
||||
var size = this._csize;
|
||||
|
||||
// Initial step (permute and transform)
|
||||
var width = this._width;
|
||||
var step = 1 << width;
|
||||
var len = (size / step) << 1;
|
||||
|
||||
var outOff;
|
||||
var t;
|
||||
var bitrev = this._bitrev;
|
||||
if (len === 4) {
|
||||
for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
|
||||
const off = bitrev[t];
|
||||
this._singleRealTransform2(outOff, off >>> 1, step >>> 1);
|
||||
}
|
||||
} else {
|
||||
// len === 8
|
||||
for (outOff = 0, t = 0; outOff < size; outOff += len, t++) {
|
||||
const off = bitrev[t];
|
||||
this._singleRealTransform4(outOff, off >>> 1, step >>> 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Loop through steps in decreasing order
|
||||
var inv = this._inv ? -1 : 1;
|
||||
var table = this.table;
|
||||
for (step >>= 2; step >= 2; step >>= 2) {
|
||||
len = (size / step) << 1;
|
||||
var halfLen = len >>> 1;
|
||||
var quarterLen = halfLen >>> 1;
|
||||
var hquarterLen = quarterLen >>> 1;
|
||||
|
||||
// Loop through offsets in the data
|
||||
for (outOff = 0; outOff < size; outOff += len) {
|
||||
for (var i = 0, k = 0; i <= hquarterLen; i += 2, k += step) {
|
||||
var A = outOff + i;
|
||||
var B = A + quarterLen;
|
||||
var C = B + quarterLen;
|
||||
var D = C + quarterLen;
|
||||
|
||||
// Original values
|
||||
var Ar = out[A];
|
||||
var Ai = out[A + 1];
|
||||
var Br = out[B];
|
||||
var Bi = out[B + 1];
|
||||
var Cr = out[C];
|
||||
var Ci = out[C + 1];
|
||||
var Dr = out[D];
|
||||
var Di = out[D + 1];
|
||||
|
||||
// Middle values
|
||||
var MAr = Ar;
|
||||
var MAi = Ai;
|
||||
|
||||
var tableBr = table[k];
|
||||
var tableBi = inv * table[k + 1];
|
||||
var MBr = Br * tableBr - Bi * tableBi;
|
||||
var MBi = Br * tableBi + Bi * tableBr;
|
||||
|
||||
var tableCr = table[2 * k];
|
||||
var tableCi = inv * table[2 * k + 1];
|
||||
var MCr = Cr * tableCr - Ci * tableCi;
|
||||
var MCi = Cr * tableCi + Ci * tableCr;
|
||||
|
||||
var tableDr = table[3 * k];
|
||||
var tableDi = inv * table[3 * k + 1];
|
||||
var MDr = Dr * tableDr - Di * tableDi;
|
||||
var MDi = Dr * tableDi + Di * tableDr;
|
||||
|
||||
// Pre-Final values
|
||||
var T0r = MAr + MCr;
|
||||
var T0i = MAi + MCi;
|
||||
var T1r = MAr - MCr;
|
||||
var T1i = MAi - MCi;
|
||||
var T2r = MBr + MDr;
|
||||
var T2i = MBi + MDi;
|
||||
var T3r = inv * (MBr - MDr);
|
||||
var T3i = inv * (MBi - MDi);
|
||||
|
||||
// Final values
|
||||
var FAr = T0r + T2r;
|
||||
var FAi = T0i + T2i;
|
||||
|
||||
var FBr = T1r + T3i;
|
||||
var FBi = T1i - T3r;
|
||||
|
||||
out[A] = FAr;
|
||||
out[A + 1] = FAi;
|
||||
out[B] = FBr;
|
||||
out[B + 1] = FBi;
|
||||
|
||||
// Output final middle point
|
||||
if (i === 0) {
|
||||
var FCr = T0r - T2r;
|
||||
var FCi = T0i - T2i;
|
||||
out[C] = FCr;
|
||||
out[C + 1] = FCi;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Do not overwrite ourselves
|
||||
if (i === hquarterLen) continue;
|
||||
|
||||
// In the flipped case:
|
||||
// MAi = -MAi
|
||||
// MBr=-MBi, MBi=-MBr
|
||||
// MCr=-MCr
|
||||
// MDr=MDi, MDi=MDr
|
||||
var ST0r = T1r;
|
||||
var ST0i = -T1i;
|
||||
var ST1r = T0r;
|
||||
var ST1i = -T0i;
|
||||
var ST2r = -inv * T3i;
|
||||
var ST2i = -inv * T3r;
|
||||
var ST3r = -inv * T2i;
|
||||
var ST3i = -inv * T2r;
|
||||
|
||||
var SFAr = ST0r + ST2r;
|
||||
var SFAi = ST0i + ST2i;
|
||||
|
||||
var SFBr = ST1r + ST3i;
|
||||
var SFBi = ST1i - ST3r;
|
||||
|
||||
var SA = outOff + quarterLen - i;
|
||||
var SB = outOff + halfLen - i;
|
||||
|
||||
out[SA] = SFAr;
|
||||
out[SA + 1] = SFAi;
|
||||
out[SB] = SFBr;
|
||||
out[SB + 1] = SFBi;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// radix-2 implementation
|
||||
//
|
||||
// NOTE: Only called for len=4
|
||||
_singleRealTransform2(outOff, off, step) {
|
||||
const out = this._out;
|
||||
const data = this._data;
|
||||
|
||||
const evenR = data[off];
|
||||
const oddR = data[off + step];
|
||||
|
||||
const leftR = evenR + oddR;
|
||||
const rightR = evenR - oddR;
|
||||
|
||||
out[outOff] = leftR;
|
||||
out[outOff + 1] = 0;
|
||||
out[outOff + 2] = rightR;
|
||||
out[outOff + 3] = 0;
|
||||
}
|
||||
// radix-4
|
||||
//
|
||||
// NOTE: Only called for len=8
|
||||
_singleRealTransform4(outOff, off, step) {
|
||||
const out = this._out;
|
||||
const data = this._data;
|
||||
const inv = this._inv ? -1 : 1;
|
||||
const step2 = step * 2;
|
||||
const step3 = step * 3;
|
||||
|
||||
// Original values
|
||||
const Ar = data[off];
|
||||
const Br = data[off + step];
|
||||
const Cr = data[off + step2];
|
||||
const Dr = data[off + step3];
|
||||
|
||||
// Pre-Final values
|
||||
const T0r = Ar + Cr;
|
||||
const T1r = Ar - Cr;
|
||||
const T2r = Br + Dr;
|
||||
const T3r = inv * (Br - Dr);
|
||||
|
||||
// Final values
|
||||
const FAr = T0r + T2r;
|
||||
|
||||
const FBr = T1r;
|
||||
const FBi = -T3r;
|
||||
|
||||
const FCr = T0r - T2r;
|
||||
|
||||
const FDr = T1r;
|
||||
const FDi = T3r;
|
||||
|
||||
out[outOff] = FAr;
|
||||
out[outOff + 1] = 0;
|
||||
out[outOff + 2] = FBr;
|
||||
out[outOff + 3] = FBi;
|
||||
out[outOff + 4] = FCr;
|
||||
out[outOff + 5] = 0;
|
||||
out[outOff + 6] = FDr;
|
||||
out[outOff + 7] = FDi;
|
||||
}
|
||||
}
|
||||
|
|
@ -14,6 +14,15 @@ const getSlope = (y1, y2, x1, x2) => {
|
|||
}
|
||||
return (y2 - y1) / (x2 - x1);
|
||||
};
|
||||
|
||||
export function getWorklet(ac, processor, params, config) {
|
||||
const node = new AudioWorkletNode(ac, processor, config);
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
node.parameters.get(key).value = value;
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
export const getParamADSR = (
|
||||
param,
|
||||
attack,
|
||||
|
|
@ -103,14 +112,22 @@ export const getADSRValues = (params, curve = 'linear', defaultValues) => {
|
|||
return [Math.max(a ?? 0, envmin), Math.max(d ?? 0, envmin), Math.min(sustain, envmax), Math.max(r ?? 0, releaseMin)];
|
||||
};
|
||||
|
||||
export function createFilter(context, type, frequency, Q, att, dec, sus, rel, fenv, start, end, fanchor) {
|
||||
export function createFilter(context, type, frequency, Q, att, dec, sus, rel, fenv, start, end, fanchor, model, drive) {
|
||||
const curve = 'exponential';
|
||||
const [attack, decay, sustain, release] = getADSRValues([att, dec, sus, rel], curve, [0.005, 0.14, 0, 0.1]);
|
||||
const filter = context.createBiquadFilter();
|
||||
let filter;
|
||||
let frequencyParam;
|
||||
if (model === 'ladder') {
|
||||
filter = getWorklet(context, 'ladder-processor', { frequency, q: Q, drive });
|
||||
frequencyParam = filter.parameters.get('frequency');
|
||||
} else {
|
||||
filter = context.createBiquadFilter();
|
||||
filter.type = type;
|
||||
filter.Q.value = Q;
|
||||
filter.frequency.value = frequency;
|
||||
frequencyParam = filter.frequency;
|
||||
}
|
||||
|
||||
filter.type = type;
|
||||
filter.Q.value = Q;
|
||||
filter.frequency.value = frequency;
|
||||
// envelope is active when any of these values is set
|
||||
const hasEnvelope = att ?? dec ?? sus ?? rel ?? fenv;
|
||||
// Apply ADSR to filter frequency
|
||||
|
|
@ -122,7 +139,7 @@ export function createFilter(context, type, frequency, Q, att, dec, sus, rel, fe
|
|||
let min = clamp(2 ** -offset * frequency, 0, 20000);
|
||||
let max = clamp(2 ** (fenvAbs - offset) * frequency, 0, 20000);
|
||||
if (fenv < 0) [min, max] = [max, min];
|
||||
getParamADSR(filter.frequency, attack, decay, sustain, release, min, max, start, end, curve);
|
||||
getParamADSR(frequencyParam, attack, decay, sustain, release, min, max, start, end, curve);
|
||||
return filter;
|
||||
}
|
||||
return filter;
|
||||
|
|
@ -195,6 +212,7 @@ export function webAudioTimeout(audioContext, onComplete, startTime, stopTime) {
|
|||
constantNode.onended = () => {
|
||||
onComplete();
|
||||
};
|
||||
return constantNode;
|
||||
}
|
||||
const mod = (freq, range = 1, type = 'sine') => {
|
||||
const ctx = getAudioContext();
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
/*
|
||||
index.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/packages/superdough/index.mjs>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/superdough/index.mjs>
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
|
|
|||
185
packages/superdough/ola-processor.js
Normal file
185
packages/superdough/ola-processor.js
Normal file
|
|
@ -0,0 +1,185 @@
|
|||
'use strict';
|
||||
|
||||
// sourced from https://github.com/olvb/phaze/tree/master?tab=readme-ov-file
|
||||
const WEBAUDIO_BLOCK_SIZE = 128;
|
||||
|
||||
/** Overlap-Add Node */
|
||||
class OLAProcessor extends AudioWorkletProcessor {
|
||||
constructor(options) {
|
||||
super(options);
|
||||
this.started = false;
|
||||
this.nbInputs = options.numberOfInputs;
|
||||
this.nbOutputs = options.numberOfOutputs;
|
||||
|
||||
this.blockSize = options.processorOptions.blockSize;
|
||||
// TODO for now, the only support hop size is the size of a web audio block
|
||||
this.hopSize = WEBAUDIO_BLOCK_SIZE;
|
||||
|
||||
this.nbOverlaps = this.blockSize / this.hopSize;
|
||||
|
||||
// pre-allocate input buffers (will be reallocated if needed)
|
||||
this.inputBuffers = new Array(this.nbInputs);
|
||||
this.inputBuffersHead = new Array(this.nbInputs);
|
||||
this.inputBuffersToSend = new Array(this.nbInputs);
|
||||
// default to 1 channel per input until we know more
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
this.allocateInputChannels(i, 1);
|
||||
}
|
||||
// pre-allocate input buffers (will be reallocated if needed)
|
||||
this.outputBuffers = new Array(this.nbOutputs);
|
||||
this.outputBuffersToRetrieve = new Array(this.nbOutputs);
|
||||
// default to 1 channel per output until we know more
|
||||
for (let i = 0; i < this.nbOutputs; i++) {
|
||||
this.allocateOutputChannels(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles dynamic reallocation of input/output channels buffer
|
||||
(channel numbers may lety during lifecycle) **/
|
||||
reallocateChannelsIfNeeded(inputs, outputs) {
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
let nbChannels = inputs[i].length;
|
||||
if (nbChannels != this.inputBuffers[i].length) {
|
||||
this.allocateInputChannels(i, nbChannels);
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < this.nbOutputs; i++) {
|
||||
let nbChannels = outputs[i].length;
|
||||
if (nbChannels != this.outputBuffers[i].length) {
|
||||
this.allocateOutputChannels(i, nbChannels);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
allocateInputChannels(inputIndex, nbChannels) {
|
||||
// allocate input buffers
|
||||
|
||||
this.inputBuffers[inputIndex] = new Array(nbChannels);
|
||||
for (let i = 0; i < nbChannels; i++) {
|
||||
this.inputBuffers[inputIndex][i] = new Float32Array(this.blockSize + WEBAUDIO_BLOCK_SIZE);
|
||||
this.inputBuffers[inputIndex][i].fill(0);
|
||||
}
|
||||
|
||||
// allocate input buffers to send and head pointers to copy from
|
||||
// (cannot directly send a pointer/subarray because input may be modified)
|
||||
this.inputBuffersHead[inputIndex] = new Array(nbChannels);
|
||||
this.inputBuffersToSend[inputIndex] = new Array(nbChannels);
|
||||
for (let i = 0; i < nbChannels; i++) {
|
||||
this.inputBuffersHead[inputIndex][i] = this.inputBuffers[inputIndex][i].subarray(0, this.blockSize);
|
||||
this.inputBuffersToSend[inputIndex][i] = new Float32Array(this.blockSize);
|
||||
}
|
||||
}
|
||||
|
||||
allocateOutputChannels(outputIndex, nbChannels) {
|
||||
// allocate output buffers
|
||||
this.outputBuffers[outputIndex] = new Array(nbChannels);
|
||||
for (let i = 0; i < nbChannels; i++) {
|
||||
this.outputBuffers[outputIndex][i] = new Float32Array(this.blockSize);
|
||||
this.outputBuffers[outputIndex][i].fill(0);
|
||||
}
|
||||
|
||||
// allocate output buffers to retrieve
|
||||
// (cannot send a pointer/subarray because new output has to be add to exising output)
|
||||
this.outputBuffersToRetrieve[outputIndex] = new Array(nbChannels);
|
||||
for (let i = 0; i < nbChannels; i++) {
|
||||
this.outputBuffersToRetrieve[outputIndex][i] = new Float32Array(this.blockSize);
|
||||
this.outputBuffersToRetrieve[outputIndex][i].fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Read next web audio block to input buffers **/
|
||||
readInputs(inputs) {
|
||||
// when playback is paused, we may stop receiving new samples
|
||||
if (inputs[0].length && inputs[0][0].length == 0) {
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
for (let j = 0; j < this.inputBuffers[i].length; j++) {
|
||||
this.inputBuffers[i][j].fill(0, this.blockSize);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
for (let j = 0; j < this.inputBuffers[i].length; j++) {
|
||||
let webAudioBlock = inputs[i][j];
|
||||
this.inputBuffers[i][j].set(webAudioBlock, this.blockSize);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Write next web audio block from output buffers **/
|
||||
writeOutputs(outputs) {
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
for (let j = 0; j < this.inputBuffers[i].length; j++) {
|
||||
let webAudioBlock = this.outputBuffers[i][j].subarray(0, WEBAUDIO_BLOCK_SIZE);
|
||||
outputs[i][j].set(webAudioBlock);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Shift left content of input buffers to receive new web audio block **/
|
||||
shiftInputBuffers() {
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
for (let j = 0; j < this.inputBuffers[i].length; j++) {
|
||||
this.inputBuffers[i][j].copyWithin(0, WEBAUDIO_BLOCK_SIZE);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Shift left content of output buffers to receive new web audio block **/
|
||||
shiftOutputBuffers() {
|
||||
for (let i = 0; i < this.nbOutputs; i++) {
|
||||
for (let j = 0; j < this.outputBuffers[i].length; j++) {
|
||||
this.outputBuffers[i][j].copyWithin(0, WEBAUDIO_BLOCK_SIZE);
|
||||
this.outputBuffers[i][j].subarray(this.blockSize - WEBAUDIO_BLOCK_SIZE).fill(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Copy contents of input buffers to buffer actually sent to process **/
|
||||
prepareInputBuffersToSend() {
|
||||
for (let i = 0; i < this.nbInputs; i++) {
|
||||
for (let j = 0; j < this.inputBuffers[i].length; j++) {
|
||||
this.inputBuffersToSend[i][j].set(this.inputBuffersHead[i][j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Add contents of output buffers just processed to output buffers **/
|
||||
handleOutputBuffersToRetrieve() {
|
||||
for (let i = 0; i < this.nbOutputs; i++) {
|
||||
for (let j = 0; j < this.outputBuffers[i].length; j++) {
|
||||
for (let k = 0; k < this.blockSize; k++) {
|
||||
this.outputBuffers[i][j][k] += this.outputBuffersToRetrieve[i][j][k] / this.nbOverlaps;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process(inputs, outputs, params) {
|
||||
const input = inputs[0];
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
this.reallocateChannelsIfNeeded(inputs, outputs);
|
||||
|
||||
this.readInputs(inputs);
|
||||
this.shiftInputBuffers();
|
||||
this.prepareInputBuffersToSend();
|
||||
this.processOLA(this.inputBuffersToSend, this.outputBuffersToRetrieve, params);
|
||||
this.handleOutputBuffersToRetrieve();
|
||||
this.writeOutputs(outputs);
|
||||
this.shiftOutputBuffers();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
processOLA(inputs, outputs, params) {
|
||||
console.assert(false, 'Not overriden');
|
||||
}
|
||||
}
|
||||
|
||||
export default OLAProcessor;
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "superdough",
|
||||
"version": "1.0.1",
|
||||
"version": "1.2.3",
|
||||
"description": "simple web audio synth and sampler intended for live coding. inspired by superdirt and webdirt.",
|
||||
"main": "index.mjs",
|
||||
"type": "module",
|
||||
|
|
@ -16,7 +16,7 @@
|
|||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tidalcycles/strudel.git"
|
||||
"url": "git+https://codeberg.org/uzu/strudel.git"
|
||||
},
|
||||
"keywords": [
|
||||
"tidalcycles",
|
||||
|
|
@ -28,13 +28,14 @@
|
|||
"author": "Felix Roos <flix91@gmail.com>",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"bugs": {
|
||||
"url": "https://github.com/tidalcycles/strudel/issues"
|
||||
"url": "https://codeberg.org/uzu/strudel/issues"
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"homepage": "https://codeberg.org/uzu/strudel#readme",
|
||||
"devDependencies": {
|
||||
"vite": "^5.0.10"
|
||||
"vite": "^6.0.11",
|
||||
"vite-plugin-bundle-audioworklet": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"nanostores": "^0.9.5"
|
||||
"nanostores": "^0.11.3"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,16 +22,13 @@ function humanFileSize(bytes, si) {
|
|||
return bytes.toFixed(1) + ' ' + units[u];
|
||||
}
|
||||
|
||||
export const getSampleBufferSource = async (s, n, note, speed, freq, bank, resolveUrl) => {
|
||||
let transpose = 0;
|
||||
if (freq !== undefined && note !== undefined) {
|
||||
logger('[sampler] hap has note and freq. ignoring note', 'warning');
|
||||
}
|
||||
let midi = valueToMidi({ freq, note }, 36);
|
||||
transpose = midi - 36; // C3 is middle C
|
||||
|
||||
const ac = getAudioContext();
|
||||
|
||||
// deduces relevant info for sample loading from hap.value and sample definition
|
||||
// it encapsulates the core sampler logic into a pure and synchronous function
|
||||
// hapValue: Hap.value, bank: sample bank definition for sound "s" (values in strudel.json format)
|
||||
export function getSampleInfo(hapValue, bank) {
|
||||
const { s, n = 0, speed = 1.0 } = hapValue;
|
||||
let midi = valueToMidi(hapValue, 36);
|
||||
let transpose = midi - 36; // C3 is middle C;
|
||||
let sampleUrl;
|
||||
let index = 0;
|
||||
if (Array.isArray(bank)) {
|
||||
|
|
@ -50,19 +47,54 @@ export const getSampleBufferSource = async (s, n, note, speed, freq, bank, resol
|
|||
index = getSoundIndex(n, bank[closest].length);
|
||||
sampleUrl = bank[closest][index];
|
||||
}
|
||||
const label = `${s}:${index}`;
|
||||
let playbackRate = Math.abs(speed) * Math.pow(2, transpose / 12);
|
||||
return { transpose, sampleUrl, index, midi, label, playbackRate };
|
||||
}
|
||||
|
||||
// takes hapValue and returns buffer + playbackRate.
|
||||
export const getSampleBuffer = async (hapValue, bank, resolveUrl) => {
|
||||
let { sampleUrl, label, playbackRate } = getSampleInfo(hapValue, bank);
|
||||
if (resolveUrl) {
|
||||
sampleUrl = await resolveUrl(sampleUrl);
|
||||
}
|
||||
let buffer = await loadBuffer(sampleUrl, ac, s, index);
|
||||
if (speed < 0) {
|
||||
const ac = getAudioContext();
|
||||
const buffer = await loadBuffer(sampleUrl, ac, label);
|
||||
|
||||
if (hapValue.unit === 'c') {
|
||||
playbackRate = playbackRate * buffer.duration;
|
||||
}
|
||||
return { buffer, playbackRate };
|
||||
};
|
||||
|
||||
// creates playback ready AudioBufferSourceNode from hapValue
|
||||
export const getSampleBufferSource = async (hapValue, bank, resolveUrl) => {
|
||||
let { buffer, playbackRate } = await getSampleBuffer(hapValue, bank, resolveUrl);
|
||||
if (hapValue.speed < 0) {
|
||||
// should this be cached?
|
||||
buffer = reverseBuffer(buffer);
|
||||
}
|
||||
const ac = getAudioContext();
|
||||
const bufferSource = ac.createBufferSource();
|
||||
bufferSource.buffer = buffer;
|
||||
const playbackRate = 1.0 * Math.pow(2, transpose / 12);
|
||||
bufferSource.playbackRate.value = playbackRate;
|
||||
return bufferSource;
|
||||
|
||||
const { s, loopBegin = 0, loopEnd = 1, begin = 0, end = 1 } = hapValue;
|
||||
|
||||
// "The computation of the offset into the sound is performed using the sound buffer's natural sample rate,
|
||||
// rather than the current playback rate, so even if the sound is playing at twice its normal speed,
|
||||
// the midway point through a 10-second audio buffer is still 5."
|
||||
const offset = begin * bufferSource.buffer.duration;
|
||||
|
||||
const loop = s.startsWith('wt_') ? 1 : hapValue.loop;
|
||||
if (loop) {
|
||||
bufferSource.loop = true;
|
||||
bufferSource.loopStart = loopBegin * bufferSource.buffer.duration - offset;
|
||||
bufferSource.loopEnd = loopEnd * bufferSource.buffer.duration - offset;
|
||||
}
|
||||
const bufferDuration = bufferSource.buffer.duration / bufferSource.playbackRate.value;
|
||||
const sliceDuration = (end - begin) * bufferDuration;
|
||||
return { bufferSource, offset, bufferDuration, sliceDuration };
|
||||
};
|
||||
|
||||
export const loadBuffer = (url, ac, s, n = 0) => {
|
||||
|
|
@ -232,10 +264,10 @@ export const samples = async (sampleMap, baseUrl = sampleMap._base || '', option
|
|||
const { prebake, tag } = options;
|
||||
processSampleMap(
|
||||
sampleMap,
|
||||
(key, value) =>
|
||||
registerSound(key, (t, hapValue, onended) => onTriggerSample(t, hapValue, onended, value), {
|
||||
(key, bank) =>
|
||||
registerSound(key, (t, hapValue, onended) => onTriggerSample(t, hapValue, onended, bank), {
|
||||
type: 'sample',
|
||||
samples: value,
|
||||
samples: bank,
|
||||
baseUrl,
|
||||
prebake,
|
||||
tag,
|
||||
|
|
@ -249,38 +281,26 @@ const cutGroups = [];
|
|||
export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
|
||||
let {
|
||||
s,
|
||||
freq,
|
||||
unit,
|
||||
nudge = 0, // TODO: is this in seconds?
|
||||
cut,
|
||||
loop,
|
||||
clip = undefined, // if set, samples will be cut off when the hap ends
|
||||
n = 0,
|
||||
note,
|
||||
speed = 1, // sample playback speed
|
||||
loopBegin = 0,
|
||||
begin = 0,
|
||||
loopEnd = 1,
|
||||
end = 1,
|
||||
duration,
|
||||
} = value;
|
||||
|
||||
// load sample
|
||||
if (speed === 0) {
|
||||
// no playback
|
||||
return;
|
||||
}
|
||||
loop = s.startsWith('wt_') ? 1 : value.loop;
|
||||
const ac = getAudioContext();
|
||||
|
||||
// destructure adsr here, because the default should be different for synths and samples
|
||||
|
||||
let [attack, decay, sustain, release] = getADSRValues([value.attack, value.decay, value.sustain, value.release]);
|
||||
//const soundfont = getSoundfontKey(s);
|
||||
const time = t + nudge;
|
||||
|
||||
const bufferSource = await getSampleBufferSource(s, n, note, speed, freq, bank, resolveUrl);
|
||||
|
||||
// vibrato
|
||||
let vibratoOscillator = getVibratoOscillator(bufferSource.detune, value, t);
|
||||
const { bufferSource, sliceDuration, offset } = await getSampleBufferSource(value, bank, resolveUrl);
|
||||
|
||||
// asny stuff above took too long?
|
||||
if (ac.currentTime > t) {
|
||||
|
|
@ -292,26 +312,19 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
|
|||
logger(`[sampler] could not load "${s}:${n}"`, 'error');
|
||||
return;
|
||||
}
|
||||
bufferSource.playbackRate.value = Math.abs(speed) * bufferSource.playbackRate.value;
|
||||
if (unit === 'c') {
|
||||
// are there other units?
|
||||
bufferSource.playbackRate.value = bufferSource.playbackRate.value * bufferSource.buffer.duration * 1; //cps;
|
||||
}
|
||||
// "The computation of the offset into the sound is performed using the sound buffer's natural sample rate,
|
||||
// rather than the current playback rate, so even if the sound is playing at twice its normal speed,
|
||||
// the midway point through a 10-second audio buffer is still 5."
|
||||
const offset = begin * bufferSource.buffer.duration;
|
||||
if (loop) {
|
||||
bufferSource.loop = true;
|
||||
bufferSource.loopStart = loopBegin * bufferSource.buffer.duration - offset;
|
||||
bufferSource.loopEnd = loopEnd * bufferSource.buffer.duration - offset;
|
||||
}
|
||||
|
||||
// vibrato
|
||||
let vibratoOscillator = getVibratoOscillator(bufferSource.detune, value, t);
|
||||
|
||||
const time = t + nudge;
|
||||
bufferSource.start(time, offset);
|
||||
|
||||
const envGain = ac.createGain();
|
||||
const node = bufferSource.connect(envGain);
|
||||
|
||||
// if none of these controls is set, the duration of the sound will be set to the duration of the sample slice
|
||||
if (clip == null && loop == null && value.release == null) {
|
||||
const bufferDuration = bufferSource.buffer.duration / bufferSource.playbackRate.value;
|
||||
duration = (end - begin) * bufferDuration;
|
||||
duration = sliceDuration;
|
||||
}
|
||||
let holdEnd = t + duration;
|
||||
|
||||
|
|
@ -331,7 +344,9 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
|
|||
};
|
||||
let envEnd = holdEnd + release + 0.01;
|
||||
bufferSource.stop(envEnd);
|
||||
const stop = (endTime, playWholeBuffer) => {};
|
||||
const stop = (endTime) => {
|
||||
bufferSource.stop(endTime);
|
||||
};
|
||||
const handle = { node: out, bufferSource, stop };
|
||||
|
||||
// cut groups
|
||||
|
|
|
|||
|
|
@ -1,27 +1,176 @@
|
|||
/*
|
||||
superdough.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/packages/superdough/superdough.mjs>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/superdough/superdough.mjs>
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import './feedbackdelay.mjs';
|
||||
import './reverb.mjs';
|
||||
import './vowel.mjs';
|
||||
import { clamp, nanFallback } from './util.mjs';
|
||||
import workletsUrl from './worklets.mjs?url';
|
||||
import { createFilter, gainNode, getCompressor } from './helpers.mjs';
|
||||
import { clamp, nanFallback, _mod, cycleToSeconds } from './util.mjs';
|
||||
import workletsUrl from './worklets.mjs?audioworklet';
|
||||
import { createFilter, gainNode, getCompressor, getWorklet } from './helpers.mjs';
|
||||
import { map } from 'nanostores';
|
||||
import { logger } from './logger.mjs';
|
||||
import { loadBuffer } from './sampler.mjs';
|
||||
|
||||
export const DEFAULT_MAX_POLYPHONY = 128;
|
||||
const DEFAULT_AUDIO_DEVICE_NAME = 'System Standard';
|
||||
|
||||
let maxPolyphony = DEFAULT_MAX_POLYPHONY;
|
||||
|
||||
export function setMaxPolyphony(polyphony) {
|
||||
maxPolyphony = parseInt(polyphony) ?? DEFAULT_MAX_POLYPHONY;
|
||||
}
|
||||
|
||||
let multiChannelOrbits = false;
|
||||
export function setMultiChannelOrbits(bool) {
|
||||
multiChannelOrbits = bool == true;
|
||||
}
|
||||
|
||||
export const soundMap = map();
|
||||
|
||||
export function registerSound(key, onTrigger, data = {}) {
|
||||
key = key.toLowerCase().replace(/\s+/g, '_');
|
||||
soundMap.setKey(key, { onTrigger, data });
|
||||
}
|
||||
|
||||
let gainCurveFunc = (val) => val;
|
||||
|
||||
export function applyGainCurve(val) {
|
||||
return gainCurveFunc(val);
|
||||
}
|
||||
|
||||
export function setGainCurve(newGainCurveFunc) {
|
||||
gainCurveFunc = newGainCurveFunc;
|
||||
}
|
||||
|
||||
function aliasBankMap(aliasMap) {
|
||||
// Make all bank keys lower case for case insensitivity
|
||||
for (const key in aliasMap) {
|
||||
aliasMap[key.toLowerCase()] = aliasMap[key];
|
||||
}
|
||||
|
||||
// Look through every sound...
|
||||
const soundDictionary = soundMap.get();
|
||||
for (const key in soundDictionary) {
|
||||
// Check if the sound is part of a bank...
|
||||
const [bank, suffix] = key.split('_');
|
||||
if (!suffix) continue;
|
||||
|
||||
// Check if the bank is aliased...
|
||||
const aliasValue = aliasMap[bank];
|
||||
if (aliasValue) {
|
||||
if (typeof aliasValue === 'string') {
|
||||
// Alias a single alias
|
||||
soundDictionary[`${aliasValue}_${suffix}`.toLowerCase()] = soundDictionary[key];
|
||||
} else if (Array.isArray(aliasValue)) {
|
||||
// Alias multiple aliases
|
||||
for (const alias of aliasValue) {
|
||||
soundDictionary[`${alias}_${suffix}`.toLowerCase()] = soundDictionary[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Update the sound map!
|
||||
// We need to destructure here to trigger the update
|
||||
soundMap.set({ ...soundDictionary });
|
||||
}
|
||||
|
||||
async function aliasBankPath(path) {
|
||||
const response = await fetch(path);
|
||||
const aliasMap = await response.json();
|
||||
aliasBankMap(aliasMap);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register an alias for a bank of sounds.
|
||||
* Optionally accepts a single argument map of bank aliases.
|
||||
* Optionally accepts a single argument string of a path to a JSON file containing bank aliases.
|
||||
* @param {string} bank - The bank to alias
|
||||
* @param {string} alias - The alias to use for the bank
|
||||
*/
|
||||
export async function aliasBank(...args) {
|
||||
switch (args.length) {
|
||||
case 1:
|
||||
if (typeof args[0] === 'string') {
|
||||
return aliasBankPath(args[0]);
|
||||
} else {
|
||||
return aliasBankMap(args[0]);
|
||||
}
|
||||
case 2:
|
||||
return aliasBankMap({ [args[0]]: args[1] });
|
||||
default:
|
||||
throw new Error('aliasMap expects 1 or 2 arguments, received ' + args.length);
|
||||
}
|
||||
}
|
||||
|
||||
export function getSound(s) {
|
||||
return soundMap.get()[s];
|
||||
if (typeof s !== 'string') {
|
||||
console.warn(`getSound: expected string got "${s}". fall back to triangle`);
|
||||
return soundMap.get().triangle; // is this good?
|
||||
}
|
||||
return soundMap.get()[s.toLowerCase()];
|
||||
}
|
||||
|
||||
export const getAudioDevices = async () => {
|
||||
await navigator.mediaDevices.getUserMedia({ audio: true });
|
||||
let mediaDevices = await navigator.mediaDevices.enumerateDevices();
|
||||
mediaDevices = mediaDevices.filter((device) => device.kind === 'audiooutput' && device.deviceId !== 'default');
|
||||
const devicesMap = new Map();
|
||||
devicesMap.set(DEFAULT_AUDIO_DEVICE_NAME, '');
|
||||
mediaDevices.forEach((device) => {
|
||||
devicesMap.set(device.label, device.deviceId);
|
||||
});
|
||||
return devicesMap;
|
||||
};
|
||||
|
||||
const defaultDefaultValues = {
|
||||
s: 'triangle',
|
||||
gain: 0.8,
|
||||
postgain: 1,
|
||||
density: '.03',
|
||||
ftype: '12db',
|
||||
fanchor: 0,
|
||||
resonance: 1,
|
||||
hresonance: 1,
|
||||
bandq: 1,
|
||||
channels: [1, 2],
|
||||
phaserdepth: 0.75,
|
||||
shapevol: 1,
|
||||
distortvol: 1,
|
||||
delay: 0,
|
||||
byteBeatExpression: '0',
|
||||
delayfeedback: 0.5,
|
||||
delaysync: 3 / 16,
|
||||
orbit: 1,
|
||||
i: 1,
|
||||
velocity: 1,
|
||||
fft: 8,
|
||||
};
|
||||
|
||||
let defaultControls = new Map(Object.entries(defaultDefaultValues));
|
||||
|
||||
export function setDefaultValue(key, value) {
|
||||
defaultControls.set(key, value);
|
||||
}
|
||||
export function getDefaultValue(key) {
|
||||
return defaultControls.get(key);
|
||||
}
|
||||
export function setDefaultValues(defaultsobj) {
|
||||
Object.keys(defaultsobj).forEach((key) => {
|
||||
setDefaultValue(key, defaultsobj[key]);
|
||||
});
|
||||
}
|
||||
export function resetDefaultValues() {
|
||||
defaultControls = new Map(Object.entries(defaultDefaultValues));
|
||||
}
|
||||
export function setVersionDefaults(version) {
|
||||
resetDefaultValues();
|
||||
if (version === '1.0') {
|
||||
setDefaultValue('fanchor', 0.5);
|
||||
}
|
||||
}
|
||||
|
||||
export const resetLoadedSounds = () => soundMap.set({});
|
||||
|
|
@ -37,50 +186,82 @@ export const getAudioContext = () => {
|
|||
if (!audioContext) {
|
||||
return setDefaultAudioContext();
|
||||
}
|
||||
|
||||
return audioContext;
|
||||
};
|
||||
|
||||
let workletsLoading;
|
||||
|
||||
function loadWorklets() {
|
||||
if (workletsLoading) {
|
||||
return workletsLoading;
|
||||
}
|
||||
workletsLoading = getAudioContext().audioWorklet.addModule(workletsUrl);
|
||||
return workletsLoading;
|
||||
export function getAudioContextCurrentTime() {
|
||||
return getAudioContext().currentTime;
|
||||
}
|
||||
|
||||
export function getWorklet(ac, processor, params, config) {
|
||||
const node = new AudioWorkletNode(ac, processor, config);
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
node.parameters.get(key).value = value;
|
||||
});
|
||||
return node;
|
||||
let workletsLoading;
|
||||
function loadWorklets() {
|
||||
if (!workletsLoading) {
|
||||
const audioCtx = getAudioContext();
|
||||
workletsLoading = audioCtx.audioWorklet.addModule(workletsUrl);
|
||||
}
|
||||
|
||||
return workletsLoading;
|
||||
}
|
||||
|
||||
// this function should be called on first user interaction (to avoid console warning)
|
||||
export async function initAudio(options = {}) {
|
||||
const { disableWorklets = false } = options;
|
||||
if (typeof window !== 'undefined') {
|
||||
await getAudioContext().resume();
|
||||
if (!disableWorklets) {
|
||||
await loadWorklets().catch((err) => {
|
||||
console.warn('could not load AudioWorklet effects coarse, crush and shape', err);
|
||||
});
|
||||
} else {
|
||||
console.log('disableWorklets: AudioWorklet effects coarse, crush and shape are skipped!');
|
||||
const {
|
||||
disableWorklets = false,
|
||||
maxPolyphony,
|
||||
audioDeviceName = DEFAULT_AUDIO_DEVICE_NAME,
|
||||
multiChannelOrbits = false,
|
||||
} = options;
|
||||
|
||||
setMaxPolyphony(maxPolyphony);
|
||||
setMultiChannelOrbits(multiChannelOrbits);
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const audioCtx = getAudioContext();
|
||||
|
||||
if (audioDeviceName != null && audioDeviceName != DEFAULT_AUDIO_DEVICE_NAME) {
|
||||
try {
|
||||
const devices = await getAudioDevices();
|
||||
const id = devices.get(audioDeviceName);
|
||||
const isValidID = (id ?? '').length > 0;
|
||||
if (audioCtx.sinkId !== id && isValidID) {
|
||||
await audioCtx.setSinkId(id);
|
||||
}
|
||||
logger(
|
||||
`[superdough] Audio Device set to ${audioDeviceName}, it might take a few seconds before audio plays on all output channels`,
|
||||
);
|
||||
} catch {
|
||||
logger('[superdough] failed to set audio interface', 'warning');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await audioCtx.resume();
|
||||
if (disableWorklets) {
|
||||
logger('[superdough]: AudioWorklets disabled with disableWorklets');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await loadWorklets();
|
||||
logger('[superdough] AudioWorklets loaded');
|
||||
} catch (err) {
|
||||
console.warn('could not load AudioWorklet effects', err);
|
||||
}
|
||||
logger('[superdough] ready');
|
||||
}
|
||||
let audioReady;
|
||||
export async function initAudioOnFirstClick(options) {
|
||||
return new Promise((resolve) => {
|
||||
document.addEventListener('click', async function listener() {
|
||||
await initAudio(options);
|
||||
resolve();
|
||||
document.removeEventListener('click', listener);
|
||||
if (!audioReady) {
|
||||
audioReady = new Promise((resolve) => {
|
||||
document.addEventListener('click', async function listener() {
|
||||
document.removeEventListener('click', listener);
|
||||
await initAudio(options);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
return audioReady;
|
||||
}
|
||||
|
||||
let delays = {};
|
||||
|
|
@ -114,7 +295,7 @@ export const connectToDestination = (input, channels = [0, 1]) => {
|
|||
});
|
||||
stereoMix.connect(splitter);
|
||||
channels.forEach((ch, i) => {
|
||||
splitter.connect(channelMerger, i % stereoMix.channelCount, clamp(ch, 0, ctx.destination.channelCount - 1));
|
||||
splitter.connect(channelMerger, i % stereoMix.channelCount, ch % ctx.destination.channelCount);
|
||||
});
|
||||
};
|
||||
|
||||
|
|
@ -127,7 +308,7 @@ export const panic = () => {
|
|||
channelMerger == null;
|
||||
};
|
||||
|
||||
function getDelay(orbit, delaytime, delayfeedback, t) {
|
||||
function getDelay(orbit, delaytime, delayfeedback, t, channels) {
|
||||
if (delayfeedback > maxfeedback) {
|
||||
//logger(`delayfeedback was clamped to ${maxfeedback} to save your ears`);
|
||||
}
|
||||
|
|
@ -136,7 +317,7 @@ function getDelay(orbit, delaytime, delayfeedback, t) {
|
|||
const ac = getAudioContext();
|
||||
const dly = ac.createFeedbackDelay(1, delaytime, delayfeedback);
|
||||
dly.start?.(t); // for some reason, this throws when audion extension is installed..
|
||||
connectToDestination(dly, [0, 1]);
|
||||
connectToDestination(dly, channels);
|
||||
delays[orbit] = dly;
|
||||
}
|
||||
delays[orbit].delayTime.value !== delaytime && delays[orbit].delayTime.setValueAtTime(delaytime, t);
|
||||
|
|
@ -144,26 +325,23 @@ function getDelay(orbit, delaytime, delayfeedback, t) {
|
|||
return delays[orbit];
|
||||
}
|
||||
|
||||
// each orbit will have its own lfo
|
||||
const phaserLFOs = {};
|
||||
function getPhaser(orbit, t, speed = 1, depth = 0.5, centerFrequency = 1000, sweep = 2000) {
|
||||
//gain
|
||||
export function getLfo(audioContext, time, end, properties = {}) {
|
||||
return getWorklet(audioContext, 'lfo-processor', {
|
||||
frequency: 1,
|
||||
depth: 1,
|
||||
skew: 0,
|
||||
phaseoffset: 0,
|
||||
time,
|
||||
end,
|
||||
shape: 1,
|
||||
dcoffset: -0.5,
|
||||
...properties,
|
||||
});
|
||||
}
|
||||
|
||||
function getPhaser(time, end, frequency = 1, depth = 0.5, centerFrequency = 1000, sweep = 2000) {
|
||||
const ac = getAudioContext();
|
||||
const lfoGain = ac.createGain();
|
||||
lfoGain.gain.value = sweep;
|
||||
|
||||
//LFO
|
||||
if (phaserLFOs[orbit] == null) {
|
||||
phaserLFOs[orbit] = ac.createOscillator();
|
||||
phaserLFOs[orbit].frequency.value = speed;
|
||||
phaserLFOs[orbit].type = 'sine';
|
||||
phaserLFOs[orbit].start();
|
||||
}
|
||||
|
||||
phaserLFOs[orbit].connect(lfoGain);
|
||||
if (phaserLFOs[orbit].frequency.value != speed) {
|
||||
phaserLFOs[orbit].frequency.setValueAtTime(speed, t);
|
||||
}
|
||||
const lfoGain = getLfo(ac, time, end, { frequency, depth: sweep * 2 });
|
||||
|
||||
//filters
|
||||
const numStages = 2; //num of filters in series
|
||||
|
|
@ -186,16 +364,20 @@ function getPhaser(orbit, t, speed = 1, depth = 0.5, centerFrequency = 1000, swe
|
|||
return filterChain[filterChain.length - 1];
|
||||
}
|
||||
|
||||
function getFilterType(ftype) {
|
||||
ftype = ftype ?? 0;
|
||||
const filterTypes = ['12db', 'ladder', '24db'];
|
||||
return typeof ftype === 'number' ? filterTypes[Math.floor(_mod(ftype, filterTypes.length))] : ftype;
|
||||
}
|
||||
|
||||
let reverbs = {};
|
||||
|
||||
let hasChanged = (now, before) => now !== undefined && now !== before;
|
||||
|
||||
function getReverb(orbit, duration, fade, lp, dim, ir) {
|
||||
function getReverb(orbit, duration, fade, lp, dim, ir, channels) {
|
||||
// If no reverb has been created for a given orbit, create one
|
||||
if (!reverbs[orbit]) {
|
||||
const ac = getAudioContext();
|
||||
const reverb = ac.createReverb(duration, fade, lp, dim, ir);
|
||||
connectToDestination(reverb, [0, 1]);
|
||||
connectToDestination(reverb, channels);
|
||||
reverbs[orbit] = reverb;
|
||||
}
|
||||
if (
|
||||
|
|
@ -218,11 +400,12 @@ function getReverb(orbit, duration, fade, lp, dim, ir) {
|
|||
export let analysers = {},
|
||||
analysersData = {};
|
||||
|
||||
export function getAnalyserById(id, fftSize = 1024) {
|
||||
export function getAnalyserById(id, fftSize = 1024, smoothingTimeConstant = 0.5) {
|
||||
if (!analysers[id]) {
|
||||
// make sure this doesn't happen too often as it piles up garbage
|
||||
const analyserNode = getAudioContext().createAnalyser();
|
||||
analyserNode.fftSize = fftSize;
|
||||
analyserNode.smoothingTimeConstant = smoothingTimeConstant;
|
||||
// getDestination().connect(analyserNode);
|
||||
analysers[id] = analyserNode;
|
||||
analysersData[id] = new Float32Array(analysers[id].frequencyBinCount);
|
||||
|
|
@ -260,8 +443,22 @@ export function resetGlobalEffects() {
|
|||
analysersData = {};
|
||||
}
|
||||
|
||||
export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
||||
let activeSoundSources = new Map();
|
||||
//music programs/audio gear usually increments inputs/outputs from 1, we need to subtract 1 from the input because the webaudio API channels start at 0
|
||||
|
||||
function mapChannelNumbers(channels) {
|
||||
return (Array.isArray(channels) ? channels : [channels]).map((ch) => ch - 1);
|
||||
}
|
||||
|
||||
export const superdough = async (value, t, hapDuration, cps = 0.5) => {
|
||||
const ac = getAudioContext();
|
||||
t = typeof t === 'string' && t.startsWith('=') ? Number(t.slice(1)) : ac.currentTime + t;
|
||||
let { stretch } = value;
|
||||
if (stretch != null) {
|
||||
//account for phase vocoder latency
|
||||
const latency = 0.04;
|
||||
t = t - latency;
|
||||
}
|
||||
if (typeof value !== 'object') {
|
||||
throw new Error(
|
||||
`expected hap.value to be an object, but got "${value}". Hint: append .note() or .s() to the end`,
|
||||
|
|
@ -272,7 +469,7 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
// duration is passed as value too..
|
||||
value.duration = hapDuration;
|
||||
// calculate absolute time
|
||||
t = typeof t === 'string' && t.startsWith('=') ? Number(t.slice(1)) : ac.currentTime + t;
|
||||
|
||||
if (t < ac.currentTime) {
|
||||
console.warn(
|
||||
`[superdough]: cannot schedule sounds in the past (target: ${t.toFixed(2)}, now: ${ac.currentTime.toFixed(2)})`,
|
||||
|
|
@ -285,15 +482,15 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
amdepth = 1,
|
||||
amskew = 0.5,
|
||||
amphase = 0,
|
||||
s = 'triangle',
|
||||
s = getDefaultValue('s'),
|
||||
bank,
|
||||
source,
|
||||
gain = 0.8,
|
||||
postgain = 1,
|
||||
density = 0.03,
|
||||
gain = getDefaultValue('gain'),
|
||||
postgain = getDefaultValue('postgain'),
|
||||
density = getDefaultValue('density'),
|
||||
// filters
|
||||
ftype = '12db',
|
||||
fanchor = 0.5,
|
||||
fanchor = getDefaultValue('fanchor'),
|
||||
drive = 0.69,
|
||||
// low pass
|
||||
cutoff,
|
||||
lpenv,
|
||||
|
|
@ -301,7 +498,7 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
lpdecay,
|
||||
lpsustain,
|
||||
lprelease,
|
||||
resonance = 1,
|
||||
resonance = getDefaultValue('resonance'),
|
||||
// high pass
|
||||
hpenv,
|
||||
hcutoff,
|
||||
|
|
@ -309,7 +506,7 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
hpdecay,
|
||||
hpsustain,
|
||||
hprelease,
|
||||
hresonance = 1,
|
||||
hresonance = getDefaultValue('hresonance'),
|
||||
// band pass
|
||||
bpenv,
|
||||
bandf,
|
||||
|
|
@ -317,11 +514,11 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
bpdecay,
|
||||
bpsustain,
|
||||
bprelease,
|
||||
bandq = 1,
|
||||
channels = [1, 2],
|
||||
bandq = getDefaultValue('bandq'),
|
||||
|
||||
//phaser
|
||||
phaser,
|
||||
phaserdepth = 0.75,
|
||||
phaserrate: phaser,
|
||||
phaserdepth = getDefaultValue('phaserdepth'),
|
||||
phasersweep,
|
||||
phasercenter,
|
||||
//
|
||||
|
|
@ -329,26 +526,26 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
|
||||
crush,
|
||||
shape,
|
||||
|
||||
shapevol = 1,
|
||||
shapevol = getDefaultValue('shapevol'),
|
||||
distort,
|
||||
distortvol = 1,
|
||||
distortvol = getDefaultValue('distortvol'),
|
||||
pan,
|
||||
vowel,
|
||||
delay = 0,
|
||||
delayfeedback = 0.5,
|
||||
delaytime = 0.25,
|
||||
orbit = 1,
|
||||
delay = getDefaultValue('delay'),
|
||||
delayfeedback = getDefaultValue('delayfeedback'),
|
||||
delaysync = getDefaultValue('delaysync'),
|
||||
delaytime,
|
||||
orbit = getDefaultValue('orbit'),
|
||||
room,
|
||||
roomfade,
|
||||
roomlp,
|
||||
roomdim,
|
||||
roomsize,
|
||||
ir,
|
||||
i = 0,
|
||||
velocity = 1,
|
||||
i = getDefaultValue('i'),
|
||||
velocity = getDefaultValue('velocity'),
|
||||
analyze, // analyser wet
|
||||
fft = 8, // fftSize 0 - 10
|
||||
fft = getDefaultValue('fft'), // fftSize 0 - 10
|
||||
compressor: compressorThreshold,
|
||||
compressorRatio,
|
||||
compressorKnee,
|
||||
|
|
@ -356,30 +553,59 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
compressorRelease,
|
||||
} = value;
|
||||
|
||||
gain = nanFallback(gain, 1);
|
||||
delaytime = delaytime ?? cycleToSeconds(delaysync, cps);
|
||||
|
||||
//music programs/audio gear usually increments inputs/outputs from 1, so imitate that behavior
|
||||
channels = (Array.isArray(channels) ? channels : [channels]).map((ch) => ch - 1);
|
||||
const orbitChannels = mapChannelNumbers(
|
||||
multiChannelOrbits && orbit > 0 ? [orbit * 2 - 1, orbit * 2] : getDefaultValue('channels'),
|
||||
);
|
||||
const channels = value.channels != null ? mapChannelNumbers(value.channels) : orbitChannels;
|
||||
|
||||
gain = applyGainCurve(nanFallback(gain, 1));
|
||||
postgain = applyGainCurve(postgain);
|
||||
shapevol = applyGainCurve(shapevol);
|
||||
distortvol = applyGainCurve(distortvol);
|
||||
delay = applyGainCurve(delay);
|
||||
velocity = applyGainCurve(velocity);
|
||||
gain *= velocity; // velocity currently only multiplies with gain. it might do other things in the future
|
||||
let toDisconnect = []; // audio nodes that will be disconnected when the source has ended
|
||||
const onended = () => {
|
||||
toDisconnect.forEach((n) => n?.disconnect());
|
||||
};
|
||||
|
||||
const chainID = Math.round(Math.random() * 1000000);
|
||||
|
||||
// oldest audio nodes will be destroyed if maximum polyphony is exceeded
|
||||
for (let i = 0; i <= activeSoundSources.size - maxPolyphony; i++) {
|
||||
const ch = activeSoundSources.entries().next();
|
||||
const source = ch.value[1];
|
||||
const chainID = ch.value[0];
|
||||
const endTime = t + 0.25;
|
||||
source?.node?.gain?.linearRampToValueAtTime(0, endTime);
|
||||
source?.stop?.(endTime);
|
||||
activeSoundSources.delete(chainID);
|
||||
}
|
||||
|
||||
let audioNodes = [];
|
||||
|
||||
if (['-', '~', '_'].includes(s)) {
|
||||
return;
|
||||
}
|
||||
if (bank && s) {
|
||||
s = `${bank}_${s}`;
|
||||
value.s = s;
|
||||
}
|
||||
|
||||
// get source AudioNode
|
||||
let sourceNode;
|
||||
if (source) {
|
||||
sourceNode = source(t, value, hapDuration);
|
||||
sourceNode = source(t, value, hapDuration, cps);
|
||||
} else if (getSound(s)) {
|
||||
const { onTrigger } = getSound(s);
|
||||
const soundHandle = await onTrigger(t, value, onended);
|
||||
const onEnded = () => {
|
||||
audioNodes.forEach((n) => n?.disconnect());
|
||||
activeSoundSources.delete(chainID);
|
||||
};
|
||||
const soundHandle = await onTrigger(t, value, onEnded);
|
||||
|
||||
if (soundHandle) {
|
||||
sourceNode = soundHandle.node;
|
||||
soundHandle.stop(t + hapDuration);
|
||||
activeSoundSources.set(chainID, soundHandle);
|
||||
}
|
||||
} else {
|
||||
throw new Error(`sound ${s} not found! Is it loaded?`);
|
||||
|
|
@ -396,10 +622,13 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
}
|
||||
const chain = []; // audio nodes that will be connected to each other sequentially
|
||||
chain.push(sourceNode);
|
||||
stretch !== undefined && chain.push(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch }));
|
||||
|
||||
// gain stage
|
||||
chain.push(gainNode(gain));
|
||||
|
||||
//filter
|
||||
const ftype = getFilterType(value.ftype);
|
||||
if (cutoff !== undefined) {
|
||||
let lp = () =>
|
||||
createFilter(
|
||||
|
|
@ -415,6 +644,8 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
t,
|
||||
t + hapDuration,
|
||||
fanchor,
|
||||
ftype,
|
||||
drive,
|
||||
);
|
||||
chain.push(lp());
|
||||
if (ftype === '24db') {
|
||||
|
|
@ -503,7 +734,7 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
}
|
||||
// phaser
|
||||
if (phaser !== undefined && phaserdepth > 0) {
|
||||
const phaserFX = getPhaser(orbit, t, phaser, phaserdepth, phasercenter, phasersweep);
|
||||
const phaserFX = getPhaser(t, t + hapDuration, phaser, phaserdepth, phasercenter, phasersweep);
|
||||
chain.push(phaserFX);
|
||||
}
|
||||
|
||||
|
|
@ -515,8 +746,9 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
// delay
|
||||
let delaySend;
|
||||
if (delay > 0 && delaytime > 0 && delayfeedback > 0) {
|
||||
const delyNode = getDelay(orbit, delaytime, delayfeedback, t);
|
||||
delaySend = effectSend(post, delyNode, delay);
|
||||
const delayNode = getDelay(orbit, delaytime, delayfeedback, t, orbitChannels);
|
||||
delaySend = effectSend(post, delayNode, delay);
|
||||
audioNodes.push(delaySend);
|
||||
}
|
||||
// reverb
|
||||
let reverbSend;
|
||||
|
|
@ -532,8 +764,9 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
}
|
||||
roomIR = await loadBuffer(url, ac, ir, 0);
|
||||
}
|
||||
const reverbNode = getReverb(orbit, roomsize, roomfade, roomlp, roomdim, roomIR);
|
||||
const reverbNode = getReverb(orbit, roomsize, roomfade, roomlp, roomdim, roomIR, orbitChannels);
|
||||
reverbSend = effectSend(post, reverbNode, room);
|
||||
audioNodes.push(reverbSend);
|
||||
}
|
||||
|
||||
// analyser
|
||||
|
|
@ -541,14 +774,14 @@ export const superdough = async (value, t, hapDuration, cps, cycle) => {
|
|||
if (analyze) {
|
||||
const analyserNode = getAnalyserById(analyze, 2 ** (fft + 5));
|
||||
analyserSend = effectSend(post, analyserNode, 1);
|
||||
audioNodes.push(analyserSend);
|
||||
}
|
||||
|
||||
// connect chain elements together
|
||||
chain.slice(1).reduce((last, current) => last.connect(current), chain[0]);
|
||||
|
||||
// toDisconnect = all the node that should be disconnected in onended callback
|
||||
// this is crucial for performance
|
||||
toDisconnect = chain.concat([delaySend, reverbSend, analyserSend]);
|
||||
audioNodes = audioNodes.concat(chain);
|
||||
};
|
||||
|
||||
export const superdoughTrigger = (t, hap, ct, cps) => superdough(hap, t - ct, hap.duration / cps, cps);
|
||||
export const superdoughTrigger = (t, hap, ct, cps) => {
|
||||
superdough(hap, t - ct, hap.duration / cps, cps);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { clamp, midiToFreq, noteToMidi } from './util.mjs';
|
||||
import { registerSound, getAudioContext, getWorklet } from './superdough.mjs';
|
||||
import { registerSound, getAudioContext, soundMap, getLfo } from './superdough.mjs';
|
||||
import {
|
||||
applyFM,
|
||||
gainNode,
|
||||
|
|
@ -8,6 +8,7 @@ import {
|
|||
getPitchEnvelope,
|
||||
getVibratoOscillator,
|
||||
webAudioTimeout,
|
||||
getWorklet,
|
||||
} from './helpers.mjs';
|
||||
import { getNoiseMix, getNoiseOscillator } from './noise.mjs';
|
||||
|
||||
|
|
@ -24,8 +25,21 @@ const getFrequencyFromValue = (value) => {
|
|||
|
||||
return Number(freq);
|
||||
};
|
||||
function destroyAudioWorkletNode(node) {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
node.disconnect();
|
||||
node.parameters.get('end')?.setValueAtTime(0, 0);
|
||||
}
|
||||
|
||||
const waveforms = ['triangle', 'square', 'sawtooth', 'sine'];
|
||||
const waveformAliases = [
|
||||
['tri', 'triangle'],
|
||||
['sqr', 'square'],
|
||||
['saw', 'sawtooth'],
|
||||
['sin', 'sine'],
|
||||
];
|
||||
const noises = ['pink', 'white', 'brown', 'crackle'];
|
||||
|
||||
export function registerSynthSounds() {
|
||||
|
|
@ -62,7 +76,9 @@ export function registerSynthSounds() {
|
|||
stop(envEnd);
|
||||
return {
|
||||
node,
|
||||
stop: (releaseTime) => {},
|
||||
stop: (endTime) => {
|
||||
stop(endTime);
|
||||
},
|
||||
};
|
||||
},
|
||||
{ type: 'synth', prebake: true },
|
||||
|
|
@ -109,10 +125,12 @@ export function registerSynthSounds() {
|
|||
let envGain = gainNode(1);
|
||||
envGain = o.connect(envGain);
|
||||
|
||||
webAudioTimeout(
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 0.3 * gainAdjustment, begin, holdend, 'linear');
|
||||
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
o.disconnect();
|
||||
destroyAudioWorkletNode(o);
|
||||
envGain.disconnect();
|
||||
onended();
|
||||
fm?.stop();
|
||||
|
|
@ -122,11 +140,164 @@ export function registerSynthSounds() {
|
|||
end,
|
||||
);
|
||||
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 0.3 * gainAdjustment, begin, holdend, 'linear');
|
||||
return {
|
||||
node: envGain,
|
||||
stop: (time) => {
|
||||
timeoutNode.stop(time);
|
||||
},
|
||||
};
|
||||
},
|
||||
{ prebake: true, type: 'synth' },
|
||||
);
|
||||
|
||||
registerSound(
|
||||
'bytebeat',
|
||||
(begin, value, onended) => {
|
||||
const defaultBeats = [
|
||||
'(t%255 >= t/255%255)*255',
|
||||
'(t*(t*8%60 <= 300)|(-t)*(t*4%512 < 256))+t/400',
|
||||
't',
|
||||
't*(t >> 10^t)',
|
||||
't&128',
|
||||
't&t>>8',
|
||||
'((t%255+t%128+t%64+t%32+t%16+t%127.8+t%64.8+t%32.8+t%16.8)/3)',
|
||||
'((t%64+t%63.8+t%64.15+t%64.35+t%63.5)/1.25)',
|
||||
'(t&(t>>7)-t)',
|
||||
'(sin(t*PI/128)*127+127)',
|
||||
'((t^t/2+t+64*(sin((t*PI/64)+(t*PI/32768))+64))%128*2)',
|
||||
'((t^t/2+t+64*(cos >> 0))%127.85*2)',
|
||||
'((t^t/2+t+64)%128*2)',
|
||||
'(((t * .25)^(t * .25)/100+(t * .25))%128)*2',
|
||||
'((t^t/2+t+64)%7 * 24)',
|
||||
];
|
||||
const { n = 0 } = value;
|
||||
const frequency = getFrequencyFromValue(value);
|
||||
const { byteBeatExpression = defaultBeats[n % defaultBeats.length], byteBeatStartTime } = value;
|
||||
|
||||
const ac = getAudioContext();
|
||||
|
||||
let { duration } = value;
|
||||
const [attack, decay, sustain, release] = getADSRValues(
|
||||
[value.attack, value.decay, value.sustain, value.release],
|
||||
'linear',
|
||||
[0.001, 0.05, 0.6, 0.01],
|
||||
);
|
||||
const holdend = begin + duration;
|
||||
const end = holdend + release + 0.01;
|
||||
|
||||
let o = getWorklet(
|
||||
ac,
|
||||
'byte-beat-processor',
|
||||
{
|
||||
frequency,
|
||||
begin,
|
||||
end,
|
||||
},
|
||||
{
|
||||
outputChannelCount: [2],
|
||||
},
|
||||
);
|
||||
|
||||
o.port.postMessage({ codeText: byteBeatExpression, byteBeatStartTime, frequency });
|
||||
|
||||
let envGain = gainNode(1);
|
||||
envGain = o.connect(envGain);
|
||||
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear');
|
||||
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
envGain.disconnect();
|
||||
onended();
|
||||
},
|
||||
begin,
|
||||
end,
|
||||
);
|
||||
|
||||
return {
|
||||
node: envGain,
|
||||
stop: (time) => {},
|
||||
stop: (time) => {
|
||||
timeoutNode.stop(time);
|
||||
},
|
||||
};
|
||||
},
|
||||
{ prebake: true, type: 'synth' },
|
||||
);
|
||||
|
||||
registerSound(
|
||||
'pulse',
|
||||
(begin, value, onended) => {
|
||||
const ac = getAudioContext();
|
||||
let { pwrate, pwsweep } = value;
|
||||
if (pwsweep == null) {
|
||||
if (pwrate != null) {
|
||||
pwsweep = 0.3;
|
||||
} else {
|
||||
pwsweep = 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (pwrate == null && pwsweep != null) {
|
||||
pwrate = 1;
|
||||
}
|
||||
|
||||
let { duration, pw: pulsewidth = 0.5 } = value;
|
||||
const frequency = getFrequencyFromValue(value);
|
||||
|
||||
const [attack, decay, sustain, release] = getADSRValues(
|
||||
[value.attack, value.decay, value.sustain, value.release],
|
||||
'linear',
|
||||
[0.001, 0.05, 0.6, 0.01],
|
||||
);
|
||||
const holdend = begin + duration;
|
||||
const end = holdend + release + 0.01;
|
||||
let o = getWorklet(
|
||||
ac,
|
||||
'pulse-oscillator',
|
||||
{
|
||||
frequency,
|
||||
begin,
|
||||
end,
|
||||
pulsewidth,
|
||||
},
|
||||
{
|
||||
outputChannelCount: [2],
|
||||
},
|
||||
);
|
||||
|
||||
getPitchEnvelope(o.parameters.get('detune'), value, begin, holdend);
|
||||
const vibratoOscillator = getVibratoOscillator(o.parameters.get('detune'), value, begin);
|
||||
const fm = applyFM(o.parameters.get('frequency'), value, begin);
|
||||
let envGain = gainNode(1);
|
||||
envGain = o.connect(envGain);
|
||||
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear');
|
||||
let lfo;
|
||||
if (pwsweep != 0) {
|
||||
lfo = getLfo(ac, begin, end, { frequency: pwrate, depth: pwsweep });
|
||||
lfo.connect(o.parameters.get('pulsewidth'));
|
||||
}
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
destroyAudioWorkletNode(lfo);
|
||||
envGain.disconnect();
|
||||
onended();
|
||||
fm?.stop();
|
||||
vibratoOscillator?.stop();
|
||||
},
|
||||
begin,
|
||||
end,
|
||||
);
|
||||
|
||||
return {
|
||||
node: envGain,
|
||||
stop: (time) => {
|
||||
timeoutNode.stop(time);
|
||||
},
|
||||
};
|
||||
},
|
||||
{ prebake: true, type: 'synth' },
|
||||
|
|
@ -169,12 +340,15 @@ export function registerSynthSounds() {
|
|||
stop(envEnd);
|
||||
return {
|
||||
node,
|
||||
stop: (releaseTime) => {},
|
||||
stop: (endTime) => {
|
||||
stop(endTime);
|
||||
},
|
||||
};
|
||||
},
|
||||
{ type: 'synth', prebake: true },
|
||||
);
|
||||
});
|
||||
waveformAliases.forEach(([alias, actual]) => soundMap.set({ ...soundMap.get(), [alias]: soundMap.get()[actual] }));
|
||||
}
|
||||
|
||||
export function waveformN(partials, type) {
|
||||
|
|
|
|||
|
|
@ -68,3 +68,7 @@ export const _mod = (n, m) => ((n % m) + m) % m;
|
|||
export const getSoundIndex = (n, numSounds) => {
|
||||
return _mod(Math.round(nanFallback(n, 0)), numSounds);
|
||||
};
|
||||
|
||||
export function cycleToSeconds(cycle, cps) {
|
||||
return cycle / cps;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +1,11 @@
|
|||
import { defineConfig } from 'vite';
|
||||
import { dependencies } from './package.json';
|
||||
import { resolve } from 'path';
|
||||
import bundleAudioWorkletPlugin from 'vite-plugin-bundle-audioworklet';
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [],
|
||||
plugins: [bundleAudioWorkletPlugin()],
|
||||
build: {
|
||||
lib: {
|
||||
entry: resolve(__dirname, 'index.mjs'),
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
// coarse, crush, and shape processors adapted from dktr0's webdirt: https://github.com/dktr0/WebDirt/blob/5ce3d698362c54d6e1b68acc47eb2955ac62c793/dist/AudioWorklets.js
|
||||
// LICENSE GNU General Public License v3.0 see https://github.com/dktr0/WebDirt/blob/main/LICENSE
|
||||
import { clamp, _mod } from './util.mjs';
|
||||
// const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
// TOFIX: THIS FILE DOES NOT SUPPORT IMPORTS ON DEPOLYMENT
|
||||
|
||||
import OLAProcessor from './ola-processor';
|
||||
import FFT from './fft.js';
|
||||
|
||||
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
const _mod = (n, m) => ((n % m) + m) % m;
|
||||
|
||||
const blockSize = 128;
|
||||
// adjust waveshape to remove frequencies above nyquist to prevent aliasing
|
||||
// referenced from https://www.kvraudio.com/forum/viewtopic.php?t=375517
|
||||
|
|
@ -27,8 +33,28 @@ function polyBlep(phase, dt) {
|
|||
}
|
||||
|
||||
const waveshapes = {
|
||||
tri(phase, skew = 0.5) {
|
||||
const x = 1 - skew;
|
||||
if (phase >= skew) {
|
||||
return 1 / x - phase / x;
|
||||
}
|
||||
return phase / skew;
|
||||
},
|
||||
sine(phase) {
|
||||
return Math.sin(Math.PI * 2 * phase);
|
||||
return Math.sin(Math.PI * 2 * phase) * 0.5 + 0.5;
|
||||
},
|
||||
ramp(phase) {
|
||||
return phase;
|
||||
},
|
||||
saw(phase) {
|
||||
return 1 - phase;
|
||||
},
|
||||
|
||||
square(phase, skew = 0.5) {
|
||||
if (phase >= skew) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
custom(phase, values = [0, 1]) {
|
||||
const numParts = values.length - 1;
|
||||
|
|
@ -48,43 +74,31 @@ const waveshapes = {
|
|||
const v = 2 * phase - 1;
|
||||
return v - polyBlep(phase, dt);
|
||||
},
|
||||
ramp(phase) {
|
||||
return phase;
|
||||
},
|
||||
saw(phase) {
|
||||
return 1 - phase;
|
||||
},
|
||||
tri(phase, skew = 0.5) {
|
||||
const x = 1 - skew;
|
||||
if (phase >= skew) {
|
||||
return 1 / x - phase / x;
|
||||
}
|
||||
return phase / skew;
|
||||
},
|
||||
square(phase, skew = 0.5) {
|
||||
if (phase >= skew) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
},
|
||||
};
|
||||
|
||||
class AMProcessor extends AudioWorkletProcessor {
|
||||
function getParamValue(block, param) {
|
||||
if (param.length > 1) {
|
||||
return param[block];
|
||||
}
|
||||
return param[0];
|
||||
}
|
||||
const waveShapeNames = Object.keys(waveshapes);
|
||||
class LFOProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{ name: 'cps', defaultValue: 0.5 },
|
||||
{ name: 'speed', defaultValue: 0.5 },
|
||||
{ name: 'cycle', defaultValue: 0 },
|
||||
{ name: 'time', defaultValue: 0 },
|
||||
{ name: 'end', defaultValue: 0 },
|
||||
{ name: 'frequency', defaultValue: 0.5 },
|
||||
{ name: 'skew', defaultValue: 0.5 },
|
||||
{ name: 'depth', defaultValue: 1 },
|
||||
{ name: 'phaseoffset', defaultValue: 0 },
|
||||
{ name: 'shape', defaultValue: 0 },
|
||||
{ name: 'dcoffset', defaultValue: 0 },
|
||||
];
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.phase;
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
incrementPhase(dt) {
|
||||
|
|
@ -95,39 +109,41 @@ class AMProcessor extends AudioWorkletProcessor {
|
|||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
// eslint-disable-next-line no-undef
|
||||
if (currentTime >= parameters.end[0]) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
|
||||
const speed = parameters['speed'][0];
|
||||
const cps = parameters['cps'][0];
|
||||
const cycle = parameters['cycle'][0];
|
||||
const output = outputs[0];
|
||||
const frequency = parameters['frequency'][0];
|
||||
|
||||
const time = parameters['time'][0];
|
||||
const depth = parameters['depth'][0];
|
||||
const skew = parameters['skew'][0];
|
||||
const phaseoffset = parameters['phaseoffset'][0];
|
||||
|
||||
const frequency = speed * cps;
|
||||
const dcoffset = parameters['dcoffset'][0];
|
||||
const shape = waveShapeNames[parameters['shape'][0]];
|
||||
|
||||
const blockSize = output[0].length ?? 0;
|
||||
|
||||
if (this.phase == null) {
|
||||
const secondsPassed = cycle / cps;
|
||||
this.phase = _mod(secondsPassed * frequency + phaseoffset, 1);
|
||||
this.phase = _mod(time * frequency + phaseoffset, 1);
|
||||
}
|
||||
// eslint-disable-next-line no-undef
|
||||
const dt = frequency / sampleRate;
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const modval = clamp(waveshapes.tri(this.phase, skew) * depth + (1 - depth), 0, 1);
|
||||
output[i][n] = input[i][n] * modval;
|
||||
for (let i = 0; i < output.length; i++) {
|
||||
const modval = (waveshapes[shape](this.phase, skew) + dcoffset) * depth;
|
||||
output[i][n] = modval;
|
||||
}
|
||||
this.incrementPhase(dt);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('am-processor', AMProcessor);
|
||||
registerProcessor('lfo-processor', LFOProcessor);
|
||||
|
||||
class CoarseProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
|
|
@ -233,6 +249,77 @@ class ShapeProcessor extends AudioWorkletProcessor {
|
|||
}
|
||||
registerProcessor('shape-processor', ShapeProcessor);
|
||||
|
||||
function fast_tanh(x) {
|
||||
const x2 = x * x;
|
||||
return (x * (27.0 + x2)) / (27.0 + 9.0 * x2);
|
||||
}
|
||||
const _PI = 3.14159265359;
|
||||
//adapted from https://github.com/TheBouteillacBear/webaudioworklet-wasm?tab=MIT-1-ov-file
|
||||
class LadderProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{ name: 'frequency', defaultValue: 500 },
|
||||
{ name: 'q', defaultValue: 1 },
|
||||
{ name: 'drive', defaultValue: 0.69 },
|
||||
];
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.started = false;
|
||||
this.p0 = [0, 0];
|
||||
this.p1 = [0, 0];
|
||||
this.p2 = [0, 0];
|
||||
this.p3 = [0, 0];
|
||||
this.p32 = [0, 0];
|
||||
this.p33 = [0, 0];
|
||||
this.p34 = [0, 0];
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.started = hasInput;
|
||||
|
||||
const resonance = parameters.q[0];
|
||||
const drive = clamp(Math.exp(parameters.drive[0]), 0.1, 2000);
|
||||
|
||||
let cutoff = parameters.frequency[0];
|
||||
// eslint-disable-next-line no-undef
|
||||
cutoff = (cutoff * 2 * _PI) / sampleRate;
|
||||
cutoff = cutoff > 1 ? 1 : cutoff;
|
||||
|
||||
const k = Math.min(8, resonance * 0.13);
|
||||
// drive makeup * resonance volume loss makeup
|
||||
let makeupgain = (1 / drive) * Math.min(1.75, 1 + k);
|
||||
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const out = this.p3[i] * 0.360891 + this.p32[i] * 0.41729 + this.p33[i] * 0.177896 + this.p34[i] * 0.0439725;
|
||||
|
||||
this.p34[i] = this.p33[i];
|
||||
this.p33[i] = this.p32[i];
|
||||
this.p32[i] = this.p3[i];
|
||||
|
||||
this.p0[i] += (fast_tanh(input[i][n] * drive - k * out) - fast_tanh(this.p0[i])) * cutoff;
|
||||
this.p1[i] += (fast_tanh(this.p0[i]) - fast_tanh(this.p1[i])) * cutoff;
|
||||
this.p2[i] += (fast_tanh(this.p1[i]) - fast_tanh(this.p2[i])) * cutoff;
|
||||
this.p3[i] += (fast_tanh(this.p2[i]) - fast_tanh(this.p3[i])) * cutoff;
|
||||
|
||||
output[i][n] = out * makeupgain;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('ladder-processor', LadderProcessor);
|
||||
|
||||
class DistortProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
|
|
@ -280,6 +367,11 @@ function getUnisonDetune(unison, detune, voiceIndex) {
|
|||
}
|
||||
return lerp(-detune * 0.5, detune * 0.5, voiceIndex / (unison - 1));
|
||||
}
|
||||
|
||||
function applySemitoneDetuneToFrequency(frequency, detune) {
|
||||
return frequency * Math.pow(2, detune / 12);
|
||||
}
|
||||
|
||||
class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
|
|
@ -356,7 +448,7 @@ class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
|||
const isOdd = (n & 1) == 1;
|
||||
|
||||
//applies unison "spread" detune in semitones
|
||||
const freq = frequency * Math.pow(2, getUnisonDetune(voices, freqspread, n) / 12);
|
||||
const freq = applySemitoneDetuneToFrequency(frequency, getUnisonDetune(voices, freqspread, n));
|
||||
let gainL = gain1;
|
||||
let gainR = gain2;
|
||||
// invert right and left gain
|
||||
|
|
@ -386,3 +478,480 @@ class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
|||
}
|
||||
|
||||
registerProcessor('supersaw-oscillator', SuperSawOscillatorProcessor);
|
||||
|
||||
// Phase Vocoder sourced from // sourced from https://github.com/olvb/phaze/tree/master?tab=readme-ov-file
|
||||
const BUFFERED_BLOCK_SIZE = 2048;
|
||||
|
||||
function genHannWindow(length) {
|
||||
let win = new Float32Array(length);
|
||||
for (var i = 0; i < length; i++) {
|
||||
win[i] = 0.5 * (1 - Math.cos((2 * Math.PI * i) / length));
|
||||
}
|
||||
return win;
|
||||
}
|
||||
|
||||
class PhaseVocoderProcessor extends OLAProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{
|
||||
name: 'pitchFactor',
|
||||
defaultValue: 1.0,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
constructor(options) {
|
||||
options.processorOptions = {
|
||||
blockSize: BUFFERED_BLOCK_SIZE,
|
||||
};
|
||||
super(options);
|
||||
|
||||
this.fftSize = this.blockSize;
|
||||
this.timeCursor = 0;
|
||||
|
||||
this.hannWindow = genHannWindow(this.blockSize);
|
||||
// prepare FFT and pre-allocate buffers
|
||||
this.fft = new FFT(this.fftSize);
|
||||
this.freqComplexBuffer = this.fft.createComplexArray();
|
||||
this.freqComplexBufferShifted = this.fft.createComplexArray();
|
||||
this.timeComplexBuffer = this.fft.createComplexArray();
|
||||
this.magnitudes = new Float32Array(this.fftSize / 2 + 1);
|
||||
this.peakIndexes = new Int32Array(this.magnitudes.length);
|
||||
this.nbPeaks = 0;
|
||||
}
|
||||
|
||||
processOLA(inputs, outputs, parameters) {
|
||||
// no automation, take last value
|
||||
|
||||
let pitchFactor = parameters.pitchFactor[parameters.pitchFactor.length - 1];
|
||||
|
||||
if (pitchFactor < 0) {
|
||||
pitchFactor = pitchFactor * 0.25;
|
||||
}
|
||||
pitchFactor = Math.max(0, pitchFactor + 1);
|
||||
|
||||
for (var i = 0; i < this.nbInputs; i++) {
|
||||
for (var j = 0; j < inputs[i].length; j++) {
|
||||
// big assumption here: output is symetric to input
|
||||
var input = inputs[i][j];
|
||||
var output = outputs[i][j];
|
||||
|
||||
this.applyHannWindow(input);
|
||||
|
||||
this.fft.realTransform(this.freqComplexBuffer, input);
|
||||
|
||||
this.computeMagnitudes();
|
||||
this.findPeaks();
|
||||
this.shiftPeaks(pitchFactor);
|
||||
|
||||
this.fft.completeSpectrum(this.freqComplexBufferShifted);
|
||||
this.fft.inverseTransform(this.timeComplexBuffer, this.freqComplexBufferShifted);
|
||||
this.fft.fromComplexArray(this.timeComplexBuffer, output);
|
||||
this.applyHannWindow(output);
|
||||
}
|
||||
}
|
||||
|
||||
this.timeCursor += this.hopSize;
|
||||
}
|
||||
|
||||
/** Apply Hann window in-place */
|
||||
applyHannWindow(input) {
|
||||
for (var i = 0; i < this.blockSize; i++) {
|
||||
input[i] = input[i] * this.hannWindow[i] * 1.62;
|
||||
}
|
||||
}
|
||||
|
||||
/** Compute squared magnitudes for peak finding **/
|
||||
computeMagnitudes() {
|
||||
var i = 0,
|
||||
j = 0;
|
||||
while (i < this.magnitudes.length) {
|
||||
let real = this.freqComplexBuffer[j];
|
||||
let imag = this.freqComplexBuffer[j + 1];
|
||||
// no need to sqrt for peak finding
|
||||
this.magnitudes[i] = real ** 2 + imag ** 2;
|
||||
i += 1;
|
||||
j += 2;
|
||||
}
|
||||
}
|
||||
|
||||
/** Find peaks in spectrum magnitudes **/
|
||||
findPeaks() {
|
||||
this.nbPeaks = 0;
|
||||
var i = 2;
|
||||
let end = this.magnitudes.length - 2;
|
||||
|
||||
while (i < end) {
|
||||
let mag = this.magnitudes[i];
|
||||
|
||||
if (this.magnitudes[i - 1] >= mag || this.magnitudes[i - 2] >= mag) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (this.magnitudes[i + 1] >= mag || this.magnitudes[i + 2] >= mag) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
this.peakIndexes[this.nbPeaks] = i;
|
||||
this.nbPeaks++;
|
||||
i += 2;
|
||||
}
|
||||
}
|
||||
|
||||
/** Shift peaks and regions of influence by pitchFactor into new specturm */
|
||||
shiftPeaks(pitchFactor) {
|
||||
// zero-fill new spectrum
|
||||
this.freqComplexBufferShifted.fill(0);
|
||||
|
||||
for (var i = 0; i < this.nbPeaks; i++) {
|
||||
let peakIndex = this.peakIndexes[i];
|
||||
let peakIndexShifted = Math.round(peakIndex * pitchFactor);
|
||||
|
||||
if (peakIndexShifted > this.magnitudes.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
// find region of influence
|
||||
var startIndex = 0;
|
||||
var endIndex = this.fftSize;
|
||||
if (i > 0) {
|
||||
let peakIndexBefore = this.peakIndexes[i - 1];
|
||||
startIndex = peakIndex - Math.floor((peakIndex - peakIndexBefore) / 2);
|
||||
}
|
||||
if (i < this.nbPeaks - 1) {
|
||||
let peakIndexAfter = this.peakIndexes[i + 1];
|
||||
endIndex = peakIndex + Math.ceil((peakIndexAfter - peakIndex) / 2);
|
||||
}
|
||||
|
||||
// shift whole region of influence around peak to shifted peak
|
||||
let startOffset = startIndex - peakIndex;
|
||||
let endOffset = endIndex - peakIndex;
|
||||
for (var j = startOffset; j < endOffset; j++) {
|
||||
let binIndex = peakIndex + j;
|
||||
let binIndexShifted = peakIndexShifted + j;
|
||||
|
||||
if (binIndexShifted >= this.magnitudes.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
// apply phase correction
|
||||
let omegaDelta = (2 * Math.PI * (binIndexShifted - binIndex)) / this.fftSize;
|
||||
let phaseShiftReal = Math.cos(omegaDelta * this.timeCursor);
|
||||
let phaseShiftImag = Math.sin(omegaDelta * this.timeCursor);
|
||||
|
||||
let indexReal = binIndex * 2;
|
||||
let indexImag = indexReal + 1;
|
||||
let valueReal = this.freqComplexBuffer[indexReal];
|
||||
let valueImag = this.freqComplexBuffer[indexImag];
|
||||
|
||||
let valueShiftedReal = valueReal * phaseShiftReal - valueImag * phaseShiftImag;
|
||||
let valueShiftedImag = valueReal * phaseShiftImag + valueImag * phaseShiftReal;
|
||||
|
||||
let indexShiftedReal = binIndexShifted * 2;
|
||||
let indexShiftedImag = indexShiftedReal + 1;
|
||||
this.freqComplexBufferShifted[indexShiftedReal] += valueShiftedReal;
|
||||
this.freqComplexBufferShifted[indexShiftedImag] += valueShiftedImag;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('phase-vocoder-processor', PhaseVocoderProcessor);
|
||||
|
||||
// Adapted from https://www.musicdsp.org/en/latest/Effects/221-band-limited-pwm-generator.html
|
||||
class PulseOscillatorProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.pi = _PI;
|
||||
this.phi = -this.pi; // phase
|
||||
this.Y0 = 0; // feedback memories
|
||||
this.Y1 = 0;
|
||||
this.PW = this.pi; // pulse width
|
||||
this.B = 2.3; // feedback coefficient
|
||||
this.dphif = 0; // filtered phase increment
|
||||
this.envf = 0; // filtered envelope
|
||||
}
|
||||
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{
|
||||
name: 'begin',
|
||||
defaultValue: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
min: 0,
|
||||
},
|
||||
|
||||
{
|
||||
name: 'end',
|
||||
defaultValue: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
min: 0,
|
||||
},
|
||||
|
||||
{
|
||||
name: 'frequency',
|
||||
defaultValue: 440,
|
||||
min: Number.EPSILON,
|
||||
},
|
||||
{
|
||||
name: 'detune',
|
||||
defaultValue: 0,
|
||||
min: Number.NEGATIVE_INFINITY,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
{
|
||||
name: 'pulsewidth',
|
||||
defaultValue: 1,
|
||||
min: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
process(inputs, outputs, params) {
|
||||
if (this.disconnected) {
|
||||
return false;
|
||||
}
|
||||
if (currentTime <= params.begin[0]) {
|
||||
return true;
|
||||
}
|
||||
if (currentTime >= params.end[0]) {
|
||||
return false;
|
||||
}
|
||||
const output = outputs[0];
|
||||
let env = 1,
|
||||
dphi;
|
||||
|
||||
for (let i = 0; i < (output[0].length ?? 0); i++) {
|
||||
const pw = (1 - clamp(getParamValue(i, params.pulsewidth), -0.99, 0.99)) * this.pi;
|
||||
const detune = getParamValue(i, params.detune);
|
||||
const freq = applySemitoneDetuneToFrequency(getParamValue(i, params.frequency), detune / 100);
|
||||
|
||||
dphi = freq * (this.pi / (sampleRate * 0.5)); // phase increment
|
||||
this.dphif += 0.1 * (dphi - this.dphif);
|
||||
|
||||
env *= 0.9998; // exponential decay envelope
|
||||
this.envf += 0.1 * (env - this.envf);
|
||||
|
||||
// Feedback coefficient control
|
||||
this.B = 2.3 * (1 - 0.0001 * freq); // feedback limitation
|
||||
if (this.B < 0) this.B = 0;
|
||||
|
||||
// Waveform generation (half-Tomisawa oscillators)
|
||||
this.phi += this.dphif; // phase increment
|
||||
if (this.phi >= this.pi) this.phi -= 2 * this.pi; // phase wrapping
|
||||
|
||||
// First half-Tomisawa generator
|
||||
let out0 = Math.cos(this.phi + this.B * this.Y0); // self-phase modulation
|
||||
this.Y0 = 0.5 * (out0 + this.Y0); // anti-hunting filter
|
||||
|
||||
// Second half-Tomisawa generator (with phase offset for pulse width)
|
||||
let out1 = Math.cos(this.phi + this.B * this.Y1 + pw);
|
||||
this.Y1 = 0.5 * (out1 + this.Y1); // anti-hunting filter
|
||||
|
||||
for (let o = 0; o < output.length; o++) {
|
||||
// Combination of both oscillators with envelope applied
|
||||
output[o][i] = 0.15 * (out0 - out1) * this.envf;
|
||||
}
|
||||
}
|
||||
|
||||
return true; // keep the audio processing going
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('pulse-oscillator', PulseOscillatorProcessor);
|
||||
|
||||
/** BYTE BEATS */
|
||||
const chyx = {
|
||||
/*bit*/ bitC: function (x, y, z) {
|
||||
return x & y ? z : 0;
|
||||
},
|
||||
/*bit reverse*/ br: function (x, size = 8) {
|
||||
if (size > 32) {
|
||||
throw new Error('br() Size cannot be greater than 32');
|
||||
} else {
|
||||
let result = 0;
|
||||
for (let idx = 0; idx < size - 0; idx++) {
|
||||
result += chyx.bitC(x, 2 ** idx, 2 ** (size - (idx + 1)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
},
|
||||
/*sin that loops every 128 "steps", instead of every pi steps*/ sinf: function (x) {
|
||||
return Math.sin(x / (128 / Math.PI));
|
||||
},
|
||||
/*cos that loops every 128 "steps", instead of every pi steps*/ cosf: function (x) {
|
||||
return Math.cos(x / (128 / Math.PI));
|
||||
},
|
||||
/*tan that loops every 128 "steps", instead of every pi steps*/ tanf: function (x) {
|
||||
return Math.tan(x / (128 / Math.PI));
|
||||
},
|
||||
/*converts t into a string composed of it's bits, regex's that*/ regG: function (t, X) {
|
||||
return X.test(t.toString(2));
|
||||
},
|
||||
};
|
||||
|
||||
// Create shortened Math functions
|
||||
let mathParams, byteBeatHelperFuncs;
|
||||
function getByteBeatFunc(codetext) {
|
||||
if ((mathParams || byteBeatHelperFuncs) == null) {
|
||||
mathParams = Object.getOwnPropertyNames(Math);
|
||||
byteBeatHelperFuncs = mathParams.map((k) => Math[k]);
|
||||
const chyxNames = Object.getOwnPropertyNames(chyx);
|
||||
const chyxFuncs = chyxNames.map((k) => chyx[k]);
|
||||
mathParams.push('int', 'window', ...chyxNames);
|
||||
byteBeatHelperFuncs.push(Math.floor, globalThis, ...chyxFuncs);
|
||||
}
|
||||
return new Function(...mathParams, 't', `return 0,\n${codetext || 0};`).bind(globalThis, ...byteBeatHelperFuncs);
|
||||
}
|
||||
|
||||
class ByteBeatProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
super();
|
||||
this.port.onmessage = (event) => {
|
||||
let { codeText } = event.data;
|
||||
const { byteBeatStartTime } = event.data;
|
||||
if (byteBeatStartTime != null) {
|
||||
this.t = 0;
|
||||
this.initialOffset = Math.floor(byteBeatStartTime);
|
||||
}
|
||||
|
||||
//Optimization pulled from dollchan.net: https://github.com/Chasyxx/EnBeat_NEW, it seemed important
|
||||
//Optimize code like eval(unescape(escape`XXXX`.replace(/u(..)/g,"$1%")))
|
||||
codeText = codeText
|
||||
.trim()
|
||||
.replace(
|
||||
/^eval\(unescape\(escape(?:`|\('|\("|\(`)(.*?)(?:`|'\)|"\)|`\)).replace\(\/u\(\.\.\)\/g,["'`]\$1%["'`]\)\)\)$/,
|
||||
(match, m1) => unescape(escape(m1).replace(/u(..)/g, '$1%')),
|
||||
);
|
||||
|
||||
this.func = getByteBeatFunc(codeText);
|
||||
};
|
||||
this.initialOffset = null;
|
||||
this.t = null;
|
||||
this.func = null;
|
||||
}
|
||||
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{
|
||||
name: 'begin',
|
||||
defaultValue: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
min: 0,
|
||||
},
|
||||
{
|
||||
name: 'frequency',
|
||||
defaultValue: 440,
|
||||
min: Number.EPSILON,
|
||||
},
|
||||
{
|
||||
name: 'detune',
|
||||
defaultValue: 0,
|
||||
min: Number.NEGATIVE_INFINITY,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
},
|
||||
{
|
||||
name: 'end',
|
||||
defaultValue: 0,
|
||||
max: Number.POSITIVE_INFINITY,
|
||||
min: 0,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
process(inputs, outputs, params) {
|
||||
if (this.disconnected) {
|
||||
return false;
|
||||
}
|
||||
if (currentTime <= params.begin[0]) {
|
||||
return true;
|
||||
}
|
||||
if (currentTime >= params.end[0]) {
|
||||
return false;
|
||||
}
|
||||
if (this.t == null) {
|
||||
this.t = params.begin[0] * sampleRate;
|
||||
}
|
||||
const output = outputs[0];
|
||||
for (let i = 0; i < output[0].length; i++) {
|
||||
const detune = getParamValue(i, params.detune);
|
||||
const freq = applySemitoneDetuneToFrequency(getParamValue(i, params.frequency), detune / 100);
|
||||
let local_t = (this.t / (sampleRate / 256)) * freq + this.initialOffset;
|
||||
const funcValue = this.func(local_t);
|
||||
let signal = (funcValue & 255) / 127.5 - 1;
|
||||
const out = signal * 0.2;
|
||||
for (let c = 0; c < output.length; c++) {
|
||||
//prevent speaker blowout via clipping if threshold exceeds
|
||||
output[c][i] = clamp(out, -0.4, 0.4);
|
||||
}
|
||||
this.t = this.t + 1;
|
||||
}
|
||||
|
||||
return true; // keep the audio processing going
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('byte-beat-processor', ByteBeatProcessor);
|
||||
|
||||
|
||||
class AMProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
{ name: 'cps', defaultValue: 0.5 },
|
||||
{ name: 'speed', defaultValue: 0.5 },
|
||||
{ name: 'cycle', defaultValue: 0 },
|
||||
{ name: 'skew', defaultValue: 0.5 },
|
||||
{ name: 'depth', defaultValue: 1 },
|
||||
{ name: 'phaseoffset', defaultValue: 0 },
|
||||
];
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.phase;
|
||||
this.started = false;
|
||||
}
|
||||
|
||||
incrementPhase(dt) {
|
||||
this.phase += dt;
|
||||
if (this.phase > 1.0) {
|
||||
this.phase = this.phase - 1;
|
||||
}
|
||||
}
|
||||
|
||||
process(inputs, outputs, parameters) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
const hasInput = !(input[0] === undefined);
|
||||
if (this.started && !hasInput) {
|
||||
return false;
|
||||
}
|
||||
this.started = hasInput;
|
||||
|
||||
const speed = parameters['speed'][0];
|
||||
const cps = parameters['cps'][0];
|
||||
const cycle = parameters['cycle'][0];
|
||||
const depth = parameters['depth'][0];
|
||||
const skew = parameters['skew'][0];
|
||||
const phaseoffset = parameters['phaseoffset'][0];
|
||||
|
||||
const frequency = speed * cps;
|
||||
if (this.phase == null) {
|
||||
const secondsPassed = cycle / cps;
|
||||
this.phase = _mod(secondsPassed * frequency + phaseoffset, 1);
|
||||
}
|
||||
// eslint-disable-next-line no-undef
|
||||
const dt = frequency / sampleRate;
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
const modval = clamp(waveshapes.tri(this.phase, skew) * depth + (1 - depth), 0, 1);
|
||||
output[i][n] = input[i][n] * modval;
|
||||
}
|
||||
this.incrementPhase(dt);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
registerProcessor('am-processor', AMProcessor);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue