Skip to content

Audio: palette pools, and BGM palette layers on the context clock (runtime 20261130.2) - #102

Open
Xehanort88 wants to merge 2 commits into
Psychronic-Games:mainfrom
Xehanort88:pr/palette-clock
Open

Xehanort88 wants to merge 2 commits into
Psychronic-Games:mainfrom
Xehanort88:pr/palette-clock

Conversation

@Xehanort88

@Xehanort88 Xehanort88 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Two commits, on main at 0.99.8 (c22a4c48):

  1. Palette pools: a tail per track, a draw weight per entry, layers that may repeat (runtime 20261130.1). The palette rules the second commit puts on the clock.
  2. BGM palette layers on the context clock (runtime 20261130.2). Builds on the scheduled-playback API from PR 100.

They come as one pull request because the second calls into the first (_bgmSequencePoolTail, _bgmSequenceLayerFade) and cannot be applied without it. The first was not sent upstream on its own before.

A follow-up fix, Fade Out BGM falls from where it is, is stacked on this branch in its own pull request (#103).


1. Palette pools: a tail per track, a draw weight per entry, layers that may repeat

Adaptive scores are written in segments that overlap by different amounts: a 28.4 s file holding 24 s of music and a 4.4 s tail beside segments with 4.8 s tails and one-shots with none. They draw with weights, and some layers may repeat. A palette had one fadeOut for every track, drew evenly and never repeated the entry just played, so such a score could only be approximated by padding the audio files with silence.

Three optional keys. A sequence that uses none of them plays exactly as before, and an older runtime ignores them.

Key On Meaning Written when
tail pool track Seconds before its end that the next draw starts, this track fading out under it. Overrides the palette's fadeOut for that hand-over. 0 plays the track to its end. set (empty = palette's fade-out)
weight pool track or silence Share of a random draw against the rest of the pool. 0 is never drawn; all zero falls back to an even draw. Random order only. not 1
repeats layer A random draw may pick the entry that just played. true

Runtime (runtime/reactor_managers.js): AudioManager._bgmSequenceLayerFade(layer, palette) gives the layer's current tail, or else the palette's fadeOut; it decides _bgmSequenceLayerIsEnding, the fade of the track it retires, and a single-shot's advance. _pickBgmSequencePoolEntry draws Random by weight, the last entry sitting out unless repeats is set. With every weight at 1 it is the same even draw as before. Shuffle and In order are unchanged.

Editor (editor/src/utils/BgmSequenceEditor.js, shared by Database › Music Sequences and Map Properties): a pool track gets Tail (s) and Draw weight, a pool silence Draw weight, a layer Allow repeats beside Order. normalize() writes the keys only when they say something, so existing data does not churn. The label is "Draw weight", not "Weight": the catalog already translates "Weight" as body weight for the character generator. Six new phrases in all 17 locales, a machine-assisted first pass that needs a native review.

Tests: bgm-sequence-runtime.test.cjs (a 4.4 s tail hands over at 24.0 s, not the palette's 23.6 s; no tail uses the palette's; tail 0 plays a one-shot out; a single-shot moves on by its tail; weighted draws against fixed Math.random rolls; zero and all-zero weights; repeats on and off; an unweighted pool still draws a third each) and bgm-sequence-editor.test.cjs (normalize, emptying Tail, the round-trip sweep over the three controls). On screen, when this was written on 0.99.7: the editor driven over CDP on NW.js 0.120, typing, stepping and emptying both fields and ticking Allow repeats, read back from the stored record, at 1280×800, 2560×1392 and with the detail pane forced to 600 and 480 px. Map Properties' own modal was not opened.


2. BGM palette layers on the context clock

The problem

A BGM palette sounds several layers at once. Each layer draws from its own pool, one track after
another, and a track hands over to the next draw at its end, less its tail or the palette's
fadeOut. Until now every one of those events was decided on the frame loop:

  • each layer's first track started when its own file had loaded, so stems decoded at different
    speeds started at different times and stayed apart for the whole palette;
  • a hand-over was noticed once per frame (_bgmSequenceLayerIsEnding, from
    updateBgmSequence), so a join landed wherever the next frame fell (up to 16.7 ms late at
    60 fps, more during a stall), and the incoming track then still had to load before it sounded;
  • a track that plays to its end (tail: 0) handed over from its stop listener, which is a
    setTimeout, plus the load of the next file: a gap, every time;
  • the palette's own end after duration was also noticed on a frame.

