tetorica-fm2612 0.2.4 → 0.2.6

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,27 @@ 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
+ ## Chip output transports (0.2.6)
212
+
213
+ Basic chip examples use a shared factory followed by a transport and Synth.
214
+ Browser `createSoundChip(name, {execution: 'worklet'})` creates the WASM chip
215
+ inside AudioWorklet. `YM2612WorkletTransport` / `YM2608WorkletTransport` send
216
+ register commands from Main, and accept an existing AudioWorkletNode or MessagePort
217
+ for applications that manage the connection themselves.
218
+ Gameboy, SegaPSG and YM2151 transports are exported by `chip_worklet_transport.js`.
219
+ The worklet factory supports `ym2612`, `ym2608`, `gameboy`, `segapsg`, `ym2151`.
220
+ Default factory execution stays local; Game Boy and Sega PSG now also support
221
+ `createSoundChip('gameboy')` and `createSoundChip('segapsg')`.
222
+
223
+ Node `YM2612AudifyTransport(chip)` and the corresponding YM2608 / Gameboy /
224
+ SegaPSG / YM2151 classes are exported by `tetorica-fm2612/node/transports`.
225
+ They borrow the caller's chip, render PCM on the calling thread, and own a
226
+ device-only Worker. Use `await start()`, `await stop()`, `await close()`, then
227
+ `chip.dispose()`. Audify remains optional, but is required by this chosen output.
228
+ MegaSynth stays available as the integrated game-embedding API.
229
+ DirectTransport is the separate offline PCM / WAV interface.
230
+ These transport/factory APIs are available starting in 0.2.6.
231
+
211
232
  ## Local packaging
212
233
 
213
234
  From the repository root:
@@ -232,10 +253,10 @@ FM/PSG/PCM mixing, stop/reset and close/restart. Playwright is a development
232
253
  dependency; it is not required by users of the sound-chip runtime.
233
254
 
234
255
  The build is staged in `dist/fm2612/`; packing produces
235
- `tetorica-fm2612-0.2.4.tgz`. To install a local build in another project:
256
+ `tetorica-fm2612-0.2.6.tgz`. To install a local build in another project:
236
257
 
237
258
  ```sh
238
- npm install /absolute/path/to/tetorica-fm2612-0.2.4.tgz
259
+ npm install /absolute/path/to/tetorica-fm2612-0.2.6.tgz
239
260
  ```
240
261
 
241
262
  The existing `tetorica-vgm` CLI package is built separately. This first package
@@ -251,6 +272,18 @@ and generator. External instrument/sample ROMs are not included.
251
272
 
252
273
  ## Release notes
253
274
 
275
+ `0.2.6` adds browser Worklet chip creation and chip-specific Audify transports
276
+ for YM2612, YM2608, Game Boy, Sega PSG and YM2151. Basic examples use
277
+ WorkletTransport on Web and AudifyTransport on Node; DirectTransport remains
278
+ available for explicit PCM generation and WAV export. Applications can move
279
+ Synth/Transport into their own Worker using a dedicated MessagePort.
280
+ MegaSynthNode can also start without an audio driver, render PCM offline,
281
+ and attach, detach or replace an output adapter later.
282
+
283
+ `0.2.5` adds experimental MegaSynth Node APIs for offline nativeFX rendering,
284
+ event recording, PCM looping and Worker-based realtime device output.
285
+ Audify is an optional peer dependency.
286
+
254
287
  `0.2.4` removes the ymfm YM2612 DAC ladder's idle offset from AudioWorklet
255
288
  output and keeps output silent until FM/PSG initialization completes. This
256
289
  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 142 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
 
@@ -0,0 +1,36 @@
1
+ /** Shared sample-rate conversion for chip output transports. No audio device. */
2
+ export class ChipPCMRenderer {
3
+ constructor(chip, {sampleRate, gain = .25, generate, removeIdleOffset = false} = {}) {
4
+ if (!Number.isInteger(sampleRate) || sampleRate <= 0) throw new RangeError('Invalid output sample rate');
5
+ if (!Number.isFinite(gain) || gain < 0 || gain > 4) throw new RangeError('Invalid output gain');
6
+ this.chip = chip; this.rate = chip.sampleRate(); this.sampleRate = sampleRate; this.gain = gain;
7
+ if (!Number.isFinite(this.rate) || this.rate <= 0) throw new RangeError('Invalid chip sample rate');
8
+ this.generate = generate ?? (chip.generateStereoView ?? chip.generateStereo).bind(chip);
9
+ this.idleLeft = this.idleRight = 0;
10
+ if (removeIdleOffset) {
11
+ if (!chip.supportsState?.()) throw new Error('Idle calibration requires chip state support');
12
+ const state = chip.saveState();
13
+ try {chip.reset(); const idle = chip.generateStereo(1); this.idleLeft = idle.left[0]; this.idleRight = idle.right[0];}
14
+ finally {chip.loadState(state);}
15
+ }
16
+ this.resetHistory();
17
+ }
18
+ resetHistory() {this.phase = 0; this.left = this.right = 0;}
19
+ render(frames) {
20
+ const left = new Float32Array(frames), right = new Float32Array(frames);
21
+ const nativeFrames = Math.floor((this.phase + frames * this.rate) / this.sampleRate);
22
+ const pcm = nativeFrames ? this.generate(nativeFrames) : null;
23
+ let offset = 0;
24
+ for (let i = 0; i < frames; i++) {
25
+ this.phase += this.rate;
26
+ const count = Math.floor(this.phase / this.sampleRate); this.phase -= count * this.sampleRate;
27
+ if (count) {
28
+ let l = 0, r = 0;
29
+ for (let j = 0; j < count; j++, offset++) {l += pcm.left[offset] - this.idleLeft; r += pcm.right[offset] - this.idleRight;}
30
+ this.left = l / count; this.right = r / count;
31
+ }
32
+ left[i] = this.left * this.gain; right[i] = this.right * this.gain;
33
+ }
34
+ return {left, right, sampleRate: this.sampleRate};
35
+ }
36
+ }
@@ -0,0 +1,21 @@
1
+ /** Register transports: Synth stays on the caller thread, chip runs in AudioWorklet. */
2
+ export class ChipWorkletTransport {
3
+ constructor(endpoint) {
4
+ this.endpoint = endpoint?.execution === 'worklet' ? endpoint : null;
5
+ this.port = endpoint?.port ?? endpoint;
6
+ if (!this.port?.postMessage) throw new TypeError('Expected worklet chip endpoint or MessagePort');
7
+ this.disposed = false;
8
+ }
9
+ send(method, args) {if (this.disposed) throw new Error('Transport disposed'); this.port.postMessage({method, args});}
10
+ reset() {this.send('reset', []);}
11
+ write(...args) {this.send('write', args);}
12
+ writeRegister(...args) {this.send('writeRegister', args);}
13
+ start() {if (!this.endpoint) return Promise.reject(new Error('start() requires a worklet chip endpoint')); return this.endpoint.start();}
14
+ stop() {return this.endpoint?.stop() ?? Promise.resolve();}
15
+ flush() {return this.endpoint?.request('barrier') ?? Promise.resolve();}
16
+ dispose() {this.disposed = true;}
17
+ async close() {this.dispose(); await this.endpoint?.dispose();}
18
+ }
19
+ export class GameboyWorkletTransport extends ChipWorkletTransport {}
20
+ export class SegaPSGWorkletTransport extends ChipWorkletTransport {}
21
+ export class YM2151WorkletTransport extends ChipWorkletTransport {}
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
+ }