mirror of
https://codeberg.org/uzu/strudel
synced 2026-09-16 10:46:57 -04:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a969c9a279 | |||
| e8db161126 | |||
| 2e4947bca6 | |||
| 96a6e0aeec |
@@ -162,7 +162,6 @@ export class StrudelMirror {
|
||||
this.onDraw = onDraw || this.draw;
|
||||
this.id = id || s4();
|
||||
this.solo = solo;
|
||||
this.hasPainters = false;
|
||||
|
||||
this.drawer = new Drawer((haps, time, _, painters) => {
|
||||
const currentFrame = haps.filter((hap) => hap.isActive(time));
|
||||
@@ -178,7 +177,7 @@ export class StrudelMirror {
|
||||
onToggle: (started) => {
|
||||
replOptions?.onToggle?.(started);
|
||||
if (started) {
|
||||
this.shouldAnimate() && this.drawer.start(this.repl.scheduler);
|
||||
this.drawer.start(this.repl.scheduler);
|
||||
if (this.solo) {
|
||||
// stop other repls when this one is started
|
||||
document.dispatchEvent(
|
||||
@@ -208,10 +207,9 @@ export class StrudelMirror {
|
||||
updateWidgets(this.editor, widgets);
|
||||
updateMiniLocations(this.editor, this.miniLocations);
|
||||
replOptions?.afterEval?.(options);
|
||||
this.hasPainters = options.pattern.getPainters().length > 0;
|
||||
// if no painters are set (.onPaint was not called), then we only need
|
||||
// the present moment (for highlighting)
|
||||
const drawTime = this.hasPainters ? this.drawTime : [0, 0];
|
||||
const drawTime = options.pattern.getPainters().length ? this.drawTime : [0, 0];
|
||||
this.drawer.setDrawTime(drawTime);
|
||||
// invalidate drawer after we've set the appropriate drawTime
|
||||
this.drawer.invalidate(this.repl.scheduler);
|
||||
@@ -239,7 +237,6 @@ export class StrudelMirror {
|
||||
cmEditor.style.backgroundColor = 'transparent';
|
||||
}
|
||||
const settings = codemirrorSettings.get();
|
||||
this.isPatternHighlightingEnabled = parseBooleans(settings.isPatternHighlightingEnabled);
|
||||
this.setFontSize(settings.fontSize);
|
||||
this.setFontFamily(settings.fontFamily);
|
||||
|
||||
@@ -324,17 +321,8 @@ export class StrudelMirror {
|
||||
flash(this.editor, ms);
|
||||
}
|
||||
highlight(haps, time) {
|
||||
if (!this.isPatternHighlightingEnabled) {
|
||||
return;
|
||||
}
|
||||
highlightMiniLocations(this.editor, time, haps);
|
||||
}
|
||||
shouldAnimate() {
|
||||
return (
|
||||
this.repl.scheduler.started &&
|
||||
(this.isPatternHighlightingEnabled || this.hasPainters || this.onDraw !== this.draw)
|
||||
);
|
||||
}
|
||||
setFontSize(size) {
|
||||
this.root.style.fontSize = size + 'px';
|
||||
}
|
||||
@@ -355,11 +343,6 @@ export class StrudelMirror {
|
||||
this.editor.dispatch({
|
||||
effects: compartments[key].reconfigure(newValue),
|
||||
});
|
||||
if (key === 'isPatternHighlightingEnabled') {
|
||||
this.isPatternHighlightingEnabled = value;
|
||||
this.drawer.stop();
|
||||
this.shouldAnimate() && this.drawer.start(this.repl.scheduler);
|
||||
}
|
||||
if (key === 'theme') {
|
||||
activateTheme(value);
|
||||
}
|
||||
|
||||
@@ -1622,6 +1622,40 @@ export const { unison } = registerControl('unison');
|
||||
*
|
||||
*/
|
||||
export const { spread } = registerControl('spread');
|
||||
|
||||
/**
|
||||
* Controls how much the detune is concentrated outwards or inwards. A value of 0 will be
|
||||
* linear spacing of voices; -1 will be concentrated outwards (inverse power law); 1 will be concentrated inwards
|
||||
*
|
||||
* @name dpow
|
||||
* @synonyms detunepower
|
||||
* @param {number | Pattern} power between -1 and 1
|
||||
*
|
||||
*/
|
||||
export const { dpow, detunepower } = registerControl('dpow', 'detunepower');
|
||||
|
||||
/**
|
||||
* Controls how much the central voices are emphasized in a detuned oscillator. -1 will emphasize detuned voices;
|
||||
* 1 will emphasize central voices (i.e. either the raw frequency if `unison` is odd or the central two detuned frequencies
|
||||
* if it is even); 0 will be the default blending
|
||||
*
|
||||
* @name dblend
|
||||
* @synonyms detuneblend
|
||||
* @param {number | Pattern} blend between -1 and 1
|
||||
*
|
||||
*/
|
||||
export const { dblend, detuneblend } = registerControl('dblend', 'detuneblend');
|
||||
|
||||
/**
|
||||
* Sets the stacking mode of detuned oscillators
|
||||
*
|
||||
* @name dstack
|
||||
* @synonyms detunestack
|
||||
* @param {number | Pattern} mode mode index starting at 0
|
||||
*
|
||||
*/
|
||||
export const { dstack, detunestack } = registerControl('dstack', 'detunestack');
|
||||
|
||||
/**
|
||||
* Set dryness of reverb. See `room` and `size` for more information about reverb.
|
||||
*
|
||||
|
||||
@@ -91,9 +91,6 @@ Fraction.prototype.or = function (other) {
|
||||
};
|
||||
|
||||
const fraction = (n) => {
|
||||
if (n instanceof Fraction) {
|
||||
return n;
|
||||
}
|
||||
if (typeof n === 'number') {
|
||||
/*
|
||||
https://github.com/infusion/Fraction.js/#doubles
|
||||
|
||||
+3
-14
@@ -152,9 +152,9 @@ export function repl({
|
||||
// allows muting a pattern x with x_ or _x
|
||||
return silence;
|
||||
}
|
||||
if (id.includes('$')) {
|
||||
if (id === '$') {
|
||||
// allows adding anonymous patterns with $:
|
||||
id = `${id}${anonymousIndex}`;
|
||||
id = `$${anonymousIndex}`;
|
||||
anonymousIndex++;
|
||||
}
|
||||
pPatterns[id] = this;
|
||||
@@ -215,19 +215,8 @@ export function repl({
|
||||
let { pattern, meta } = await _evaluate(code, transpiler, transpilerOptions);
|
||||
if (Object.keys(pPatterns).length) {
|
||||
let patterns = [];
|
||||
let soloActive = false;
|
||||
for (const [key, value] of Object.entries(pPatterns)) {
|
||||
// handle soloed patterns ex: S$: s("bd!4")
|
||||
const isSolod = key.length > 1 && key.startsWith('S');
|
||||
if (isSolod && soloActive === false) {
|
||||
// first time we see a soloed pattern, clear existing patterns
|
||||
patterns = [];
|
||||
soloActive = true;
|
||||
}
|
||||
if (!soloActive || (soloActive && isSolod)) {
|
||||
const valWithState = value.withState((state) => state.setControls({ id: key }));
|
||||
patterns.push(valWithState);
|
||||
}
|
||||
patterns.push(value.withState((state) => state.setControls({ id: key })));
|
||||
}
|
||||
if (eachTransform) {
|
||||
// Explicit lambda so only element (not index and array) are passed
|
||||
|
||||
@@ -524,7 +524,7 @@ export const wchoose = (...pairs) => wchooseWith(rand, ...pairs);
|
||||
* @example
|
||||
* wchooseCycles(["bd",10], ["hh",1], ["sd",1]).s().fast(8)
|
||||
* @example
|
||||
* wchooseCycles(["c c c",5], ["a a a",3], ["f f f",1]).fast(4).note()
|
||||
* wchooseCycles(["bd bd bd",5], ["hh hh hh",3], ["sd sd sd",1]).fast(4).s()
|
||||
* @example
|
||||
* // The probability can itself be a pattern
|
||||
* wchooseCycles(["bd(3,8)","<5 0>"], ["hh hh hh",3]).fast(4).s()
|
||||
|
||||
@@ -253,12 +253,7 @@ export const pairs = function (xs) {
|
||||
return result;
|
||||
};
|
||||
|
||||
// Optimized clamp (~1.7x faster than Math.max/min approach)
|
||||
export const clamp = (num, min, max) => {
|
||||
if (num < min) return min;
|
||||
if (num > max) return max;
|
||||
return num;
|
||||
};
|
||||
export const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
|
||||
/* solmization, not used yet */
|
||||
const solfeggio = ['Do', 'Reb', 'Re', 'Mib', 'Mi', 'Fa', 'Solb', 'Sol', 'Lab', 'La', 'Sib', 'Si']; /*solffegio notes*/
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import { clamp, nanFallback, midiToFreq, noteToMidi } from './util.mjs';
|
||||
import { clamp, midiToFreq, nanFallback, noteToMidi } from './util.mjs';
|
||||
import { getNoiseBuffer } from './noise.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
|
||||
@@ -36,27 +36,6 @@ export function getWorklet(ac, processor, params, config) {
|
||||
return node;
|
||||
}
|
||||
|
||||
// Pool of inactive (weakly referenced) voices to be reused if possible
|
||||
const voicePools = {};
|
||||
|
||||
// Cycles through the pool attempting to find an inactive voice that hasn't been GC'd
|
||||
export const claimVoice = (key) => {
|
||||
voicePools[key] ??= [];
|
||||
const pool = voicePools[key];
|
||||
let node;
|
||||
while (pool.length && !node) {
|
||||
const ref = pool.pop();
|
||||
node = ref?.deref?.();
|
||||
}
|
||||
return node;
|
||||
};
|
||||
|
||||
// Releases a voice from use and adds to the inactive pool
|
||||
export const releaseVoice = (key, node) => {
|
||||
voicePools[key] ??= [];
|
||||
voicePools[key].push(new WeakRef(node));
|
||||
};
|
||||
|
||||
export const getParamADSR = (
|
||||
param,
|
||||
attack,
|
||||
@@ -259,7 +238,7 @@ export function createFilter(context, start, end, params, cps) {
|
||||
if (sync != null) {
|
||||
rate = cps * sync;
|
||||
}
|
||||
const lfoValues = { depth, dcoffset, skew, shape, frequency: rate, min: 10, max: 20000 };
|
||||
const lfoValues = { depth, dcoffset, skew, shape, frequency: rate };
|
||||
getParamLfo(context, frequencyParam, start, end, lfoValues);
|
||||
return filter;
|
||||
}
|
||||
@@ -283,15 +262,7 @@ export function drywet(dry, wet, wetAmount = 0) {
|
||||
let mix = ac.createGain();
|
||||
dry_gain.connect(mix);
|
||||
wet_gain.connect(mix);
|
||||
return {
|
||||
node: mix,
|
||||
onended: () => {
|
||||
dry_gain.disconnect(mix);
|
||||
wet_gain.disconnect(mix);
|
||||
dry.disconnect(dry_gain);
|
||||
wet.disconnect(wet_gain);
|
||||
},
|
||||
};
|
||||
return mix;
|
||||
}
|
||||
|
||||
let curves = ['linear', 'exponential'];
|
||||
@@ -326,10 +297,6 @@ export function getVibratoOscillator(param, value, t) {
|
||||
gain.gain.value = vibmod * 100;
|
||||
vibratoOscillator.connect(gain);
|
||||
gain.connect(param);
|
||||
vibratoOscillator.onended = () => {
|
||||
gain.disconnect(param);
|
||||
vibratoOscillator.disconnect(gain);
|
||||
};
|
||||
vibratoOscillator.start(t);
|
||||
return vibratoOscillator;
|
||||
}
|
||||
@@ -339,17 +306,6 @@ export function scheduleAtTime(callback, targetTime, audioContext = getAudioCont
|
||||
const currentTime = audioContext.currentTime;
|
||||
webAudioTimeout(audioContext, callback, currentTime, targetTime);
|
||||
}
|
||||
|
||||
let silencer;
|
||||
function getSilencer() {
|
||||
const ac = getAudioContext();
|
||||
if (!silencer) {
|
||||
silencer = gainNode(0);
|
||||
silencer.connect(ac.destination);
|
||||
}
|
||||
return silencer;
|
||||
}
|
||||
|
||||
// ConstantSource inherits AudioScheduledSourceNode, which has scheduling abilities
|
||||
// a bit of a hack, but it works very well :)
|
||||
export function webAudioTimeout(audioContext, onComplete, startTime, stopTime) {
|
||||
@@ -357,11 +313,18 @@ export function webAudioTimeout(audioContext, onComplete, startTime, stopTime) {
|
||||
|
||||
// Certain browsers requires audio nodes to be connected in order for their onended events
|
||||
// to fire, so we _mute it_ and then connect it to the destination
|
||||
const zeroGain = getSilencer();
|
||||
const zeroGain = gainNode(0);
|
||||
zeroGain.connect(audioContext.destination);
|
||||
constantNode.connect(zeroGain);
|
||||
|
||||
// Schedule the `onComplete` callback to occur at `stopTime`
|
||||
constantNode.onended = () => {
|
||||
// Ensure garbage collection
|
||||
try {
|
||||
zeroGain.disconnect();
|
||||
} catch {
|
||||
// pass
|
||||
}
|
||||
try {
|
||||
constantNode.disconnect();
|
||||
} catch {
|
||||
@@ -447,16 +410,11 @@ export function applyFM(param, value, begin) {
|
||||
|
||||
// Saturation curves
|
||||
|
||||
const fastTanh = (x) => {
|
||||
const x2 = x * x;
|
||||
const y = (x * (27 + x2)) / (27 + 9 * x2);
|
||||
return y < -1 ? -1 : y > 1 ? 1 : y;
|
||||
};
|
||||
const __squash = (x) => x / (1 + x); // [0, inf) to [0, 1)
|
||||
const _mod = (n, m) => ((n % m) + m) % m;
|
||||
|
||||
const _scurve = (x, k) => ((1 + k) * x) / (1 + k * Math.abs(x));
|
||||
const _soft = (x, k) => fastTanh(x * (1 + k));
|
||||
const _soft = (x, k) => Math.tanh(x * (1 + k));
|
||||
const _hard = (x, k) => clamp((1 + k) * x, -1, 1);
|
||||
|
||||
const _fold = (x, k) => {
|
||||
@@ -496,8 +454,13 @@ const _chebyshev = (x, k) => {
|
||||
let tnm1 = 1;
|
||||
let tnm2 = x;
|
||||
let tn;
|
||||
let y = x;
|
||||
for (let i = 2; i < 64; i++) {
|
||||
let y = 0;
|
||||
for (let i = 1; i < 64; i++) {
|
||||
if (i < 2) {
|
||||
// Already set inital conditions
|
||||
y += i == 0 ? tnm1 : tnm2;
|
||||
continue;
|
||||
}
|
||||
tn = 2 * x * tnm1 - tnm2; // https://en.wikipedia.org/wiki/Chebyshev_polynomials#Recurrence_definition
|
||||
tnm2 = tnm1;
|
||||
tnm1 = tn;
|
||||
@@ -563,24 +526,22 @@ export const destroyAudioWorkletNode = (node) => {
|
||||
node.parameters.get('end')?.setValueAtTime(0, 0);
|
||||
};
|
||||
|
||||
export const setParams = (node, params, t) => {
|
||||
const ac = getAudioContext();
|
||||
t ??= ac.currentTime;
|
||||
const workletParams = node && node.parameters && typeof node.parameters.get === 'function';
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value == null) continue;
|
||||
let param;
|
||||
if (workletParams) {
|
||||
param = node.parameters.get(key);
|
||||
}
|
||||
if (param == null && node[key] instanceof AudioParam) {
|
||||
param = node[key];
|
||||
}
|
||||
if (param instanceof AudioParam) {
|
||||
param.cancelScheduledValues(t);
|
||||
param.setValueAtTime(value, t);
|
||||
} else {
|
||||
node[key] = value;
|
||||
}
|
||||
export const getDetuner = (detune = 0, power = 0) => {
|
||||
if (detune <= 0) {
|
||||
return () => 0;
|
||||
}
|
||||
const curve = (x) => {
|
||||
if (power === 0) {
|
||||
return x;
|
||||
}
|
||||
const a = Math.abs(x),
|
||||
s = Math.sign(x);
|
||||
if (power > 0) {
|
||||
return s * Math.pow(a, 1 + 4 * power);
|
||||
}
|
||||
return s * (1 - Math.pow(1 - a, 1 - 4 * power));
|
||||
};
|
||||
return (t) => {
|
||||
return curve(2 * t - 1) * detune;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -65,9 +65,8 @@ export function getNoiseOscillator(type = 'white', t, density = 0.02) {
|
||||
export function getNoiseMix(inputNode, wet, t) {
|
||||
const noiseOscillator = getNoiseOscillator('pink', t);
|
||||
const noiseMix = drywet(inputNode, noiseOscillator.node, wet);
|
||||
noiseOscillator.node.onended = () => noiseMix.onended();
|
||||
return {
|
||||
node: noiseMix.node,
|
||||
node: noiseMix,
|
||||
stop: (time) => noiseOscillator?.stop(time),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -478,16 +478,15 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
const endWithRelease = end + release;
|
||||
const chainID = Math.round(Math.random() * 1000000);
|
||||
|
||||
// oldest audio nodes will be stopped if maximum polyphony is exceeded
|
||||
while (activeSoundSources.size >= maxPolyphony) {
|
||||
const { value: entry } = activeSoundSources.entries().next();
|
||||
if (!entry) break;
|
||||
const [oldChainID, ref] = entry;
|
||||
const handle = ref?.deref();
|
||||
// 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].deref();
|
||||
const chainID = ch.value[0];
|
||||
const endTime = t + 0.25;
|
||||
handle?.node?.gain?.linearRampToValueAtTime?.(0, endTime);
|
||||
handle?.stop?.(endTime);
|
||||
activeSoundSources.delete(oldChainID);
|
||||
source?.node?.gain?.linearRampToValueAtTime(0, endTime);
|
||||
source?.stop?.(endTime);
|
||||
activeSoundSources.delete(chainID);
|
||||
}
|
||||
|
||||
let audioNodes = [];
|
||||
@@ -693,8 +692,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
// delay
|
||||
if (delay > 0 && delaytime > 0 && delayfeedback > 0) {
|
||||
orbitBus.getDelay(delaytime, delayfeedback, t);
|
||||
const send = orbitBus.sendDelay(post, delay);
|
||||
audioNodes.push(send);
|
||||
orbitBus.sendDelay(post, delay);
|
||||
}
|
||||
// reverb
|
||||
if (room > 0) {
|
||||
|
||||
@@ -82,7 +82,7 @@ export class Orbit {
|
||||
}
|
||||
|
||||
sendDelay(node, amount) {
|
||||
return effectSend(node, this.delayNode, amount);
|
||||
effectSend(node, this.delayNode, amount);
|
||||
}
|
||||
|
||||
duck(t, onsettime = 0, attacktime = 0.1, depth = 1) {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { registerSound, soundMap } from './superdough.mjs';
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import {
|
||||
applyFM,
|
||||
claimVoice,
|
||||
destroyAudioWorkletNode,
|
||||
gainNode,
|
||||
getADSRValues,
|
||||
@@ -13,8 +12,6 @@ import {
|
||||
getPitchEnvelope,
|
||||
getVibratoOscillator,
|
||||
getWorklet,
|
||||
setParams,
|
||||
releaseVoice,
|
||||
noises,
|
||||
webAudioTimeout,
|
||||
} from './helpers.mjs';
|
||||
@@ -51,17 +48,19 @@ export function registerSynthSounds() {
|
||||
[0.001, 0.05, 0.6, 0.01],
|
||||
);
|
||||
|
||||
let sound = getOscillator(s, t, value);
|
||||
let { node: o, stop, triggerRelease } = sound;
|
||||
|
||||
// turn down
|
||||
const g = gainNode(0.3);
|
||||
|
||||
let sound = getOscillator(s, t, value, () => {
|
||||
const { duration } = value;
|
||||
|
||||
o.onended = () => {
|
||||
o.disconnect();
|
||||
g.disconnect();
|
||||
onended();
|
||||
});
|
||||
|
||||
let { node: o, stop, triggerRelease } = sound;
|
||||
|
||||
const { duration } = value;
|
||||
};
|
||||
|
||||
const envGain = gainNode(1);
|
||||
let node = o.connect(g).connect(envGain);
|
||||
@@ -167,38 +166,39 @@ export function registerSynthSounds() {
|
||||
const end = holdend + release + 0.01;
|
||||
const voices = clamp(unison, 1, 100);
|
||||
let panspread = voices > 1 ? clamp(spread, 0, 1) : 0;
|
||||
let o = claimVoice('supersaw');
|
||||
const params = {
|
||||
frequency,
|
||||
begin,
|
||||
end,
|
||||
freqspread: detune,
|
||||
panspread,
|
||||
};
|
||||
const processorOptions = {
|
||||
voices,
|
||||
};
|
||||
if (o == null) {
|
||||
o = getWorklet(ac, 'supersaw-oscillator', params, {
|
||||
let o = getWorklet(
|
||||
ac,
|
||||
'supersaw-oscillator',
|
||||
{
|
||||
frequency,
|
||||
begin,
|
||||
end,
|
||||
freqspread: detune,
|
||||
panspread,
|
||||
power: value.dpow,
|
||||
blend: value.dblend,
|
||||
},
|
||||
{
|
||||
outputChannelCount: [2],
|
||||
processorOptions,
|
||||
});
|
||||
} else {
|
||||
setParams(o, params);
|
||||
o.port.postMessage({ type: 'reset', payload: { processorOptions } });
|
||||
}
|
||||
const gainAdjustment = 1 / Math.sqrt(voices);
|
||||
processorOptions: {
|
||||
voices,
|
||||
stackmode: value.dstack,
|
||||
},
|
||||
},
|
||||
);
|
||||
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);
|
||||
const envGain = o.connect(gainNode(1));
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 0.3 * gainAdjustment, begin, holdend, 'linear');
|
||||
const timeoutNode = webAudioTimeout(
|
||||
let envGain = gainNode(1);
|
||||
envGain = o.connect(envGain);
|
||||
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 0.3, begin, holdend, 'linear');
|
||||
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
envGain.disconnect();
|
||||
releaseVoice('supersaw', o);
|
||||
onended();
|
||||
fm?.stop();
|
||||
vibratoOscillator?.stop();
|
||||
@@ -272,7 +272,7 @@ export function registerSynthSounds() {
|
||||
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 1, begin, holdend, 'linear');
|
||||
|
||||
const timeoutNode = webAudioTimeout(
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
@@ -346,7 +346,7 @@ export function registerSynthSounds() {
|
||||
lfo = getLfo(ac, begin, end, { frequency: pwrate, depth: pwsweep });
|
||||
lfo.connect(o.parameters.get('pulsewidth'));
|
||||
}
|
||||
const timeoutNode = webAudioTimeout(
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
@@ -463,7 +463,7 @@ export function waveformN(partials, phases, type) {
|
||||
}
|
||||
|
||||
// expects one of waveforms as s
|
||||
export function getOscillator(s, t, value, onended) {
|
||||
export function getOscillator(s, t, value) {
|
||||
const { duration, noise = 0 } = value;
|
||||
const partials = value.partials ?? value.n;
|
||||
let o;
|
||||
@@ -485,6 +485,7 @@ export function getOscillator(s, t, value, onended) {
|
||||
}
|
||||
// set frequency
|
||||
o.frequency.value = getFrequencyFromValue(value);
|
||||
o.start(t);
|
||||
|
||||
let vibratoOscillator = getVibratoOscillator(o.detune, value, t);
|
||||
|
||||
@@ -497,13 +498,6 @@ export function getOscillator(s, t, value, onended) {
|
||||
noiseMix = getNoiseMix(o, noise, t);
|
||||
}
|
||||
|
||||
o.onended = () => {
|
||||
o.disconnect();
|
||||
noiseMix?.node.disconnect();
|
||||
onended();
|
||||
};
|
||||
o.start(t);
|
||||
|
||||
return {
|
||||
node: noiseMix?.node || o,
|
||||
stop: (time) => {
|
||||
|
||||
@@ -3,8 +3,6 @@ import { logger } from './logger.mjs';
|
||||
// currently duplicate with core util.mjs to skip dependency
|
||||
// TODO: add separate util module?
|
||||
|
||||
export const LN2 = Math.LN2;
|
||||
|
||||
export const tokenizeNote = (note) => {
|
||||
if (typeof note !== 'string') {
|
||||
return [];
|
||||
@@ -34,9 +32,10 @@ export const noteToMidi = (note, defaultOctave = 3) => {
|
||||
export const midiToFreq = (n) => {
|
||||
return Math.pow(2, (n - 69) / 12) * 440;
|
||||
};
|
||||
export const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
|
||||
export const freqToMidi = (freq) => {
|
||||
return (12 * Math.log(freq / 440)) / LN2 + 69;
|
||||
return (12 * Math.log(freq / 440)) / Math.LN2 + 69;
|
||||
};
|
||||
|
||||
export const valueToMidi = (value, fallbackValue) => {
|
||||
@@ -115,38 +114,3 @@ export function getCommonSampleInfo(hapValue, bank) {
|
||||
export const pickAndRename = (source, map) => {
|
||||
return Object.fromEntries(Object.entries(map).map(([newKey, oldKey]) => [newKey, source[oldKey]]));
|
||||
};
|
||||
|
||||
// Optimized / numerical functions (ideal for hot dsp loops)
|
||||
|
||||
// Optimized clamp (~1.7x faster than Math.max/min approach)
|
||||
export const clamp = (num, min, max) => {
|
||||
if (num < min) return min;
|
||||
if (num > max) return max;
|
||||
return num;
|
||||
};
|
||||
export const mod = (n, m) => ((n % m) + m) % m;
|
||||
export const lerp = (a, b, n) => n * (b - a) + a;
|
||||
export const frac = (x) => x - Math.floor(x);
|
||||
|
||||
// Fast integer ops for non-negative values
|
||||
export const ffloor = (x) => x | 0;
|
||||
export const fround = (x) => ffloor(x + 0.5);
|
||||
export const fceil = (x) => ffloor(x + 1);
|
||||
export const ffrac = (x) => x - ffloor(x);
|
||||
|
||||
export const fastexpm1 = (x) => x * (1 + x + 0.5 * x * x); // Taylor approximation
|
||||
|
||||
export const fastpow2 = (x) => {
|
||||
// Taylor approximation of 2 ^ x
|
||||
const a = x * LN2;
|
||||
return 1 + a * (1 + a * (0.5 + a / 6));
|
||||
};
|
||||
|
||||
export const applySemitoneDetuneToFrequency = (frequency, detune) => {
|
||||
return frequency * Math.pow(2, detune / 12);
|
||||
};
|
||||
|
||||
export const applyFastDetune = (frequency, detune) => {
|
||||
if (detune < 4) return frequency * fastpow2(detune / 12);
|
||||
return applySemitoneDetuneToFrequency(frequency, detune);
|
||||
};
|
||||
|
||||
@@ -3,18 +3,14 @@ import { getCommonSampleInfo } from './util.mjs';
|
||||
import {
|
||||
applyFM,
|
||||
applyParameterModulators,
|
||||
claimVoice,
|
||||
gainNode,
|
||||
destroyAudioWorkletNode,
|
||||
getADSRValues,
|
||||
getFrequencyFromValue,
|
||||
getParamADSR,
|
||||
getPitchEnvelope,
|
||||
getVibratoOscillator,
|
||||
getWorklet,
|
||||
setParams,
|
||||
releaseVoice,
|
||||
webAudioTimeout,
|
||||
destroyAudioWorkletNode,
|
||||
} from './helpers.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
|
||||
@@ -222,39 +218,39 @@ export async function onTriggerSynth(t, value, onended, tables, cps, frameLen) {
|
||||
const frequency = getFrequencyFromValue(value);
|
||||
const { url, label } = getCommonSampleInfo(value, tables);
|
||||
const payload = await getPayload(url, label, frameLen);
|
||||
const voiceKey = `wavetable:${payload.key}`;
|
||||
let holdEnd = t + duration;
|
||||
if (clip !== undefined) {
|
||||
holdEnd = Math.min(t + clip * duration, holdEnd);
|
||||
}
|
||||
const endWithRelease = holdEnd + release;
|
||||
const envEnd = endWithRelease + 0.01;
|
||||
let source = claimVoice(voiceKey);
|
||||
const params = {
|
||||
begin: t,
|
||||
end: envEnd,
|
||||
frequency,
|
||||
freqspread: value.detune,
|
||||
position: value.wt,
|
||||
warp: value.warp,
|
||||
warpMode: warpmode,
|
||||
panspread: value.spread,
|
||||
};
|
||||
const processorOptions = {
|
||||
phaseRand: value.wtphaserand ?? (value.unison > 1 ? 1 : 0),
|
||||
voices: Math.max(value.unison ?? 1, 1),
|
||||
};
|
||||
if (source == null) {
|
||||
source = getWorklet(ac, 'wavetable-oscillator-processor', params, { outputChannelCount: [2], processorOptions });
|
||||
} else {
|
||||
setParams(source, params);
|
||||
source.port.postMessage({ type: 'reset', payload: { processorOptions } });
|
||||
}
|
||||
const source = getWorklet(
|
||||
ac,
|
||||
'wavetable-oscillator-processor',
|
||||
{
|
||||
begin: t,
|
||||
end: envEnd,
|
||||
frequency,
|
||||
freqspread: value.detune,
|
||||
position: value.wt,
|
||||
warp: value.warp,
|
||||
panspread: value.spread,
|
||||
power: value.dpow,
|
||||
blend: value.dblend,
|
||||
},
|
||||
{
|
||||
outputChannelCount: [2],
|
||||
processorOptions: {
|
||||
voices: Math.max(value.unison ?? 1, 1),
|
||||
stackmode: value.dstack,
|
||||
phaserand: (value.wtphaserand ?? value.unison > 1) ? 1 : 0,
|
||||
warpmode,
|
||||
},
|
||||
},
|
||||
);
|
||||
source.port.postMessage({ type: 'table', payload });
|
||||
if (ac.currentTime > t) {
|
||||
logger(`[wavetable] still loading sound "${s}:${n}"`, 'highlight');
|
||||
destroyAudioWorkletNode(source);
|
||||
releaseVoice(voiceKey, source);
|
||||
return;
|
||||
}
|
||||
const posADSRParams = [value.wtattack, value.wtdecay, value.wtsustain, value.wtrelease];
|
||||
@@ -321,20 +317,20 @@ export async function onTriggerSynth(t, value, onended, tables, cps, frameLen) {
|
||||
);
|
||||
const vibratoOscillator = getVibratoOscillator(source.parameters.get('detune'), value, t);
|
||||
const fm = applyFM(source.parameters.get('frequency'), value, t);
|
||||
const envGain = source.connect(gainNode(1));
|
||||
getParamADSR(envGain.gain, attack, decay, sustain, release, 0, 0.3, t, holdEnd, 'linear');
|
||||
const envGain = ac.createGain();
|
||||
const node = source.connect(envGain);
|
||||
getParamADSR(node.gain, attack, decay, sustain, release, 0, 0.3, t, holdEnd, 'linear');
|
||||
getPitchEnvelope(source.parameters.get('detune'), value, t, holdEnd);
|
||||
const handle = { node: envGain };
|
||||
const handle = { node, source };
|
||||
const timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(source);
|
||||
vibratoOscillator?.stop();
|
||||
fm?.stop();
|
||||
node.disconnect();
|
||||
wtPosModulators?.disconnect();
|
||||
wtWarpModulators?.disconnect();
|
||||
envGain.disconnect();
|
||||
destroyAudioWorkletNode(source);
|
||||
releaseVoice(voiceKey, source);
|
||||
onended();
|
||||
},
|
||||
t,
|
||||
|
||||
+193
-147
@@ -4,40 +4,32 @@
|
||||
|
||||
import OLAProcessor from './ola-processor';
|
||||
import FFT from './fft.js';
|
||||
import { getDistortionAlgorithm } from './helpers.mjs';
|
||||
import {
|
||||
applyFastDetune,
|
||||
applySemitoneDetuneToFrequency,
|
||||
clamp,
|
||||
fastexpm1,
|
||||
fceil,
|
||||
ffloor,
|
||||
ffrac,
|
||||
frac,
|
||||
fround,
|
||||
lerp,
|
||||
} from './util.mjs';
|
||||
import { getDistortionAlgorithm, getDetuner } from './helpers.mjs';
|
||||
|
||||
const blockSize = 128;
|
||||
const PI = Math.PI;
|
||||
const TWO_PI = 2 * PI;
|
||||
const INVSR = 1 / sampleRate;
|
||||
const MAX_VOICES = 64;
|
||||
|
||||
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
const mod = (n, m) => ((n % m) + m) % m;
|
||||
const lerp = (a, b, n) => n * (b - a) + a;
|
||||
const pv = (arr, n) => arr[n] ?? arr[0];
|
||||
const frac = (x) => x - Math.floor(x);
|
||||
|
||||
// Fast integer ops for non-negative values
|
||||
const ffloor = (x) => x | 0;
|
||||
const fround = (x) => ffloor(x + 0.5);
|
||||
const fceil = (x) => ffloor(x + 1);
|
||||
const ffrac = (x) => x - ffloor(x);
|
||||
|
||||
const fast_tanh = (x) => {
|
||||
const x2 = x * x;
|
||||
return (x * (27 + x2)) / (27 + 9 * x2);
|
||||
const x2 = x ** 2;
|
||||
return (x * (27.0 + x2)) / (27.0 + 9.0 * x2);
|
||||
};
|
||||
|
||||
// Optimized per-voice detuner which precomputes constants
|
||||
const getDetuner = (unison, detune) => {
|
||||
if (unison < 2) {
|
||||
return (_voiceIdx) => 0;
|
||||
}
|
||||
const scale = detune / (unison - 1);
|
||||
const center = detune * 0.5;
|
||||
return (voiceIdx) => voiceIdx * scale - center;
|
||||
const applySemitoneDetuneToFrequency = (frequency, detune) => {
|
||||
return frequency * Math.pow(2, detune / 12);
|
||||
};
|
||||
|
||||
// Smooth waveshape near discontinuities to remove frequencies above Nyquist and prevent aliasing
|
||||
@@ -167,11 +159,10 @@ class LFOProcessor extends AudioWorkletProcessor {
|
||||
}
|
||||
const dt = frequency * INVSR;
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
let modval = (waveshapes[shape](this.phase, skew) + dcoffset) * depth;
|
||||
modval = curve !== 1 ? Math.pow(modval, curve) : modval;
|
||||
const out = clamp(modval, min, max);
|
||||
for (let i = 0; i < output.length; i++) {
|
||||
output[i][n] = out;
|
||||
let modval = (waveshapes[shape](this.phase, skew) + dcoffset) * depth;
|
||||
modval = Math.pow(modval, curve);
|
||||
output[i][n] = clamp(modval, min, max);
|
||||
}
|
||||
this.incrementPhase(dt);
|
||||
}
|
||||
@@ -442,7 +433,7 @@ class DistortProcessor extends AudioWorkletProcessor {
|
||||
this.started = hasInput;
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
const postgain = clamp(pv(parameters.postgain, n), 0.001, 1);
|
||||
const shape = fastexpm1(pv(parameters.distort, n));
|
||||
const shape = Math.expm1(pv(parameters.distort, n));
|
||||
for (let ch = 0; ch < input.length; ch++) {
|
||||
const x = input[ch][n];
|
||||
output[ch][n] = postgain * this.algorithm(x, shape);
|
||||
@@ -453,19 +444,68 @@ class DistortProcessor extends AudioWorkletProcessor {
|
||||
}
|
||||
registerProcessor('distort-processor', DistortProcessor);
|
||||
|
||||
const INTERVALS = [
|
||||
[1],
|
||||
[1, 2],
|
||||
[1, 3],
|
||||
[1, 2, 4],
|
||||
[1, 2, 4, 8],
|
||||
[1, 2, 3],
|
||||
[1, 1.5, 2.4],
|
||||
[1, 2.5],
|
||||
[1, 1.782],
|
||||
[1, 2.4],
|
||||
[1, 1.5, 2.5],
|
||||
[1, 1.667],
|
||||
[1, 2.25],
|
||||
];
|
||||
const _getIntervals = (mode = 0) => {
|
||||
return INTERVALS[mode] ?? INTERVALS[0];
|
||||
};
|
||||
|
||||
const initUnisonProcessor = (processor, processorOptions) => {
|
||||
processor.intervals = _getIntervals(processorOptions.stackmode);
|
||||
processor.intervalGains = processor.intervals.map((i) => 1 / i ** 0.5); // reduce volume of upper harmonics
|
||||
processor.intNorm = Math.sqrt(1 / processor.intervalGains.reduce((acc, i) => acc + i ** 2, 0));
|
||||
processor.numIntervals = processor.intervals.length;
|
||||
processor.voices = processorOptions.voices;
|
||||
processor.isDetuned = processor.voices > 1;
|
||||
processor.isCenter = (idx) => {
|
||||
if (!processor.isDetuned) return true;
|
||||
if (processor.voices % 2 === 1) {
|
||||
return idx === (processor.voices - 1) >> 1;
|
||||
} else {
|
||||
const right = processor.voices >> 1;
|
||||
const left = right - 1;
|
||||
return idx === left || idx === right;
|
||||
}
|
||||
};
|
||||
const totalVoices = processor.voices * processor.numIntervals;
|
||||
processor.blendGains = new Array(processor.voices).fill(1);
|
||||
const phaserand = processorOptions.phaserand ?? 1;
|
||||
processor.phases = new Array(totalVoices).fill(0).map(() => Math.random() * phaserand);
|
||||
return totalVoices;
|
||||
};
|
||||
|
||||
const getUnisonData = (processor, params, i) => {
|
||||
const detune = pv(params.detune, i);
|
||||
const freqspread = pv(params.freqspread, i);
|
||||
const blend = pv(params.blend, i) * 0.95;
|
||||
const blendGains = processor.blendGains.map((_, idx) => (processor.isCenter(idx) ? 1 - blend : 1 + blend));
|
||||
const blendNorm = 1 / Math.sqrt(blendGains.reduce((acc, g) => acc + g ** 2, 0));
|
||||
const normalizer = blendNorm * processor.intNorm;
|
||||
const power = pv(params.power, i);
|
||||
const freq = applySemitoneDetuneToFrequency(pv(params.frequency, i), detune / 100);
|
||||
const detuner = getDetuner(freqspread, power);
|
||||
const inv = processor.voices > 1 ? 1 / (processor.voices - 1) : 0;
|
||||
return { blendGains, normalizer, detuner, inv, freq };
|
||||
};
|
||||
|
||||
// SUPERSAW
|
||||
class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
||||
constructor(options) {
|
||||
constructor({ processorOptions }) {
|
||||
super();
|
||||
this.phases = new Float32Array(MAX_VOICES);
|
||||
this.reset(options.processorOptions);
|
||||
}
|
||||
reset(options) {
|
||||
const phases = this.phases;
|
||||
for (let i = 0; i < phases.length; i++) {
|
||||
phases[i] = Math.random();
|
||||
}
|
||||
this.voices = options.voices;
|
||||
initUnisonProcessor(this, processorOptions);
|
||||
}
|
||||
static get parameterDescriptors() {
|
||||
return [
|
||||
@@ -502,57 +542,54 @@ class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
||||
defaultValue: 0,
|
||||
min: 0,
|
||||
},
|
||||
{
|
||||
name: 'blend',
|
||||
defaultValue: 0,
|
||||
min: -1,
|
||||
max: 1,
|
||||
},
|
||||
{
|
||||
name: 'power',
|
||||
defaultValue: 0,
|
||||
min: -1,
|
||||
max: 1,
|
||||
},
|
||||
];
|
||||
}
|
||||
process(_input, outputs, params) {
|
||||
const started = currentTime >= params.begin[0];
|
||||
const ended = currentTime >= params.end[0];
|
||||
if (!started || ended) {
|
||||
if (currentTime <= params.begin[0]) {
|
||||
return true;
|
||||
}
|
||||
if (currentTime >= params.end[0]) {
|
||||
return false;
|
||||
}
|
||||
const output = outputs[0];
|
||||
// fast k-rate paths
|
||||
let freq, detune, freqspread, detuner;
|
||||
if (params.freqspread.length === 1) {
|
||||
freqspread = params.freqspread[0];
|
||||
detuner = getDetuner(this.voices, freqspread);
|
||||
}
|
||||
if (params.frequency.length === 1 && params.detune.length === 1) {
|
||||
freq = params.frequency[0];
|
||||
detune = params.detune[0];
|
||||
freq = applySemitoneDetuneToFrequency(freq, detune / 100);
|
||||
}
|
||||
let panspread, gainL, gainR;
|
||||
if (params.panspread.length === 1) {
|
||||
panspread = this.voices > 1 ? clamp(params.panspread[0], 0, 1) : 0;
|
||||
gainL = Math.sqrt(0.5 - 0.5 * panspread);
|
||||
gainR = Math.sqrt(0.5 + 0.5 * panspread);
|
||||
}
|
||||
for (let i = 0; i < output[0].length; i++) {
|
||||
const { blendGains, normalizer, detuner, inv, freq } = getUnisonData(this, params, i);
|
||||
const panspread = pv(params.panspread, i) * 0.5 + 0.5;
|
||||
gainL = Math.sqrt(1 - panspread);
|
||||
gainR = Math.sqrt(panspread);
|
||||
// Main detuning (a-rate path)
|
||||
detune ??= pv(params.detune, i);
|
||||
freqspread ??= pv(params.freqspread, i);
|
||||
freq ??= applySemitoneDetuneToFrequency(pv(params.frequency, i), detune / 100);
|
||||
detuner ??= getDetuner(this.voices, freqspread);
|
||||
let gainL = Math.sqrt(1 - panspread) * normalizer;
|
||||
let gainR = Math.sqrt(panspread) * normalizer;
|
||||
for (let n = 0; n < this.voices; n++) {
|
||||
// Individual voice detuning
|
||||
const freqVoice = applyFastDetune(freq, detuner(n));
|
||||
// We must wrap this here because it is passed into sawblep below which
|
||||
// has domain [0, 1]
|
||||
const dt = frac(freqVoice * INVSR);
|
||||
const v = waveshapes.sawblep(this.phases[n], dt);
|
||||
output[0][i] += v * gainL;
|
||||
output[1][i] += v * gainR;
|
||||
let pn = this.phases[n] + dt;
|
||||
if (pn >= 1.0) pn -= 1.0;
|
||||
this.phases[n] = pn;
|
||||
// invert right and left gain
|
||||
const tmp = gainL;
|
||||
gainL = gainR;
|
||||
gainR = tmp;
|
||||
const freqVoice = this.isDetuned ? applySemitoneDetuneToFrequency(freq, detuner(n * inv)) : freq; // voice detune
|
||||
const bG = blendGains[n];
|
||||
for (let idx = 0; idx < this.numIntervals; idx++) {
|
||||
const g = bG * this.intervalGains[idx];
|
||||
const freqStack = freqVoice * this.intervals[idx];
|
||||
// We must wrap this here because it is passed into sawblep below which
|
||||
// has domain [0, 1]
|
||||
const dt = ffrac(freqStack * INVSR);
|
||||
const voiceNum = n * this.numIntervals + idx;
|
||||
const v = waveshapes.sawblep(this.phases[voiceNum], dt);
|
||||
output[0][i] += v * gainL * g;
|
||||
output[1][i] += v * gainR * g;
|
||||
let pn = this.phases[voiceNum] + dt;
|
||||
if (pn >= 1.0) pn -= 1.0;
|
||||
this.phases[voiceNum] = pn;
|
||||
// invert right and left gain
|
||||
gainL = gainR;
|
||||
gainR = gainL;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -1132,41 +1169,46 @@ class WavetableOscillatorProcessor extends AudioWorkletProcessor {
|
||||
{ name: 'freqspread', defaultValue: 0.18, min: 0 },
|
||||
{ name: 'position', defaultValue: 0, min: 0, max: 1 },
|
||||
{ name: 'warp', defaultValue: 0, min: 0, max: 1 },
|
||||
{ name: 'warpMode', defaultValue: 0, automationRate: 'k-rate' },
|
||||
{ name: 'panspread', defaultValue: 0.7, min: 0, max: 1 },
|
||||
{ name: 'blend', defaultValue: 0, min: -1, max: 1 },
|
||||
{ name: 'power', defaultValue: 0, min: -1, max: 1 },
|
||||
];
|
||||
}
|
||||
|
||||
constructor(options) {
|
||||
super(options);
|
||||
constructor({ processorOptions }) {
|
||||
super();
|
||||
initUnisonProcessor(this, processorOptions);
|
||||
this.warpmode = processorOptions.warpmode;
|
||||
this.frameLen = 0;
|
||||
this.numFrames = 0;
|
||||
this.phases = new Float32Array(MAX_VOICES);
|
||||
this.port.onmessage = (e) => {
|
||||
const { type, payload } = e.data || {};
|
||||
if (type === 'table') {
|
||||
const key = payload.key;
|
||||
this.frameLen = payload.frameLen;
|
||||
this.baseThreshold = this.frameLen >>> 3; // used for mipmaps
|
||||
if (!tablesCache[key]) {
|
||||
tablesCache[key] = payload.frames;
|
||||
const tables = [payload.frames];
|
||||
let table = tables[0];
|
||||
for (let level = 1; level < 1; level++) {
|
||||
const nextLen = table.length >> 1;
|
||||
const nextTable = table.map((frame) => {
|
||||
const avg = new Float32Array(nextLen);
|
||||
for (let i = 0; i < nextLen; i++) {
|
||||
avg[i] = (frame[2 * i] + frame[2 * i + 1]) / 2;
|
||||
}
|
||||
return avg;
|
||||
});
|
||||
tables.push(nextTable);
|
||||
table = nextTable;
|
||||
if (nextLen <= 32) break;
|
||||
}
|
||||
tablesCache[key] = tables;
|
||||
}
|
||||
this.table = tablesCache[key];
|
||||
this.numFrames = this.table.length;
|
||||
} else if (type === 'reset') {
|
||||
this.reset(payload.processorOptions);
|
||||
this.tables = tablesCache[key];
|
||||
this.numFrames = this.tables[0].length;
|
||||
}
|
||||
};
|
||||
this.reset(options.processorOptions);
|
||||
}
|
||||
|
||||
reset(options) {
|
||||
const phaseRand = options.phaseRand ?? 1;
|
||||
const phases = this.phases;
|
||||
for (let i = 0; i < phases.length; i++) {
|
||||
phases[i] = Math.random() * phaseRand;
|
||||
}
|
||||
this.voices = options.voices;
|
||||
this.normalizer = 1 / Math.sqrt(this.voices);
|
||||
}
|
||||
|
||||
_mirror(x) {
|
||||
@@ -1311,63 +1353,67 @@ class WavetableOscillatorProcessor extends AudioWorkletProcessor {
|
||||
return a + (b - a) * frac;
|
||||
}
|
||||
|
||||
process(_inputs, outputs, params) {
|
||||
const started = currentTime >= params.begin[0];
|
||||
const ended = currentTime >= params.end[0];
|
||||
if (!started || ended) {
|
||||
_chooseMip(dphi) {
|
||||
const approxHarm = Math.min(64, 1 / Math.max(1e-6, dphi));
|
||||
const numTables = this.tables.length;
|
||||
let level = 0,
|
||||
threshold = this.baseThreshold;
|
||||
while (level + 1 < numTables && approxHarm < threshold) {
|
||||
level++;
|
||||
threshold *= 2;
|
||||
}
|
||||
return level;
|
||||
}
|
||||
|
||||
process(_inputs, outputs, parameters) {
|
||||
if (currentTime >= parameters.end[0]) {
|
||||
return false;
|
||||
}
|
||||
if (currentTime <= parameters.begin[0]) {
|
||||
return true;
|
||||
}
|
||||
const outL = outputs[0][0];
|
||||
const outR = outputs[0][1] || outputs[0][0];
|
||||
// fast k-rate paths
|
||||
let freq, detune, freqspread, detuner;
|
||||
if (params.freqspread.length === 1) {
|
||||
freqspread = params.freqspread[0];
|
||||
detuner = getDetuner(this.voices, freqspread);
|
||||
if (!this.tables) {
|
||||
outL.fill(0);
|
||||
if (outR !== outL) outR.set(outL);
|
||||
return true;
|
||||
}
|
||||
if (params.frequency.length === 1 && params.detune.length === 1) {
|
||||
freq = params.frequency[0];
|
||||
detune = params.detune[0];
|
||||
freq = applySemitoneDetuneToFrequency(freq, detune / 100);
|
||||
}
|
||||
let panspread, gainL, gainR;
|
||||
if (params.panspread.length === 1) {
|
||||
panspread = this.voices > 1 ? clamp(params.panspread[0], 0, 1) : 0;
|
||||
gainL = Math.sqrt(0.5 - 0.5 * panspread);
|
||||
gainR = Math.sqrt(0.5 + 0.5 * panspread);
|
||||
}
|
||||
const warpMode = params.warpMode[0];
|
||||
for (let i = 0; i < outL.length; i++) {
|
||||
const tablePos = clamp(pv(params.position, i), 0, 1);
|
||||
const { blendGains, normalizer, detuner, inv, freq } = getUnisonData(this, parameters, i);
|
||||
const tablePos = clamp(pv(parameters.position, i), 0, 1);
|
||||
const idx = tablePos * (this.numFrames - 1);
|
||||
const fIdx = idx | 0;
|
||||
const interpT = idx - fIdx;
|
||||
const warpAmount = clamp(pv(params.warp, i), 0, 1);
|
||||
panspread ??= this.voices > 1 ? clamp(pv(params.panspread, i), 0, 1) : 0;
|
||||
gainL ??= Math.sqrt(0.5 - 0.5 * panspread);
|
||||
gainR ??= Math.sqrt(0.5 + 0.5 * panspread);
|
||||
detune ??= pv(params.detune, i);
|
||||
freqspread ??= pv(params.freqspread, i);
|
||||
freq ??= applySemitoneDetuneToFrequency(pv(params.frequency, i), detune / 100); // overall detune
|
||||
detuner ??= getDetuner(this.voices, freqspread);
|
||||
const frac = idx - fIdx;
|
||||
const warpAmount = clamp(pv(parameters.warp, i), 0, 1);
|
||||
const panspread = this.isDetuned ? clamp(pv(parameters.panspread, i), 0, 1) : 0;
|
||||
let gainL = Math.sqrt(0.5 - 0.5 * panspread) * normalizer;
|
||||
let gainR = Math.sqrt(0.5 + 0.5 * panspread) * normalizer;
|
||||
for (let n = 0; n < this.voices; n++) {
|
||||
const freqVoice = applyFastDetune(freq, detuner(n)); // voice detune
|
||||
const dPhase = freqVoice * INVSR;
|
||||
// warp phase then sample
|
||||
const ph = this._warpPhase(this.phases[n], warpAmount, warpMode);
|
||||
const s0 = this._sampleFrame(this.table[fIdx], ph);
|
||||
const s1 = this._sampleFrame(this.table[Math.min(this.numFrames - 1, fIdx + 1)], ph);
|
||||
let s = lerp(s0, s1, interpT);
|
||||
if (warpMode === WarpMode.FLIP && this.phases[n] < warpAmount) {
|
||||
s = -s;
|
||||
const fVoice = this.isDetuned ? applySemitoneDetuneToFrequency(freq, detuner(n * inv)) : freq; // voice detune
|
||||
const bG = blendGains[n];
|
||||
for (let idx = 0; idx < this.numIntervals; idx++) {
|
||||
const g = bG * this.intervalGains[idx];
|
||||
const fStack = fVoice * this.intervals[idx];
|
||||
const dt = fStack * INVSR;
|
||||
const voiceNum = n * this.numIntervals + idx;
|
||||
const level = this._chooseMip(dt);
|
||||
const table = this.tables[level];
|
||||
// warp phase then sample
|
||||
const ph = this._warpPhase(this.phases[voiceNum], warpAmount, this.warpmode);
|
||||
const s0 = this._sampleFrame(table[fIdx], ph);
|
||||
const s1 = this._sampleFrame(table[Math.min(this.numFrames - 1, fIdx + 1)], ph);
|
||||
let s = s0 + (s1 - s0) * frac;
|
||||
if (this.warpmode === WarpMode.FLIP && this.phase[n] < warpAmount) {
|
||||
s = -s;
|
||||
}
|
||||
outL[i] += s * gainL * g;
|
||||
outR[i] += s * gainR * g;
|
||||
this.phases[voiceNum] = ffrac(this.phases[voiceNum] + dt);
|
||||
// invert right and left gain
|
||||
gainL = gainR;
|
||||
gainR = gainL;
|
||||
}
|
||||
outL[i] += s * gainL * this.normalizer;
|
||||
outR[i] += s * gainR * this.normalizer;
|
||||
this.phases[n] = frac(this.phases[n] + dPhase);
|
||||
// invert right and left gain
|
||||
const tmp = gainL;
|
||||
gainR = gainL;
|
||||
gainL = tmp;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { Dough } from './dough.mjs';
|
||||
|
||||
const clamp = (num, min, max) => {
|
||||
if (num < min) return min;
|
||||
if (num > max) return max;
|
||||
return num;
|
||||
};
|
||||
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
|
||||
class DoughProcessor extends AudioWorkletProcessor {
|
||||
constructor() {
|
||||
|
||||
@@ -6,11 +6,7 @@ const PI_DIV_SR = Math.PI / SAMPLE_RATE;
|
||||
const ISR = 1 / SAMPLE_RATE;
|
||||
|
||||
let gainCurveFunc = (val) => Math.pow(val, 2);
|
||||
const clamp = (num, min, max) => {
|
||||
if (num < min) return min;
|
||||
if (num > max) return max;
|
||||
return num;
|
||||
};
|
||||
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
|
||||
function applyGainCurve(val) {
|
||||
return gainCurveFunc(val);
|
||||
|
||||
@@ -12484,54 +12484,54 @@ exports[`runs examples > example "wchooseCycles" example index 0 1`] = `
|
||||
|
||||
exports[`runs examples > example "wchooseCycles" example index 1 1`] = `
|
||||
[
|
||||
"[ 0/1 → 1/12 | note:c ]",
|
||||
"[ 1/12 → 1/6 | note:c ]",
|
||||
"[ 1/6 → 1/4 | note:c ]",
|
||||
"[ 1/4 → 1/3 | note:c ]",
|
||||
"[ 1/3 → 5/12 | note:c ]",
|
||||
"[ 5/12 → 1/2 | note:c ]",
|
||||
"[ 1/2 → 7/12 | note:f ]",
|
||||
"[ 7/12 → 2/3 | note:f ]",
|
||||
"[ 2/3 → 3/4 | note:f ]",
|
||||
"[ 3/4 → 5/6 | note:c ]",
|
||||
"[ 5/6 → 11/12 | note:c ]",
|
||||
"[ 11/12 → 1/1 | note:c ]",
|
||||
"[ 1/1 → 13/12 | note:c ]",
|
||||
"[ 13/12 → 7/6 | note:c ]",
|
||||
"[ 7/6 → 5/4 | note:c ]",
|
||||
"[ 5/4 → 4/3 | note:c ]",
|
||||
"[ 4/3 → 17/12 | note:c ]",
|
||||
"[ 17/12 → 3/2 | note:c ]",
|
||||
"[ 3/2 → 19/12 | note:a ]",
|
||||
"[ 19/12 → 5/3 | note:a ]",
|
||||
"[ 5/3 → 7/4 | note:a ]",
|
||||
"[ 7/4 → 11/6 | note:c ]",
|
||||
"[ 11/6 → 23/12 | note:c ]",
|
||||
"[ 23/12 → 2/1 | note:c ]",
|
||||
"[ 2/1 → 25/12 | note:a ]",
|
||||
"[ 25/12 → 13/6 | note:a ]",
|
||||
"[ 13/6 → 9/4 | note:a ]",
|
||||
"[ 9/4 → 7/3 | note:a ]",
|
||||
"[ 7/3 → 29/12 | note:a ]",
|
||||
"[ 29/12 → 5/2 | note:a ]",
|
||||
"[ 5/2 → 31/12 | note:c ]",
|
||||
"[ 31/12 → 8/3 | note:c ]",
|
||||
"[ 8/3 → 11/4 | note:c ]",
|
||||
"[ 11/4 → 17/6 | note:c ]",
|
||||
"[ 17/6 → 35/12 | note:c ]",
|
||||
"[ 35/12 → 3/1 | note:c ]",
|
||||
"[ 3/1 → 37/12 | note:c ]",
|
||||
"[ 37/12 → 19/6 | note:c ]",
|
||||
"[ 19/6 → 13/4 | note:c ]",
|
||||
"[ 13/4 → 10/3 | note:f ]",
|
||||
"[ 10/3 → 41/12 | note:f ]",
|
||||
"[ 41/12 → 7/2 | note:f ]",
|
||||
"[ 7/2 → 43/12 | note:a ]",
|
||||
"[ 43/12 → 11/3 | note:a ]",
|
||||
"[ 11/3 → 15/4 | note:a ]",
|
||||
"[ 15/4 → 23/6 | note:c ]",
|
||||
"[ 23/6 → 47/12 | note:c ]",
|
||||
"[ 47/12 → 4/1 | note:c ]",
|
||||
"[ 0/1 → 1/12 | s:bd ]",
|
||||
"[ 1/12 → 1/6 | s:bd ]",
|
||||
"[ 1/6 → 1/4 | s:bd ]",
|
||||
"[ 1/4 → 1/3 | s:bd ]",
|
||||
"[ 1/3 → 5/12 | s:bd ]",
|
||||
"[ 5/12 → 1/2 | s:bd ]",
|
||||
"[ 1/2 → 7/12 | s:sd ]",
|
||||
"[ 7/12 → 2/3 | s:sd ]",
|
||||
"[ 2/3 → 3/4 | s:sd ]",
|
||||
"[ 3/4 → 5/6 | s:bd ]",
|
||||
"[ 5/6 → 11/12 | s:bd ]",
|
||||
"[ 11/12 → 1/1 | s:bd ]",
|
||||
"[ 1/1 → 13/12 | s:bd ]",
|
||||
"[ 13/12 → 7/6 | s:bd ]",
|
||||
"[ 7/6 → 5/4 | s:bd ]",
|
||||
"[ 5/4 → 4/3 | s:bd ]",
|
||||
"[ 4/3 → 17/12 | s:bd ]",
|
||||
"[ 17/12 → 3/2 | s:bd ]",
|
||||
"[ 3/2 → 19/12 | s:hh ]",
|
||||
"[ 19/12 → 5/3 | s:hh ]",
|
||||
"[ 5/3 → 7/4 | s:hh ]",
|
||||
"[ 7/4 → 11/6 | s:bd ]",
|
||||
"[ 11/6 → 23/12 | s:bd ]",
|
||||
"[ 23/12 → 2/1 | s:bd ]",
|
||||
"[ 2/1 → 25/12 | s:hh ]",
|
||||
"[ 25/12 → 13/6 | s:hh ]",
|
||||
"[ 13/6 → 9/4 | s:hh ]",
|
||||
"[ 9/4 → 7/3 | s:hh ]",
|
||||
"[ 7/3 → 29/12 | s:hh ]",
|
||||
"[ 29/12 → 5/2 | s:hh ]",
|
||||
"[ 5/2 → 31/12 | s:bd ]",
|
||||
"[ 31/12 → 8/3 | s:bd ]",
|
||||
"[ 8/3 → 11/4 | s:bd ]",
|
||||
"[ 11/4 → 17/6 | s:bd ]",
|
||||
"[ 17/6 → 35/12 | s:bd ]",
|
||||
"[ 35/12 → 3/1 | s:bd ]",
|
||||
"[ 3/1 → 37/12 | s:bd ]",
|
||||
"[ 37/12 → 19/6 | s:bd ]",
|
||||
"[ 19/6 → 13/4 | s:bd ]",
|
||||
"[ 13/4 → 10/3 | s:sd ]",
|
||||
"[ 10/3 → 41/12 | s:sd ]",
|
||||
"[ 41/12 → 7/2 | s:sd ]",
|
||||
"[ 7/2 → 43/12 | s:hh ]",
|
||||
"[ 43/12 → 11/3 | s:hh ]",
|
||||
"[ 11/3 → 15/4 | s:hh ]",
|
||||
"[ 15/4 → 23/6 | s:bd ]",
|
||||
"[ 23/6 → 47/12 | s:bd ]",
|
||||
"[ 47/12 → 4/1 | s:bd ]",
|
||||
]
|
||||
`;
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ export function SoundsTab() {
|
||||
try {
|
||||
// Pre-load the sample by calling onTrigger with a future time
|
||||
// This triggers the loading but schedules playback for later
|
||||
const time = ctx.currentTime + 0.05;
|
||||
const time = ctx.currentTime + 0.5; // Give 500ms for loading
|
||||
const ref = await onTrigger(time, params, onended);
|
||||
trigRef.current = ref;
|
||||
if (ref?.node) {
|
||||
|
||||
Reference in New Issue
Block a user