tetorica-fm2612 0.2.39 → 0.2.41

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.
Files changed (164) hide show
  1. package/README.md +142 -2
  2. package/RUNTIME.md +1 -1
  3. package/ay8910.js +1 -1
  4. package/ay8910_operations.d.ts +62 -0
  5. package/ay8910_operations.js +222 -0
  6. package/ay8910_timed_client.d.ts +3 -0
  7. package/ay8910_timed_client.js +194 -0
  8. package/ay8910_timed_processor.d.ts +17 -0
  9. package/ay8910_timed_processor.js +138 -0
  10. package/ay8910_timed_state.d.ts +38 -0
  11. package/ay8910_timed_state.js +45 -0
  12. package/gameboy_runtime_synth.d.ts +18 -4
  13. package/generated/ay8910_wasm.wasm +0 -0
  14. package/generated/huc6280_wasm.js +1 -1
  15. package/generated/huc6280_wasm.wasm +0 -0
  16. package/generated/ps1_spu_build.json +43 -9
  17. package/generated/sid8580-machine/sid8580-endpoint.wasm +0 -0
  18. package/generated/sid8580-machine/sid8580-machine-build.json +32 -26
  19. package/generated/sid8580-machine/sid8580-machine.wasm +0 -0
  20. package/generated/spc_wasm.js +1 -1
  21. package/generated/spc_wasm.wasm +0 -0
  22. package/generated/ym2608_wasm.js +1 -1
  23. package/generated/ym2608_wasm.wasm +0 -0
  24. package/huc6280audioengine.d.ts +16 -6
  25. package/huc6280audioengine.js +47 -1
  26. package/licenses/mame-ay8910/README.md +14 -14
  27. package/licenses/snes-spc/README.md +2 -0
  28. package/megasynth.d.ts +17 -1
  29. package/megasynth.js +9 -2
  30. package/native-fx-worklet.d.ts +50 -0
  31. package/native_fx_rack.d.ts +28 -1
  32. package/native_genesis_extra_ay8910.js +6 -1
  33. package/native_genesis_extra_snes.d.ts +1 -1
  34. package/native_genesis_extra_ym2612.js +3 -0
  35. package/native_genesis_media.d.ts +1 -1
  36. package/native_genesis_msx.js +12 -6
  37. package/native_genesis_scsp.d.ts +2 -0
  38. package/native_genesis_synth.d.ts +5 -1
  39. package/native_genesis_synth.js +2 -0
  40. package/native_runtime_synth.d.ts +18 -4
  41. package/native_runtime_synth.js +1 -1
  42. package/opn_runtime_synth.d.ts +18 -4
  43. package/package.json +1 -1
  44. package/playground_audition_guard.d.ts +6 -0
  45. package/playground_audition_guard.js +16 -0
  46. package/playground_ay8910.d.ts +4 -7
  47. package/playground_ay8910.js +20 -13
  48. package/playground_ay8910_audio.d.ts +1 -0
  49. package/playground_ay8910_audio.js +5 -2
  50. package/playground_ay8910_worklet.js +22 -6
  51. package/playground_ay_timed_lifecycle.d.ts +31 -0
  52. package/playground_ay_timed_lifecycle.js +155 -0
  53. package/playground_code_runtime.d.ts +13 -1
  54. package/playground_code_runtime.js +143 -17
  55. package/playground_log.d.ts +3 -0
  56. package/playground_log.js +18 -0
  57. package/playground_logic_worker.js +37 -10
  58. package/playground_native_primary.d.ts +1 -224
  59. package/playground_opn.d.ts +11 -3
  60. package/playground_opn.js +3 -1
  61. package/playground_opn_inspector.d.ts +5 -0
  62. package/playground_opn_inspector.js +12 -0
  63. package/playground_opn_worklet.js +28 -5
  64. package/playground_performance_processor.d.ts +54 -1
  65. package/playground_performance_processor.js +13 -2
  66. package/playground_performance_queue.d.ts +61 -1
  67. package/playground_performance_queue.js +295 -12
  68. package/playground_performance_sender.js +5 -0
  69. package/playground_ps1.d.ts +3 -5
  70. package/playground_ps1.js +4 -4
  71. package/playground_ps1_inspector.js +1 -1
  72. package/playground_ps1_worklet.d.ts +52 -0
  73. package/playground_ps1_worklet.js +1 -1
  74. package/playground_runtime.d.ts +2 -0
  75. package/playground_runtime.js +53 -12
  76. package/playground_scsp.d.ts +1 -0
  77. package/playground_scsp_worklet.d.ts +52 -0
  78. package/playground_snes_worklet.d.ts +52 -0
  79. package/playground_spc.d.ts +2 -0
  80. package/playground_spc.js +10 -7
  81. package/playground_spc_audio.js +2 -2
  82. package/playground_sync.js +7 -1
  83. package/playground_worker_chip.d.ts +4 -1
  84. package/playground_worker_chip.js +12 -2
  85. package/ps1_vab.d.ts +195 -0
  86. package/ps1_vab.js +237 -0
  87. package/ps1synth.d.ts +3 -1
  88. package/ps1synth.js +5 -3
  89. package/runtime-manifest.json +12 -0
  90. package/scspsynth.d.ts +2 -0
  91. package/scspsynth.js +7 -6
  92. package/soundchip-output-worklet.js +18 -2
  93. package/soundchip.d.ts +7 -0
  94. package/soundchip.js +7 -0
  95. package/soundchip_mixer_presets.js +1 -1
  96. package/sources/CDDA.json +44 -10
  97. package/sources/CDDA.md +1 -1
  98. package/sources/MSM5205.json +44 -10
  99. package/sources/MSM5205.md +1 -1
  100. package/sources/POKEY-SDK.json +40 -6
  101. package/sources/POKEY.md +1 -1
  102. package/sources/PS1-SPU.json +97 -29
  103. package/sources/PS1-SPU.md +1 -1
  104. package/sources/README.md +1 -1
  105. package/sources/SCSP.json +42 -8
  106. package/sources/SegaPSG.md +1 -1
  107. package/sources/native/cdda/README.md +1 -1
  108. package/sources/native/msm5205/README.md +1 -1
  109. package/sources/scripts/build_spc_wasm.sh +1 -1
  110. package/sources/scsp-sdk/RELEASE-MANIFEST.json +69 -45
  111. package/sources/scsp-sdk/sdk.json +1 -1
  112. package/sources/sdk/RELEASE-MANIFEST.json +69 -45
  113. package/sources/sdk/catalog/source_inventory.json +41 -9
  114. package/sources/sdk/sdk.json +1 -1
  115. package/sources/sdk/soundchip-sdk.json +40 -6
  116. package/sources/sid/tetorica_src/runtime/playground_performance_processor.js +13 -2
  117. package/sources/sid/tetorica_src/runtime/playground_performance_queue.js +295 -12
  118. package/sources/sid8580-machine/scripts/prepare_sid8580_machine_core.mjs +2 -1
  119. package/sources/sid8580-machine/scripts/sid8580_machine_artifacts.mjs +1 -1
  120. package/sources/sid8580-machine/sid8580-machine-build.json +32 -26
  121. package/sources/sid8580-machine/source-kit.json +46 -46
  122. package/sources/sid8580-machine/tetorica_src/wasm/sid8580-machine/endpoint.rs +8 -0
  123. package/sources/sid8580-machine/tetorica_src/wasm/sid8580-machine/generated/sid8580_machine_core.h +13 -3
  124. package/sources/sid8580-machine/tetorica_src/wasm/sid8580-machine/generated/source-manifest.json +8 -4
  125. package/sources/sid8580-machine/tetorica_src/wasm/sid8580-machine/machine_wasm.cpp +2 -0
  126. package/sources/sid8580-machine/tetorica_src/wasm/sid8580-machine/sid_endpoint.cpp +4 -0
  127. package/sources/sid8580-machine/tetorica_src/wasm/sid_rsid_chip.cpp +5 -0
  128. package/sources/sid8580-machine/tetorica_src/wasm/sid_rsid_core.h +12 -2
  129. package/sources/sid8580-machine/tetorica_src/wasm/sid_rsid_wasm.cpp +2 -0
  130. package/sources/third_party/snes-spc/README.md +2 -0
  131. package/sources/third_party/snes-spc/snes_spc/SNES_SPC.h +10 -0
  132. package/sources/wasm/spc_wasm.cpp +9 -0
  133. package/spc-worklet.d.ts +1 -0
  134. package/spc-worklet.js +17 -11
  135. package/spc.d.ts +2 -0
  136. package/spc.js +8 -0
  137. package/spc_voice_edit.d.ts +2 -0
  138. package/spc_voice_edit.js +33 -0
  139. package/tetorica_audio_runtime.d.ts +338 -12
  140. package/wonderswan_timeline.d.ts +4 -2
  141. package/wonderswan_timeline.js +7 -4
  142. package/ym2608-worklet.js +11 -1
  143. package/ym2608.d.ts +29 -0
  144. package/ym2608.js +47 -2
  145. package/ym2608audioengine.d.ts +10 -1
  146. package/ym2608audioengine.js +18 -3
  147. package/ym2608synth.d.ts +16 -2
  148. package/ym2608synth.js +24 -1
  149. package/ym2612-worklet-nuked.d.ts +63 -2
  150. package/ym2612-worklet-nuked.js +23 -1
  151. package/ym2612-worklet.d.ts +63 -2
  152. package/ym2612-worklet.js +23 -1
  153. package/ym2612_operation_state.d.ts +26 -0
  154. package/ym2612_operation_state.js +80 -0
  155. package/ym2612_operations.d.ts +77 -0
  156. package/ym2612_operations.js +239 -0
  157. package/ym2612_timed_client.d.ts +44 -0
  158. package/ym2612_timed_client.js +232 -0
  159. package/ym2612_timed_processor.d.ts +22 -0
  160. package/ym2612_timed_processor.js +163 -0
  161. package/ym2612_timed_state.d.ts +37 -0
  162. package/ym2612_timed_state.js +53 -0
  163. package/ym2612synth.d.ts +5 -0
  164. package/ym2612synth.js +13 -0
