tetorica-fm2612 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -2
- package/RUNTIME.md +1 -1
- package/looper.js +8 -3
- package/megasynth_offline.js +170 -0
- package/megasynth_pcm_looper.js +69 -0
- package/megasynth_recording.js +3 -1
- package/megasynth_session.js +171 -0
- package/native-fx-worklet.js +18 -60
- package/native_fx_engine.js +77 -0
- package/node/README.md +152 -0
- package/node/megasynth.mjs +106 -0
- package/node/megasynth_worker.mjs +129 -0
- package/node/output_audify.mjs +48 -0
- package/package.json +5 -2
- package/runtime-manifest.json +5 -0
- package/sample_clock.js +36 -0
- package/ym2612-worklet.js +18 -3
package/README.md
CHANGED
|
@@ -208,6 +208,37 @@ Worklet uploads complete before the returned promise resolves.
|
|
|
208
208
|
`loadMemory()` remains the API for already-encoded ADPCM-B bytes.
|
|
209
209
|
This does not add arbitrary sample loading to YM2608's fixed ADPCM-A rhythm.
|
|
210
210
|
|
|
211
|
+
## Experimental MegaSynth for Node
|
|
212
|
+
|
|
213
|
+
Version 0.2.5 adds standalone YM2612 FM / DAC rendering through the shared
|
|
214
|
+
nativeFX DSP, sample-clock event recording and event / PCM loopers.
|
|
215
|
+
|
|
216
|
+
```js
|
|
217
|
+
import {createMegaSynthSession} from 'tetorica-fm2612/megasynth_session.js';
|
|
218
|
+
import {FM_PRESETS} from 'tetorica-fm2612/megasynth-fm-presets.js';
|
|
219
|
+
import {encodeWav} from 'tetorica-fm2612';
|
|
220
|
+
|
|
221
|
+
const synth = await createMegaSynthSession({sampleRate: 48000});
|
|
222
|
+
try {
|
|
223
|
+
synth.fm.setPreset(0, FM_PRESETS.sine);
|
|
224
|
+
synth.fx.setChain([synth.fx.delay({time: 0.12, mix: 0.25})]);
|
|
225
|
+
synth.schedule(0, {target: 'fm', method: 'noteOn', args: [0, 4, 553]});
|
|
226
|
+
synth.schedule(12000, {target: 'fm', method: 'noteOff', args: [0]});
|
|
227
|
+
const wav = encodeWav(await synth.render(48000));
|
|
228
|
+
// Save wav using node:fs/promises or another destination.
|
|
229
|
+
} finally {await synth.close();}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
For realtime device output, `import {MegaSynthNode} from 'tetorica-fm2612/node'`.
|
|
233
|
+
Install the optional `audify` peer dependency in your application. The owned
|
|
234
|
+
Worker renders FM, nativeFX and output without transferring normal playback
|
|
235
|
+
PCM to Main. Controls are asynchronous; await FM / recording / looper commands.
|
|
236
|
+
Use `engineOptions: {looperMode: 'pcm'}` for dry FM capture and native PCM playback.
|
|
237
|
+
See [Node API and lifecycle](./node/README.md) for recording, export, audio budget,
|
|
238
|
+
stop / resume / close and output adapters. macOS / Node 22 / CoreAudio is tested;
|
|
239
|
+
other platforms are not yet verified. PSG, Mega CD PCM and microphone input are
|
|
240
|
+
not included in this experimental Node MegaSynth runtime.
|
|
241
|
+
|
|
211
242
|
## Local packaging
|
|
212
243
|
|
|
213
244
|
From the repository root:
|
|
@@ -232,10 +263,10 @@ FM/PSG/PCM mixing, stop/reset and close/restart. Playwright is a development
|
|
|
232
263
|
dependency; it is not required by users of the sound-chip runtime.
|
|
233
264
|
|
|
234
265
|
The build is staged in `dist/fm2612/`; packing produces
|
|
235
|
-
`tetorica-fm2612-0.2.
|
|
266
|
+
`tetorica-fm2612-0.2.5.tgz`. To install a local build in another project:
|
|
236
267
|
|
|
237
268
|
```sh
|
|
238
|
-
npm install /absolute/path/to/tetorica-fm2612-0.2.
|
|
269
|
+
npm install /absolute/path/to/tetorica-fm2612-0.2.5.tgz
|
|
239
270
|
```
|
|
240
271
|
|
|
241
272
|
The existing `tetorica-vgm` CLI package is built separately. This first package
|
|
@@ -251,6 +282,18 @@ and generator. External instrument/sample ROMs are not included.
|
|
|
251
282
|
|
|
252
283
|
## Release notes
|
|
253
284
|
|
|
285
|
+
`0.2.5` adds experimental Node MegaSynth offline / realtime Worker runtimes,
|
|
286
|
+
shared nativeFX DSP, sample-clock event recording and event / PCM loopers.
|
|
287
|
+
The optional audify adapter supports Worker-owned output; explicit PCM export
|
|
288
|
+
supports WAV saving. Browser nativeFX uses the same DSP and retains its existing
|
|
289
|
+
AudioWorklet API. PCM capture excludes previous loop playback and FX tails.
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
`0.2.4` removes the ymfm YM2612 DAC ladder's idle offset from AudioWorklet
|
|
293
|
+
output and keeps output silent until FM/PSG initialization completes. This
|
|
294
|
+
reduces clicks when browser audio starts or disconnects. Raw chip PCM remains
|
|
295
|
+
unchanged.
|
|
296
|
+
|
|
254
297
|
`0.2.3` adds common `encodeWav()` for mono/stereo PCM16 WAV bytes and fixes
|
|
255
298
|
default browser/Worker `createSoundChip()` loading by reading WASM internally.
|
|
256
299
|
Node and browsers use the same chip creation and WAV encoding API; output
|
package/RUNTIME.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Full web runtime
|
|
2
2
|
|
|
3
|
-
Includes all
|
|
3
|
+
Includes all 138 top-level web runtime modules and 23 generated chip/engine pairs.
|
|
4
4
|
|
|
5
5
|
ay8910, gameboy_apu, huc6280, k051649, nuked_opn2, okim6258, rf5c164, segapcm, segapsg, y8950, ym2151, ym2203, ym2413, ym2608, ym2610b, ym2612, ym3438, ym3526, ym3812, ymf262, ymf276, ymf278b, ymf288
|
|
6
6
|
|
package/looper.js
CHANGED
|
@@ -72,6 +72,7 @@ export class MegaSynthLooper {
|
|
|
72
72
|
* scheduleAudioPlayback?: (unit: MegaSynthLooperUnit, startTime: number) => void,
|
|
73
73
|
* stopAudioPlayback?: (unit?: MegaSynthLooperUnit | string | null) => void,
|
|
74
74
|
* onStateChange?: (detail: { reason: string, unit?: MegaSynthLooperUnit | null, auto?: boolean }) => void,
|
|
75
|
+
* audioPaddingSeconds?: number,
|
|
75
76
|
* }} options
|
|
76
77
|
*/
|
|
77
78
|
constructor(options = {}) {
|
|
@@ -80,6 +81,10 @@ export class MegaSynthLooper {
|
|
|
80
81
|
}
|
|
81
82
|
|
|
82
83
|
this.synth = options.synth;
|
|
84
|
+
this.audioPaddingSeconds = options.audioPaddingSeconds ?? 0.01;
|
|
85
|
+
if (!Number.isFinite(this.audioPaddingSeconds) || this.audioPaddingSeconds < 0) {
|
|
86
|
+
throw new RangeError('Invalid audioPaddingSeconds');
|
|
87
|
+
}
|
|
83
88
|
this.now =
|
|
84
89
|
options.now ??
|
|
85
90
|
(() => performance.now() / 1000);
|
|
@@ -777,7 +782,7 @@ export class MegaSynthLooper {
|
|
|
777
782
|
this.scheduleAudioPlayback(
|
|
778
783
|
unit,
|
|
779
784
|
unitStartTime <= now
|
|
780
|
-
? now +
|
|
785
|
+
? now + this.audioPaddingSeconds
|
|
781
786
|
: unitStartTime
|
|
782
787
|
);
|
|
783
788
|
}
|
|
@@ -815,7 +820,7 @@ export class MegaSynthLooper {
|
|
|
815
820
|
) {
|
|
816
821
|
this.scheduleAudioPlayback(
|
|
817
822
|
unit,
|
|
818
|
-
now +
|
|
823
|
+
now + this.audioPaddingSeconds
|
|
819
824
|
);
|
|
820
825
|
return;
|
|
821
826
|
}
|
|
@@ -963,7 +968,7 @@ export class MegaSynthLooper {
|
|
|
963
968
|
return;
|
|
964
969
|
}
|
|
965
970
|
|
|
966
|
-
this.finishRecording({
|
|
971
|
+
return this.finishRecording({
|
|
967
972
|
auto: true,
|
|
968
973
|
});
|
|
969
974
|
}, remainingSeconds * 1000);
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/** Experimental offline MegaSynth engine. Browser / Node; no audio device. */
|
|
2
|
+
import {createSoundChip} from './soundchip.js';
|
|
3
|
+
import {YM2612Synth, YM2612DirectTransport} from './ym2612synth.js';
|
|
4
|
+
import {NativeFXEngine} from './native_fx_engine.js';
|
|
5
|
+
import {createNativeFXController} from './native_fx.js';
|
|
6
|
+
|
|
7
|
+
const FM_METHODS = new Set(['setPreset', 'setOperator', 'setAlgo', 'setPan',
|
|
8
|
+
'setLfo', 'setFrequency', 'noteOn', 'noteOff', 'write', 'reset']);
|
|
9
|
+
|
|
10
|
+
/** Load the same native FX WASM used by the browser Worklet. */
|
|
11
|
+
async function loadFX(options) {
|
|
12
|
+
if (options.fxModule) return options.fxModule;
|
|
13
|
+
let bytes = options.fxWasmBinary;
|
|
14
|
+
if (!bytes) {
|
|
15
|
+
const url = new URL(options.fxWasmUrl ?? './native_audio_effect.wasm', import.meta.url);
|
|
16
|
+
if (url.protocol === 'file:' && typeof process !== 'undefined' && process.versions?.node) {
|
|
17
|
+
const {readFile} = await import('node:fs/promises');
|
|
18
|
+
bytes = await readFile(url, {signal: options.signal});
|
|
19
|
+
} else {
|
|
20
|
+
const response = await fetch(url, {signal: options.signal});
|
|
21
|
+
if (!response.ok) throw new Error(`Native FX WASM: HTTP ${response.status}`);
|
|
22
|
+
bytes = await response.arrayBuffer();
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return WebAssembly.compile(bytes);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Create an experimental YM2612 + nativeFX offline renderer.
|
|
30
|
+
* This is a separate entry point; the existing browser MegaSynth is unchanged.
|
|
31
|
+
* Options: sampleRate (default 48000), masterVolume (default 1), chipOptions,
|
|
32
|
+
* fxModule / fxWasmBinary / fxWasmUrl, signal.
|
|
33
|
+
*/
|
|
34
|
+
export async function createMegaSynthOffline(options = {}) {
|
|
35
|
+
const sampleRate = options.sampleRate ?? 48000;
|
|
36
|
+
const masterVolume = options.masterVolume ?? 1;
|
|
37
|
+
if (!Number.isInteger(sampleRate) || sampleRate < 8000 || sampleRate > 192000) {
|
|
38
|
+
throw new RangeError('sampleRate must be an integer from 8000 to 192000');
|
|
39
|
+
}
|
|
40
|
+
if (!Number.isFinite(masterVolume) || masterVolume < 0 || masterVolume > 3.8) {
|
|
41
|
+
throw new RangeError('masterVolume must be from 0 to 3.8');
|
|
42
|
+
}
|
|
43
|
+
options.signal?.throwIfAborted();
|
|
44
|
+
const module = await loadFX(options);
|
|
45
|
+
options.signal?.throwIfAborted();
|
|
46
|
+
const dsp = new NativeFXEngine(module, sampleRate);
|
|
47
|
+
const chip = await createSoundChip('ym2612', {...options.chipOptions, signal: options.signal});
|
|
48
|
+
try {
|
|
49
|
+
options.signal?.throwIfAborted();
|
|
50
|
+
return new MegaSynthOffline(chip, dsp, sampleRate, masterVolume);
|
|
51
|
+
} catch (error) { chip.dispose(); throw error; }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
class MegaSynthOffline {
|
|
55
|
+
#chip; #dsp; #transport; #frame = 0; #closed = false;
|
|
56
|
+
#events = []; #order = 0; #phase = 0; #lastLeft = 0; #lastRight = 0;
|
|
57
|
+
#idleLeft; #idleRight; #chipRate;
|
|
58
|
+
#sampleRate; #masterVolume;
|
|
59
|
+
|
|
60
|
+
constructor(chip, dsp, sampleRate, masterVolume) {
|
|
61
|
+
this.#chip = chip; this.#dsp = dsp; this.#sampleRate = sampleRate;
|
|
62
|
+
this.#masterVolume = masterVolume; this.#chipRate = chip.sampleRate();
|
|
63
|
+
const idle = chip.generateStereoView(1);
|
|
64
|
+
this.#idleLeft = idle.left[0]; this.#idleRight = idle.right[0]; chip.reset();
|
|
65
|
+
this.#transport = new YM2612DirectTransport(chip);
|
|
66
|
+
// Retained fm/fx handles must reject commands after close().
|
|
67
|
+
const write = this.#transport.write.bind(this.#transport);
|
|
68
|
+
this.#transport.write = (port, register, value) => {
|
|
69
|
+
this.#assertOpen(); return write(port, register, value);
|
|
70
|
+
};
|
|
71
|
+
for (const method of ['reset', 'dacCommand']) {
|
|
72
|
+
if (typeof this.#transport[method] !== 'function') continue;
|
|
73
|
+
const original = this.#transport[method].bind(this.#transport);
|
|
74
|
+
this.#transport[method] = (...args) => {
|
|
75
|
+
this.#assertOpen();
|
|
76
|
+
if (method === 'reset') { this.#phase = 0; this.#lastLeft = 0; this.#lastRight = 0; }
|
|
77
|
+
return original(...args);
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
this.fm = new YM2612Synth({transport: this.#transport});
|
|
81
|
+
this.fx = createNativeFXController(command => {
|
|
82
|
+
this.#assertOpen(); this.#dsp.command(structuredClone(command));
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
get currentFrame() { return this.#frame; }
|
|
87
|
+
get sampleRate() { return this.#sampleRate; }
|
|
88
|
+
get masterVolume() { return this.#masterVolume; }
|
|
89
|
+
get currentTime() { return this.#frame / this.sampleRate; }
|
|
90
|
+
#assertOpen() { if (this.#closed) throw new Error('MegaSynthOffline is closed'); }
|
|
91
|
+
|
|
92
|
+
/** Cancel future notes and FX tails while retaining the configured patches/chain. */
|
|
93
|
+
stop() {
|
|
94
|
+
this.#assertOpen(); this.clearSchedule();
|
|
95
|
+
for (let channel = 0; channel < 6; channel++) this.fm.noteOff(channel);
|
|
96
|
+
this.#transport.dacPlayer?.reset();
|
|
97
|
+
this.#transport.write(0, 0x2b, 0);
|
|
98
|
+
this.#dsp.samples.clear(); this.#dsp.resetNoise(); this.#dsp.command({op: 'clear'});
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
clearSchedule() {this.#assertOpen(); this.#events.length = 0;}
|
|
102
|
+
|
|
103
|
+
/** Apply the shared native FX command protocol without a Web Audio transport. */
|
|
104
|
+
applyFX(command) { this.#assertOpen(); this.#dsp.command(structuredClone(command)); }
|
|
105
|
+
|
|
106
|
+
/** Session-owned PCM banks/voices use the same native mixer as the Worklet. */
|
|
107
|
+
sampleCommand(command) {this.#assertOpen(); return this.#dsp.samples.command(command);}
|
|
108
|
+
|
|
109
|
+
/** Absolute output-frame timestamp; serializable FM commands, stable order. */
|
|
110
|
+
schedule(frame, command) {
|
|
111
|
+
this.#assertOpen();
|
|
112
|
+
if (!Number.isSafeInteger(frame) || frame < this.#frame) throw new RangeError('Cannot schedule before currentFrame');
|
|
113
|
+
if (!command || command.target !== 'fm' || !FM_METHODS.has(command.method) ||
|
|
114
|
+
typeof this.fm[command.method] !== 'function' || !Array.isArray(command.args)) {
|
|
115
|
+
throw new TypeError('Expected {target: "fm", method, args}');
|
|
116
|
+
}
|
|
117
|
+
this.#events.push({frame, command: structuredClone(command), order: this.#order++});
|
|
118
|
+
this.#events.sort((a, b) => a.frame - b.frame || a.order - b.order);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Advance the sample clock, render the chip, then apply native FX. */
|
|
122
|
+
render(frames, {onSource} = {}) {
|
|
123
|
+
this.#assertOpen();
|
|
124
|
+
if (!Number.isSafeInteger(frames) || frames < 0 || frames > 10000000 || !Number.isSafeInteger(this.#frame + frames)) {
|
|
125
|
+
throw new RangeError('frames must be an integer from 0 to 10000000');
|
|
126
|
+
}
|
|
127
|
+
const left = new Float32Array(frames), right = new Float32Array(frames);
|
|
128
|
+
let offset = 0;
|
|
129
|
+
while (true) {
|
|
130
|
+
while (this.#events[0]?.frame === this.#frame) {
|
|
131
|
+
const {command} = this.#events.shift();
|
|
132
|
+
this.fm[command.method](...command.args);
|
|
133
|
+
}
|
|
134
|
+
if (offset === frames) break;
|
|
135
|
+
// Match AudioWorklet's usual render quantum; split at event boundaries.
|
|
136
|
+
const count = Math.min(128, frames - offset, (this.#events[0]?.frame ?? Infinity) - this.#frame);
|
|
137
|
+
const nativeFrames = Math.floor((this.#phase + count * this.#chipRate) / this.sampleRate);
|
|
138
|
+
const pcm = nativeFrames ? this.#transport.generateStereo(nativeFrames) : null;
|
|
139
|
+
const input = [new Float32Array(count), new Float32Array(count)];
|
|
140
|
+
let nativeOffset = 0;
|
|
141
|
+
for (let i = 0; i < count; i++) {
|
|
142
|
+
this.#phase += this.#chipRate;
|
|
143
|
+
const consumed = Math.floor(this.#phase / this.sampleRate);
|
|
144
|
+
this.#phase -= consumed * this.sampleRate;
|
|
145
|
+
if (consumed) {
|
|
146
|
+
let l = 0, r = 0;
|
|
147
|
+
for (let j = 0; j < consumed; j++, nativeOffset++) {
|
|
148
|
+
l += pcm.left[nativeOffset] - this.#idleLeft;
|
|
149
|
+
r += pcm.right[nativeOffset] - this.#idleRight;
|
|
150
|
+
}
|
|
151
|
+
this.#lastLeft = l / consumed; this.#lastRight = r / consumed;
|
|
152
|
+
}
|
|
153
|
+
input[0][i] = this.#lastLeft; input[1][i] = this.#lastRight;
|
|
154
|
+
}
|
|
155
|
+
// Capture FM before sample playback, FX and master volume, avoiding overdub feedback.
|
|
156
|
+
onSource?.(input);
|
|
157
|
+
const output = [left.subarray(offset, offset + count), right.subarray(offset, offset + count)];
|
|
158
|
+
this.#dsp.process(input, output);
|
|
159
|
+
for (const channel of output) for (let i = 0; i < count; i++) channel[i] *= this.masterVolume;
|
|
160
|
+
this.#frame += count; offset += count;
|
|
161
|
+
}
|
|
162
|
+
return {left, right, sampleRate: this.sampleRate};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
close() {
|
|
166
|
+
if (this.#closed) return;
|
|
167
|
+
this.#closed = true; this.#events.length = 0;
|
|
168
|
+
this.#chip.dispose(); this.#chip = null; this.#dsp = null;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/** Worker-owned dry FM capture and native sample playback for a session looper. */
|
|
2
|
+
export class MegaSynthPCMLooper {
|
|
3
|
+
#engine; #clock; #capture = null; #banks = new Map(); #timers = new Map(); #sequence = 0; #limit;
|
|
4
|
+
#lastPlayed = new Map();
|
|
5
|
+
constructor(engine, clock, maxSeconds = 60) {
|
|
6
|
+
if (!Number.isFinite(maxSeconds) || maxSeconds <= 0 || maxSeconds > 600) throw new RangeError('looperMaxAudioSeconds must be from >0 to 600');
|
|
7
|
+
this.#engine = engine; this.#clock = clock; this.#limit = Math.floor(maxSeconds * engine.sampleRate);
|
|
8
|
+
}
|
|
9
|
+
startCapture = () => {
|
|
10
|
+
if (this.#banks.size >= 64) throw new Error('PCM looper bank limit (64) reached');
|
|
11
|
+
this.#capture = {chunks: [], frames: 0};
|
|
12
|
+
};
|
|
13
|
+
assertCanRender(frames) {
|
|
14
|
+
if (!this.#capture) return;
|
|
15
|
+
const retained = [...this.#banks.values()].reduce((sum, pcm) => sum + pcm.channels[0].length, 0);
|
|
16
|
+
if (retained + this.#capture.frames + frames > this.#limit) {
|
|
17
|
+
throw new Error('PCM looper audio limit reached; undo or clear before recording more');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
capture = channels => {
|
|
21
|
+
if (!this.#capture) return;
|
|
22
|
+
this.#capture.chunks.push(channels.map(channel => channel.slice()));
|
|
23
|
+
this.#capture.frames += channels[0].length;
|
|
24
|
+
};
|
|
25
|
+
stopCapture = () => {
|
|
26
|
+
const capture = this.#capture; this.#capture = null;
|
|
27
|
+
if (!capture?.frames) return null;
|
|
28
|
+
const channels = [new Float32Array(capture.frames), new Float32Array(capture.frames)];
|
|
29
|
+
let offset = 0;
|
|
30
|
+
for (const chunk of capture.chunks) {channels.forEach((channel, i) => channel.set(chunk[i], offset)); offset += chunk[0].length;}
|
|
31
|
+
const name = `looper-pcm-${++this.#sequence}`;
|
|
32
|
+
const pcm = {channels, sampleRate: this.#engine.sampleRate};
|
|
33
|
+
this.#engine.sampleCommand({action: 'load', name, pcm}); this.#banks.set(name, pcm);
|
|
34
|
+
return {audio: {name, frames: capture.frames, sampleRate: pcm.sampleRate}, audioDuration: capture.frames / pcm.sampleRate};
|
|
35
|
+
};
|
|
36
|
+
schedulePlayback = (unit, startTime) => {
|
|
37
|
+
const name = unit.audio.name;
|
|
38
|
+
const frame = Math.max(this.#engine.currentFrame, Math.round(startTime * this.#engine.sampleRate));
|
|
39
|
+
const play = () => {
|
|
40
|
+
if (this.#lastPlayed.get(name) === frame) return;
|
|
41
|
+
this.#engine.sampleCommand({action: 'play', name, options: {
|
|
42
|
+
playbackRate: 1, gain: 1, pan: 0, offset: 0, duration: -1, loop: false,
|
|
43
|
+
loopStart: 0, loopEnd: 0, fadeIn: 0, fadeOut: 0,
|
|
44
|
+
}}); this.#lastPlayed.set(name, frame);
|
|
45
|
+
};
|
|
46
|
+
if (frame === this.#engine.currentFrame) {play(); return;}
|
|
47
|
+
if ([...this.#timers.values()].some(timer => timer.name === name && timer.frame === frame)) return;
|
|
48
|
+
const id = this.#clock.atFrame(frame, () => {this.#timers.delete(id); play();});
|
|
49
|
+
this.#timers.set(id, {name, frame});
|
|
50
|
+
};
|
|
51
|
+
stopPlayback = unit => {
|
|
52
|
+
const name = unit?.audio?.name;
|
|
53
|
+
for (const [id, timer] of this.#timers) if (!name || timer.name === name) {this.#clock.clearTimer(id); this.#timers.delete(id);}
|
|
54
|
+
if (name) this.#lastPlayed.delete(name); else this.#lastPlayed.clear();
|
|
55
|
+
this.#engine.sampleCommand({action: 'stop', name});
|
|
56
|
+
};
|
|
57
|
+
prune(units) {
|
|
58
|
+
const retained = new Set(units.map(unit => unit.audio?.name));
|
|
59
|
+
for (const name of this.#banks.keys()) if (!retained.has(name)) {
|
|
60
|
+
this.#engine.sampleCommand({action: 'unload', name}); this.#banks.delete(name);
|
|
61
|
+
this.#lastPlayed.delete(name);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
exportAudio(unit) {
|
|
65
|
+
const pcm = this.#banks.get(unit?.audio?.name);
|
|
66
|
+
if (!pcm) throw new Error('No PCM audio for this looper unit');
|
|
67
|
+
return {sampleRate: pcm.sampleRate, channels: pcm.channels.map(channel => channel.slice())};
|
|
68
|
+
}
|
|
69
|
+
}
|
package/megasynth_recording.js
CHANGED
|
@@ -21,6 +21,8 @@ export class MegaSynthRecordingManager {
|
|
|
21
21
|
this.clearTimer =
|
|
22
22
|
options.clearTimer ??
|
|
23
23
|
((timerId) => window.clearTimeout(timerId));
|
|
24
|
+
this.cyclePaddingSeconds = options.cyclePaddingSeconds ?? 0.01;
|
|
25
|
+
if (!Number.isFinite(this.cyclePaddingSeconds) || this.cyclePaddingSeconds < 0) throw new RangeError('Invalid recording cycle padding');
|
|
24
26
|
|
|
25
27
|
this.recording = false;
|
|
26
28
|
this.playing = false;
|
|
@@ -208,7 +210,7 @@ export class MegaSynthRecordingManager {
|
|
|
208
210
|
0,
|
|
209
211
|
recording.durationSeconds *
|
|
210
212
|
1000
|
|
211
|
-
) +
|
|
213
|
+
) + this.cyclePaddingSeconds * 1000;
|
|
212
214
|
this._schedulePlayback(() => {
|
|
213
215
|
if (this.loopPlayback) {
|
|
214
216
|
this._playCycle(recording, options);
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/** Render-clock event recording / looping for offline and Node Worker engines. */
|
|
2
|
+
import {createMegaSynthOffline} from './megasynth_offline.js';
|
|
3
|
+
import {MegaSynthRecordingManager} from './megasynth_recording.js';
|
|
4
|
+
import {MegaSynthLooper} from './looper.js';
|
|
5
|
+
import {SampleClock} from './sample_clock.js';
|
|
6
|
+
import {YM2612Synth} from './ym2612synth.js';
|
|
7
|
+
import {MegaSynthPCMLooper} from './megasynth_pcm_looper.js';
|
|
8
|
+
|
|
9
|
+
const COMMANDS = {
|
|
10
|
+
reset: () => ({type: 'reset'}),
|
|
11
|
+
setOperator: (channel, operator, params) => ({type: 'setOperator', channel, operator, params}),
|
|
12
|
+
setAlgo: (channel, algorithm, feedback = 0) => ({type: 'setAlgo', channel, algorithm, feedback}),
|
|
13
|
+
setPan: (channel, left, right, ams, pms) => ({type: 'setPan', channel, left, right, ams, pms}),
|
|
14
|
+
setLfo: (enabled, frequency) => ({type: 'setLfo', enabled, frequency}),
|
|
15
|
+
setDacEnabled: enabled => ({type: 'setDacEnabled', enabled}),
|
|
16
|
+
writeDac: value => ({type: 'writeDac', value}),
|
|
17
|
+
setChannel3SpecialMode: enabled => ({type: 'setChannel3SpecialMode', enabled}),
|
|
18
|
+
setChannel3SpecialFrequency: (operator, block, fnum) => ({type: 'setChannel3SpecialFrequency', operator, block, fnum}),
|
|
19
|
+
noteOn: (channel, block, fnum) => ({type: 'noteOn', channel, block, fnum}),
|
|
20
|
+
noteOff: channel => ({type: 'noteOff', channel}),
|
|
21
|
+
};
|
|
22
|
+
const FM_METHODS = new Set([...Object.keys(COMMANDS), 'setPreset', 'setFrequency', 'write']);
|
|
23
|
+
const LOOP_METHODS = new Set(['start', 'stop', 'clear', 'startRecording', 'finishRecording',
|
|
24
|
+
'toggleRecord', 'undo', 'noteOn', 'noteOff', 'getState', 'getUnits', 'exportAudio']);
|
|
25
|
+
const validationFM = () => new YM2612Synth({transport: {write(port, register, value) {}, reset() {}}});
|
|
26
|
+
|
|
27
|
+
export async function createMegaSynthSession(options = {}) {
|
|
28
|
+
if (!['events', 'pcm'].includes(options.looperMode ?? 'events')) throw new Error('Invalid looperMode');
|
|
29
|
+
const engine = await createMegaSynthOffline(options);
|
|
30
|
+
try {return new MegaSynthSession(engine, options);} catch (error) {engine.close(); throw error;}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
class MegaSynthSession {
|
|
34
|
+
#engine; #clock; #suppressed = 0; #closed = false; #rendering = false;
|
|
35
|
+
#userTimers = new Set(); #recording;
|
|
36
|
+
#closing;
|
|
37
|
+
#pcmLooper;
|
|
38
|
+
constructor(engine, options) {
|
|
39
|
+
this.#engine = engine; this.fm = engine.fm; this.fx = engine.fx;
|
|
40
|
+
this.#clock = new SampleClock(engine.sampleRate, () => engine.currentFrame);
|
|
41
|
+
if (options.looperMode === 'pcm') this.#pcmLooper = new MegaSynthPCMLooper(engine, this.#clock, options.looperMaxAudioSeconds);
|
|
42
|
+
const original = Object.fromEntries([...FM_METHODS, 'getState'].map(method => [method, this.fm[method].bind(this.fm)]));
|
|
43
|
+
// Replayed commands and patch restoration must not record themselves.
|
|
44
|
+
const playback = Object.fromEntries(Object.entries(original).map(([method, fn]) => [method, (...args) => {
|
|
45
|
+
this.#suppressed++;
|
|
46
|
+
try {return fn(...args);} finally {this.#suppressed--;}
|
|
47
|
+
}]));
|
|
48
|
+
this.#recording = new MegaSynthRecordingManager({synth: playback, now: () => this.currentTime,
|
|
49
|
+
setTimer: this.#clock.setTimer, clearTimer: this.#clock.clearTimer, cyclePaddingSeconds: 0});
|
|
50
|
+
for (const [method, toCommand] of Object.entries(COMMANDS)) {
|
|
51
|
+
this.fm[method] = (...args) => {
|
|
52
|
+
this.#assertOpen(); const result = original[method](...args);
|
|
53
|
+
if (!this.#suppressed) this.#recording.recordCommand(toCommand(...args));
|
|
54
|
+
return result;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
const applyPatch = (patch, channel, event) => {
|
|
58
|
+
const source = patch.channels[event.channel];
|
|
59
|
+
source.operators.forEach((operator, index) => playback.setOperator(channel, index, operator));
|
|
60
|
+
playback.setAlgo(channel, source.algorithm, source.feedback);
|
|
61
|
+
playback.setPan(channel, source.left, source.right, source.ams, source.pms);
|
|
62
|
+
};
|
|
63
|
+
this.looper = new MegaSynthLooper({synth: this.fm, liveTarget: this.fm, playbackTarget: playback,
|
|
64
|
+
now: () => this.currentTime, setTimer: this.#clock.setTimer, clearTimer: this.#clock.clearTimer,
|
|
65
|
+
getPatch: original.getState, applyPatch, audioPaddingSeconds: 0,
|
|
66
|
+
...(this.#pcmLooper ? {
|
|
67
|
+
startAudioCapture: this.#pcmLooper.startCapture, stopAudioCapture: this.#pcmLooper.stopCapture,
|
|
68
|
+
scheduleAudioPlayback: this.#pcmLooper.schedulePlayback, stopAudioPlayback: this.#pcmLooper.stopPlayback,
|
|
69
|
+
onStateChange: () => this.#pcmLooper.prune(this.looper.getUnits()),
|
|
70
|
+
} : {})});
|
|
71
|
+
this.recording = {
|
|
72
|
+
start: () => {this.#assertOpen(); return this.#recording.start();},
|
|
73
|
+
stop: () => {this.#assertOpen(); return this.#recording.stop();},
|
|
74
|
+
export: () => {this.#assertOpen(); return this.#recording.exportRecording();},
|
|
75
|
+
import: data => {this.#assertOpen(); this.#validateRecording(data); return this.#recording.importRecording(data);},
|
|
76
|
+
play: (data = null, options = {}) => {
|
|
77
|
+
this.#assertOpen(); const selected = data ?? this.#recording.exportRecording();
|
|
78
|
+
if (!selected) throw new Error('No recording to play');
|
|
79
|
+
this.#validateRecording(selected, options);
|
|
80
|
+
if (options.loop && Math.round(selected.durationSeconds * this.sampleRate) < 1) throw new Error('Recording loop must advance at least one frame');
|
|
81
|
+
try {return this.#recording.play(selected, options);}
|
|
82
|
+
catch (error) {this.#recording.stopPlayback(); throw error;}
|
|
83
|
+
},
|
|
84
|
+
stopPlayback: () => {this.#assertOpen(); this.#recording.stopPlayback();},
|
|
85
|
+
getState: () => ({recording: this.#recording.isRecording(), playing: this.#recording.isPlaying()}),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
#assertOpen() {if (this.#closed) throw new Error('MegaSynthSession is closed');}
|
|
89
|
+
#validateRecording(data, options = {}) {
|
|
90
|
+
if (!data || data.format !== 'megasynth-recording-v1' || !Array.isArray(data.commands) ||
|
|
91
|
+
!Number.isFinite(data.durationSeconds) || data.durationSeconds < 0) throw new Error('Invalid recording');
|
|
92
|
+
for (const command of data.commands) {
|
|
93
|
+
if (!command || !Object.hasOwn(COMMANDS, command.type) || !Number.isFinite(command.time) ||
|
|
94
|
+
command.time < 0 || command.time > data.durationSeconds) throw new Error('Invalid recording command/time');
|
|
95
|
+
}
|
|
96
|
+
// Validate the public recording format before mutating the live chip.
|
|
97
|
+
// A no-op transport exercises the same Synth range checks without WASM.
|
|
98
|
+
const fm = validationFM();
|
|
99
|
+
const callbacks = [];
|
|
100
|
+
const validator = new MegaSynthRecordingManager({synth: fm, now: () => 0,
|
|
101
|
+
setTimer: callback => {callbacks.push(callback); return callbacks.length;}, clearTimer() {}});
|
|
102
|
+
validator.play(data, {...options, loop: false});
|
|
103
|
+
for (const callback of callbacks.slice(0, -1)) callback();
|
|
104
|
+
validator.stopPlayback();
|
|
105
|
+
}
|
|
106
|
+
get sampleRate() {return this.#engine.sampleRate;}
|
|
107
|
+
get currentFrame() {return this.#engine.currentFrame;}
|
|
108
|
+
get currentTime() {return this.#engine.currentTime;}
|
|
109
|
+
get pendingTimers() {return this.#clock.pendingCount;}
|
|
110
|
+
applyFX(command) {this.#assertOpen(); this.#engine.applyFX(command);}
|
|
111
|
+
callFM(method, args) {
|
|
112
|
+
this.#assertOpen(); if (!FM_METHODS.has(method) || !Array.isArray(args)) throw new Error('Invalid FM command');
|
|
113
|
+
return this.fm[method](...args);
|
|
114
|
+
}
|
|
115
|
+
async callLooper(method, args = []) {
|
|
116
|
+
this.#assertOpen(); if (!LOOP_METHODS.has(method) || !Array.isArray(args)) throw new Error('Invalid looper command');
|
|
117
|
+
if (method === 'exportAudio') {
|
|
118
|
+
if (!this.#pcmLooper) throw new Error('PCM looper mode is not enabled');
|
|
119
|
+
return this.#pcmLooper.exportAudio(this.looper.getUnits().find(unit => unit.id === args[0]));
|
|
120
|
+
}
|
|
121
|
+
// start() returns its class instance, which is not a transferable RPC result.
|
|
122
|
+
const result = await this.looper[method](...args);
|
|
123
|
+
return method === 'start' ? this.looper.getState() : result;
|
|
124
|
+
}
|
|
125
|
+
schedule(frame, command) {
|
|
126
|
+
this.#assertOpen();
|
|
127
|
+
if (!command || !Array.isArray(command.args) ||
|
|
128
|
+
!(command.target === 'fm' && FM_METHODS.has(command.method)) &&
|
|
129
|
+
!(command.target === 'looper' && LOOP_METHODS.has(command.method))) throw new Error('Invalid scheduled command');
|
|
130
|
+
const copy = structuredClone(command);
|
|
131
|
+
if (copy.target === 'fm' || ['noteOn', 'noteOff'].includes(copy.method)) validationFM()[copy.method](...copy.args);
|
|
132
|
+
const id = this.#clock.atFrame(frame, () => {
|
|
133
|
+
this.#userTimers.delete(id);
|
|
134
|
+
return copy.target === 'fm' ? this.callFM(copy.method, copy.args) : this.callLooper(copy.method, copy.args);
|
|
135
|
+
});
|
|
136
|
+
this.#userTimers.add(id);
|
|
137
|
+
}
|
|
138
|
+
clearSchedule() {this.#assertOpen(); for (const id of this.#userTimers) this.#clock.clearTimer(id); this.#userTimers.clear();}
|
|
139
|
+
async stopEvents() {
|
|
140
|
+
this.#assertOpen(); this.clearSchedule();
|
|
141
|
+
this.#recording.stop(); this.#recording.stopPlayback(); await this.looper.stop(); this.#clock.clear();
|
|
142
|
+
}
|
|
143
|
+
async stop() {await this.stopEvents(); this.#engine.stop();}
|
|
144
|
+
/** Async only to await looper transitions; time still advances exclusively by PCM frames. */
|
|
145
|
+
async render(frames) {
|
|
146
|
+
this.#assertOpen();
|
|
147
|
+
if (this.#rendering) throw new Error('Concurrent session render is not supported');
|
|
148
|
+
if (!Number.isSafeInteger(frames) || frames < 0 || frames > 10000000) throw new RangeError('Invalid render frames');
|
|
149
|
+
this.#rendering = true;
|
|
150
|
+
try {
|
|
151
|
+
const left = new Float32Array(frames), right = new Float32Array(frames);
|
|
152
|
+
let offset = 0;
|
|
153
|
+
while (true) {
|
|
154
|
+
await this.#clock.runDue();
|
|
155
|
+
if (offset === frames) break;
|
|
156
|
+
const count = Math.min(frames - offset, this.#clock.nextFrame - this.currentFrame);
|
|
157
|
+
this.#pcmLooper?.assertCanRender(count);
|
|
158
|
+
const pcm = this.#engine.render(count, {onSource: this.#pcmLooper?.capture}); left.set(pcm.left, offset); right.set(pcm.right, offset); offset += count;
|
|
159
|
+
}
|
|
160
|
+
return {left, right, sampleRate: this.sampleRate};
|
|
161
|
+
} finally {this.#rendering = false;}
|
|
162
|
+
}
|
|
163
|
+
close() {
|
|
164
|
+
if (this.#closing) return this.#closing;
|
|
165
|
+
if (this.#closed) return Promise.resolve();
|
|
166
|
+
this.#closing = (async () => {
|
|
167
|
+
try {await this.stopEvents();} finally {this.#pcmLooper?.prune([]); this.#closed = true; this.#clock.clear(); this.#engine.close();}
|
|
168
|
+
})();
|
|
169
|
+
return this.#closing;
|
|
170
|
+
}
|
|
171
|
+
}
|
package/native-fx-worklet.js
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {NativeFXEngine} from './native_fx_engine.js';
|
|
2
2
|
/** Browser AudioWorklet: one WASM graph for all Playground FX. */
|
|
3
|
-
import {createSampleProcessor} from './native_sample_processor.js';
|
|
4
3
|
import {setChain} from './native_fx_graph.js';
|
|
5
|
-
import {FX_TYPES} from './native_fx.js';
|
|
6
4
|
export class NativeFXProcessor extends AudioWorkletProcessor {
|
|
7
5
|
constructor(options){
|
|
8
|
-
super();this.
|
|
9
|
-
this.api._initialize?.();this.api.graph_reset(sampleRate);this.api.noise_reset(sampleRate);this.noiseTokens=new Map();this.samples=createSampleProcessor(this.api,sampleRate);setChain(this.api,[]);
|
|
10
|
-
this.units=new Map();this.ramps=new Map();this.beatSeconds=.5;this.active=true;
|
|
6
|
+
super();this.engine=new NativeFXEngine(options.processorOptions.module,sampleRate);this.active=true;
|
|
11
7
|
this.port.onmessage=({data})=>{
|
|
12
8
|
if(data.op==='fx-monitor'){
|
|
13
9
|
this.monitor=null;
|
|
@@ -24,6 +20,9 @@ export class NativeFXProcessor extends AudioWorkletProcessor {
|
|
|
24
20
|
else if(data.op==='emergency'){this.liveFX.clear();this.cancelMonitor();this.samples.clear();this.resetNoise();setChain(this.api,[]);this.api.graph_clear();this.ramps.clear();}
|
|
25
21
|
else if(this.active)this.receive(data);
|
|
26
22
|
};
|
|
23
|
+
// Offline rendering can finish before port messages arrive. Seed its graph
|
|
24
|
+
// synchronously when constructing the processor; live controls still use ports.
|
|
25
|
+
for(const command of options.processorOptions.initialCommands??[])this.command(command);
|
|
27
26
|
}
|
|
28
27
|
// One requested window at a time: no unsolicited stream or unbounded queue.
|
|
29
28
|
observeFX=(name,input,output)=>{
|
|
@@ -41,65 +40,24 @@ export class NativeFXProcessor extends AudioWorkletProcessor {
|
|
|
41
40
|
if(this.monitor)this.port.postMessage({op:'fx-monitor',id:this.monitor.id,names:[...this.liveFX.effects.keys()]});
|
|
42
41
|
this.monitor=null;
|
|
43
42
|
}
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
get api(){return this.engine.api;}
|
|
44
|
+
get liveFX(){return this.engine.liveFX;}
|
|
45
|
+
get samples(){return this.engine.samples;}
|
|
46
|
+
get ramps(){return this.engine.ramps;}
|
|
47
|
+
get beatSeconds(){return this.engine.beatSeconds;}
|
|
48
|
+
resetNoise(){this.engine.resetNoise();}
|
|
49
|
+
reset(){this.cancelMonitor();this.engine.reset();}
|
|
50
|
+
|
|
46
51
|
receive(data){try{if(data.op==='sample'){const value=this.samples.command(data);if(data.id)(this.controlPort??this.port).postMessage({op:'sample-response',id:data.id,value});return;}this.command(data);}catch(e){if(data.op==='sample'&&data.id)(this.controlPort??this.port).postMessage({op:'sample-response',id:data.id,error:e.message});else this.port.postMessage({error:e.message});}}
|
|
47
52
|
command(d){
|
|
48
|
-
|
|
49
|
-
if(d.op==='
|
|
50
|
-
const a=this.api,s=d.slot;
|
|
51
|
-
if(d.action==='create'){if(!a.noise_create(s,d.type,d.seed))throw new Error('Invalid noise voice');this.noiseTokens.set(s,d.token);return;}
|
|
52
|
-
if(this.noiseTokens.get(s)!==d.token)return;
|
|
53
|
-
if(d.action==='parameter'){if(!a.noise_set(s,d.param,d.value,Math.round(d.seconds*sampleRate)))throw new Error('Invalid noise parameter');}
|
|
54
|
-
else if(d.action==='filter')a.noise_filter(s,d.mode);
|
|
55
|
-
else {const action={start:0,stop:1,dispose:2}[d.action];if(action!==undefined)a.noise_action(s,action);if(d.action==='dispose')this.noiseTokens.delete(s);}
|
|
56
|
-
return;
|
|
57
|
-
}
|
|
58
|
-
if(d.beatSeconds>0)this.beatSeconds=d.beatSeconds;
|
|
59
|
-
if(d.op==='reset'){this.reset();return;}
|
|
60
|
-
if(d.op==='clear'){this.api.graph_clear();return;}
|
|
61
|
-
if(d.op==='tempo'){for(const u of this.units.values())this.apply(u);return;}
|
|
62
|
-
if(d.op==='chain'){
|
|
63
|
-
setChain(this.api,d.children);
|
|
64
|
-
for(const u of d.units){const id=u.type+u.slot;if(!this.units.has(id))this.units.set(id,u);this.apply(this.units.get(id));}return;
|
|
65
|
-
}
|
|
66
|
-
if(d.op==='create'){
|
|
67
|
-
const {type,slot}=d.unit; const id=type+slot;
|
|
68
|
-
for(const key of this.ramps.keys())if(key.startsWith(id+':'))this.ramps.delete(key);
|
|
69
|
-
if(FX_TYPES[type]>=7)this.api.extra_reset_slot(FX_TYPES[type],slot);
|
|
70
|
-
else if(type!=='gain'){this.api[type+'_select'](slot);this.api[type+'_reset'](sampleRate);}
|
|
71
|
-
this.units.set(d.unit.type+d.unit.slot,d.unit);this.apply(d.unit);return;}
|
|
72
|
-
if(d.op==='parameter'){
|
|
73
|
-
const id=d.unit.type+d.unit.slot;const u=this.units.get(id);if(!u)return;
|
|
74
|
-
const key=id+':'+d.key;this.ramps.delete(key);
|
|
75
|
-
if(d.seconds>0)this.ramps.set(key,{u,key:d.key,start:u.values[d.key],end:d.value,elapsed:0,total:Math.max(1,Math.round(d.seconds*sampleRate))});
|
|
76
|
-
else{u.values[d.key]=d.value;if(u.type==='reverb'&&d.key==='tone')u.values.damping=1-(d.value-200)/19800;this.apply(u);}return;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
apply({type,slot,values:v}){
|
|
80
|
-
const a=this.api;const clamp=(x,l,h)=>Math.max(l,Math.min(h,x));
|
|
81
|
-
const hz=(beats,max)=>clamp(1/(beats*this.beatSeconds),.05,max);
|
|
82
|
-
if(type==='gain'){a.gain_select(slot);a.gain_set(v.gain,Math.round(sampleRate*.005));return;}
|
|
83
|
-
if(type==='eq'){a.eq_select(slot);[v.bass,v.mid,v.treble].forEach((db,i)=>a.eq_set(i,db));return;}
|
|
84
|
-
if(type==='gate'){a.gate_select(slot);a.gate_set(20*Math.log10(v.threshold),v.hysteresis,v.attack*1000,v.hold*1000,v.release*1000,0);return;}
|
|
85
|
-
if(type==='compressor'){a.compressor_select(slot);a.compressor_set(v.threshold,v.ratio,v.attack*1000,v.release*1000,v.makeup,0);return;}
|
|
86
|
-
if(type==='reverb'){a.reverb_select(slot);a.reverb_set(v.mix,v.room,v.damping);return;}
|
|
87
|
-
const params={filter:[v.cutoff,v.q,v.mode],delay:[v.time*1000,v.feedback],distortion:[v.drive],bitcrusher:[v.bitDepth,clamp(sampleRate/v.holdFrames,100,sampleRate)],wobble:[v.cutoff,clamp(Math.log2(1+v.depth/v.cutoff),0,4),hz(v.rate,20),v.resonance],flanger:[v.time*1000,v.depth*1000,hz(v.rate,10),v.feedback],slicer:[hz(v.phase,30),v.duty,v.floor],chorus:[v.time*1000,v.depth*1000,hz(v.rate,10)]}[type];
|
|
88
|
-
params.forEach((x,i)=>{if(!a.extra_set(FX_TYPES[type],slot,i,x))throw new Error(`Invalid native ${type} parameter ${i}`);});
|
|
89
|
-
a.extra_set(FX_TYPES[type],slot,6,v.mix??1);a.extra_set(FX_TYPES[type],slot,7,0);
|
|
53
|
+
this.engine.command(d);
|
|
54
|
+
if(d.op==='reset'||(this.monitor&&!this.liveFX.effects.has(this.monitor.name)))this.cancelMonitor();
|
|
90
55
|
}
|
|
91
56
|
process(inputs,outputs){
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
if(r.u.type==='reverb'&&r.key==='tone')r.u.values.damping=1-(r.u.values.tone-200)/19800;
|
|
95
|
-
this.apply(r.u);if(r.elapsed===r.total)this.ramps.delete(key);
|
|
96
|
-
}
|
|
97
|
-
const cap=a.gain_capacity();if(!this.input||this.input.buffer!==a.memory.buffer){this.input=new Float32Array(a.memory.buffer,a.gain_input(),cap*2);this.output=new Float32Array(a.memory.buffer,a.gain_output(),cap*2);}
|
|
98
|
-
const source=inputs[0]??[];
|
|
99
|
-
for(let c=0;c<2;c++){const ch=source[c]??source[0];if(ch)this.input.set(ch,c*cap);else this.input.fill(0,c*cap,c*cap+n);}
|
|
100
|
-
a.noise_mix(n);a.sample_mix(n);a.graph_process(n);for(let c=0;c<target.length;c++)target[c].set(this.output.subarray(c*cap,c*cap+n));
|
|
101
|
-
this.liveFX.process(target,error=>this.port.postMessage({error}),this.monitor?this.observeFX:undefined);
|
|
57
|
+
const target=outputs[0];if(!target?.length)return true;
|
|
58
|
+
this.engine.process(inputs[0]??[],target,error=>this.port.postMessage({error}),this.monitor?this.observeFX:undefined);
|
|
102
59
|
return true;
|
|
103
60
|
}
|
|
61
|
+
|
|
104
62
|
}
|
|
105
63
|
registerProcessor('tetorica-native-fx',NativeFXProcessor);
|