For adaptive scores written in overlapping segments, all of that is audible as drift and as joins
in the wrong place.

What changed

runtime/reactor_managers.js: palettes on the clock

When the scheduled API is there (an audio context and a WebAudio with playAt, stopAt,
fadeInAt, fadeOutAt, isDecoded, addDecodeListener), a palette plays like this:

  1. Start together. Every layer's first draw is chosen and starts loading. Nothing sounds until
    all of them are decoded. Then all layers start on one context frame,
    BGM_SEQUENCE_START_LEAD (50 ms) later.
  2. Decode ahead. When a draw starts sounding, the layer chooses its next draw and starts loading
    it. That draw has the whole of the current one (less its fade) to decode.
  3. Commit to the clock. Once decoded, the next draw is committed with playAt at the frame its
    predecessor hands over: start + round((length − fade) × rate / pitch), where fade is the
    track's tail or else the palette's fadeOut. A track shorter than its fade, or with
    tail: 0, hands over at its exact end, gapless. Its fade-in is written with fadeInAt.
  4. Write the release on the clock. At commit time the outgoing fade is written as well
    (fadeOutAt from the hand-over frame, then stopAt when it reaches silence). If the palette's
    end (startFrame + duration) falls first, the release is the palette's: from the end frame, over
    fadeOut. No draw is ever chosen to start at or after the end frame.
  5. Silences are draws of a known length, so they commit at once, and the track after them
    starts loading at the same moment.
  6. The frame loop keeps the books. updateBgmSequence moves each layer on to the draws whose
    frame has come (the outgoing track goes to retiring with its own release end). It also handles
    a single-shot's end and the palette's end, and starts the entry that follows. None of that moves
    a sound.

