tetorica-fm2612 0.2.2 → 0.2.4

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
@@ -54,6 +54,42 @@ Both `tetorica-fm2612/ym2612` and `tetorica-fm2612/ym2612.js` are available.
54
54
  Synth APIs vary by chip; directly generating PCM does not play it on a speaker.
55
55
  No Node audio output dependency (`audioworklet`) is installed by this package.
56
56
 
57
+ ## Automatic WASM loading and WAV export
58
+
59
+ Since `0.2.3`, the default package entry exports `encodeWav` and default
60
+ browser WASM loading works without separate WASM options.
61
+ `await createSoundChip('ym2612')` loads the generated JS and WASM beside the
62
+ runtime without separate WASM options. Node reads file URLs; browsers/Workers
63
+ fetch HTTP URLs. `signal`, `assetBaseUrl`, explicit `wasmBinary` and injected
64
+ `moduleFactory` remain available for advanced asset loading.
65
+
66
+ ```js
67
+ import {createSoundChip, encodeWav} from 'tetorica-fm2612';
68
+ import {YM2612Synth, YM2612DirectTransport} from 'tetorica-fm2612/ym2612synth.js';
69
+ import {FM_PRESETS} from 'tetorica-fm2612/megasynth-fm-presets.js';
70
+
71
+ const chip = await createSoundChip('ym2612');
72
+ let wav;
73
+ try {
74
+ const transport = new YM2612DirectTransport(chip);
75
+ const synth = new YM2612Synth({transport});
76
+ synth.setPreset(0, FM_PRESETS.sine);
77
+ synth.noteOn(0, 4, 553);
78
+ const pcm = transport.generateStereo(chip.sampleRate());
79
+ wav = encodeWav({...pcm, sampleRate: chip.sampleRate()}, {gain: 0.25});
80
+ } finally {
81
+ chip.dispose();
82
+ }
83
+ ```
84
+
85
+ `encodeWav` returns `Uint8Array` containing mono/stereo PCM16 RIFF WAV.
86
+ It accepts `{left, right, sampleRate}`, `{channels, sampleRate}`, or AudioBuffer.
87
+ The default gain is 1; values outside -1..1 are clipped. Sample rate is a
88
+ positive integer. Node can save the returned bytes with
89
+ `await writeFile('tone.wav', wav)` from `node:fs/promises`; browsers can create
90
+ `new Blob([wav], {type: 'audio/wav'})` for a download or media player.
91
+ Chip creation, PCM generation and WAV encoding do not create an audio device.
92
+
57
93
  ## Browser runtime
58
94
 
59
95
  Browser-only modules are included through separate module entry points:
@@ -196,10 +232,10 @@ FM/PSG/PCM mixing, stop/reset and close/restart. Playwright is a development
196
232
  dependency; it is not required by users of the sound-chip runtime.
197
233
 
198
234
  The build is staged in `dist/fm2612/`; packing produces
199
- `tetorica-fm2612-0.2.2.tgz`. To install a local build in another project:
235
+ `tetorica-fm2612-0.2.4.tgz`. To install a local build in another project:
200
236
 
201
237
  ```sh
202
- npm install /absolute/path/to/tetorica-fm2612-0.2.2.tgz
238
+ npm install /absolute/path/to/tetorica-fm2612-0.2.4.tgz
203
239
  ```
204
240
 
205
241
  The existing `tetorica-vgm` CLI package is built separately. This first package
@@ -215,6 +251,16 @@ and generator. External instrument/sample ROMs are not included.
215
251
 
216
252
  ## Release notes
217
253
 
254
+ `0.2.4` removes the ymfm YM2612 DAC ladder's idle offset from AudioWorklet
255
+ output and keeps output silent until FM/PSG initialization completes. This
256
+ reduces clicks when browser audio starts or disconnects. Raw chip PCM remains
257
+ unchanged.
258
+
259
+ `0.2.3` adds common `encodeWav()` for mono/stereo PCM16 WAV bytes and fixes
260
+ default browser/Worker `createSoundChip()` loading by reading WASM internally.
261
+ Node and browsers use the same chip creation and WAV encoding API; output
262
+ file saving or Blob/media playback remains the embedding application's choice.
263
+
218
264
  `0.2.2` adds YM2608 ADPCM-B `loadSample()` for decoded PCM, AudioBuffer and
219
265
  PCM/Float WAV sources, with mono conversion, ADPCM-B encoding, memory upload
220
266
  and range/rate setup. Worklet memory uploads are acknowledged, and OPN browser
package/RUNTIME.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Full web runtime
2
2
 