package/README.md CHANGED
@@ -70,6 +70,7 @@ entry points, rather than every internal Worker or Worklet module.
70
70
  | Experimental PlayStation SPU, low level | `tetorica-fm2612/ps1_spu.js` | `Ps1Spu`: explicit factory initialization, register/RAM access and 44.1 kHz stereo PCM |
71
71
  | PS1 tuned sample instruments / host PCM rate | `tetorica-fm2612/ps1synth.js`, `tetorica-fm2612/ps1_resampler.js` | `Ps1Synth`, `createPs1InitSample`, `Ps1Resampler` |
72
72
  | PS1 named ADSR / reverb parameters | `tetorica-fm2612/ps1_parameters.js` | `decodePs1Envelope`, `encodePs1Envelope`, `patchPs1Envelope`, `PS1_REVERB_PRESETS` |
73
+ | Standard PS1 VAB banks / selected Tone export | `tetorica-fm2612`, `tetorica-fm2612/ps1_vab.js` | `readVab`, `prepareVabTone`, `exportVab`, `MAX_VAB_FILE_BYTES` |
73
74
  | PCM to PS1 SPU ADPCM | `tetorica-fm2612/ps1_adpcm_encoder.js` | `encodePs1Adpcm`, `encodePs1AdpcmCycle` |