A draw that decodes after its frame enters part-way, in its place (playAt's "late is never
wrong-footed"). The draw after it keeps its own frame.

Everything else behaves as it did:

Behaviour On the clock path
Weights, repeats, order (random / sequential / shuffle), the no-repeat guard carried across a cycle Same picker (_pickBgmSequencePoolEntry). A queued draw that is thrown away unheard gives its pick back (last, and the shuffle bag).
Per-track tail, trim (volume on a pool item) Same rules. Each draw carries its own trim and tail.
single palettes Move on from the hand-over frame of the draw that ends. The other layers fade from that same frame, not from the frame that noticed.
once entries Unchanged (entry-level).
Next entry with a fade-in (overlap) vs without (sequential) Same decision. Layers fade from the end frame either way.
ME duck, BGM volume option Reach queued draws too (they are in state.buffers; each carries its own level in _rrAudio).
Fade Out BGM Sounding draws are ramped down from now, rewritten so a due hand-over cannot cut them mid-fade. Queued draws are dropped. Tails already under way keep their ramp.
Fade In BGM (replay after a battle) Asked while the first draws load, it is the fade they open with, which is what used to happen. Asked while sounding, it swells what is sounding and re-writes any hand-over still due.
Stop BGM, Play BGM, save/replay Unchanged. stopBgmSequence destroys queued draws with the rest.
checkErrors Sees queued draws. A first draw whose file fails does not hold the other layers back; its layer stays quiet, as before.

New functions: _bgmSequenceUsesClock, _startBgmSequenceClockPalette, _drawBgmSequenceLayer,
_commitBgmSequenceDraw, _commitBgmSequenceSilence, _onBgmSequenceDrawDecoded,
_tryStartBgmSequenceClockPalette, _planBgmSequenceLayer, _updateBgmSequenceClockLayer,
_updateBgmSequenceClockPalette, _dropBgmSequenceQueue, _releaseBgmSequenceBuffer,
_fadeInBgmSequence, _createBgmSequenceTrack (split out of _startBgmSequenceTrack, which is
otherwise unchanged). _retireBgmSequenceBuffer, _advanceBgmSequence and
_endBgmSequencePalette take an optional at (the frame the event was due), which only the clock
path uses.

The frame path is kept, unchanged, for a WebAudio without the scheduled API: a plugin that
replaces the class, a stub, or no audio context. The existing bgm-sequence-runtime tests run on
it (their fake WebAudio has no playAt), so they still pass untouched but do not reach the new
code. The new tests below re-check the same behaviours on the clock path. If you would rather have
one path, the fallback and _startBgmSequenceLayer / _bgmSequenceLayerIsEnding's palette uses
can go, at the cost of rewriting the old tests' fake. That is a choice for review.

runtime/reactor_core_io.js: two more scheduled calls

  • WebAudio.prototype.fadeInAt(time, duration): the fade stage is shut until time and opens over
    duration. A time already past opens from the level it would have reached.
  • WebAudio.prototype.fadeOutAt(time, duration): from time the fade stage falls to silence,
    from whatever level it is at then, a fade-in part-way included. It leaves the object playing;
    stopAt ends it.

fadeOutAt always writes setValueAtTime(level, time) after cancelAndHoldAtTime(time). This
was found by the Chromium run, not the model
(see below). cancelAndHoldAtTime inserts an event
only when a ramp is under way at that time. Otherwise, per spec, it inserts nothing, and a
following linearRampToValueAtTime ramps from the previous event. The level at a future time
comes from the last fadeInAt, which is the only other automation the stage carries on this path.
playAt now clears that record.

play, stop, fadeIn, fadeOut, playAt's timing and every other existing method are
unchanged.

Tests and the model

  • editor/tests/helpers/offline-audio-model.cjs: cancelAndHoldAtTime now follows the spec,
    inserting an event only for a ramp under way or a curve cut short. A ramp with no earlier event
    now starts when it is written, not at time 0. The old model inserted a hold event every time,
    which is exactly the case where it disagreed with Chromium. The plan-player tests pass on the
    corrected model, as they do on Chromium.
  • editor/tests/helpers/plan-player-scenarios.cjs: buildRuntime takes options.globals and
    options.decodeDelay (a number, or a function of the URL), so files can decode after a delay
    through loads.due(now). Timers record when they were set, and clearTimeout works. Existing
    callers are unaffected.
  • New editor/tests/helpers/palette-clock-scenarios.cjs: five render scenarios and
    mixPalette(), the palette rules written out directly as the reference.
  • New editor/tests/bgm-palette-clock.test.cjs (19 tests).
  • New editor/tests/smoke/palette-clock-offline/ (NW.js, Chromium's own OfflineAudioContext).

Verification

Frame-exact hand-overs, offline at 48 kHz (bgm-palette-clock.test.cjs, 19 tests, all pass)

Each scenario plays a palette through the real AudioManager and WebAudio, sourced from
runtime/. Files decode 30 ms after they are asked for, the frame loop steps at its own rate, and
the render is held frame by frame to mixPalette() at 1e-5. All fixtures are generated tone and
noise. Each scenario also asserts that the same output shifted one frame either way is not
within tolerance, and that every track the runtime committed went to a frame the rules give.

  1. Two layers start on one frame after both first draws decode. Hand-overs by tail (0.02 s), by
    palette fade-out (0.04 s), end to end (tail: 0), and across a 15 ms silence: 15 hand-overs in
    2 s.
  2. The same palette with the frame loop at 20 fps and a 100 ms stall gives bit-for-bit the same
    output as at 60 fps.
  3. A palette with duration: every layer fades from the end frame, a tail that began before the
    end keeps its own ramp, nothing is committed at or past the end, and the next entry follows the
    fade-out.
  4. A draw that decodes 0.5 s late enters part-way in its place, and the draw after it keeps its
    frame.
  5. Fade Out BGM during a hand-over: the incoming draw is held at its fade-in level and ramped down,
    the outgoing tail keeps its ramp, the queued draws never start, and the sequence is let go once
    silent.

Plus, on a clock moved by hand: the clock path is taken only with a context and the full API; the
next draw loads while the current one plays, is committed about 0.3 s before its frame, and is
ducked and levelled with the rest; a replay fade-in during loading is the one the first draws open
with, and Fade In BGM while sounding keeps a due hand-over; a single-shot moves on from its draw's
hand-over frame, with the other layer fading from that frame; a palette ending into a fade-in entry
hands over on its end frame; a weighted random layer never repeats a pick and never draws a weight
of 0 (over 100 draws); a once entry plays on the first pass only; and stopping leaves no
sources, listeners or pending decodes.

Mutation check: adding one frame to the hand-over (handOver + 1) fails 8 of the 19 tests,
including all five render scenarios.

On Chromium's own OfflineAudioContext (measured on this branch)

tests/smoke/palette-clock-offline, run on this branch (0.99.8 base) with the NW.js 0.120.0 SDK, Chromium 157.0.8103.39. Same numbers as on the 0.99.7 base:

Scenario Worst vs rules One frame early One frame late
Start together, hand-overs by tail / fade-out / end to end / across silence 5.4e-7 0.548 0.548
Slow, stalling frame loop 5.4e-7 0.548 0.548
Palette end 4.1e-7 0.256 0.256
Late decode enters part-way 5.5e-7 0.313 0.313
Fade Out BGM during a hand-over 5.3e-7 0.524 0.524

That is float32 rounding.

The first Chromium run did not pass: worst 0.49 to 0.997, while the node model said 1e-5. Micro
cases on Chromium showed that a fadeOutAt written ahead fell from the stage's creation event, not
from its own time (cancelAndHoldAtTime + ramp with no ramp under way; see above). The model was
modelling a hold event Chromium does not insert. Both were fixed: fadeOutAt anchors its level,
and the model follows the spec. The model now reproduces Chromium's behaviour exactly on the same
micro case (0.157895 against Chromium's 0.157895).

Tests on this branch (base 0.99.8)

  • On this branch alone: bgm-palette-clock, bgm-plan-player and webaudio-fade-automation, 43 tests; bgm-sequence-runtime and bgm-sequence-editor, 64 tests. All pass.
  • With the follow-up fix on top: every bgm-*, audio-* and webaudio-* file (16 files, 216 tests), i18n, user-visible-i18n-routing and i18n-routing-audit (40), and runtime-manifest, audit-shell-sync-runtime and project-manager, which read the revision (35). All pass. sync-runtime.cjs --check reports template/Demo/js in step with runtime/.
  • Whole suite on 0.99.8 plus the three commits of this stack (Windows, Git Bash, all 1,046 test files, run with npm run test:changed in four slices): 25 files fail, none of them an audio test. 23 are on the known Windows list as of 0.99.7: symlinks refused without Developer Mode, no zip, GNU tar reading C: as a host, Linux-only AppImage tooling, POSIX fixture paths (database-sections, audit-3d-editor-workshop, media-surface-panel, rgss-port-screenshots, vehicles-starting-position, tactics-card-convert), and the RTP tests that read APPDATA. The other two were checked on plain 0.99.8: distribution-staging fails there in the same way, and character-helper-threads failed only under 16 workers and passes when run alone on both trees. character-3d-creatures (a time budget) failed once under load and passed on its rerun.

Data shape

No data format changed. Runtime state only: a clock palette carries clock, started,
startFrame, endFrame and openFade. Each layer carries queue (draws { index, previous, frame, endFrame, silence, buffer, committed, tail, trim, releaseFade, fadeIn }), endFrame,
releaseFade and spent. Clock buffers carry _rrClock, _rrAudio, _rrStartAt,
_rrReleaseAt, _rrReleaseFade and _rrReleaseEnd.

Limits

  • Only palettes are on the clock. Entry-level transitions are not: a track entry, a silence
    entry, the start of the entry after a palette, and a track entry's own fadeOut hand-over
    (_bgmSequenceLayerIsEnding) are still decided on the frame loop, with the next file loaded when
    it is needed. The palette's layers fade from its exact end frame, but what follows starts on the
    next frame after that, once loaded.
  • duration now counts from the audible start (all first draws decoded, plus 50 ms), not from
    the request. A palette with a 60 s duration now sounds for 60 s whatever the decode time. That is
    a small behaviour change.
  • The draw after next is chosen on the frame loop, when the next one starts sounding. A stall
    longer than a whole draw (less its fade and its decode time) runs that layer out until updates
    resume. With real tracks of tens of seconds this needs a long stall. There is no 250 ms timer of
    its own as the plan player has, so a window that stops updating its scene behaves as the frame
    path did.
  • Memory: one more decoded track per layer (the next draw) while a track plays.
  • Fade Out BGM over a due hand-over rewrites the release from now. The cut moves to now + duration, so a tail can ring a little longer than written.
  • A tail that is already retiring is not ducked by an ME, as before: only live draws are.
  • Plugins: playAt builds its stages through _createPannerNode / _createGainNode, so
    DA_AudioManager and DA_MapReverb's reverb and echo taps still apply. Cae_Tweaks patches
    _startPlaying, which playAt does not call, so its compressor refresh does not run on a
    palette draw (it runs on any other play). Its createBuffer cache can hand two draws of one
    track the same object, which was equally a problem on the frame path.
  • Non-48 kHz devices: every position is in the context's own frames, from the decoded length at
    the context rate, so joins should be exact at any rate. That is read from the code, not measured.
  • Not done: the real game, and listening. No palette was played in the game or the test bed,
    and I cannot hear the result. Everything above is offline renders on the node model and on
    Chromium's OfflineAudioContext. The Chromium smoke is not part of npm test.

Changelog text for the next release

No changelog/ file: docs.test.cjs ties the newest entry to the package version, and 0.99.8 is released.

Palettes play on the audio clock. A BGM palette's layers now start together once every
layer's first track has loaded. Each next track is loaded while the one before it plays and
starts on the exact frame it is due, its tail or fade-out included, so stems stay locked and
joins no longer depend on the frame rate. A track with no tail now follows the one before it
with no gap. For plugin and engine code, WebAudio gains fadeInAt and fadeOutAt.


🤖 Generated with Claude Code

Xehanort88 and others added 2 commits November 30, 2026 07:30
… may repeat (runtime 20261130.1)

Adaptive scores overlap their segments by different amounts (a 28.4s file
holding 24s of music and a 4.4s tail beside segments with 4.8s and one-shots
with none), draw with weights, and let some layers repeat. A palette had one
fade-out for every track, drew evenly and never repeated, so such a score could
only be approximated by padding the audio files with silence.

- tail on a pool track: seconds before its end that the next draw starts, the
  track fading out under it; overrides the palette fade-out for that hand-over,
  0 plays it to its end. AudioManager._bgmSequenceLayerFade decides
  _bgmSequenceLayerIsEnding, the retire fade and a single-shot advance.
- weight on a pool track or silence: its share of a Random draw (0 never
  drawn; all zero falls back to an even draw).
- repeats on a layer: a Random draw may pick the entry just played.

All three are optional and written only when they say something; a sequence
without them plays as before, and an older runtime ignores them. The editor
gets Tail (s) and Draw weight on pool rows and Allow repeats on a layer, with
the six phrases in all 17 locales (machine-assisted first pass). "Draw weight",
not "Weight": the catalog already holds "Weight" as body weight.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A palette's layers used to start each track when its file had loaded and
hand over from a once-per-frame check, so stems drifted apart and joins
landed wherever a frame fell. Now, with the scheduled WebAudio API:

- every layer's first draw is decoded before any sounds, and all start on
  one context frame;
- each next draw is decoded while the one before it plays and committed
  with playAt on the frame its predecessor hands over (end less its tail
  or the palette fade-out; exactly at the end for tail 0, gapless);
- the outgoing fade and the palette's own end after `duration` are written
  on the clock (fadeOutAt + stopAt); nothing is drawn past the end frame;
- the frame loop only keeps the books: promotions, retiring tails, a
  single-shot's end, and starting what follows the palette.

Weights, repeats, order, once-entries, trims, tails, ME duck, the volume
option, Fade In/Out BGM and stop all behave as before. A WebAudio without
the scheduled API (a replacement class, a stub, no context) keeps the old
frame path, which the existing bgm-sequence-runtime tests exercise.

WebAudio gains fadeInAt and fadeOutAt. fadeOutAt always anchors its level
with setValueAtTime: Chromium's cancelAndHoldAtTime inserts no event when
no ramp is under way, so a ramp written next would start from the event
before (measured on NW.js 0.120 / Chromium 157).

The offline audio model's cancelAndHoldAtTime now follows the spec the
same way, and a ramp with no earlier event starts when it is written.
New tests: bgm-palette-clock (19), rendered at 48 kHz and held frame by
frame to the palette rules; the same scenarios on Chromium's own
OfflineAudioContext (tests/smoke/palette-clock-offline) come out within
5.5e-7, a one-frame shift 0.26-0.55.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

1 participant