3
- Includes all 132 top-level web runtime modules and 23 generated chip/engine pairs.
3
+ Includes all 133 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tetorica-fm2612",
3
- "version": "0.2.2",
3
+ "version": "0.2.4",
4
4
  "description": "Tetorica sound chip WASM cores, Synth helpers and browser audio runtime",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",
@@ -94,6 +94,7 @@
94
94
  "vgm_file.js",
95
95
  "vgm_runtime.js",
96
96
  "vgmplayer.js",
97
+ "wav.js",
97
98
  "y8950.js",
98
99
  "y8950audioengine.js",
99
100
  "ym2151.js",
package/soundchip.js CHANGED
@@ -4,14 +4,17 @@
4
4
  * 動的 import の配布方法はバンドラーに依存するため、この入口はサイズ削減を保証しない。
5
5
  */
6
6
  import { createSoundChipFactory } from './soundchip_factory.js';
7
+ export {encodeWav} from './wav.js';
7
8
 
8
9
  /**
9
10
  * @typedef {Object} SoundChipOptions
10
11
  * @property {URL|string} [assetBaseUrl] 生成済み *_wasm.js / .wasm のディレクトリURL(末尾 /)。
11
12
  * @property {Function} [moduleFactory] 注入する Emscripten factory。指定時は自動ロードを省略。
12
13
  * @property {Object} [moduleOptions] wasmBinary、locateFile などをそのまま渡す。
14
+ * @property {AbortSignal} [signal] WASM ファイルの読み込みを中断する。
13
15
  */
