Skip to content

Audio: scheduled playback on the context clock, and a BGM plan player (runtime 20261129.3) - #100

Merged
Psychronic-Games merged 1 commit into
Psychronic-Games:mainfrom
Xehanort88:pr/plan-player
Nov 30, 2026
Merged

Psychronic-Games merged 1 commit into
Psychronic-Games:mainfrom
Xehanort88:pr/plan-player

Conversation

@Xehanort88

Copy link
Copy Markdown
Contributor

The problem

Adaptive game music is assembled from many short files. Sections, layers and phrases are chosen and joined while the game runs, and every join has to land on the frame. A music tool can work all of that out ahead of time and export it as a plan: a list of clips, each a stretch of one file with a start, an offset, a length, a release tail and gains.

Reactor could not play one. WebAudio.play() starts a sound now, and everything after that is decided on the frame loop. That is how BGM sequences work: palette layers start when their file has loaded and hand over from a once-per-frame check, so stems drift and joins land wherever a frame falls.

What changed

runtime/reactor_core_io.js: scheduled playback in WebAudio

This is new code beside the old. play, _startPlaying and _startSourceNode are unchanged, and a test asserts that they do not use the new path.

  • scheduleVoice(spec): one run through the decoded file into a node of the caller's. It starts at a context time, from an offset, and is cut at a given time. It can loop a region of the caller's (overriding the file's tags) and take a pitch. Several voices can play from one object at once, and its play()/stop() state is left alone. A single buffer loops natively; decoder chunks are laid end to end. A start that has already passed enters as far in as the time gone, so a late voice stays where it should be.

  • scheduleClip(spec): a voice positioned in frames, with its envelope written once on the clock:

    • a linear fade-in;
    • a release tail from logical that reaches silence tail_full − 1 frames later, cut short and never squeezed, in five shapes (linear, sqrt, sin, square, none);
    • a gain per source channel, times volume;
    • piecewise-linear gain automation;
    • stereo-pair folding: mono goes to both sides, pairs are summed, an odd last channel is dropped.

    A clip can be entered part-way at clip frame k. The source position (wrapped at the file's loop), the fade-in, the tail and the gain points all carry on from k. Each stage owns one param.

  • playAt(when, offset, {loop, duration}) and stopAt(time): play() and stop() on the clock, through the object's own volume, fade and pan stages, with its stop listeners. They exist so the palette code can move onto the clock in a later change.

  • frameTime and frameClock: Web Audio starts an event at the first frame at or after its time. frame / rate can land a hair past the frame in floating point, which would push the event a whole frame late, so times are placed 2⁻²⁰ of a frame before their frame.

  • isDecoded() and addDecodeListener(): "the whole file is decoded", which isReady() is not; isReady() turns true on the first streamed part. The PCM-WAV fallback now records its decoded size, as the native path already did.

runtime/reactor_managers.js: AudioManager.playBgmPlan(folder, { volume, fadeIn, data })

This plays audio/<folder>/plan.json. The format id is reactor/music-plan, version 1, and every position is in frames at rate:

{ format: "reactor/music-plan", version: 1, rate: 48000, length,
  loop: null | { start, end },
  files: { <name>: { path, frames, channels, rate, loop: null | [start, end] } },
  clips: [{ file, start, offset, logical, tail, tail_full, fade_in,
            gains, volume, fade_shape, gain_points }] }
  • Shape check: a plan with a different format string still plays if its shape checks out, with a console warning. The check covers version and rate, paths that stay inside the plan's folder, file rate equal to plan rate, [start, end) loops, and clips that name real files. A refused or missing plan.json goes through checkErrors like a missing track.
  • Decode first: every piece is decoded before the first clip sounds.
  • Lookahead: each update commits the clips that start within BGM_PLAN_LOOKAHEAD (2 s) to the audio clock. Updates come from Scene_Base.update and from a 250 ms timer, because scenes stop updating while the window is unfocused.
  • Loop, by the window rule: the plan plays to loop.end, everything cut there. Then it replays [loop.start, loop.end) forever. Clips that started earlier enter part-way, and everything is cut at loop.end.
  • Beside the BGM slot, like a sequence. It is reached by stop, fade-out and fade-in, the ME duck, the BGM volume option, Save/Replay BGM and save files. A replay restarts the plan from frame 0; a replay of the plan already playing leaves it alone, with no restart and no dip.
  • bgmPlanInfo() reports the context rate, decoded lengths against the plan's frames, and decoded bytes in memory.

There is no editor UI and there are no new user-visible strings. Palette playback is unchanged.

Verification

  • editor/tests/bgm-plan-player.test.cjs, 18 tests, all pass. Node has no OfflineAudioContext, so the ten rendering scenarios run at 48 kHz on tests/helpers/offline-audio-model.cjs. That is a frame-by-frame model of the Web Audio subset used: sub-frame starts, a-rate automation including setValueCurveAtTime and cancelAndHoldAtTime, splitters and mergers, a centred panner, and suspend/resume. Each scenario is held to a sample-by-sample reference mixer at a tolerance of 1e-5, using synthetic fixtures only. The scenarios cover:
    • voice starts across chunk edges, a loop and pitch;
    • every envelope shape;
    • entering a clip part-way;
    • looping files and 6-channel, mono and 3-channel folding;
    • a looping plan whose tails cross both window edges;
    • incremental scheduling in 20 ms steps;
    • fade-out and stop mid-plan;
    • a plan without a loop ending at its length;
    • playAt/stopAt.
  • The same scenarios on Chromium's own OfflineAudioContext (tests/smoke/plan-player-offline, NW.js 0.120.0, Chromium 157) came out within 4.5e-7 of the reference, which is float32 rounding.
  • Real exported plans, kept locally and not in this repository: five of them, 97 to 330 s long, with 1 to 37 clips, 2- and 6-channel pieces, gain automation and two loops. Each was rendered by the real plan player on Chromium's OfflineAudioContext and null-tested against the tool's own reference mix. With pieces decoded the tool's way (16-bit ÷ 32768), the worst residuals are −134 to −154 dBFS, which is float32 rounding.
    • With Chromium's decodeAudioData the floor is −97 to −109 dBFS. Chromium decodes 16-bit PCM WAV asymmetrically: negative samples ÷ 32768, positive ÷ 32767. This was measured on a synthetic WAV and is a 0.00026 dB difference on positive half-waves.
    • Every piece decoded to exactly its declared length.
  • In the game, NW.js with a real project's plugin list, recorded by an AudioWorklet tap on the master gain aligned by context frame: the live output equalled the offline render, through a loop wrap and a deliberate 1.5 s main-thread stall. A one-frame slip would have shown at −23 to −35 dBFS.
  • Full npm test (Git Bash, Windows): the failing-test names are identical to the main baseline. Those are the known environmental and POSIX-path failures, plus three-version, which fails in a worktree whose node_modules is a junction. The bgm-sequence-*, audio-* and webaudio-* files all pass. On this branch, which is cut from upstream/main, the audio, docs and i18n test files pass: 218 of 218.

Limits

  • A replayed plan restarts from frame 0 instead of resuming.
  • Plans take no pitch or pan, and bypass any plugin that patches _createGainNode/_createPannerNode (reverb, echo).
  • The context still runs at the device's default rate. On a 44.1 kHz device the pieces are resampled and joins are no longer frame-exact. This was read from source, not measured.
  • The 2 s lookahead is how long a blocked main thread can be hidden. Hidden-window behaviour was not measured.
  • Files from the fallback Vorbis decoder (never used in NW.js) are scheduled from the chunks decoded once loading ends.

Changelog entry

This was not added as a version file, because docs.test.cjs ties the newest entry to package.json's version.

Music plans. AudioManager.playBgmPlan(folder) plays music assembled from many short files exactly as a music tool planned it. Each clip has its start, offset, release tail, gains and gain automation, and is scheduled on the audio clock, so every join lands on its frame whatever the frame rate does. A plan can loop, and it fades, stops, ducks under an ME, follows the BGM volume option and is saved like any BGM. For plugin and engine code, WebAudio gains playAt, stopAt, scheduleVoice and scheduleClip, which start sound at a time on the audio clock.

🤖 Generated with Claude Code

… (runtime 20261129.3)

Music assembled from many short files has to join on the frame: sections,
layers and phrases whose starts, release tails and gains a music tool has
already worked out. WebAudio could only start a sound now, and everything
after that ran on the frame loop, so stems drifted and joins landed wherever
a frame fell.

WebAudio (reactor_core_io.js):
- scheduleVoice: one run through the decoded file into a node of the
  caller's, at a context time, from an offset, until a cut, with a loop
  region of its own and pitch; decoder chunks laid end to end. Any number
  per object, and play()/stop() state is left alone.
- scheduleClip: a voice positioned in frames with its envelope written
  once on the clock: fade-in, a release tail (linear, sqrt, sin, square,
  none) cut short rather than squeezed, a gain per source channel with
  gain automation, stereo-pair folding. It can be entered part-way, the
  source position, fade and tail carrying on from that frame.
- playAt / stopAt: play() and stop() on the clock through the object's
  own volume, fade and pan stages, for the sequence code to move onto.
- frameTime / frameClock place an event a millionth of a frame before
  its frame, so floating point cannot push it to the next one.
- isDecoded / addDecodeListener: the whole file, not a first part. A WAV
  read by the PCM fallback now records its decoded size too.

AudioManager (reactor_managers.js): playBgmPlan(folder, options) plays
audio/<folder>/plan.json (format "reactor/music-plan", version 1, read by
its shape whatever its format names). Every file decodes first; then each
update commits what starts within two seconds, from Scene_Base.update and
a timer of its own, so the frame rate has no say. A loop plays to its end,
then replays its window forever, clips entering part-way and everything cut
at the end. Beside the BGM slot like a sequence: stop, fade-out, fade-in,
the ME duck, the BGM volume option, Save/Replay BGM and save files (which
restart it from its first frame). bgmPlanInfo reports decoded lengths and
memory. Palette playback is unchanged.

Tests: bgm-plan-player.test.cjs renders ten scenarios at 48 kHz over an
OfflineAudioContext model and holds them to the mixing rules frame by
frame (synthetic fixtures only); tests/smoke/plan-player-offline runs the
same scenarios on Chromium's own OfflineAudioContext (NW.js 0.120,
Chromium 157): every one within 4.5e-7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Psychronic-Games
Psychronic-Games merged commit 1f26fe0 into Psychronic-Games:main Nov 30, 2026
8 of 9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants