tetorica-fm2612 0.2.6 → 0.2.7

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
@@ -253,10 +253,10 @@ FM/PSG/PCM mixing, stop/reset and close/restart. Playwright is a development
253
253
  dependency; it is not required by users of the sound-chip runtime.
254
254
 
255
255
  The build is staged in `dist/fm2612/`; packing produces
256
- `tetorica-fm2612-0.2.6.tgz`. To install a local build in another project:
256
+ `tetorica-fm2612-0.2.7.tgz`. To install a local build in another project:
257
257
 
258
258
  ```sh
259
- npm install /absolute/path/to/tetorica-fm2612-0.2.6.tgz
259
+ npm install /absolute/path/to/tetorica-fm2612-0.2.7.tgz
260
260
  ```
261
261
 
262
262
  The existing `tetorica-vgm` CLI package is built separately. This first package
@@ -272,6 +272,12 @@ and generator. External instrument/sample ROMs are not included.
272
272
 
273
273
  ## Release notes
274
274
 
275
+ `0.2.7` adds the MAME-derived 32X PWM core, output-frame scheduling,
276
+ MegaSynth/MegaSynthNode integration, Playground support and PWM Worklet/Audify/Direct
277
+ transports. Integrated output uses cycle-normalized amplitude; the low-level
278
+ core also offers raw DAC scaling. The BSD license and source provenance are included.
279
+
280
+
275
281
  `0.2.6` adds browser Worklet chip creation and chip-specific Audify transports
276
282
  for YM2612, YM2608, Game Boy, Sega PSG and YM2151. Basic examples use
277
283
  WorkletTransport on Web and AudifyTransport on Node; DirectTransport remains
@@ -302,3 +308,16 @@ runtimes release routing nodes when closed so they can restart safely.
302
308
  `0.2.1` updates the npm Homepage link to