14
16
  async function loadModule(name, options = {}) {
17
+ options.signal?.throwIfAborted();
15
18
  if (options.moduleFactory) return options;
16
19
  // Source tree: web/ -> docs/generated/. Published tree: js/ -> generated/.
17
20
  const base = new URL(options.assetBaseUrl ??
@@ -22,11 +25,16 @@ async function loadModule(name, options = {}) {
22
25
  const wasmUrl = new URL(`${name}_wasm.wasm`, base);
23
26
  if (wasmUrl.protocol === 'file:' && typeof process !== 'undefined' && process.versions?.node) {
24
27
  const { readFile } = await import('node:fs/promises');
25
- moduleOptions.wasmBinary = await readFile(wasmUrl);
28
+ moduleOptions.wasmBinary = await readFile(wasmUrl, {signal: options.signal});
26
29
  } else {
27
- moduleOptions.locateFile = path => new URL(path, base).href;
30
+ // Not all generated loaders accept locateFile. Read the bytes ourselves
31
+ // and pass the supported wasmBinary option in every environment.
32
+ const response = await fetch(wasmUrl, {signal: options.signal});
33
+ if (!response.ok) throw new Error(`Failed to load ${name} WASM: HTTP ${response.status}`);
34
+ moduleOptions.wasmBinary = new Uint8Array(await response.arrayBuffer());
28
35
  }
29
36
  }
37
+ options.signal?.throwIfAborted();
30
38
  return { moduleFactory, moduleOptions };
31
39
  }
32
40
 
package/wav.js ADDED
@@ -0,0 +1,33 @@
1
+ /** Browser / Worker / Node: decoded mono/stereo PCM -> PCM16 RIFF WAV bytes.
2
+ * Does not create AudioContext, save a file or play audio.
3
+ */
4
+ export function encodeWav(pcm, {gain = 1} = {}) {
5
+ const sampleRate = pcm?.sampleRate;
6
+ const channels = typeof pcm?.getChannelData === 'function'
7
+ ? Array.from({length: pcm.numberOfChannels}, (_, i) => pcm.getChannelData(i))
8
+ : pcm?.channels ?? (pcm?.right ? [pcm.left, pcm.right] : [pcm?.left]);
9
+ if (!Number.isInteger(sampleRate) || sampleRate < 1 || sampleRate > 0xffffffff) throw new RangeError('WAV sampleRate must be a positive integer');
10
+ if (!Array.isArray(channels) || ![1, 2].includes(channels.length)) throw new TypeError('WAV requires mono or stereo PCM');
11
+ const frames = channels[0]?.length;
12
+ if (!Number.isSafeInteger(frames) || frames < 1 || channels.some(channel => channel?.length !== frames)) throw new RangeError('WAV channel lengths must match and be nonempty');
13
+ if (!Number.isFinite(gain) || gain < 0) throw new RangeError('WAV gain must be finite and nonnegative');
14
+ const blockAlign = channels.length * 2, dataSize = frames * blockAlign;
15
+ if (dataSize > 0xffffffff - 36 || sampleRate * blockAlign > 0xffffffff) throw new RangeError('PCM exceeds RIFF WAV limits');
16
+ const bytes = new Uint8Array(44 + dataSize), view = new DataView(bytes.buffer);
17
+ const writeText = (offset, value) => {
18
+ for (let i = 0; i < value.length; i++) view.setUint8(offset + i, value.charCodeAt(i));
19
+ };
20
+ writeText(0, 'RIFF'); view.setUint32(4, 36 + dataSize, true);
21
+ writeText(8, 'WAVE'); writeText(12, 'fmt '); view.setUint32(16, 16, true);
22
+ view.setUint16(20, 1, true); view.setUint16(22, channels.length, true);
23
+ view.setUint32(24, sampleRate, true); view.setUint32(28, sampleRate * blockAlign, true);
24
+ view.setUint16(32, blockAlign, true); view.setUint16(34, 16, true);
25
+ writeText(36, 'data'); view.setUint32(40, dataSize, true);
26
+ for (let i = 0; i < frames; i++) for (let channel = 0; channel < channels.length; channel++) {
27
+ const input = channels[channel][i];
28
+ if (!Number.isFinite(input)) throw new TypeError('WAV PCM must contain finite samples');
29
+ const value = Math.max(-1, Math.min(1, input * gain));
30
+ view.setInt16(44 + i * blockAlign + channel * 2, Math.round(value * (value < 0 ? 32768 : 32767)), true);
31
+ }
32
+ return bytes;
33
+ }
package/ym2612-worklet.js CHANGED
@@ -32,9 +32,12 @@ class YM2612Processor extends AudioWorkletProcessor {
32
32
 
33
33
  this.ym2612 = null;
34
34
  this.psg = null;
35
+ this.initializing = false;
35
36
  this.resampleRemainder = 0;
36
37
  this.lastLeft = 0;
37
38
  this.lastRight = 0;
39
+ this.idleLeft = 0;
40
+ this.idleRight = 0;
38
41
  this.pendingCommands = [];
39
42
  this.scheduledCommands = [];
40
43
  this.scheduledHead = 0;
@@ -73,6 +76,7 @@ class YM2612Processor extends AudioWorkletProcessor {
73
76
  }
74
77
 
75
78
  async init(wasmBinary, psgWasmBinary) {
79
+ this.initializing = true;
76
80
  try {
77
81
  this.ym2612 = await createYm2612(
78
82
  ym2612ModuleFactory,
@@ -115,11 +119,20 @@ class YM2612Processor extends AudioWorkletProcessor {
115
119
  this.ym2612.reserveStereoFrames(capacity);
116
120
  this.psg?.reserveStereoFrames(capacity);
117
121
 
122
+ // ymfm models the YM2612 DAC ladder's nonzero idle level. Keep that
123
+ // behavior in the raw chip API, but center browser output on silence:
124
+ // connecting/disconnecting a constant DC level otherwise makes a click.
125
+ const idle = this.ym2612.generateStereoView(1);
126
+ this.idleLeft = idle.left[0];
127
+ this.idleRight = idle.right[0];
128
+ this.ym2612.reset();
129
+
118
130
  for (const command of this.pendingCommands) {
119
131
  this.applyCommand(command);
120
132
  }
121
133
 
122
134
  this.pendingCommands.length = 0;
135
+ this.initializing = false;
123
136
 
124
137
  this.port.postMessage({
125
138
  type: "ready",
@@ -250,7 +263,7 @@ class YM2612Processor extends AudioWorkletProcessor {
250
263
  const leftOut = output[0];
251
264
  const rightOut = output[1];
252
265
 
253
- if (!this.ym2612) {
266
+ if (!this.ym2612 || this.initializing) {
254
267
  leftOut.fill(0);
255
268
  rightOut.fill(0);
256
269
  return true;
@@ -364,8 +377,10 @@ class YM2612Processor extends AudioWorkletProcessor {
364
377
  if (count > 0) {
365
378
  let left = 0, right = 0;
366
379
  for (let j = 0; j < count; j++, sourceOffset++) {
367
- left += psg ? clampSample(pcm.left[sourceOffset] * YM_GAIN + psg.left[sourceOffset] * PSG_GAIN) : pcm.left[sourceOffset];
368
- right += psg ? clampSample(pcm.right[sourceOffset] * YM_GAIN + psg.right[sourceOffset] * PSG_GAIN) : pcm.right[sourceOffset];
380
+ const fmLeft = pcm.left[sourceOffset] - this.idleLeft;
381
+ const fmRight = pcm.right[sourceOffset] - this.idleRight;
382
+ left += psg ? clampSample(fmLeft * YM_GAIN + psg.left[sourceOffset] * PSG_GAIN) : fmLeft;
383
+ right += psg ? clampSample(fmRight * YM_GAIN + psg.right[sourceOffset] * PSG_GAIN) : fmRight;
369
384
  }
370
385
  this.lastLeft = left / count;
371
386
  this.lastRight = right / count;