tetorica-fm2612 0.2.4 → 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 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.4.tgz`. To install a local build in another project:
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.4.tgz
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,13 @@ 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
+
254
292
  `0.2.4` removes the ymfm YM2612 DAC ladder's idle offset from AudioWorklet
255
293
  output and keeps output silent until FM/PSG initialization completes. This
256
294
  reduces clicks when browser audio starts or disconnects. Raw chip PCM remains
package/RUNTIME.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Full web runtime
2
2
 
3
- Includes all 133 top-level web runtime modules and 23 generated chip/engine pairs.
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 + 0.01
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 + 0.01
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
+ }
@@ -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
- ) + 10;
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
+ }
@@ -1,13 +1,9 @@
1
- import {LiveFX} from './custom_fx.js';
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.liveFX=new LiveFX(sampleRate);this.api=new WebAssembly.Instance(options.processorOptions.module,{env:{emscripten_notify_memory_growth(){}}}).exports;
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
- resetNoise(){this.api.noise_reset(sampleRate);this.noiseTokens.clear();}
45
- reset(){this.liveFX.clear();this.cancelMonitor();this.ramps.clear();this.units.clear();this.api.graph_reset(sampleRate);setChain(this.api,[]);}
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
- if(d.op==='live-fx'){this.liveFX.command(d);if(this.monitor&&!this.liveFX.effects.has(this.monitor.name))this.cancelMonitor();return;}
49
- if(d.op==='noise'){
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 a=this.api,target=outputs[0];if(!target?.length)return true;const n=target[0].length;
93
- for(const [key,r] of this.ramps){r.elapsed=Math.min(r.total,r.elapsed+n);r.u.values[r.key]=r.start+(r.end-r.start)*r.elapsed/r.total;
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);
@@ -0,0 +1,77 @@
1
+ /** Shared native DSP: no AudioContext, AudioWorklet or DOM dependency. */
2
+ import {LiveFX} from './custom_fx.js';
3
+ import {createSampleProcessor} from './native_sample_processor.js';
4
+ import {setChain} from './native_fx_graph.js';
5
+ import {FX_TYPES} from './native_fx.js';
6
+
7
+ export class NativeFXEngine {
8
+ constructor(module, sampleRate) {
9
+ if(!Number.isInteger(sampleRate)||sampleRate<=0)throw new RangeError('Invalid native FX sample rate');
10
+ this.sampleRate=sampleRate;
11
+ this.liveFX=new LiveFX(sampleRate);
12
+ this.api=new WebAssembly.Instance(module,{env:{emscripten_notify_memory_growth(){}}}).exports;
13
+ this.api._initialize?.();this.api.graph_reset(sampleRate);this.api.noise_reset(sampleRate);
14
+ this.noiseTokens=new Map();this.samples=createSampleProcessor(this.api,sampleRate);
15
+ this.units=new Map();this.ramps=new Map();this.beatSeconds=.5;setChain(this.api,[]);
16
+ }
17
+ resetNoise(){this.api.noise_reset(this.sampleRate);this.noiseTokens.clear();}
18
+ reset(){this.liveFX.clear();this.ramps.clear();this.units.clear();this.api.graph_reset(this.sampleRate);setChain(this.api,[]);}
19
+ command(d){
20
+ if(d.op==='live-fx'){this.liveFX.command(d);return;}
21
+ if(d.op==='noise'){
22
+ const a=this.api,s=d.slot;
23
+ 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;}
24
+ if(this.noiseTokens.get(s)!==d.token)return;
25
+ if(d.action==='parameter'){if(!a.noise_set(s,d.param,d.value,Math.round(d.seconds*this.sampleRate)))throw new Error('Invalid noise parameter');}
26
+ else if(d.action==='filter')a.noise_filter(s,d.mode);
27
+ 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);}
28
+ return;
29
+ }
30
+ if(d.beatSeconds>0)this.beatSeconds=d.beatSeconds;
31
+ if(d.op==='reset'){this.reset();return;}
32
+ if(d.op==='clear'){this.api.graph_clear();return;}
33
+ if(d.op==='tempo'){for(const u of this.units.values())this.apply(u);return;}
34
+ if(d.op==='chain'){
35
+ setChain(this.api,d.children);
36
+ 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;
37
+ }
38
+ if(d.op==='create'){
39
+ const {type,slot}=d.unit; const id=type+slot;
40
+ for(const key of this.ramps.keys())if(key.startsWith(id+':'))this.ramps.delete(key);
41
+ if(FX_TYPES[type]>=7)this.api.extra_reset_slot(FX_TYPES[type],slot);
42
+ else if(type!=='gain'){this.api[type+'_select'](slot);this.api[type+'_reset'](this.sampleRate);}
43
+ this.units.set(d.unit.type+d.unit.slot,d.unit);this.apply(d.unit);return;}
44
+ if(d.op==='parameter'){
45
+ const id=d.unit.type+d.unit.slot;const u=this.units.get(id);if(!u)return;
46
+ const key=id+':'+d.key;this.ramps.delete(key);
47
+ 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*this.sampleRate))});
48
+ 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;
49
+ }
50
+ }
51
+ apply({type,slot,values:v}){
52
+ const a=this.api;const clamp=(x,l,h)=>Math.max(l,Math.min(h,x));
53
+ const hz=(beats,max)=>clamp(1/(beats*this.beatSeconds),.05,max);
54
+ if(type==='gain'){a.gain_select(slot);a.gain_set(v.gain,Math.round(this.sampleRate*.005));return;}
55
+ if(type==='eq'){a.eq_select(slot);[v.bass,v.mid,v.treble].forEach((db,i)=>a.eq_set(i,db));return;}
56
+ 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;}
57
+ if(type==='compressor'){a.compressor_select(slot);a.compressor_set(v.threshold,v.ratio,v.attack*1000,v.release*1000,v.makeup,0);return;}
58
+ if(type==='reverb'){a.reverb_select(slot);a.reverb_set(v.mix,v.room,v.damping);return;}
59
+ const params={filter:[v.cutoff,v.q,v.mode],delay:[v.time*1000,v.feedback],distortion:[v.drive],bitcrusher:[v.bitDepth,clamp(this.sampleRate/v.holdFrames,100,this.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];
60
+ params.forEach((x,i)=>{if(!a.extra_set(FX_TYPES[type],slot,i,x))throw new Error(`Invalid native ${type} parameter ${i}`);});
61
+ a.extra_set(FX_TYPES[type],slot,6,v.mix??1);a.extra_set(FX_TYPES[type],slot,7,0);
62
+ }
63
+ process(source,target,onError=error=>{throw new Error(error);},observe) {
64
+ const a=this.api,n=target[0]?.length;
65
+ if(!Number.isInteger(n)||n>a.gain_capacity()||target.length!==2||target[1].length!==n)throw new RangeError('Invalid native FX stereo block');
66
+ if(source.some(channel=>channel.length!==n))throw new RangeError('Native FX input/output lengths differ');
67
+ for(const [key,r] of this.ramps){r.elapsed=Math.min(r.total,r.elapsed+n);r.u.values[r.key]=r.start+(r.end-r.start)*r.elapsed/r.total;
68
+ if(r.u.type==='reverb'&&r.key==='tone')r.u.values.damping=1-(r.u.values.tone-200)/19800;
69
+ this.apply(r.u);if(r.elapsed===r.total)this.ramps.delete(key);
70
+ }
71
+ 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);}
72
+
73
+ 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);}
74
+ 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));
75
+ this.liveFX.process(target,onError,observe);
76
+ }
77
+ }
package/node/README.md ADDED
@@ -0,0 +1,152 @@
1
+ # MegaSynth Node realtime(実験用)
2
+
3
+ `MegaSynthNode` は Worker 内で YM2612、nativeFX、音声出力アダプターを動かす。
4
+ Main へ送るのは操作命令・応答・状態だけで、通常再生の PCM は Main を通らない。
5
+ この実験入口は npm `tetorica-fm2612@0.2.5` から提供する。
6
+
7
+ ## 実行
8
+
9
+ アプリ側で `npm install audify` を実行する。ブラウザとオフライン利用では不要。
10
+ 初期アダプターは audify 1.10.1 の RtAudio。macOS の CoreAudio を Worker から開いて検証した。
11
+ Windows / Linux と他の音声デバイスは未検証。
12
+
13
+ ```js
14
+ import {MegaSynthNode} from 'tetorica-fm2612/node';
15
+ import {FM_PRESETS} from 'tetorica-fm2612/megasynth-fm-presets.js';
16
+
17
+ const synth = new MegaSynthNode({sampleRate: 48000, masterVolume: 0.15});
18
+ synth.on('error', error => console.error(error));
19
+ try {
20
+ await synth.start();
21
+ const fx = synth.fx;
22
+ fx.setChain([fx.delay({time: 0.12, mix: 0.25}), fx.reverb({mix: 0.15})]);
23
+ await synth.fm.setPreset(0, FM_PRESETS.sine);
24
+ await synth.flush();
25
+ await synth.fm.noteOn(0, 4, 553);
26
+ await new Promise(resolve => setTimeout(resolve, 300));
27
+ await synth.fm.noteOff(0);
28
+ await synth.stop();
29
+ } finally { await synth.close(); }
30
+ ```
31
+
32
+ `tetorica-fm2612/node` から import できる。
33
+ 実行例は `node scripts/demo_megasynth_node.mjs`。
34
+ 検証用に別の場所へ audify をインストールした場合は、実行例の第1引数に `audify/index.js` の file URL を渡せる。
35
+
36
+ ## 操作と時計
37
+
38
+ - `start()`:Worker とデバイスを初期化し、無音から短いフェードで開始する。
39
+ - `fm`:非同期の命令 API。各メソッドの Promise を await する。
40
+ - `fx`:既存の nativeFX controller。命令は FIFO で送る。`flush()` を await して Worker での設定完了・エラーを確認する。
41
+ - `schedule(frame, command)`:絶対出力フレーム位置へ FM 命令を登録する。
42
+ - `getState()`:生成済み・消費済み・キュー内のフレーム数などを取得する。
43
+ - `stop()`:既存キューの後ろへ20msのフェードを追加し、排出後にデバイスを停止する。未来の命令と FX tail を消し、音色・FX chain を保つ。
44
+ - `resume()`:同じ Worker・設定で再開する。
45
+ - `close()`:初期化待ちと未完了 RPC をキャンセルし、デバイスを閉じて Worker を終了する。再度 `start()` できる。
46
+
47
+ `currentFrame` は生成側のサンプル時計。スピーカーがその時点まで再生したという意味ではない。
48
+ デバイスの消費通知でキューを補充し、通常は `queueBlocks * bufferFrames` まで先行生成する。
49
+ 既定値は4ブロック × 512フレーム(48kHzで約42.7ms)。デバイス内部の遅延は別にある。
50
+ 停止フェードの間だけ、キュー上限に20ms分を追加する。
51
+ Main の JavaScript が忙しくても Worker の生成・出力は続くが、Worker 自体の長い処理での音切れを防ぐ保証ではない。
52
+
53
+ 非同期の重大エラーは `error` listener と `lastError` で確認できる。音声処理が失敗した場合は自動で終了する。
54
+ 終了後の FX handle は再利用せず、新しい `start()` 後の `synth.fx` から作り直す。
55
+
56
+ ## 出力アダプター
57
+
58
+ 初期化オプションの `outputModule`(Node ESM の URL)と `outputOptions` で差し替えられる。
59
+ モジュールは `createOutput({sampleRate, bufferFrames, onDrain, onError, ...outputOptions})` を export する。
60
+ 返すオブジェクトは `frames`、`queuedFrames`、`write(pcm)`、`start()`、`stop()`、`close()`、`getState()` を持つ。
61
+ PCM は stereo Float32。デバイスから1ブロック消費されるごとに `queuedFrames` を更新して `onDrain()` を呼ぶ。
62
+ 初期化と操作は Worker 内で実行される。オプションは structured clone 可能な値だけを指定する。
63
+
64
+ 検証した `@kmamal/sdl@0.11.13` は Main Thread 専用だったため、このアダプターには採用していない。
65
+ audify の callback 参照が stream 終了後も残るケースに備え、音声 stream の解放後に所有 Worker を明示的に terminate する。
66
+ 依存 library の読み込み・デバイスを開く処理は `start()` まで行わない。
67
+
68
+ ## イベント録音と looper
69
+
70
+ 音声と同じ Worker 内に recording / looper を置き、生成フレーム数を時計として使う。
71
+ Main のタイマーや AudioContext は使わない。API は非同期で、Promise を await する。
72
+
73
+ ```js
74
+ await synth.recording.start();
75
+ await synth.fm.noteOn(0, 4, 553);
76
+ await new Promise(resolve => setTimeout(resolve, 150));
77
+ await synth.fm.noteOff(0);
78
+ const recording = await synth.recording.stop();
79
+ await synth.recording.import(JSON.parse(JSON.stringify(recording)));
80
+ await synth.recording.play(null, {loop: true});
81
+ // …
82
+ await synth.recording.stopPlayback();
83
+
84
+ await synth.looper.start();
85
+ await synth.looper.startRecording();
86
+ await synth.looper.noteOn(0, 4, 696);
87
+ await new Promise(resolve => setTimeout(resolve, 150));
88
+ await synth.looper.noteOff(0);
89
+ await synth.looper.finishRecording();
90
+ // ここから録音した1周分の noteOn / noteOff を繰り返す。
91
+ await synth.looper.undo();
92
+ await synth.looper.stop();
93
+ ```
94
+
95
+ 上の `setTimeout` は実演のキーを離す時刻を決めるだけで、再生エンジンの時計ではない。
96
+ 正確な入力時刻が必要なら `schedule(frame, {target: 'fm' または 'looper', method, args})` を使う。
97
+ 録音のタイムスタンプは Worker に届いて適用したフレーム位置であり、Main が命令を送った実時間ではない。
98
+
99
+ - `recording`:`start`、`stop`、`export`、`import`、`play`、`stopPlayback`、`getState`。
100
+ - `looper`:`start`、`stop`、`clear`、`startRecording`、`finishRecording`、`toggleRecord`、`undo`、`noteOn`、`noteOff`、`getState`、`getUnits`。
101
+ - JSON はブラウザと同じ `megasynth-recording-v1`。FM の音色・モード・発音イベントを扱い、FX 操作・PCM 波形は保存しない。
102
+ - JSON にはチップ内部の発振・エンベロープ位相を含まないため、イベント再演と PCM の完全保存は異なる。
103
+ - looper は既定で音符イベントと音色を保存する。PCM モードは下記のオプションで選ぶ。
104
+ - 再演したイベントを再び録音することを避け、演奏入力と再生側を分けている。
105
+ - Node の録音ループは、ブラウザ実時間タイマー用の10ms余白を使わず、録音長のフレーム数で繰り返す。
106
+ - `stop()` / `close()` は録音・ループを停止し、予定したイベントを消す。`resume()` で古いループを勝手に再開しない。保持した looper unit は明示的に `looper.start()` すると再利用できる。
107
+
108
+ `close()` は Worker 自体を破棄するため、録音 JSON や unit が必要なら終了前に取得・保存する。
109
+
110
+ 実行例: `node scripts/demo_megasynth_node_events.mjs`。
111
+ 録音 JSON を `/private/tmp/megasynth-events.json` に保存し、録音再生・looper・undo を短く実演する。
112
+
113
+ オフラインで同じイベント処理を検証する入口は `web/megasynth_session.js` の `createMegaSynthSession()`。
114
+ `await session.render(frames)` でのみ時計が進み、壁時計を待たずに録音・ループを生成できる。
115
+ ループ中の音符イベントを sample frame の境界で適用し、録音データの読み込みは live chip を変更する前に検証する。
116
+
117
+ ## PCM looper
118
+
119
+ ```js
120
+ const synth = new MegaSynthNode({engineOptions: {
121
+ looperMode: 'pcm', looperMaxAudioSeconds: 60,
122
+ }});
123
+ // start()、音色設定、looper の演奏・録音操作は上の例と同じ。
124
+ const unit = await synth.looper.finishRecording();
125
+ const pcm = await synth.looper.exportAudio(unit.id);
126
+ // pcm = {sampleRate, channels: [Float32Array, Float32Array]}
127
+ ```
128
+
129
+ FM を nativeFX・masterVolume・録音済み PCM のミックス前に取り込む。
130
+ 重ね録りで以前のループを取り込まず、native の sample mixer で再生してから現在の FX と masterVolume を適用する。
131
+ 録音対象は FM 全チャンネルで、FM 経路の DAC も含む。マイク入力や FX の残響を含む最終出力の録音ではない。
132
+ 現在の FM に同時にイベント録音を再演していれば、その FM 出力も録音対象になる。
133
+ ノートイベントのない録音は従来どおり破棄する。
134
+
135
+ `finishRecording()` と `getUnits()` の `audio` は `{name, frames, sampleRate}` の情報だけ。
136
+ PCM は Worker 内に保持し、`exportAudio(unit.id)` で明示的に取得したときだけ Main へコピーする。
137
+ 書き出す波形は FX と masterVolume の適用前である。
138
+ `undo()` / `clear()` は不要な PCM bank を解放し、`stop()` は再生 voice と予定した再生を止める。
139
+ `close()` 前に保存が必要な PCM を export する。
140
+
141
+ メモリーを制限するため、録音中の音声と保持済み unit の合計に `looperMaxAudioSeconds`(既定60秒、最大600秒)を適用する。
142
+ 上限に達すると render はエラーを返す。リアルタイム Worker は音声処理エラーとして終了するため、長い録音には事前に十分な上限を指定する。
143
+ オフライン session では `undo()` / `clear()` で解放して続行できる。
144
+ PCM bank は最大64個。PCM モードでもサンプル時計を使い、ブラウザ用の10ms余白を加えない。
145
+
146
+ 実行例: `node scripts/demo_megasynth_node_pcm_looper.mjs`。
147
+ CoreAudio で短い PCM ループを再生し、`/private/tmp/megasynth-pcm-loop.wav` に dry PCM を保存する。
148
+
149
+ ## 未対応
150
+
151
+ PSG / Mega CD PCM、マイク入力、他の AudioNode への接続は未対応。
152
+ 既存のブラウザ MegaSynth を置き換える API ではなく、Node 用の実験入口として検証を進める。
@@ -0,0 +1,106 @@
1
+ /** Experimental Node controller. PCM stays in the owned Worker. */
2
+ import {Worker} from 'node:worker_threads';
3
+ import {EventEmitter} from 'node:events';
4
+ import {createNativeFXController} from '../native_fx.js';
5
+
6
+ const methods = ['setPreset', 'setOperator', 'setAlgo', 'setPan', 'setLfo',
7
+ 'setFrequency', 'noteOn', 'noteOff', 'write', 'reset', 'setDacEnabled', 'writeDac',
8
+ 'setChannel3SpecialMode', 'setChannel3SpecialFrequency'];
9
+ const aborted = () => new DOMException('MegaSynthNode was closed', 'AbortError');
10
+
11
+ export class MegaSynthNode extends EventEmitter {
12
+ #options; #worker; #pending = new Map(); #id = 0; #generation = 0;
13
+ #starting; #ready; #closing; #closed; #failure;
14
+ state = 'idle'; fx;
15
+ constructor(options = {}) {
16
+ super();
17
+ if (!Number.isInteger(options.queueBlocks ?? 4) || (options.queueBlocks ?? 4) < 2 || (options.queueBlocks ?? 4) > 16) throw new RangeError('queueBlocks must be from 2 to 16');
18
+ if (!Number.isInteger(options.bufferFrames ?? 512) || (options.bufferFrames ?? 512) < 128 || (options.bufferFrames ?? 512) > 8192) throw new RangeError('bufferFrames must be from 128 to 8192');
19
+ this.#options = structuredClone(options);
20
+ this.fm = Object.fromEntries(methods.map(method => [method, (...args) => this.#request('fm', [method, args])]));
21
+ this.recording = Object.fromEntries(['start', 'stop', 'export', 'import', 'play', 'stopPlayback', 'getState']
22
+ .map(method => [method, (...args) => this.#request('recording', [method, args])]));
23
+ this.looper = Object.fromEntries(['start', 'stop', 'clear', 'startRecording', 'finishRecording',
24
+ 'toggleRecord', 'undo', 'noteOn', 'noteOff', 'getState', 'getUnits', 'exportAudio']
25
+ .map(method => [method, (...args) => this.#request('looper', [method, args])]));
26
+ }
27
+ start() {
28
+ if (this.#closing) return this.#closing.then(() => this.start());
29
+ if (this.#starting) return this.#starting;
30
+ if (this.state === 'playing' || this.state === 'stopped') return Promise.resolve(this);
31
+ this.state = 'starting'; this.#failure = null;
32
+ const generation = ++this.#generation;
33
+ let worker;
34
+ try {worker = this.#worker = new Worker(new URL('./megasynth_worker.mjs', import.meta.url), {workerData: this.#options});}
35
+ catch (error) {this.state = 'error'; return Promise.reject(error);}
36
+ this.#starting = new Promise((resolve, reject) => {this.#ready = {resolve: () => resolve(this), reject};});
37
+ this.#starting.catch(() => {});
38
+ this.fx = createNativeFXController(command => {
39
+ if (generation !== this.#generation) throw new Error('FX handle belongs to an earlier Worker');
40
+ void this.#request('fx', [command]);
41
+ });
42
+ worker.on('message', message => {
43
+ if (worker !== this.#worker) return;
44
+ if (message.type === 'ready') {this.state = 'playing'; this.#ready?.resolve(); this.#ready = null;}
45
+ else if (message.type === 'reply') {
46
+ const pending = this.#pending.get(message.id); if (!pending) return;
47
+ this.#pending.delete(message.id);
48
+ if (message.error) {const error = new Error(message.error); this.#failure = error; pending.reject(error);}
49
+ else pending.resolve(message.result);
50
+ } else if (message.type === 'fatal') {this.#fail(new Error(message.error)); void this.close();}
51
+ else if (message.type === 'closed') {this.#closed?.();}
52
+ });
53
+ worker.on('error', error => {this.#fail(error); void this.close();});
54
+ worker.on('exit', code => {
55
+ if (worker !== this.#worker) return;
56
+ if (!this.#closing) this.#fail(new Error(`MegaSynth Worker exited unexpectedly (${code})`));
57
+ this.#closed?.();
58
+ });
59
+ return this.#starting;
60
+ }
61
+ #fail(error) {
62
+ this.state = 'error'; this.#failure = error;
63
+ this.#ready?.reject(error); this.#ready = null;
64
+ for (const pending of this.#pending.values()) pending.reject(error);
65
+ this.#pending.clear();
66
+ if (this.listenerCount('error')) this.emit('error', error);
67
+ }
68
+ get lastError() {return this.#failure;}
69
+ #request(op, args = []) {
70
+ if (!['playing', 'stopped'].includes(this.state) || !this.#worker) {
71
+ const promise = Promise.reject(new Error('MegaSynthNode is not ready')); promise.catch(() => {}); return promise;
72
+ }
73
+ const id = ++this.#id;
74
+ const promise = new Promise((resolve, reject) => {
75
+ this.#pending.set(id, {resolve, reject});
76
+ try {this.#worker.postMessage({id, op, args});}
77
+ catch (error) {this.#pending.delete(id); reject(error);}
78
+ });
79
+ promise.catch(error => {this.#failure = error;});
80
+ return promise;
81
+ }
82
+ async flush() {await this.#request('flush'); if (this.#failure) {const error = this.#failure; this.#failure = null; throw error;}}
83
+ schedule(frame, command) {return this.#request('schedule', [frame, command]);}
84
+ getState() {return this.#request('status');}
85
+ async stop() {await this.#request('stop'); this.state = 'stopped';}
86
+ async resume() {await this.#request('resume'); this.state = 'playing';}
87
+ close() {
88
+ if (this.#closing) return this.#closing;
89
+ if (!this.#worker) {this.state = 'closed'; return Promise.resolve();}
90
+ const worker = this.#worker; this.state = 'closing';
91
+ this.#ready?.reject(aborted()); this.#ready = null;
92
+ for (const pending of this.#pending.values()) pending.reject(aborted());
93
+ this.#pending.clear();
94
+ this.#closing = (async () => {
95
+ await new Promise(resolve => {
96
+ const timer = setTimeout(resolve, 5000);
97
+ this.#closed = () => {clearTimeout(timer); resolve();};
98
+ worker.postMessage({type: 'shutdown'});
99
+ });
100
+ await worker.terminate();
101
+ if (this.#worker === worker) this.#worker = null;
102
+ this.#starting = null; this.#closing = null; this.#closed = null; this.state = 'closed';
103
+ })();
104
+ return this.#closing;
105
+ }
106
+ }
@@ -0,0 +1,129 @@
1
+ import {parentPort, workerData} from 'node:worker_threads';
2
+ import {createMegaSynthSession} from '../megasynth_session.js';
3
+
4
+ const options = workerData;
5
+ const abort = new AbortController();
6
+ let synth, output, state = 'starting', closing, draining;
7
+ let rampFrame = 0, maxQueuedFrames = 0, peak = 0;
8
+ let pumping, stopping;
9
+ const sampleRate = options.sampleRate ?? 48000;
10
+ const queueBlocks = options.queueBlocks ?? 4;
11
+ const fadeFrames = Math.round(sampleRate * .02);
12
+ function status() {
13
+ return {state, sampleRate, currentFrame: synth?.currentFrame ?? 0,
14
+ currentTime: synth?.currentTime ?? 0, maxQueuedFrames, peak,
15
+ output: output?.getState() ?? null, pendingTimers: synth?.pendingTimers ?? 0,
16
+ recording: synth?.recording.getState() ?? null, looper: synth?.looper.getState() ?? null};
17
+ }
18
+ function write(pcm) {
19
+ for (const channel of [pcm.left, pcm.right]) for (const value of channel) peak = Math.max(peak, Math.abs(value));
20
+ output.write(pcm); maxQueuedFrames = Math.max(maxQueuedFrames, output.queuedFrames);
21
+ }
22
+ function pump() {
23
+ if (pumping) return pumping;
24
+ if (state !== 'playing') return Promise.resolve();
25
+ pumping = (async () => {
26
+ while (state === 'playing' && output.queuedFrames < output.frames * queueBlocks) {
27
+ const pcm = await synth.render(output.frames);
28
+ for (let i = 0; i < output.frames; i++) {
29
+ const gain = Math.min(1, ++rampFrame / fadeFrames);
30
+ pcm.left[i] *= gain; pcm.right[i] *= gain;
31
+ }
32
+ write(pcm);
33
+ }
34
+ })().catch(error => {void fail(error).catch(() => {});}).finally(() => {pumping = null;});
35
+ return pumping;
36
+ }
37
+ function onDrain() {
38
+ if (draining && output.queuedFrames === 0) {draining(); draining = null;}
39
+ pump();
40
+ }
41
+ function stop() {
42
+ if (stopping) return stopping;
43
+ if (state !== 'playing') return Promise.resolve();
44
+ state = 'stopping';
45
+ stopping = (async () => {
46
+ await pumping;
47
+ await synth.stopEvents();
48
+ // Append a short fade after already-buffered audio, then clear future commands.
49
+ const blocks = Math.ceil(fadeFrames / output.frames);
50
+ for (let block = 0; block < blocks; block++) {
51
+ const pcm = await synth.render(output.frames);
52
+ for (let i = 0; i < output.frames; i++) {
53
+ const gain = Math.max(0, 1 - (block * output.frames + i + 1) / fadeFrames);
54
+ pcm.left[i] *= gain; pcm.right[i] *= gain;
55
+ }
56
+ write(pcm);
57
+ }
58
+ await new Promise(resolve => {
59
+ const timer = setTimeout(() => {draining = null; resolve();}, output.queuedFrames * 1000 / sampleRate + 250);
60
+ draining = () => {clearTimeout(timer); resolve();};
61
+ });
62
+ output.stop(); await synth.stop(); state = 'stopped';
63
+ })().finally(() => {stopping = null;});
64
+ return stopping;
65
+ }
66
+ async function resume() {
67
+ if (state === 'playing') return;
68
+ state = 'playing'; rampFrame = 0; await pump(); if (!closing) output.start();
69
+ }
70
+ async function fail(error) {
71
+ parentPort.postMessage({type: 'fatal', error: error.message});
72
+ await shutdown();
73
+ }
74
+ async function shutdown() {
75
+ if (closing) return closing;
76
+ abort.abort();
77
+ closing = (async () => {
78
+ await initialized.catch(() => {});
79
+ try {await stop();} catch (error) {
80
+ parentPort.postMessage({type: 'fatal', error: error.message});
81
+ } finally {
82
+ state = 'closed';
83
+ try {output?.close();} finally {await synth?.close(); parentPort.postMessage({type: 'closed'});}
84
+ // The owner terminates this Worker after native stream cleanup. Some
85
+ // native addons retain callback references even after closeStream().
86
+ }
87
+ })();
88
+ return closing;
89
+ }
90
+ let commands = Promise.resolve();
91
+ parentPort.on('message', message => {
92
+ if (message.type === 'shutdown') {void shutdown().catch(error => parentPort.postMessage({type: 'fatal', error: error.message})); return;}
93
+ commands = commands.then(async () => {
94
+ try {
95
+ await initialized;
96
+ if (closing) throw new Error('MegaSynthNode is closing');
97
+ let result;
98
+ const {op, args = []} = message;
99
+ if (op === 'fm') {
100
+ const [method, parameters] = args;
101
+ result = synth.callFM(method, parameters);
102
+ } else if (op === 'fx') synth.applyFX(args[0]);
103
+ else if (op === 'recording') {
104
+ const [method, parameters] = args;
105
+ if (!['start', 'stop', 'export', 'import', 'play', 'stopPlayback', 'getState'].includes(method)) throw new Error('Invalid recording command');
106
+ result = synth.recording[method](...parameters);
107
+ } else if (op === 'looper') result = await synth.callLooper(...args);
108
+ else if (op === 'schedule') synth.schedule(...args);
109
+ else if (op === 'stop') await stop();
110
+ else if (op === 'resume') await resume();
111
+ else if (op === 'status') result = status();
112
+ else if (op === 'flush') result = status();
113
+ else throw new Error(`Unknown operation: ${op}`);
114
+ parentPort.postMessage({type: 'reply', id: message.id, result});
115
+ } catch (error) {parentPort.postMessage({type: 'reply', id: message.id, error: error.message});}
116
+ });
117
+ });
118
+ const initialized = (async () => {
119
+ synth = await createMegaSynthSession({...options.engineOptions, sampleRate,
120
+ masterVolume: options.masterVolume ?? .25, signal: abort.signal});
121
+ abort.signal.throwIfAborted();
122
+ const {createOutput} = await import(options.outputModule ?? new URL('./output_audify.mjs', import.meta.url).href);
123
+ output = await createOutput({...options.outputOptions, sampleRate,
124
+ bufferFrames: options.bufferFrames ?? 512, onDrain, onError: error => {void fail(error).catch(() => {});}});
125
+ abort.signal.throwIfAborted();
126
+ if (!Number.isSafeInteger(output.frames) || output.frames < 1 || output.frames > 8192) throw new Error('Invalid output frame size');
127
+ await resume(); abort.signal.throwIfAborted(); parentPort.postMessage({type: 'ready', result: status()});
128
+ })();
129
+ initialized.catch(error => {if (!closing) void fail(error).catch(() => {});});
@@ -0,0 +1,48 @@
1
+ /** Optional Node Worker output adapter. Requires audify 1.10.x, loaded only here. */
2
+ export async function createOutput({sampleRate, bufferFrames, onDrain, onError, moduleUrl, deviceId}) {
3
+ let loaded;
4
+ try { loaded = await import(moduleUrl ?? 'audify'); }
5
+ catch (cause) {throw new Error(`Could not load audify: ${cause.message}. Install with npm install audify`, {cause});}
6
+ const {RtAudio, RtAudioFormat} = loaded.default ?? loaded;
7
+ const audio = new RtAudio();
8
+ let queuedFrames = 0, consumedFrames = 0, closed = false, running = false;
9
+ let frames;
10
+ try {
11
+ frames = audio.openStream({deviceId: deviceId ?? audio.getDefaultOutputDevice(), nChannels: 2},
12
+ null, RtAudioFormat.RTAUDIO_FLOAT32, sampleRate, bufferFrames, 'Tetorica MegaSynth', null,
13
+ () => {
14
+ if (closed || !running) return;
15
+ queuedFrames = Math.max(0, queuedFrames - frames); consumedFrames += frames;
16
+ onDrain();
17
+ }, 0, (_type, message) => {if (!closed) onError(new Error(message));});
18
+ if (audio.getStreamSampleRate() !== sampleRate) throw new Error('Audio device sample rate differs from renderer');
19
+ } catch (error) {if (audio.isStreamOpen()) audio.closeStream(); throw error;}
20
+ return {
21
+ frames,
22
+ get queuedFrames() {return queuedFrames;},
23
+ write({left, right}) {
24
+ if (closed || left.length !== frames || right.length !== frames) throw new Error('Invalid audio output block');
25
+ const bytes = Buffer.allocUnsafe(frames * 8);
26
+ for (let i = 0; i < frames; i++) for (const [channel, values] of [left, right].entries()) {
27
+ const value = values[i];
28
+ if (!Number.isFinite(value)) throw new Error('Non-finite audio output');
29
+ bytes.writeFloatLE(Math.max(-1, Math.min(1, value)), i * 8 + channel * 4);
30
+ }
31
+ audio.write(bytes); queuedFrames += frames;
32
+ },
33
+ start() {running = true; audio.start();},
34
+ stop() {
35
+ running = false;
36
+ if (audio.isStreamRunning()) audio.stop();
37
+ audio.clearOutputQueue(); queuedFrames = 0;
38
+ },
39
+ getState() {return {api: audio.getApi(), consumedFrames, queuedFrames,
40
+ bufferFrames: frames, deviceLatencyFrames: audio.getStreamLatency()};},
41
+ close() {
42
+ if (closed) return;
43
+ closed = true; running = false;
44
+ if (audio.isStreamRunning()) audio.stop();
45
+ audio.clearOutputQueue(); audio.closeStream();
46
+ },
47
+ };
48
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tetorica-fm2612",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "description": "Tetorica sound chip WASM cores, Synth helpers and browser audio runtime",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -13,13 +13,16 @@
13
13
  "exports": {
14
14
  ".": "./soundchip.js",
15
15
  "./assets": "./package_assets.js",
16
+ "./node": "./node/megasynth.mjs",
16
17
  "./generated/*": "./generated/*",
17
18
  "./*.js": "./*.js",
18
19
  "./*": "./*.js"
19
20
  },
21
+ "peerDependencies": { "audify": "^1.10.1" },
22
+ "peerDependenciesMeta": { "audify": { "optional": true } },
20
23
  "files": [
21
24
  "*.js", "*.wasm", "tetorica_ym2608_adpcm_rom.bin",
22
- "generated/", "assets/", "licenses/", "sources/",
25
+ "generated/", "assets/", "licenses/", "sources/", "node/",
23
26
  "LICENSE", "THIRD_PARTY_LICENSES.txt", "RUNTIME.md",
24
27
  "soundchip.md", "runtime-manifest.json"
25
28
  ]
@@ -17,7 +17,10 @@
17
17
  "megasynth.js",
18
18
  "megasynth_fx.js",
19
19
  "megasynth_looper.js",
20
+ "megasynth_offline.js",
21
+ "megasynth_pcm_looper.js",
20
22
  "megasynth_recording.js",
23
+ "megasynth_session.js",
21
24
  "midi_file.js",
22
25
  "midi_song.js",
23
26
  "midi_source.js",
@@ -25,6 +28,7 @@
25
28
  "multichipaudioengine.js",
26
29
  "native-fx-worklet.js",
27
30
  "native_fx.js",
31
+ "native_fx_engine.js",
28
32
  "native_fx_graph.js",
29
33
  "native_fx_rack.js",
30
34
  "native_noise.js",
@@ -77,6 +81,7 @@
77
81
  "rf5c164_pcm.js",
78
82
  "rf5c164synth.js",
79
83
  "s98_file.js",
84
+ "sample_clock.js",
80
85
  "segapcm.js",
81
86
  "segapcmaudioengine.js",
82
87
  "segapsg.js",
@@ -0,0 +1,36 @@
1
+ /** Render-driven timers. No wall-clock timers, DOM or audio device dependency. */
2
+ export class SampleClock {
3
+ #now; #rate; #timers = new Map(); #id = 0;
4
+ constructor(sampleRate, currentFrame) {this.#rate = sampleRate; this.#now = currentFrame;}
5
+ get pendingCount() {return this.#timers.size;}
6
+ get nextFrame() {
7
+ let frame = Infinity;
8
+ for (const timer of this.#timers.values()) frame = Math.min(frame, timer.frame);
9
+ return frame;
10
+ }
11
+ setTimer = (callback, delayMs) => {
12
+ if (!Number.isFinite(delayMs) || delayMs < 0) throw new RangeError('Invalid sample timer delay');
13
+ return this.atFrame(this.#now() + Math.round(delayMs * this.#rate / 1000), callback);
14
+ };
15
+ atFrame(frame, callback) {
16
+ if (!Number.isSafeInteger(frame) || frame < this.#now()) throw new RangeError('Cannot schedule before currentFrame');
17
+ if (typeof callback !== 'function') throw new TypeError('Timer callback must be a function');
18
+ const id = ++this.#id; this.#timers.set(id, {frame, callback}); return id;
19
+ }
20
+ clearTimer = id => {this.#timers.delete(id);};
21
+ clear() {this.#timers.clear();}
22
+ async runDue() {
23
+ let count = 0;
24
+ while (true) {
25
+ let selected;
26
+ for (const [id, timer] of this.#timers) {
27
+ if (timer.frame > this.#now()) continue;
28
+ if (!selected || timer.frame < selected.timer.frame) selected = {id, timer};
29
+ }
30
+ if (!selected) return;
31
+ if (++count > 10000) throw new Error('Sample timers did not advance the clock');
32
+ this.#timers.delete(selected.id);
33
+ await selected.timer.callback();
34
+ }
35
+ }
36
+ }