74
75
  | PS1 Sample Editor conversion / waveform comparison | `tetorica-fm2612/playground_sample_ps1.js` | `renderPs1Sample`, `renderPs1SampleComparison` |
75
76
  | Isolated offline PS1 sample audition | `tetorica-fm2612/playground_sample_ps1_preview.js` | `renderPs1SamplePreview` with an injected PS1 WASM factory |
@@ -254,6 +255,11 @@ per-slot hardware LFO: `frequencyCode` 0..31, `pitchWave` / `amplitudeWave` 0..3
254
255
  the next keyOn. Display tables are exported as `SCSP_LFO_FREQUENCIES_HZ`,
255
256
  `SCSP_LFO_PITCH_CENTS`, `SCSP_LFO_AMPLITUDE_DB` and `SCSP_LFO_WAVEFORMS`.
256
257
  LFO requires 0.2.36 or later.
258
+ The current repository adds optional boolean `envelope.loopLink` (default
259
+ false): hardware LPSLNK transitions Attack to Decay 1 at the programmed loop
260
+ start. `setEnvelope(slot, {loopLink:true})` affects the next keyOn. This
261
+ addition is pending the next npm publication; older presets retain their
262
+ previous behavior when the field is omitted.
257
263
  See the [SCSP API and limitations](https://github.com/kyorohiro/hello_ymfm_wasm/blob/main/docs/scsp.md).
258
264
 
259
265
  Version 0.2.37 also adds `setModulation(slot, patch)` and
@@ -267,6 +273,60 @@ and updated Native hosts accept these controls. A multi-slot Synth voice allocat
267
273
  and patch serialization remain later work. These additions are not in published
268
274
  0.2.36. See the SCSP guide for a two-slot example and scheduling limitations.
269
275
 
276
+ ### Standard PS1 VAB banks
277
+
278
+ Available from **0.2.40**.
279
+
280
+ `readVab`, `prepareVabTone` and `exportVab` are pure synchronous APIs for
281
+ standard Sony VAB v6/v7. Import them from the package root or
282
+ `tetorica-fm2612/ps1_vab.js` (the extensionless `ps1_vab` path also works).
283
+ They do not create an audio device, require WASM, or convert through JSON.
284
+
285
+ ```js
286
+ import {readVab,prepareVabTone,exportVab} from 'tetorica-fm2612';
287
+
288
+ // Browser: bytes = await (await fetch(yourBankUrl)).arrayBuffer().
289
+ // Node: bytes = await readFile(yourBankPath).
290
+ const bank=readVab(bytes);
291
+ // For split banks instead: readVab(vhBytes, vbBytes).
292
+ console.table(bank.tones.map((tone,toneNumber)=>({toneNumber,...tone})));
293
+
294
+ const toneNumber=0; // Global bank.tones index, not an original Program ID.
295
+ const prepared=prepareVabTone(bank,toneNumber);
296
+ // ps1 is an initialized Ps1Synth, or the Playground's PS1 client.
297
+ const instrument=await ps1.loadADPCM(prepared.adpcm,prepared.options);
298
+ await ps1.setPreset(0,{...prepared.preset,sample:instrument});
299
+ await ps1.noteOn(0,'C4');
300
+ // Later: await ps1.keyOff(0).
301
+
302
+ const originalBankBytes=exportVab(bank);
303
+ const selectedToneBytes=exportVab(bank,{toneNumber});
304
+ ```
305
+
306
+ Inputs may be an `ArrayBuffer` or any `ArrayBufferView`, including `DataView`
307
+ and Node `Buffer`. Parsed banks retain original sparse Program IDs and Tone
308
+ metadata. Preparation returns owned ADPCM through the first END packet,
309
+ explicit `baseFrequencyHz`, an optional loop start, and ADSR/volume/pan/send
310
+ settings compatible with `Ps1Synth` and its asynchronous client. The bytes
311
+ are not decoded or re-encoded. Static volume/pan approximate libsnd;
312
+ shared reverb, key-zone layering, vibrato, portamento and song-driver logic
313
+ remain host responsibilities. Unassigned samples, libsnd Noise Tones and
314
+ unsupported ADPCM forms fail with an explanation.
315
+
316
+ Full-bank export preserves the original combined VH + VB bytes, including
317
+ padding. Selected export produces a standard one-Tone VAB, retaining its
318
+ original Program ID while packing the Tone as index 0 and its sample as 1.
319
+ Export requires the unchanged bank returned by `readVab`; it does not serialize
320
+ an arbitrary edited Synth instrument. Returned buffers are independent copies.
321
+ The exported types are `Ps1VabBank`, `Ps1VabProgram`, `Ps1VabTone`,
322
+ `Ps1VabSample`, `Ps1VabPreparedTone` and `Ps1VabExportOptions`.
323
+
324
+ In SPU Synth, **Save bank to presets** and **Save selected Tone to preset**
325
+ keep standard `.vab` files alongside portable Tone JSON. The Preset picker can
326
+ load a Program/Tone directly from a saved VAB, even with no JSON files present.
327
+ For an offline WAV example using the original demo bank, see
328
+ [main_ps1_vab.js](https://github.com/kyorohiro/hello_ymfm_wasm/blob/main/tetorica_examples/nodejs/main_ps1_vab.js).
329
+
270
330
  ### Experimental standalone PlayStation SPU
271
331
 
272
332
  `Ps1Spu` is a CPU-free MAME-derived instrument core with 24 voices and 512 KiB
@@ -1103,6 +1163,54 @@ frame rate; an explicit legacy `chipSampleRate` request remains supported. An
1103
1163
  injected AudioContext keeps its own rate. Chip clocks and note tuning are
1104
1164
  independent of the output rate.
1105
1165
 
1166
+ ### Inspect and schedule YM2612 register operations
1167
+
1168
+ Available from **0.2.41**. AY/YM2149 Playground clients expose the same
1169
+ `build()` / `compile()` / `captureState()` / `schedule()` / `clearSchedule()`
1170
+ operation model through the included `ay8910_operations` and
1171
+ `ay8910_timed_client` modules, using their own register-only authoring methods.
1172
+
1173
+ After `await synth.start()`, `synth.fm` supports the additive timed operation
1174
+ API. Existing immediate calls and `scheduleWrites()` keep their behavior.
1175
+
1176
+ ```js
1177
+ const fm = synth.fm;
1178
+ const motion = fm.build(b => {
1179
+ b.atSample(0).setOperator(0, 0, {multi: 2});
1180
+ b.atSeconds(0.1).setOperator(0, 0, {tl: 48});
1181
+ b.atSeconds(0.2).keyOff(0);
1182
+ });
1183
+ console.table(await fm.compile(motion)); // port / register / value / offsetSeconds
1184
+ await fm.schedule(motion, {name: 'operator-motion', repeatSeconds: 1});
1185
+ await fm.clearSchedule('operator-motion');
1186
+ ```
1187
+
1188
+ `build()` records serializable operations once without reading or changing the
1189
+ chip. `atSample()` uses a configurable `referenceSampleRate`, default 44100 Hz;
1190
+ both time forms are absolute offsets from the reservation start. The Worklet
1191
+ resolves packed fields against the state present when each operation executes.
1192
+ For example, MULT retains the then-current DT. Repeated Key On/Off writes stay
1193
+ in the trace. This is software scheduling of hardware registers.
1194
+
1195
+ `compile()` predicts one pass without changing live state. Its default
1196
+ `initialState: 'current'` captures coherent renderer control state asynchronously
1197
+ without stopping audio. Use `'client'` for the local write shadow with no
1198
+ renderer request, or `'reset'` for hardware reset registers. Client state may
1199
+ lag scheduled or external edits and explicitly rejects an incomplete baseline.
1200
+ For comparable traces, capture once with `await fm.captureState()` and reuse
1201
+ that detached snapshot as `{initialState: snapshot}`. Snapshots retain register
1202
+ bytes and pitch-latch metadata; they are not oscillator/envelope save states.
1203
+
1204
+ `schedule()` resolves when accepted. Named replacement and cancellation affect
1205
+ future operations, preserving already applied values. Patterns are compact,
1206
+ bounded to 4096 operations each, with aggregate limits of 128 reservations,
1207
+ 65,536 expanded writes and 48,000 expanded writes/second for repeats. These are
1208
+ admission limits, not a guarantee that every device sustains the maximum rate.
1209
+ Native timed execution and authoritative capture are unavailable; local/reset
1210
+ compilation remains available. For a custom Worklet transport, explicitly use
1211
+ `attachYm2612TimedClient` from `tetorica-fm2612/ym2612_timed_client` after creating
1212
+ the `YM2612Synth`, supplying its port and engine configuration.
1213
+
1106
1214
  Version 0.2.14 also supports chip-output RMS monitoring:
1107
1215
 
1108
1216
  ```js
@@ -1528,10 +1636,10 @@ FM/PSG/PCM mixing, stop/reset and close/restart. Playwright is a development
1528
1636
  dependency; it is not required by users of the sound-chip runtime.
1529
1637
 
1530
1638
  The build is staged in `dist/fm2612/`; packing produces
1531
- `tetorica-fm2612-0.2.39.tgz`. To install a local build in another project:
1639
+ `tetorica-fm2612-0.2.41.tgz`. To install a local build in another project:
1532
1640
 
1533
1641
  ```sh
1534
- npm install /absolute/path/to/tetorica-fm2612-0.2.39.tgz
1642
+ npm install /absolute/path/to/tetorica-fm2612-0.2.41.tgz
1535
1643
  ```
1536
1644
 
1537
1645
  The build pins an unpublished `tetorica-soundchip-native` SDK **0.1.7** source
@@ -1560,6 +1668,38 @@ notices. They are packaged alongside the unchanged fixed SDK snapshot.
1560
1668
 
1561
1669
  ## Release notes
1562
1670
 
1671
+ `0.2.41` adds timed register-operation authoring for AY/YM2149 and YM2612:
1672
+ state-free `build()`, detached `compile()` traces, reusable `captureState()`
1673
+ snapshots and named `schedule()` / `clearSchedule()` reservations. Worklets
1674
+ resolve partial fields when applied, keep repeated trigger writes, and execute
1675
+ seconds / reference-sample offsets on the audio sample clock. YM2612 supports
1676
+ ymfm and Nuked with port-aware Operator and Key On/Off operations. Main/Worker,
1677
+ Run/Apply/Stop ownership, bounded admission and public declarations are included.
1678
+ Existing immediate calls and YM2612 `scheduleWrites()` remain available. Native
1679
+ timed execution and authoritative capture explicitly reject; client/reset
1680
+ compilation remains local. See the [timed API guide](#inspect-and-schedule-ym2612-register-operations).
1681
+
1682
+ The release also includes current shared-runtime updates since 0.2.40: AY
1683
+ Single Output and flags handling with measured Mixer defaults, SCSP attack/loop
1684
+ link, dense WonderSwan VGM timelines, HuC6280 state/seek support, S-DSP direct
1685
+ voice editing and independently adjustable YM2608 FM/SSG output gains with
1686
+ updated state compatibility. Readable JavaScript, corresponding source kits,
1687
+ licenses, declarations and fixed WASM receipts remain included.
1688
+
1689
+ `0.2.40` exposes standard PS1 VAB v6/v7 helpers at the package root and
1690
+ `ps1_vab.js` / `ps1_vab` subpaths: `readVab()`, `prepareVabTone()` and
1691
+ `exportVab()`, with six public metadata and result types. Read combined VAB
1692
+ or split VH/VB, prepare tuned ADPCM for `Ps1Synth` / its asynchronous client,
1693
+ and preserve a complete source bank or extract a one-Tone standard VAB.
1694
+ The same pure helpers are available in Playground Main/Worker and Synth Code.
1695
+ They do not create an audio device or require intermediate Tetorica JSON.
1696
+ Export requires the original unchanged bank; shared effects and song-driver
1697
+ behavior remain separate. The existing SPU client declarations also retain
1698
+ valid method-return types when inferred through the generic runtime.
1699
+ SPU ADPCM preparation also accepts a LOOP START marker in a one-shot sample
1700
+ when the final END packet has Repeat disabled. Original bytes and flags are
1701
+ preserved; that marker alone does not make the sample loop.
1702
+
1563
1703
  `0.2.39` adds SID to the package-root `createSoundChip()` factory. Select
1564
1704
  6581 or PAL 8580 Preview, generate raw mono PCM directly, or use the generic
1565
1705
  browser AudioWorklet endpoint with explicit start/stop/dispose. It retains the
package/RUNTIME.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Full web runtime
2
2
 
3
- Includes all 359 top-level web runtime modules and 28 generated chip/engine pairs.
3
+ Includes all 371 top-level web runtime modules and 28 generated chip/engine pairs.
4
4
 
5
5
  ay8910, gameboy_apu, huc6280, wonderswan, pokey, k051649, nesapu, pwm32x, nuked_opn2, okim6258, rf5c164, segapcm, segapsg, spc, y8950, ym2151, ym2203, ym2413, ym2608, ym2610b, ym2612, ym3438, ym3526, ym3812, ymf262, ymf276, ymf278b, ymf288
6
6
 
package/ay8910.js CHANGED
@@ -15,7 +15,7 @@ export function validateAy8910({clock=AY8910_CLOCK,sampleRate=44100,type=0,flags
15
15
  if(!Number.isInteger(clock)||clock<=0||clock>0x3fffffff||!Number.isInteger(sampleRate)||sampleRate<=0||sampleRate>384000)
16
16
  throw new RangeError('Invalid AY clock or sample rate');
17
17
  if (![0,0x10].includes(type)) throw new Error(`AY chip type 0x${Number(type).toString(16)}: Support coming soon.`);
18
- if(!Number.isInteger(flags)||flags<0||flags>255||(flags & ~0x11)||(type===0 && (flags&0x10)))
18
+ if(!Number.isInteger(flags)||flags<0||flags>255||(flags & ~0x13)||(type===0 && (flags&0x10)))
19
19
  throw new Error(`AY flags 0x${Number(flags).toString(16)}: Support coming soon.`);
20
20
  }
21
21
  /**
@@ -0,0 +1,62 @@
1
+ export declare const AY_OPERATION_METHODS: readonly string[];
2
+ export declare const MAX_AY_OPERATIONS = 4096;
3
+ export declare function ayOperationOffsetSeconds(operation: any, referenceSampleRate?: number): any;
4
+ /** Record once. This function never constructs a chip or resolves register bytes. */
5
+ export declare function buildAyOperations(callback: any, options?: {}): {
6
+ version: number;
7
+ chip: string;
8
+ referenceSampleRate: any;
9
+ operations: {
10
+ method: string;
11
+ args: any;
12
+ time: {
13
+ unit: any;
14
+ value: any;
15
+ };
16
+ order: number;
17
+ }[];
18
+ };
19
+ /** Require complete semantic state; raw-only adoption would lose muted levels. */
20
+ export declare function validateAyOperationState(state: any): {
21
+ registers: any[];
22
+ levels: any[];
23
+ };
24
+ export declare function createAyOperationResetState(): {
25
+ registers: any[];
26
+ levels: number[];
27
+ };
28
+ /** One scratch chip shares all existing parameter validation and register math.
29
+ * Its transport only collects a batch; callers apply it after complete success. */
30
+ export declare function createAyOperationResolver({ clock }?: {
31
+ clock?: number | undefined;
32
+ }): {
33
+ resolve(operation: any, state: any): {
34
+ writes: any[];
35
+ state: {
36
+ registers: number[];
37
+ levels: number[];
38
+ };
39
+ };
40
+ };
41
+ /** Validate all calls using their shared existing conversion, without live state. */
42
+ export declare function validateAyOperations(plan: any, { clock, validateArguments }?: {
43
+ clock?: number | undefined;
44
+ validateArguments?: boolean | undefined;
45
+ }): {
46
+ version: number;
47
+ chip: string;
48
+ referenceSampleRate: any;
49
+ operations: {
50
+ method: string;
51
+ args: any;
52
+ time: {
53
+ unit: any;
54
+ value: any;
55
+ };
56
+ order: number;
57
+ }[];
58
+ };
59
+ /** Compile one virtual pass. Baseline adoption never contributes write rows. */
60
+ export declare function compileAyOperations(plan: any, state: any, { clock }?: {
61
+ clock?: number | undefined;
62
+ }): any[];
@@ -0,0 +1,222 @@
1
+ import {AY8910Synth, AY8910_CLOCK} from './ay8910synth.js';
2
+
3
+ /** Register-only authoring calls supported by the AY operation recorder.
4
+ * Validation and register conversion remain in AY8910Synth. */
5
+ const arity = Object.freeze({
6
+ writeRegister: [2, 2], setVoice: [2, 2], tone: [1, 2], setTone: [1, 2],
7
+ noise: [1, 2], setMixer: [2, 2], setVolume: [2, 3], setEnvelope: [1, 1],
8
+ setNoisePeriod: [1, 1], setTonePeriod: [2, 2], setFrequency: [2, 2],
9
+ setNote: [2, 2], keyOn: [1, 1], keyOff: [1, 1], noteOn: [2, 2],
10
+ noteOff: [1, 1], off: [1, 1], allNotesOff: [0, 0],
11
+ });
12
+
13
+ export const AY_OPERATION_METHODS = Object.freeze(Object.keys(arity));
14
+ export const MAX_AY_OPERATIONS = 4096;
15
+
16
+ function object(value, label) {
17
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
18
+ ![Object.prototype, null].includes(Object.getPrototypeOf(value))) {
19
+ throw new TypeError(`${label} must be a plain object`);
20
+ }
21
+ }
22
+
23
+ function fields(value, names, label) {
24
+ object(value, label);
25
+ for (const key of Reflect.ownKeys(value)) {
26
+ if (typeof key !== 'string' || !names.includes(key)) throw new TypeError(`Unknown ${label} field: ${String(key)}`);
27
+ if (!Object.hasOwn(Object.getOwnPropertyDescriptor(value, key), 'value')) {
28
+ throw new TypeError(`${label} must not contain accessors`);
29
+ }
30
+ }
31
+ }
32
+
33
+ /** Operation arguments deliberately use a small structured-cloneable subset. */
34
+ function copyValue(value, stack = new Set(), depth = 0) {
35
+ if (value === null || value === undefined || typeof value === 'boolean') return value;
36
+ if (typeof value === 'number') {
37
+ if (!Number.isFinite(value)) throw new TypeError('AY operation numbers must be finite');
38
+ return value;
39
+ }
40
+ if (typeof value === 'string') {
41
+ if (value.length > 1024) throw new RangeError('AY operation string is too long');
42
+ return value;
43
+ }
44
+ if (typeof value !== 'object') throw new TypeError('AY operation arguments must be serializable data');
45
+ if (depth >= 8 || stack.has(value)) throw new TypeError('AY operation arguments must be bounded, acyclic data');
46
+ if (!Array.isArray(value)) object(value, 'AY operation argument');
47
+ const keys = Reflect.ownKeys(value);
48
+ if (keys.length > 32) throw new RangeError('AY operation argument is too large');
49
+ stack.add(value);
50
+ try {
51
+ if (Array.isArray(value)) {
52
+ if (value.length > 16) throw new RangeError('AY operation argument array is too large');
53
+ const result = [];
54
+ for (let index = 0; index < value.length; index++) {
55
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
56
+ if (!descriptor || !Object.hasOwn(descriptor, 'value')) throw new TypeError('AY operation arrays must contain plain values');
57
+ result.push(copyValue(descriptor.value, stack, depth + 1));
58
+ }
59
+ for (const key of keys) if (key !== 'length' && !/^(0|[1-9]\d*)$/.test(String(key))) {
60
+ throw new TypeError('AY operation arrays must not contain extra properties');
61
+ }
62
+ return result;
63
+ }
64
+ const result = {};
65
+ for (const key of keys) {
66
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
67
+ if (typeof key !== 'string' || !Object.hasOwn(descriptor, 'value')) throw new TypeError('AY operation arguments must not contain symbols or accessors');
68
+ Object.defineProperty(result, key, {value: copyValue(descriptor.value, stack, depth + 1), enumerable: true, writable: true, configurable: true});
69
+ }
70
+ return result;
71
+ } finally {
72
+ stack.delete(value);
73
+ }
74
+ }
75
+
76
+ function referenceRate(value) {
77
+ if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError('referenceSampleRate must be a positive safe integer');
78
+ return value;
79
+ }
80
+
81
+ function copyTime(time) {
82
+ fields(time, ['unit', 'value'], 'AY operation time');
83
+ const {unit, value} = time;
84
+ if (!['sample', 'seconds'].includes(unit)) throw new TypeError('AY operation time unit must be sample or seconds');
85
+ if (!Number.isFinite(value) || value < 0 || value > Number.MAX_SAFE_INTEGER ||
86
+ (unit === 'sample' && !Number.isSafeInteger(value))) {
87
+ throw new RangeError('AY operation offset must be nonnegative and samples must be safe integers');
88
+ }
89
+ return {unit, value};
90
+ }
91
+
92
+ function copyCall(operation) {
93
+ const method = operation?.method;
94
+ if (typeof method !== 'string' || !Object.hasOwn(arity, method)) throw new TypeError(`Unsupported AY operation: ${String(method)}`);
95
+ if (!Array.isArray(operation.args)) throw new TypeError('AY operation args must be an array');
96
+ const [min, max] = arity[method];
97
+ if (operation.args.length < min || operation.args.length > max) throw new TypeError(`Invalid argument count for AY ${method}`);
98
+ return {method, args: copyValue(operation.args)};
99
+ }
100
+
101
+ export function ayOperationOffsetSeconds(operation, referenceSampleRate = 44100) {
102
+ referenceRate(referenceSampleRate);
103
+ const time = copyTime(operation.time);
104
+ return time.unit === 'sample' ? time.value / referenceSampleRate : time.value;
105
+ }
106
+
107
+ /** Copies/validates data without evaluating chip operations or reading state. */
108
+ function copyProgram(plan) {
109
+ fields(plan, ['version', 'chip', 'referenceSampleRate', 'operations'], 'AY operation program');
110
+ if (plan.version !== 1 || plan.chip !== 'ay8910') throw new TypeError('Unsupported AY operation program version or chip');
111
+ const rate = referenceRate(plan.referenceSampleRate);
112
+ if (!Array.isArray(plan.operations) || plan.operations.length > MAX_AY_OPERATIONS) throw new RangeError(`AY programs support at most ${MAX_AY_OPERATIONS} operations`);
113
+ let previous = 0;
114
+ const operations = Array.from(plan.operations, (operation, index) => {
115
+ fields(operation, ['time', 'order', 'method', 'args'], 'AY operation');
116
+ if (operation.order !== index) throw new TypeError('AY operation order must match authored order');
117
+ const time = copyTime(operation.time), call = copyCall(operation);
118
+ const offset = time.unit === 'sample' ? time.value / rate : time.value;
119
+ if (offset < previous) throw new RangeError('AY operation offsets must be nondecreasing');
120
+ previous = offset;
121
+ return {time, order: index, ...call};
122
+ });
123
+ return {version: 1, chip: 'ay8910', referenceSampleRate: rate, operations};
124
+ }
125
+
126
+ /** Record once. This function never constructs a chip or resolves register bytes. */
127
+ export function buildAyOperations(callback, options = {}) {
128
+ if (typeof callback !== 'function') throw new TypeError('AY build requires a synchronous callback');
129
+ fields(options, ['referenceSampleRate'], 'AY build options');
130
+ const rate = referenceRate(options.referenceSampleRate ?? 44100), operations = [];
131
+ let time = {unit: 'sample', value: 0}, active = true, previous = 0;
132
+ const check = () => { if (!active) throw new Error('AY operation recorder is no longer active'); };
133
+ const builder = Object.create(null);
134
+ builder.atSeconds = value => {
135
+ check(); time = copyTime({unit: 'seconds', value});
136
+ if (value < previous) throw new RangeError('AY operation offsets must be nondecreasing');
137
+ previous = value;
138
+ return builder;
139
+ };
140
+ builder.atSample = value => {
141
+ check(); time = copyTime({unit: 'sample', value});
142
+ const seconds = value / rate;
143
+ if (seconds < previous) throw new RangeError('AY operation offsets must be nondecreasing');
144
+ previous = seconds;
145
+ return builder;
146
+ };
147
+ for (const method of AY_OPERATION_METHODS) builder[method] = (...args) => {
148
+ check();
149
+ if (operations.length >= MAX_AY_OPERATIONS) throw new RangeError(`AY programs support at most ${MAX_AY_OPERATIONS} operations`);
150
+ const call = copyCall({method, args});
151
+ operations.push({time: {...time}, order: operations.length, ...call});
152
+ return builder;
153
+ };
154
+ try {
155
+ const result = callback(builder);
156
+ if (result && typeof result.then === 'function') {
157
+ Promise.resolve(result).catch(() => {});
158
+ throw new TypeError('AY build callbacks must be synchronous');
159
+ }
160
+ return copyProgram({version: 1, chip: 'ay8910', referenceSampleRate: rate, operations});
161
+ } finally {
162
+ active = false;
163
+ }
164
+ }
165
+
166
+ /** Require complete semantic state; raw-only adoption would lose muted levels. */
167
+ export function validateAyOperationState(state) {
168
+ if (!state || typeof state !== 'object') throw new TypeError('AY operation state is required');
169
+ const values = (source, length, max, label) => {
170
+ if (!(Array.isArray(source) || source instanceof Uint8Array) || source.length !== length) throw new TypeError(`AY operation state requires ${length} ${label}`);
171
+ return Array.from(source, value => {
172
+ if (!Number.isInteger(value) || value < 0 || value > max) throw new RangeError(`Invalid AY ${label}`);
173
+ return value;
174
+ });
175
+ };
176
+ return {registers: values(state.registers, 16, 255, 'register bytes'), levels: values(state.levels, 3, 31, 'retained levels')};
177
+ }
178
+
179
+ export function createAyOperationResetState() {
180
+ return {registers: Array(16).fill(0), levels: [9, 9, 9]};
181
+ }
182
+
183
+ /** One scratch chip shares all existing parameter validation and register math.
184
+ * Its transport only collects a batch; callers apply it after complete success. */
185
+ export function createAyOperationResolver({clock = AY8910_CLOCK} = {}) {
186
+ let writes = [];
187
+ const synth = new AY8910Synth({clock, transport: {writeRegister(register, value) { writes.push({register, value}); }}});
188
+ return {
189
+ resolve(operation, state) {
190
+ const input = validateAyOperationState(state), call = copyCall(operation);
191
+ synth._adoptState(input);
192
+ writes = [];
193
+ synth[call.method](...call.args);
194
+ return {writes, state: synth._getState()};
195
+ },
196
+ };
197
+ }
198
+
199
+ /** Validate all calls using their shared existing conversion, without live state. */
200
+ export function validateAyOperations(plan, {clock = AY8910_CLOCK, validateArguments = true} = {}) {
201
+ const copy = copyProgram(plan);
202
+ if (!validateArguments) return copy;
203
+ const resolver = createAyOperationResolver({clock});
204
+ let state = createAyOperationResetState();
205
+ for (const operation of copy.operations) state = resolver.resolve(operation, state).state;
206
+ return copy;
207
+ }
208
+
209
+ /** Compile one virtual pass. Baseline adoption never contributes write rows. */
210
+ export function compileAyOperations(plan, state, {clock = AY8910_CLOCK} = {}) {
211
+ const copy = copyProgram(plan), resolver = createAyOperationResolver({clock}), rows = [];
212
+ let work = validateAyOperationState(state);
213
+ for (let operationIndex = 0; operationIndex < copy.operations.length; operationIndex++) {
214
+ const operation = copy.operations[operationIndex];
215
+ const result = resolver.resolve(operation, work), offsetSeconds = ayOperationOffsetSeconds(operation, copy.referenceSampleRate);
216
+ for (let writeIndex = 0; writeIndex < result.writes.length; writeIndex++) {
217
+ rows.push({offsetSeconds, ...result.writes[writeIndex], operationIndex, writeIndex});
218
+ }
219
+ work = result.state;
220
+ }
221
+ return rows;
222
+ }
@@ -0,0 +1,3 @@
1
+ /** Attach the additive live AY API after its acknowledged control transport.
2
+ * Existing getters and immediate authoring methods retain their semantics. */
3
+ export declare function attachAyTimedClient(api: any, configuration: {} | undefined, port: any): any;