303
309
  [tetorica-fm2612-examples](https://github.com/kyorohiro/tetorica-fm2612-examples).
304
310
  Sound-chip runtime behavior is unchanged from `0.2.0`.
311
+
312
+ ### 32X PWM (0.2.7)
313
+
314
+ Version 0.2.7 adds MAME-derived PWM to `MegaSynth({mega32X: true})`,
315
+ `MegaSynthNode({mega32X: true})` and Playground's `useSoundChip('pwm')`.
316
+ After `start()`, use `synth.pwm.write(register, value)`
317
+ or `synth.pwm.scheduleWrites([{frame, register, value}, ...])`. Frames are offsets
318
+ from receipt of the batch at the output sample rate returned by `pwm.getState()`.
319
+ The integrated default is `duty` output, gain 1; `pwmOptions` can select `clock`,
320
+ `outputMode` and core `gain`. PWM is mixed before the common FX/master output.
321
+ Standalone `PWM32XWorkletTransport`, `PWM32XAudifyTransport` and PCM-only
322
+ `PWM32XDirectTransport` use the same MAME-derived core.
323
+ See [implementation and validation](https://github.com/kyorohiro/hello_ymfm_wasm/blob/main/docs/issues/pwm32x_01.md).
package/RUNTIME.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Full web runtime
2
2
 
3
- Includes all 142 top-level web runtime modules and 23 generated chip/engine pairs.
3
+ Includes all 147 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
 
@@ -8,5 +8,6 @@ mame-okim6258: see licenses/mame-okim6258/LICENSE and README.md.
8
8
  mame-okim6295: see licenses/mame-okim6295/LICENSE and README.md.
9
9
  mame-rf5c164: see licenses/mame-rf5c164/LICENSE and README.md.
10
10
  mame-segapcm: see licenses/mame-segapcm/LICENSE and README.md.
11
+ mame-32x-pwm: see licenses/mame-32x-pwm/LICENSE and README.md.
11
12
  Nuked-OPN2 is LGPL-2.1-or-later; the MAME adaptations listed above are BSD-3-Clause.
12
13
  No external instrument/sample ROMs are included.
@@ -8,6 +8,7 @@ import { Ym2612, YM2612_CLOCK } from "./ym2612.js";
8
8
  import { SegaPSG, SEGAPSG_CLOCK } from "./segapsg.js";
9
9
 
10
10
  import { Rf5c164 } from "./rf5c164.js";
11
+ import {PWM32X} from './pwm32x.js';
11
12
 
12
13
  /**
13
14
  * GenesisAudioEngine adapter for synchronous stereo rendering and VGM register dispatch.
@@ -17,11 +18,14 @@ import { Rf5c164 } from "./rf5c164.js";
17
18
  export class GenesisAudioEngine {
18
19
  #states = new WeakMap();
19
20
 
20
- constructor(ym2612, psg, sampleRate, masterVolume = 1, pcm = null) {
21
+ constructor(ym2612, psg, sampleRate, masterVolume = 1, pcm = null, pwmOptions = {}) {
21
22
  this.ym2612 = ym2612;
22
23
  this.psg = psg;
23
24
  this.pcm = pcm;
24
- this.pwm = new SimplePwm();
25
+ if (!['legacy', 'mame'].includes(pwmOptions.model ?? 'legacy')) throw new Error('Unknown PWM model');
26
+ const outputMode = pwmOptions.outputMode ?? 'duty';
27
+ this.pwm = pwmOptions.model === 'mame' ? new PWM32X({...pwmOptions, sampleRate, outputMode,
28
+ gain:outputMode === 'duty' ? 1 : .4}) : new SimplePwm();
25
29
  this._pcmMuted = false;
26
30
  this._psgMuted = false;
27
31
  this._sampleRate = sampleRate;
@@ -37,6 +41,10 @@ export class GenesisAudioEngine {
37
41
  * @returns {Promise<GenesisAudioEngine>} Initialized engine owned by the caller.
38
42
  */
39
43
  static async create(options = {}) {
44
+ if (!['legacy', 'mame'].includes(options.pwmModel ?? 'legacy')) throw new Error('Unknown PWM model');
45
+ if (!['dac', 'duty'].includes(options.pwmOutputMode ?? 'duty')) throw new Error('Unknown PWM output mode');
46
+ if (options.pwmModel === 'mame' && options.pwmClock !== undefined && options.pwmClock !== 0 &&
47
+ (!Number.isFinite(options.pwmClock) || options.pwmClock <= 0 || options.pwmClock > 100000000)) throw new RangeError('Invalid PWM clock');
40
48
  const {
41
49
  ym2612ModuleFactory,
42
50
  ym2612ModuleOptions,
@@ -81,7 +89,8 @@ export class GenesisAudioEngine {
81
89
  psg,
82
90
  sampleRate,
83
91
  masterVolume,
84
- pcm
92
+ pcm,
93
+ {model:options.pwmModel, clock:options.pwmClock || undefined, outputMode:options.pwmOutputMode}
85
94
  );
86
95
  }
87
96
 
@@ -93,6 +102,7 @@ export class GenesisAudioEngine {
93
102
  this.ym2612.dispose();
94
103
  this.psg.dispose();
95
104
  this.pcm?.dispose();
105
+ this.pwm.dispose?.();
96
106
  }
97
107
 
98
108
  supportsState() {
@@ -100,19 +110,21 @@ export class GenesisAudioEngine {
100
110
  return !this.writeOki6258 && this.ym2612.supportsState?.() && this.psg.supportsState?.() && (!this.pcm || this.pcm.supportsState?.());
101
111
  }
102
112
  stateSettingsKey() {
103
- return JSON.stringify([this._sampleRate, this._masterVolume, this._psgMuted, this._pcmMuted, this.pwm.muted]);
113
+ return JSON.stringify([this._sampleRate, this._masterVolume, this._psgMuted, this._pcmMuted, this.pwm.muted,
114
+ this.pwm.constructor.name, this.pwm.clock, this.pwm.gain, this.pwm.outputMode]);
104
115
  }
105
116
  saveState() {
106
117
  if (!this.supportsState()) throw new Error('Genesis state saving unavailable');
107
118
  const data = {ym: this.ym2612.saveState(), psg: this.psg.saveState(), pcm: this.pcm?.saveState(),
108
119
  pwm: this.pwm.saveState(), key: this.stateSettingsKey()};
109
- const state = Object.freeze({byteLength: data.ym.byteLength + data.psg.byteLength + (data.pcm?.byteLength || 0) + 64});
120
+ const state = Object.freeze({byteLength: data.ym.byteLength + data.psg.byteLength + (data.pcm?.byteLength || 0) + (data.pwm.byteLength || 64)});
110
121
  this.#states.set(state, data); return state;
111
122
  }
112
123
  validateState(state) {
113
124
  const data = this.#states.get(state);
114
125
  if (!this.supportsState() || !data || data.key !== this.stateSettingsKey()) throw new Error('Incompatible Genesis state');
115
126
  this.ym2612.validateState(data.ym); this.psg.validateState(data.psg); this.pcm?.validateState(data.pcm);
127
+ this.pwm.validateState?.(data.pwm);
116
128
  }
117
129
  loadState(state) {
118
130
  this.validateState(state);
@@ -225,14 +237,15 @@ export class GenesisAudioEngine {
225
237
  const pcm = this.pcm?.generateStereo(frames);
226
238
  const pcmGain = this._pcmMuted ? 0 : 1;
227
239
  const psgGain = this._psgMuted ? 0 : 0.35;
228
- const [pwmLeft, pwmRight] = this.pwm.output();
240
+ const pwm = this.pwm.generateStereo?.(frames);
241
+ const [pwmLeft, pwmRight] = pwm ? [0, 0] : this.pwm.output();
229
242
 
230
243
  for (let index = 0; index < frames; index += 1) {
231
244
  left[index] =
232
- (ym.left[index] * 0.9 + psg.left[index] * psgGain + pwmLeft + (pcm ? pcm.left[index] * pcmGain : 0)) *
245
+ (ym.left[index] * 0.9 + psg.left[index] * psgGain + (pwm ? pwm.left[index] : pwmLeft) + (pcm ? pcm.left[index] * pcmGain : 0)) *
233
246
  this._masterVolume;
234
247
  right[index] =
235
- (ym.right[index] * 0.9 + psg.right[index] * psgGain + pwmRight + (pcm ? pcm.right[index] * pcmGain : 0)) *
248
+ (ym.right[index] * 0.9 + psg.right[index] * psgGain + (pwm ? pwm.right[index] : pwmRight) + (pcm ? pcm.right[index] * pcmGain : 0)) *
236
249
  this._masterVolume;
237
250
  }
238
251
  }
@@ -0,0 +1,27 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) David Haywood
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+ 3. Neither the name of the copyright holder nor the names of its contributors
15
+ may be used to endorse or promote products derived from this software without
16
+ specific prior written permission.
17
+
18
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,29 @@
1
+ # MAME 32X PWM adaptation
2
+
3
+ Source revision: df862b468443b391b24405c322aea60695d1825e.
4
+ https://github.com/mamedev/mame/blob/df862b468443b391b24405c322aea60695d1825e/src/mame/shared/mega32x.cpp
5
+ Header: same revision, src/mame/shared/mega32x.h.
6
+ BSD-3-Clause; copyright David Haywood. Original files are in upstream/.
7
+
8
+ web/pwm32x.js adapts calculate_pwm_timer, pwm_w, pwm_r, handle_pwm_callback
9
+ and the three-entry FIFO. Full FIFO writes discard the oldest item. Control/cycle
10
+ writes restart an enabled timer and clear FIFOs; cycle zero means 4095.
11
+ Timer ticks every cycle-1 input clocks, consumes left then right, routes to DACs,
12
+ and holds the last output on underrun. Interrupt cadence is counted, not delivered
13
+ to an SH2 CPU. No CPUs, DMA requests, video or MAME scheduler are included.
14
+
15
+ Host differences: clocks advance synchronously with PCM rendering; output is the
16
+ duration-weighted average within each output frame. Timing uses exact input clocks
17
+ rather than MAME scheduler integer-Hz conversion. The 12-bit DAC is represented
18
+ by (value/2048-1), with MAME's 0.4 route gain by default. Output before the first
19
+ DAC write is silent. This does not model analog PWM filtering or claim hardware
20
+ accuracy. It intentionally differs from the old cycle-normalized SimplePwm and
21
+ its fallback routing. Browser/Node code can select the experimental model for
22
+ comparison. Analyzer/CLI default VGM playback uses this FIFO/timer adapter
23
+ with cycle-normalized amplitude after a user-confirmed real-track comparison.
24
+ Real-hardware equivalence remains unverified.
25
+
26
+ VGM comparison adapter uses outputMode: duty, gain 1, i.e. value/cycle*2-1,
27
+ to match legacy PCM amplitude and FM/PSG balance. This host normalization is
28
+ not MAME's fixed DAC output. Raw outputMode: dac remains the standalone default.
29
+ VGM callers select it with pwmOutputMode: dac.
package/megasynth.js CHANGED
@@ -1,3 +1,5 @@
1
+ import {createPWM32XAudio} from './playground_pwm_audio.js';
2
+ import {createPWM32XClient} from './pwm32x_playback.js';
1
3
  /**
2
4
  * @file megasynth.js
3
5
  * 実行環境: Browser(メインスレッド)
@@ -136,6 +138,8 @@ const YM2612_NATIVE_SAMPLE_RATE =
136
138
  * ym2612WasmUrl?: string,
137
139
  * segaPsgWasmUrl?: string | null,
138
140
  * megaCD?: boolean,
141
+ * mega32X?: boolean,
142
+ * pwmOptions?: {clock?: number, gain?: number, outputMode?: "duty" | "dac"},
139
143
  * rf5c164WasmUrl?: string,
140
144
  * rf5c164WorkletUrl?: string,
141
145
  * rf5c164Fetch?: typeof fetch,
@@ -311,6 +315,9 @@ export class MegaSynth {
311
315
  * default except in Mega CD mode, so FM-only callers are unaffected.
312
316
  */
313
317
  this.megaCD = options.megaCD === true;
318
+ this.mega32X = options.mega32X === true;
319
+ this.pwmOptions = options.pwmOptions ?? {};
320
+ this.pwm = null; this.pwmDevice = null;
314
321
  this.segaPsgWasmUrl = options.segaPsgWasmUrl !== undefined
315
322
  ? options.segaPsgWasmUrl
316
323
  : this.megaCD ? resolveSiblingWorkletUrl(this.ym2612WasmUrl, 'segapsg_wasm.wasm') : null;
@@ -442,6 +449,7 @@ export class MegaSynth {
442
449
  */
443
450
  reset() {
444
451
  this.fm?.reset();
452
+ if (this.pwm) return Promise.all([this.pwm.reset(), this.pcm?.reset()]).then(() => undefined);
445
453
  return this.pcm?.reset();
446
454
  }
447
455
 
@@ -862,11 +870,18 @@ export class MegaSynth {
862
870
  finally { this.sample.unload(name); }
863
871
  });
864
872
  }
873
+ if (this.mega32X) {
874
+ const device = await createPWM32XAudio(this.audioContext, this.masterInputNode, {...this.pwmOptions, signal});
875
+ if (signal.aborted) {device.dispose(); signal.throwIfAborted();}
876
+ this.pwmDevice = device; this.pwm = createPWM32XClient(device.port);
877
+ }
865
878
  this.#ensureRecordingManager();
866
879
  this.#installRecordingHooks();
867
880
  }
868
881
 
869
882
  #disposePcm() {
883
+ this.pwm?.dispose(); this.pwm = null;
884
+ this.pwmDevice?.dispose(); this.pwmDevice = null;
870
885
  this.pcm?.dispose();
871
886
  this.pcm = null;
872
887
  this.pcmDevice?.dispose();
@@ -1,3 +1,4 @@
1
+ import {PWM32XPlayback} from './pwm32x_playback.js';
1
2
  /** Experimental offline MegaSynth engine. Browser / Node; no audio device. */
2
3
  import {createSoundChip} from './soundchip.js';
3
4
  import {YM2612Synth, YM2612DirectTransport} from './ym2612synth.js';
@@ -29,7 +30,7 @@ async function loadFX(options) {
29
30
  * Create an experimental YM2612 + nativeFX offline renderer.
30
31
  * This is a separate entry point; the existing browser MegaSynth is unchanged.
31
32
  * Options: sampleRate (default 48000), masterVolume (default 1), chipOptions,
32
- * fxModule / fxWasmBinary / fxWasmUrl, signal.
33
+ * fxModule / fxWasmBinary / fxWasmUrl, signal, mega32X, pwmOptions.
33
34
  */
34
35
  export async function createMegaSynthOffline(options = {}) {
35
36
  const sampleRate = options.sampleRate ?? 48000;
@@ -47,7 +48,7 @@ export async function createMegaSynthOffline(options = {}) {
47
48
  const chip = await createSoundChip('ym2612', {...options.chipOptions, signal: options.signal});
48
49
  try {
49
50
  options.signal?.throwIfAborted();
50
- return new MegaSynthOffline(chip, dsp, sampleRate, masterVolume);
51
+ return new MegaSynthOffline(chip, dsp, sampleRate, masterVolume, options);
51
52
  } catch (error) { chip.dispose(); throw error; }
52
53
  }
53
54
 
@@ -57,7 +58,8 @@ class MegaSynthOffline {
57
58
  #idleLeft; #idleRight; #chipRate;
58
59
  #sampleRate; #masterVolume;
59
60
 
60
- constructor(chip, dsp, sampleRate, masterVolume) {
61
+ constructor(chip, dsp, sampleRate, masterVolume, options) {
62
+ this.pwm = options.mega32X === true ? new PWM32XPlayback({...options.pwmOptions, sampleRate}) : null;
61
63
  this.#chip = chip; this.#dsp = dsp; this.#sampleRate = sampleRate;
62
64
  this.#masterVolume = masterVolume; this.#chipRate = chip.sampleRate();
63
65
  const idle = chip.generateStereoView(1);
@@ -95,6 +97,7 @@ class MegaSynthOffline {
95
97
  for (let channel = 0; channel < 6; channel++) this.fm.noteOff(channel);
96
98
  this.#transport.dacPlayer?.reset();
97
99
  this.#transport.write(0, 0x2b, 0);
100
+ this.pwm?.reset();
98
101
  this.#dsp.samples.clear(); this.#dsp.resetNoise(); this.#dsp.command({op: 'clear'});
99
102
  }
100
103
 
@@ -152,7 +155,11 @@ class MegaSynthOffline {
152
155
  }
153
156
  input[0][i] = this.#lastLeft; input[1][i] = this.#lastRight;
154
157
  }
155
- // Capture FM before sample playback, FX and master volume, avoiding overdub feedback.
158
+ if (this.pwm) {
159
+ const pwm = this.pwm.generateStereo(count);
160
+ for (let i = 0; i < count; i++) {input[0][i] += pwm.left[i]; input[1][i] += pwm.right[i];}
161
+ }
162
+ // Capture FM/PWM before sample playback, FX and master volume, avoiding overdub feedback.
156
163
  onSource?.(input);
157
164
  const output = [left.subarray(offset, offset + count), right.subarray(offset, offset + count)];
158
165
  this.#dsp.process(input, output);
@@ -165,6 +172,7 @@ class MegaSynthOffline {
165
172
  close() {
166
173
  if (this.#closed) return;
167
174
  this.#closed = true; this.#events.length = 0;
175
+ this.pwm?.dispose();
168
176
  this.#chip.dispose(); this.#chip = null; this.#dsp = null;
169
177
  }
170
178
  }
@@ -1,3 +1,4 @@
1
+ import {PWM_METHODS} from './pwm32x_playback.js';
1
2
  /** Render-clock event recording / looping for offline and Node Worker engines. */
2
3
  import {createMegaSynthOffline} from './megasynth_offline.js';
3
4
  import {MegaSynthRecordingManager} from './megasynth_recording.js';
@@ -112,6 +113,12 @@ class MegaSynthSession {
112
113
  this.#assertOpen(); if (!FM_METHODS.has(method) || !Array.isArray(args)) throw new Error('Invalid FM command');
113
114
  return this.fm[method](...args);
114
115
  }
116
+ callPWM(method, args = []) {
117
+ this.#assertOpen();
118
+ if (!this.#engine.pwm) throw new Error('Enable mega32X to use PWM');
119
+ if (!PWM_METHODS.has(method) || !Array.isArray(args)) throw new Error('Invalid PWM command');
120
+ return this.#engine.pwm[method](...args);
121
+ }
115
122
  async callLooper(method, args = []) {
116
123
  this.#assertOpen(); if (!LOOP_METHODS.has(method) || !Array.isArray(args)) throw new Error('Invalid looper command');
117
124
  if (method === 'exportAudio') {
package/node/README.md CHANGED
@@ -237,3 +237,15 @@ bufferFrames(512)、queueBlocks(4)、gain(0.25)、outputModule / out
237
237
  Transport は借りた chip を破棄しない。終了は `await transport.close(); chip.dispose();` の順。
238
238
  詳細と WorkletTransport の例は [soundchip.md](../web/soundchip.md) を参照。
239
239
  この入口は npm 0.2.6 以降で利用できる。
240
+
241
+ ### 32X PWM (MAME-derived)
242
+
243
+ Enable `new MegaSynthNode({mega32X: true, outputModule: null})`, then `await synth.start()`.
244
+ The `synth.pwm` methods (`write`, `read`, `reset`, `scheduleWrites`, `clearSchedule`, `getState`) run in the existing audio Worker.
245
+ `await synth.pwm.scheduleWrites([{frame: 0, register: 0, value: 5}, {frame: 0, register: 1, value: 1047}, {frame: 32, register: 4, value: 700}])` queues output-frame offsets relative to receipt of that batch.
246
+ `await synth.render(48000)` includes PWM in the FM/nativeFX mix; `connectOutput()` uses the same mixer.
247
+ The default integrated PWM output is cycle-normalized (`duty`, gain 1), like the VGM player. Raw MAME DAC scaling is available through `pwmOptions: {outputMode: 'dac', gain: .4}`.
248
+
249
+ For standalone PWM, use `createSoundChip('pwm', {outputMode: 'duty', gain: 1})` with `PWM32XAudifyTransport` from `tetorica-fm2612/node/transports`.
250
+ PWM frame scheduling is independent of FM event recording/looping; the PWM methods are not recorded as FM events.
251
+ These additions are available from npm 0.2.7.
@@ -1,3 +1,4 @@
1
+ import {PWM32XDirectTransport} from '../pwm32x_transport.js';
1
2
  import {YM2612DirectTransport} from '../ym2612synth.js';
2
3
  import {YM2608DirectTransport} from '../ym2608synth.js';
3
4
  import {GameboyDirectTransport} from '../gameboysynth.js';
@@ -91,3 +92,5 @@ export const YM2608AudifyTransport = audifyTransport(YM2608DirectTransport, 'ym2
91
92
  export const GameboyAudifyTransport = audifyTransport(GameboyDirectTransport, 'gameboy');
92
93
  export const SegaPSGAudifyTransport = audifyTransport(SegaPSGDirectTransport, 'segapsg');
93
94
  export const YM2151AudifyTransport = audifyTransport(RegisterDirectTransport, 'ym2151');
95
+
96
+ export const PWM32XAudifyTransport = audifyTransport(PWM32XDirectTransport, 'pwm');
@@ -1,3 +1,4 @@
1
+ import {PWM_METHODS} from '../pwm32x_playback.js';
1
2
  /** Experimental Node controller. PCM stays in the owned Worker. */
2
3
  import {Worker} from 'node:worker_threads';
3
4
  import {EventEmitter} from 'node:events';
@@ -17,6 +18,7 @@ export class MegaSynthNode extends EventEmitter {
17
18
  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
19
  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
20
  this.#options = structuredClone(options);
21
+ this.pwm = Object.fromEntries([...PWM_METHODS].map(method => [method, (...args) => this.#request('pwm', [method, args])]));
20
22
  this.fm = Object.fromEntries(methods.map(method => [method, (...args) => this.#request('fm', [method, args])]));
21
23
  this.recording = Object.fromEntries(['start', 'stop', 'export', 'import', 'play', 'stopPlayback', 'getState']
22
24
  .map(method => [method, (...args) => this.#request('recording', [method, args])]));
@@ -130,7 +130,8 @@ parentPort.on('message', message => {
130
130
  if (op === 'fm') {
131
131
  const [method, parameters] = args;
132
132
  result = synth.callFM(method, parameters);
133
- } else if (op === 'fx') synth.applyFX(args[0]);
133
+ } else if (op === 'pwm') result = synth.callPWM(...args);
134
+ else if (op === 'fx') synth.applyFX(args[0]);
134
135
  else if (op === 'recording') {
135
136
  const [method, parameters] = args;
136
137
  if (!['start', 'stop', 'export', 'import', 'play', 'stopPlayback', 'getState'].includes(method)) throw new Error('Invalid recording command');
@@ -152,7 +153,9 @@ parentPort.on('message', message => {
152
153
  });
153
154
  });
154
155
  const initialized = (async () => {
155
- synth = await createMegaSynthSession({...options.engineOptions, sampleRate,
156
+ synth = await createMegaSynthSession({...options.engineOptions,
157
+ mega32X: options.mega32X ?? options.engineOptions?.mega32X,
158
+ pwmOptions: options.pwmOptions ?? options.engineOptions?.pwmOptions, sampleRate,
156
159
  masterVolume: options.masterVolume ?? .25, signal: abort.signal});
157
160
  abort.signal.throwIfAborted();
158
161
  // null explicitly selects offline mode. With no selection, only a missing
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tetorica-fm2612",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "Tetorica sound chip WASM cores, Synth helpers and browser audio runtime",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -1,3 +1,4 @@
1
+ import {createPWM32XClient} from './pwm32x_playback.js';
1
2
  import {createYm2151Client} from './playground_ym2151.js';
2
3
  import {createSegaPsgClient} from './playground_segapsg.js';
3
4
  import {resolvePlaySeconds} from './playground_duration.js';
@@ -587,7 +588,7 @@ function createRun(sourceCode, presets, scaleIntervals, capabilities = {}, timin
587
588
  if(run.stopped)throw new Error('Run stopped');
588
589
  const token=run.token;
589
590
  const port=await request('pcm.create',[name]);
590
- const pcm=['ym2612', 'ym2203', 'ym2610'].includes(name) ? createOpnClient(name, port) : name === 'ym2151' ? createYm2151Client(port) : name === 'segapsg' ? createSegaPsgClient(port) : name === 'gameboy' ? createGameboyClient(port) : name === 'ym2608' ? createYm2608Client(port) : createRf5c164Client(port,source=>request('pcm.decode',[source]));
591
+ const pcm=name === 'pwm' ? createPWM32XClient(port) : ['ym2612', 'ym2203', 'ym2610'].includes(name) ? createOpnClient(name, port) : name === 'ym2151' ? createYm2151Client(port) : name === 'segapsg' ? createSegaPsgClient(port) : name === 'gameboy' ? createGameboyClient(port) : name === 'ym2608' ? createYm2608Client(port) : createRf5c164Client(port,source=>request('pcm.decode',[source]));
591
592
  if(run.stopped || token!==run.token){pcm.dispose();throw new Error('Run stopped');}
592
593
  pcmClients.add(pcm);return pcm;
593
594
  },
@@ -0,0 +1,24 @@
1
+ /** Commands travel directly from Main or logic Worker to the PWM AudioWorklet. */
2
+ export async function createPWM32XAudio(context, destination, options = {}) {
3
+ options.signal?.throwIfAborted();
4
+ await context.audioWorklet.addModule(new URL('./playground_pwm_worklet.js', import.meta.url));
5
+ options.signal?.throwIfAborted();
6
+ const node = new AudioWorkletNode(context, 'tetorica-pwm32x', {
7
+ numberOfInputs: 0, outputChannelCount: [2],
8
+ processorOptions: Object.fromEntries(['clock', 'gain', 'outputMode'].filter(key => options[key] !== undefined).map(key => [key, options[key]])),
9
+ });
10
+ try {
11
+ await new Promise((resolve, reject) => {
12
+ node.port.onmessage = ({data}) => {if (data.ready) resolve(); else if (data.error) reject(new Error(data.error));};
13
+ node.onprocessorerror = () => reject(new Error('PWM AudioWorklet failed'));
14
+ });
15
+ options.signal?.throwIfAborted();
16
+ } catch (error) {node.port.postMessage({method: 'dispose'}); node.disconnect(); node.port.close(); throw error;}
17
+ node.connect(destination);
18
+ const channel = new MessageChannel(); node.port.postMessage({port: channel.port1}, [channel.port1]);
19
+ let disposed = false;
20
+ return {port: channel.port2, dispose() {
21
+ if (disposed) return;
22
+ disposed = true; node.port.postMessage({method: 'dispose'}); node.disconnect(); node.port.close();
23
+ }};
24
+ }
@@ -0,0 +1,33 @@
1
+ import {PWM32XPlayback, PWM_METHODS} from './pwm32x_playback.js';
2
+
3
+ class PWMProcessor extends AudioWorkletProcessor {
4
+ constructor({processorOptions = {}}) {
5
+ super(); this.dead = false;
6
+ try {
7
+ this.pwm = new PWM32XPlayback({...processorOptions, sampleRate});
8
+ this.port.onmessage = ({data}) => {
9
+ if (data.port) {
10
+ this.clientPort = data.port;
11
+ data.port.onmessage = ({data: command}) => this.receive(command, this.clientPort);
12
+ data.port.start();
13
+ } else this.receive(data, this.port);
14
+ };
15
+ this.port.postMessage({ready: true});
16
+ } catch (error) {this.dead = true; this.port.postMessage({error: error.message});}
17
+ }
18
+ receive({method, args = [], id}, port) {
19
+ try {
20
+ if (method === 'dispose') {this.dead = true; this.pwm.dispose(); this.clientPort?.close(); return;}
21
+ if (this.dead || !PWM_METHODS.has(method)) throw new Error('Invalid PWM command');
22
+ const value = this.pwm[method](...args);
23
+ if (id !== undefined) port.postMessage({id, value});
24
+ } catch (error) {port.postMessage({id, error: error.message});}
25
+ }
26
+ process(_inputs, outputs) {
27
+ const [left, right] = outputs[0];
28
+ if (this.dead) {left.fill(0); right.fill(0); return false;}
29
+ const pcm = this.pwm.generateStereo(left.length);
30
+ left.set(pcm.left); right.set(pcm.right); return true;
31
+ }
32
+ }
33
+ registerProcessor('tetorica-pwm32x', PWMProcessor);
@@ -1,3 +1,5 @@
1
+ import {createPWM32XAudio} from './playground_pwm_audio.js';
2
+ import {createPWM32XClient} from './pwm32x_playback.js';
1
3
  import {createYm2151Audio} from './playground_ym2151_audio.js';
2
4
  import {createYm2151Client} from './playground_ym2151.js';
3
5
  import {createSegaPsgAudio} from './playground_segapsg_audio.js';
@@ -201,8 +203,8 @@ export function createPlaygroundRuntime(
201
203
  let sharedFm;
202
204
  let sharedFmSynth;
203
205
  async function openPcm(name, token = currentRunToken) {
204
- if(!['ym2612', 'ym2203', 'ym2610', 'rf5c164', 'ym2608', 'gameboy', 'segapsg', 'ym2151'].includes(name)) throw new Error('Unsupported Playground sound chip: ' + name);
205
- const createAudio = ['ym2612', 'ym2203', 'ym2610'].includes(name) ? (context, destination) => createOpnAudio(context, destination, name) : name === 'ym2151' ? createYm2151Audio : name === 'segapsg' ? createSegaPsgAudio : name === 'gameboy' ? createGameboyAudio : name === 'ym2608' ? createYm2608Audio : createRf5c164Audio;
206
+ if(!['ym2612', 'ym2203', 'ym2610', 'rf5c164', 'ym2608', 'gameboy', 'segapsg', 'ym2151', 'pwm'].includes(name)) throw new Error('Unsupported Playground sound chip: ' + name);
207
+ const createAudio = name === 'pwm' ? createPWM32XAudio : ['ym2612', 'ym2203', 'ym2610'].includes(name) ? (context, destination) => createOpnAudio(context, destination, name) : name === 'ym2151' ? createYm2151Audio : name === 'segapsg' ? createSegaPsgAudio : name === 'gameboy' ? createGameboyAudio : name === 'ym2608' ? createYm2608Audio : createRf5c164Audio;
206
208
  const device = await createAudio(megaDrive.audioContext, megaDrive.audio.masterInputNode);
207
209
  if(token !== currentRunToken){device.dispose();throw new Error('Run stopped');}
208
210
  pcmDevices.add(device);return device;
@@ -1359,7 +1361,7 @@ export function createPlaygroundRuntime(
1359
1361
  },
1360
1362
  createSoundChip: async name => {
1361
1363
  const device=await openPcm(name,runToken);
1362
- const client=['ym2612', 'ym2203', 'ym2610'].includes(name) ? createOpnClient(name, device.port) : name === 'ym2151' ? createYm2151Client(device.port) : name === 'segapsg' ? createSegaPsgClient(device.port) : name === 'gameboy' ? createGameboyClient(device.port) : name === 'ym2608' ? createYm2608Client(device.port) : createRf5c164Client(device.port,decodePcm);
1364
+ const client=name === 'pwm' ? createPWM32XClient(device.port) : ['ym2612', 'ym2203', 'ym2610'].includes(name) ? createOpnClient(name, device.port) : name === 'ym2151' ? createYm2151Client(device.port) : name === 'segapsg' ? createSegaPsgClient(device.port) : name === 'gameboy' ? createGameboyClient(device.port) : name === 'ym2608' ? createYm2608Client(device.port) : createRf5c164Client(device.port,decodePcm);
1363
1365
  const dispose=device.dispose;
1364
1366
  device.dispose=()=>{client.dispose();dispose();};
1365
1367
  return client;
@@ -4,7 +4,7 @@ export function createSoundChipRegistry() {
4
4
  let generation = 0;
5
5
  return {
6
6
  use(name, options, resolve, {evictOnDispose = !['ym2612', 'ym2203', 'ym2610'].includes(name)} = {}) {
7
- if (!['ym2612', 'ym2203', 'ym2610', 'rf5c164', 'ym2608', 'gameboy', 'segapsg', 'ym2151'].includes(name)) {
7
+ if (!['ym2612', 'ym2203', 'ym2610', 'rf5c164', 'ym2608', 'gameboy', 'segapsg', 'ym2151', 'pwm'].includes(name)) {
8
8
  return Promise.reject(new Error(`Unsupported useSoundChip name: ${String(name)}`));
9
9
  }
10
10
  if (options !== undefined && (!options || typeof options !== 'object' || Array.isArray(options) || Reflect.ownKeys(options).length)) {
package/pwm32x.js ADDED
@@ -0,0 +1,98 @@
1
+ // license:BSD-3-Clause
2
+ // copyright-holders:David Haywood
3
+ // FIFO, routing and timer behavior adapted from MAME mega32x.cpp.
4
+ // See third_party/mame-32x-pwm/README.md for provenance and differences.
5
+ export const PWM32X_CLOCK = 23011361;
6
+ export class PWM32X {
7
+ #states = new WeakMap();
8
+ constructor({clock = PWM32X_CLOCK, sampleRate = 48000, gain = .4, outputMode = 'dac'} = {}) {
9
+ if (!['dac', 'duty'].includes(outputMode)) throw new RangeError('Invalid PWM output mode');
10
+ if (!Number.isFinite(clock) || clock <= 0 || clock > 100000000) throw new RangeError('Invalid PWM clock');
11
+ if (!Number.isInteger(sampleRate) || sampleRate <= 0 || sampleRate > 1000000) throw new RangeError('Invalid PWM sample rate');
12
+ if (!Number.isFinite(gain) || gain < 0 || gain > 4) throw new RangeError('Invalid PWM gain');
13
+ this.clock = clock; this.rate = sampleRate; this.gain = gain; this.outputMode = outputMode; this.muted = false; this.closed = false; this.reset();
14
+ }
15
+ sampleRate() {return this.rate;}
16
+ assertOpen() {if (this.closed) throw new Error('PWM chip is disposed');}
17
+ reset() {
18
+ this.assertOpen(); this.control = 0; this.cycle = 0; this.cycleRegister = 0;
19
+ this.leftFifo = []; this.rightFifo = []; this.left = null; this.right = null;
20
+ this.timerTick = 0; this.interruptCount = 0; this.untilTick = 0;
21
+ }
22
+ active() {return this.cycle !== 1 && (this.control & 15) !== 0;}
23
+ configureTimer() {
24
+ if (!this.cycle) this.cycle = 4095;
25
+ if (this.active()) {
26
+ this.timerTick = 0; this.leftFifo = []; this.rightFifo = [];
27
+ this.untilTick = this.cycle - 1;
28
+ }
29
+ }
30
+ write(register, value) {this.writeRegister(register, value);}
31
+ writeRegister(register, value) {
32
+ this.assertOpen();
33
+ if (!Number.isInteger(register) || register < 0 || register > 4 || !Number.isInteger(value)) throw new RangeError('Invalid PWM register write');
34
+ const push = fifo => {if (fifo.length === 3) fifo.shift(); fifo.push(value & 0xffff);};
35
+ if (register === 0) {this.control = value & 0xffff; this.configureTimer();}
36
+ else if (register === 1) {this.cycleRegister = this.cycle = value & 4095; this.configureTimer();}
37
+ else {if (register === 2 || register === 4) push(this.leftFifo); if (register === 3 || register === 4) push(this.rightFifo);}
38
+ }
39
+ read(register) {
40
+ this.assertOpen();
41
+ const flag = fifo => fifo.length === 0 ? 0x4000 : fifo.length === 3 ? 0x8000 : 0;
42
+ if (register === 0) return this.control;
43
+ if (register === 1) return this.cycleRegister;
44
+ if (register === 2) return flag(this.leftFifo);
45
+ if (register === 3) return flag(this.rightFifo);
46
+ if (register === 4) return flag(this.leftFifo) & flag(this.rightFifo);
47
+ return 0xffff;
48
+ }
49
+ tick() {
50
+ if (this.leftFifo.length) {
51
+ const value = this.leftFifo.shift(), mode = this.control & 3;
52
+ if (mode === 1) this.left = value; else if (mode === 2) this.right = value;
53
+ }
54
+ if (this.rightFifo.length) {
55
+ const value = this.rightFifo.shift(), mode = (this.control >> 2) & 3;
56
+ if (mode === 1) this.right = value; else if (mode === 2) this.left = value;
57
+ }
58
+ this.timerTick++;
59
+ if (this.timerTick === (((this.control >> 8) & 15) || 16)) {this.timerTick = 0; this.interruptCount++;}
60
+ }
61
+ output() {
62
+ const scale = this.outputMode === 'duty' ? (this.cycle || 4095) / 2 : 2048;
63
+ const sample = value => value === null ? 0 : ((value & 4095) / scale - 1) * this.gain;
64
+ return this.muted ? [0, 0] : [sample(this.left), sample(this.right)];
65
+ }
66
+ generateStereo(frames) {
67
+ this.assertOpen();
68
+ if (!Number.isInteger(frames) || frames < 0) throw new RangeError('Invalid PWM frame count');
69
+ const left = new Float32Array(frames), right = new Float32Array(frames), cyclesPerFrame = this.clock / this.rate;
70
+ for (let frame = 0; frame < frames; frame++) {
71
+ let remaining = cyclesPerFrame, l = 0, r = 0;
72
+ while (remaining > 0) {
73
+ const duration = this.active() ? Math.min(remaining, this.untilTick) : remaining;
74
+ const [a, b] = this.output(); l += a * duration; r += b * duration; remaining -= duration;
75
+ if (this.active()) {
76
+ this.untilTick -= duration;
77
+ if (this.untilTick <= 0) {this.tick(); this.untilTick = this.cycle - 1;}
78
+ }
79
+ }
80
+ left[frame] = l / cyclesPerFrame; right[frame] = r / cyclesPerFrame;
81
+ }
82
+ return {left, right};
83
+ }
84
+ supportsState() {return !this.closed;}
85
+ saveState() {
86
+ this.assertOpen(); const state = Object.freeze({byteLength: 128});
87
+ this.#states.set(state, {control:this.control, cycle:this.cycle, cycleRegister:this.cycleRegister,
88
+ leftFifo:this.leftFifo.slice(), rightFifo:this.rightFifo.slice(), left:this.left, right:this.right,
89
+ timerTick:this.timerTick, interruptCount:this.interruptCount, untilTick:this.untilTick});
90
+ return state;
91
+ }
92
+ validateState(state) {this.assertOpen(); if (!this.#states.has(state)) throw new Error('Incompatible PWM state');}
93
+ loadState(state) {
94
+ this.validateState(state); const data = this.#states.get(state);
95
+ Object.assign(this, data, {leftFifo:data.leftFifo.slice(), rightFifo:data.rightFifo.slice()});
96
+ }
97
+ dispose() {this.closed = true; this.leftFifo = []; this.rightFifo = [];}
98
+ }
@@ -0,0 +1,80 @@
1
+ import {PWM32X} from './pwm32x.js';
2
+
3
+ /** MAME-derived PWM plus output-frame scheduling; no timers or audio device. */
4
+ export class PWM32XPlayback {
5
+ constructor(options = {}, chip) {
6
+ this.chip = chip ?? new PWM32X({outputMode: 'duty', gain: 1, ...options});
7
+ this.frame = 0; this.queue = []; this.order = 0;
8
+ }
9
+ sampleRate() {return this.chip.sampleRate();}
10
+ write(register, value) {this.chip.writeRegister(register, value);}
11
+ writeRegister(register, value) {this.write(register, value);}
12
+ read(register) {return this.chip.read(register);}
13
+ reset() {this.chip.reset(); this.queue.length = 0;}
14
+ /** Entries are relative to the next output frame when this command is received. */
15
+ scheduleWrites(entries) {
16
+ this.chip.assertOpen();
17
+ if (!Array.isArray(entries) || entries.length + this.queue.length > 1000000) throw new RangeError('Invalid PWM write queue');
18
+ const pending = entries.map(({frame, register, value}) => {
19
+ if (!Number.isSafeInteger(frame) || frame < 0 || !Number.isSafeInteger(this.frame + frame) ||
20
+ !Number.isInteger(register) || register < 0 || register > 4 ||
21
+ !Number.isInteger(value) || value < 0 || value > 65535) throw new RangeError('Invalid PWM scheduled write');
22
+ return {frame: this.frame + frame, register, value};
23
+ });
24
+ for (const entry of pending) this.queue.push({...entry, order: this.order++});
25
+ this.queue.sort((a, b) => a.frame - b.frame || a.order - b.order);
26
+ return this.frame;
27
+ }
28
+ clearSchedule() {this.chip.assertOpen(); this.queue.length = 0;}
29
+ getState() {return {model: 'mame', outputMode: this.chip.outputMode, clock: this.chip.clock,
30
+ sampleRate: this.sampleRate(), currentFrame: this.frame, queuedWrites: this.queue.length};}
31
+ generateStereo(frames) {
32
+ this.chip.assertOpen();
33
+ if (!Number.isSafeInteger(frames) || frames < 0 || frames > 10000000 || !Number.isSafeInteger(this.frame + frames)) throw new RangeError('Invalid PWM render frames');
34
+ const left = new Float32Array(frames), right = new Float32Array(frames);
35
+ let offset = 0, head = 0;
36
+ while (true) {
37
+ while (this.queue[head]?.frame <= this.frame) {
38
+ const entry = this.queue[head++]; this.write(entry.register, entry.value);
39
+ }
40
+ if (offset === frames) break;
41
+ const count = Math.min(frames - offset, (this.queue[head]?.frame ?? Infinity) - this.frame);
42
+ const pcm = this.chip.generateStereo(count);
43
+ left.set(pcm.left, offset); right.set(pcm.right, offset);
44
+ offset += count; this.frame += count;
45
+ }
46
+ if (head) this.queue.splice(0, head);
47
+ return {left, right, sampleRate: this.sampleRate()};
48
+ }
49
+ dispose() {this.queue.length = 0; this.chip.dispose();}
50
+ }
51
+
52
+ export const PWM_METHODS = new Set(['write', 'writeRegister', 'read', 'reset', 'scheduleWrites', 'clearSchedule', 'getState']);
53
+
54
+ /** Main or logic Worker client; PCM and scheduling stay in the AudioWorklet. */
55
+ export function createPWM32XClient(port) {
56
+ let id = 0, disposed = false;
57
+ const pending = new Map();
58
+ port.onmessage = ({data}) => {
59
+ const request = pending.get(data.id);
60
+ if (!request) return;
61
+ pending.delete(data.id);
62
+ data.error ? request.reject(new Error(data.error)) : request.resolve(data.value);
63
+ };
64
+ port.start();
65
+ const client = Object.fromEntries([...PWM_METHODS].map(method => [method, (...args) => {
66
+ if (disposed) return Promise.reject(new Error('PWM client disposed'));
67
+ return new Promise((resolve, reject) => {
68
+ const key = ++id; pending.set(key, {resolve, reject});
69
+ try {port.postMessage({method, args, id: key});}
70
+ catch (error) {pending.delete(key); reject(error);}
71
+ });
72
+ }]));
73
+ client.dispose = () => {
74
+ if (disposed) return;
75
+ disposed = true; port.postMessage({method: 'dispose'}); port.close();
76
+ for (const request of pending.values()) request.reject(new Error('PWM client disposed'));
77
+ pending.clear();
78
+ };
79
+ return client;
80
+ }
@@ -0,0 +1,32 @@
1
+ import {PWM32X} from './pwm32x.js';
2
+ import {PWM32XPlayback, PWM_METHODS} from './pwm32x_playback.js';
3
+
4
+ /** Main-side command API; chip rendering and the schedule live in AudioWorklet. */
5
+ export class PWM32XWorkletTransport {
6
+ constructor(chip) {
7
+ if (chip.execution !== 'worklet' || chip.name !== 'pwm') throw new TypeError('Expected a PWM worklet endpoint');
8
+ this.chip = chip;
9
+ for (const method of PWM_METHODS) this[method] = (...args) => chip.request(method, args);
10
+ }
11
+ start() {return this.chip.start();}
12
+ stop() {return this.chip.stop();}
13
+ flush() {return this.chip.request('barrier');}
14
+ close() {return this.chip.dispose();}
15
+ }
16
+
17
+ /** Explicit PCM rendering for WAV export or a consumer-owned output. */
18
+ export class PWM32XDirectTransport {
19
+ constructor(chip) {
20
+ if (chip instanceof PWM32X) chip = new PWM32XPlayback({}, chip);
21
+ if (!(chip instanceof PWM32XPlayback)) throw new TypeError('Expected a PWM chip');
22
+ this.chip = chip;
23
+ }
24
+ write(register, value) {this.chip.write(register, value);}
25
+ writeRegister(register, value) {this.chip.writeRegister(register, value);}
26
+ read(register) {return this.chip.read(register);}
27
+ reset() {this.chip.reset();}
28
+ scheduleWrites(entries) {return this.chip.scheduleWrites(entries);}
29
+ clearSchedule() {this.chip.clearSchedule();}
30
+ getState() {return this.chip.getState();}
31
+ generateStereo(frames) {return this.chip.generateStereo(frames);}
32
+ }
@@ -61,6 +61,8 @@
61
61
  "playground_opn.js",
62
62
  "playground_opn_audio.js",
63
63
  "playground_opn_worklet.js",
64
+ "playground_pwm_audio.js",
65
+ "playground_pwm_worklet.js",
64
66
  "playground_rf5c164.js",
65
67
  "playground_rf5c164_audio.js",
66
68
  "playground_runtime.js",
@@ -78,6 +80,9 @@
78
80
  "playground_ym2608_audio.js",
79
81
  "playground_ym2608_timeline.js",
80
82
  "playground_ym2608_worklet.js",
83
+ "pwm32x.js",
84
+ "pwm32x_playback.js",
85
+ "pwm32x_transport.js",
81
86
  "rf5c164-worklet.js",
82
87
  "rf5c164.js",
83
88
  "rf5c164_pcm.js",
package/s98_file.js CHANGED
@@ -40,10 +40,10 @@ export function convertS98ToVgm(source) {
40
40
  }
41
41
  }
42
42
  if (!devices.length) devices.push({ type: 4, clock: 7987200, pan: 0 });
43
- if (devices.length !== 1) fail("multiple devices are not supported; use one YM2203, YM2608 or YM2612");
43
+ if (devices.length !== 1) fail("multiple devices are not supported; use one YM2203, YM2608, YM2612 or YM2151");
44
44
  const device = devices[0];
45
- const config = { 2: [0x55, 0x44, "YM2203"], 3: [0x52, 0x2c, "YM2612"], 4: [0x56, 0x48, "YM2608"] }[device.type];
46
- if (!config) fail(`unsupported device type ${device.type}; supported: YM2203, YM2608, YM2612`);
45
+ const config = { 2: [0x55, 0x44, "YM2203"], 3: [0x52, 0x2c, "YM2612"], 4: [0x56, 0x48, "YM2608"], 5: [0x54, 0x30, "YM2151"] }[device.type];
46
+ if (!config) fail(`unsupported device type ${device.type}; supported: YM2203, YM2608, YM2612, YM2151`);
47
47
  if (!device.clock || device.clock >= 0x40000000) fail("invalid device clock");
48
48
  if (device.pan) fail("device-level panning is not supported");
49
49
  const output = new Array(0x100).fill(0);
@@ -82,7 +82,7 @@ export function convertS98ToVgm(source) {
82
82
  wait(value + 2);
83
83
  continue;
84
84
  }
85
- if (command > 1 || (device.type === 2 && command === 1)) fail(`invalid device/port command ${command}`);
85
+ if (command > 1 || ([2, 5].includes(device.type) && command === 1)) fail(`invalid device/port command ${command}`);
86
86
  if (pos + 2 > dataEnd) fail("truncated register write");
87
87
  output.push(config[0] + command, bytes[pos++], bytes[pos++]);
88
88
  }
@@ -1,3 +1,4 @@
1
+ import {PWM32XPlayback, PWM_METHODS} from './pwm32x_playback.js';
1
2
  import {Ym2612} from './ym2612.js';
2
3
  import {Ym2608} from './ym2608.js';
3
4
  import {Ym2151} from './ym2151.js';
@@ -15,15 +16,15 @@ import {YM2612DacPlayer} from './ym2612_dac.js';
15
16
 
16
17
  const profiles = {ym2612: [Ym2612, ym2612Factory], ym2608: [Ym2608, ym2608Factory],
17
18
  ym2151: [Ym2151, ym2151Factory], gameboy: [GameboyApu, gameboyFactory], segapsg: [SegaPSG, psgFactory]};
18
- const createSoundChip = createSoundChipFactory(Object.fromEntries(Object.entries(profiles).map(([name, [Type, moduleFactory]]) =>
19
- [name, options => Type.create({...options, moduleFactory})])));
19
+ const createSoundChip = createSoundChipFactory(Object.fromEntries([...Object.entries(profiles).map(([name, [Type, moduleFactory]]) =>
20
+ [name, options => Type.create({...options, moduleFactory})]), ['pwm', options => new PWM32XPlayback(options)]]));
20
21
 
21
22
  class SoundChipProcessor extends AudioWorkletProcessor {
22
23
  constructor({processorOptions: {name, chipOptions, wasmBinary}}) {
23
24
  super(); this.dead = false; this.running = false; this.name = name; this.remotePorts = new Set();
24
25
  this.scheduled = []; this.banks = new Map();
25
26
  this.port.onmessage = ({data}) => this.receive(data);
26
- createSoundChip(name, {...chipOptions, ...(name === 'gameboy' || name === 'segapsg' ? {sampleRate} : {}), moduleOptions: {wasmBinary}})
27
+ createSoundChip(name, {...chipOptions, ...(name === 'gameboy' || name === 'segapsg' || name === 'pwm' ? {sampleRate} : {}), moduleOptions: {wasmBinary}})
27
28
  .then(chip => {
28
29
  if (this.dead) {chip.dispose(); return;}
29
30
  this.chip = chip;
@@ -51,6 +52,7 @@ class SoundChipProcessor extends AudioWorkletProcessor {
51
52
  let value;
52
53
  if (method === 'start') this.running = true;
53
54
  else if (method === 'stop') this.running = false;
55
+ else if (this.name === 'pwm' && PWM_METHODS.has(method)) value = this.chip[method](...args);
54
56
  else if (method === 'reset') {this.pcmDac?.reset(); this.direct ? this.direct.reset() : this.chip.reset(); this.renderer.resetHistory();}
55
57
  else if (method === 'write') {
56
58
  if (data.type) {
package/soundchip.js CHANGED
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { createSoundChipFactory } from './soundchip_factory.js';
7
7
  import {createWorkletSoundChip} from './soundchip_worklet.js';
8
+ import {PWM32X} from './pwm32x.js';
8
9
  export {encodeWav} from './wav.js';
9
10
 
10
11
  /**
@@ -142,6 +143,7 @@ export function createSoundChip(name, options = {}) {
142
143
  if (options.moduleFactory) return Promise.reject(new Error('Worklet execution uses the packaged chip factory'));
143
144
  const moduleName = name === 'gameboy' ? 'gameboy_apu' : name;
144
145
  return createWorkletSoundChip(name, options, async () => {
146
+ if (name === 'pwm') return undefined;
145
147
  const loaded = await loadModule(moduleName, options);
146
148
  const bytes = loaded.moduleOptions.wasmBinary;
147
149
  if (!bytes) throw new Error('Worklet execution requires WASM bytes; use wasmBinary or default asset loading');
@@ -149,5 +151,8 @@ export function createSoundChip(name, options = {}) {
149
151
  });
150
152
  }
151
153
  if (options.execution !== undefined && options.execution !== 'direct') return Promise.reject(new Error('Unknown sound-chip execution mode'));
154
+ if (name === 'pwm') {
155
+ return Promise.resolve().then(() => {options.signal?.throwIfAborted(); return new PWM32X(options);});
156
+ }
152
157
  return createLocalSoundChip(name, options);
153
158
  }
package/soundchip.md CHANGED
@@ -113,3 +113,40 @@ chip の `dispose()` は利用者の責任で、Transport を閉じてから行
113
113
  DirectTransport は、手元で `generateStereo()` により PCM を生成し、WAV 保存や利用者の出力へ渡す用途に使う。
114
114
  examples の `transport/direct/01-single-note` に PCM 生成・連結・Web 再生・WAV 保存をすべて記述する。
115
115
  これらの追加入口は npm 0.2.6 以降で利用できる。
116
+
117
+ ## 32X PWM 共通コア(0.2.7)
118
+
119
+ `createSoundChip('pwm', {clock: 23011361, sampleRate: 48000})` は MAME 由来の
120
+ FIFO・タイマー処理を持つ JavaScript コアを生成する。WASM・音声デバイスは不要。
121
+ レジスタ0〜4を `writeRegister(register, value)` で設定し、`generateStereo(frames)` で進める。
122
+ `reset` / `read` / `saveState` / `loadState` / `dispose` に対応。
123
+
124
+ npm 0.2.7 以降で利用できる。共通Worklet / Audify Transport、
125
+ MegaSynth / Playground / Node の入口を追加済み。利用方法は以下を参照。
126
+ VGM比較には `pwmModel: 'mame'` を使う。VGM側はcycle基準の振幅に揃える。
127
+ 元の固定DAC換算を使う場合は `pwmOutputMode: 'dac'`。コア単体の既定はDAC換算、Analyzer/CLIのVGM再生の既定はMAME由来方式とcycle基準の振幅。
128
+ 従来方式は `pwmModel: legacy` で選べる。
129
+ 詳しくは `docs/issues/pwm32x_01.md` と `docs/demos/32x-pwm-compare.html` を参照。
130
+
131
+ ### 32X PWM runtime (0.2.7)
132
+
133
+ The MAME-derived core is now available in MegaSynth (`new MegaSynth({mega32X: true})` / `synth.pwm` after `start()`), MegaSynthNode (`mega32X: true`) and Playground (`await useSoundChip('pwm')`).
134
+ Browser synthesis runs in AudioWorklet; MegaSynthNode generates it in its audio Worker. `scheduleWrites([{frame, register, value}, ...])` uses output-frame offsets relative to receipt of the batch. `getState().sampleRate` gives the units; these are not VGM 44,100 Hz offsets.
135
+
136
+ Standalone browser output:
137
+
138
+ ```js
139
+ import {createSoundChip} from 'tetorica-fm2612';
140
+ import {PWM32XWorkletTransport} from 'tetorica-fm2612/pwm32x_transport.js';
141
+ const chip = await createSoundChip('pwm', {execution: 'worklet'});
142
+ const transport = new PWM32XWorkletTransport(chip);
143
+ await transport.write(0, 5);
144
+ await transport.write(1, 1047);
145
+ await transport.write(4, 700);
146
+ await transport.start();
147
+ // await transport.close() when finished.
148
+ ```
149
+
150
+ The runtime wrappers use `duty` output with core gain 1; low-level direct `createSoundChip('pwm')` keeps raw `dac` gain .4. The Worklet endpoint's `gain` controls output volume (default .25).
151
+ For standalone Node playback, use `PWM32XAudifyTransport` from `tetorica-fm2612/node/transports`; it accepts the direct factory chip, wraps the same frame scheduler and borrows rather than disposes that chip. `PWM32XDirectTransport` generates PCM for a consumer-owned output or WAV export.
152
+ These APIs are available from npm 0.2.7. A PCM `loadSample`/`play` facade is not included; register writes and scheduling are available.
@@ -1,5 +1,5 @@
1
1
  /** Main-side chip endpoint. The actual WASM chip is created inside AudioWorklet. */
2
- const supported = new Set(['ym2612', 'ym2608', 'gameboy', 'segapsg', 'ym2151']);
2
+ const supported = new Set(['ym2612', 'ym2608', 'gameboy', 'segapsg', 'ym2151', 'pwm']);
3
3
  export async function createWorkletSoundChip(name, options, loadBinary) {
4
4
  if (!supported.has(name)) throw new Error(`Worklet chip not supported: ${name}`);
5
5
  options.signal?.throwIfAborted();
@@ -42,7 +42,7 @@ export async function createWorkletSoundChip(name, options, loadBinary) {
42
42
  const wasmBinary = await loadBinary();
43
43
  await context.audioWorklet.addModule(new URL('./soundchip-output-worklet.js', import.meta.url).href);
44
44
  options.signal?.throwIfAborted();
45
- const chipOptions = Object.fromEntries(['clock', 'sampleRate', 'flags', 'variant'].filter(key => options[key] !== undefined).map(key => [key, options[key]]));
45
+ const chipOptions = Object.fromEntries(['clock', 'sampleRate', 'flags', 'variant', 'outputMode'].filter(key => options[key] !== undefined).map(key => [key, options[key]]));
46
46
  node = new AudioWorkletNode(context, 'tetorica-soundchip', {
47
47
  numberOfInputs: 0, outputChannelCount: [2],
48
48
  processorOptions: {name, chipOptions, wasmBinary},