Repository navigation
Audio: palette pools, and BGM palette layers on the context clock (runtime 20261130.2) - #102
Open
Xehanort88 wants to merge 2 commits into
Open
Xehanort88 wants to merge 2 commits into
Xehanort88 wants to merge 2 commits into
Conversation
… 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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two commits, on
mainat 0.99.8 (c22a4c48):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
fadeOutfor 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.
tailfadeOutfor that hand-over.0plays the track to its end.weight0is never drawn; all zero falls back to an even draw. Random order only.repeatstrueRuntime (
runtime/reactor_managers.js):AudioManager._bgmSequenceLayerFade(layer, palette)gives the layer's current tail, or else the palette'sfadeOut; it decides_bgmSequenceLayerIsEnding, the fade of the track it retires, and a single-shot's advance._pickBgmSequencePoolEntrydraws Random by weight, the last entry sitting out unlessrepeatsis 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 fixedMath.randomrolls; zero and all-zero weights; repeats on and off; an unweighted pool still draws a third each) andbgm-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
tailor the palette'sfadeOut. Until now every one of those events was decided on the frame loop:speeds started at different times and stayed apart for the whole palette;
_bgmSequenceLayerIsEnding, fromupdateBgmSequence), so a join landed wherever the next frame fell (up to 16.7 ms late at60 fps, more during a stall), and the incoming track then still had to load before it sounded;
tail: 0) handed over from its stop listener, which is asetTimeout, plus the load of the next file: a gap, every time;durationwas 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 clockWhen the scheduled API is there (an audio context and a
WebAudiowithplayAt,stopAt,fadeInAt,fadeOutAt,isDecoded,addDecodeListener), a palette plays like this:all of them are decoded. Then all layers start on one context frame,
BGM_SEQUENCE_START_LEAD(50 ms) later.it. That draw has the whole of the current one (less its fade) to decode.
playAtat the frame itspredecessor hands over:
start + round((length − fade) × rate / pitch), wherefadeis thetrack's
tailor else the palette'sfadeOut. A track shorter than its fade, or withtail: 0, hands over at its exact end, gapless. Its fade-in is written withfadeInAt.(
fadeOutAtfrom the hand-over frame, thenstopAtwhen it reaches silence). If the palette'send (
startFrame + duration) falls first, the release is the palette's: from the end frame, overfadeOut. No draw is ever chosen to start at or after the end frame.starts loading at the same moment.
updateBgmSequencemoves each layer on to the draws whoseframe has come (the outgoing track goes to
retiringwith its own release end). It also handlesa 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 neverwrong-footed"). The draw after it keeps its own frame.
Everything else behaves as it did:
repeats,order(random / sequential / shuffle), the no-repeat guard carried across a cycle_pickBgmSequencePoolEntry). A queued draw that is thrown away unheard gives its pick back (last, and the shuffle bag).tail, trim (volumeon a pool item)singlepalettesonceentriesstate.buffers; each carries its own level in_rrAudio).stopBgmSequencedestroys queued draws with the rest.checkErrorsNew functions:
_bgmSequenceUsesClock,_startBgmSequenceClockPalette,_drawBgmSequenceLayer,_commitBgmSequenceDraw,_commitBgmSequenceSilence,_onBgmSequenceDrawDecoded,_tryStartBgmSequenceClockPalette,_planBgmSequenceLayer,_updateBgmSequenceClockLayer,_updateBgmSequenceClockPalette,_dropBgmSequenceQueue,_releaseBgmSequenceBuffer,_fadeInBgmSequence,_createBgmSequenceTrack(split out of_startBgmSequenceTrack, which isotherwise unchanged).
_retireBgmSequenceBuffer,_advanceBgmSequenceand_endBgmSequencePalettetake an optionalat(the frame the event was due), which only the clockpath uses.
The frame path is kept, unchanged, for a
WebAudiowithout the scheduled API: a plugin thatreplaces the class, a stub, or no audio context. The existing
bgm-sequence-runtimetests run onit (their fake
WebAudiohas noplayAt), so they still pass untouched but do not reach the newcode. 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 usescan go, at the cost of rewriting the old tests' fake. That is a choice for review.
runtime/reactor_core_io.js: two more scheduled callsWebAudio.prototype.fadeInAt(time, duration): the fade stage is shut untiltimeand opens overduration. A time already past opens from the level it would have reached.WebAudio.prototype.fadeOutAt(time, duration): fromtimethe fade stage falls to silence,from whatever level it is at then, a fade-in part-way included. It leaves the object playing;
stopAtends it.fadeOutAtalways writessetValueAtTime(level, time)aftercancelAndHoldAtTime(time). Thiswas found by the Chromium run, not the model (see below).
cancelAndHoldAtTimeinserts an eventonly when a ramp is under way at that time. Otherwise, per spec, it inserts nothing, and a
following
linearRampToValueAtTimeramps from the previous event. The level at a futuretimecomes from the last
fadeInAt, which is the only other automation the stage carries on this path.playAtnow clears that record.play,stop,fadeIn,fadeOut,playAt's timing and every other existing method areunchanged.
Tests and the model
editor/tests/helpers/offline-audio-model.cjs:cancelAndHoldAtTimenow 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:buildRuntimetakesoptions.globalsandoptions.decodeDelay(a number, or a function of the URL), so files can decode after a delaythrough
loads.due(now). Timers record when they were set, andclearTimeoutworks. Existingcallers are unaffected.
editor/tests/helpers/palette-clock-scenarios.cjs: five render scenarios andmixPalette(), the palette rules written out directly as the reference.editor/tests/bgm-palette-clock.test.cjs(19 tests).editor/tests/smoke/palette-clock-offline/(NW.js, Chromium's ownOfflineAudioContext).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
AudioManagerandWebAudio, sourced fromruntime/. Files decode 30 ms after they are asked for, the frame loop steps at its own rate, andthe render is held frame by frame to
mixPalette()at 1e-5. All fixtures are generated tone andnoise. 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.
palette fade-out (0.04 s), end to end (
tail: 0), and across a 15 ms silence: 15 hand-overs in2 s.
output as at 60 fps.
duration: every layer fades from the end frame, a tail that began before theend keeps its own ramp, nothing is committed at or past the end, and the next entry follows the
fade-out.
frame.
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
onceentry plays on the first pass only; and stopping leaves nosources, 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: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
fadeOutAtwritten ahead fell from the stage's creation event, notfrom its own time (
cancelAndHoldAtTime+ ramp with no ramp under way; see above). The model wasmodelling a hold event Chromium does not insert. Both were fixed:
fadeOutAtanchors 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)
bgm-palette-clock,bgm-plan-playerandwebaudio-fade-automation, 43 tests;bgm-sequence-runtimeandbgm-sequence-editor, 64 tests. All pass.bgm-*,audio-*andwebaudio-*file (16 files, 216 tests),i18n,user-visible-i18n-routingandi18n-routing-audit(40), andruntime-manifest,audit-shell-sync-runtimeandproject-manager, which read the revision (35). All pass.sync-runtime.cjs --checkreportstemplate/Demo/jsin step withruntime/.npm run test:changedin 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, nozip, GNUtarreadingC: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 readAPPDATA. The other two were checked on plain 0.99.8:distribution-stagingfails there in the same way, andcharacter-helper-threadsfailed 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,endFrameandopenFade. Each layer carriesqueue(draws{ index, previous, frame, endFrame, silence, buffer, committed, tail, trim, releaseFade, fadeIn }),endFrame,releaseFadeandspent. Clock buffers carry_rrClock,_rrAudio,_rrStartAt,_rrReleaseAt,_rrReleaseFadeand_rrReleaseEnd.Limits
entry, the start of the entry after a palette, and a track entry's own
fadeOuthand-over(
_bgmSequenceLayerIsEnding) are still decided on the frame loop, with the next file loaded whenit is needed. The palette's layers fade from its exact end frame, but what follows starts on the
next frame after that, once loaded.
durationnow counts from the audible start (all first draws decoded, plus 50 ms), not fromthe request. A palette with a 60 s duration now sounds for 60 s whatever the decode time. That is
a small behaviour change.
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.
now + duration, so a tail can ring a little longer than written.playAtbuilds its stages through_createPannerNode/_createGainNode, soDA_AudioManagerandDA_MapReverb's reverb and echo taps still apply.Cae_Tweakspatches_startPlaying, whichplayAtdoes not call, so its compressor refresh does not run on apalette draw (it runs on any other play). Its
createBuffercache can hand two draws of onetrack the same object, which was equally a problem on the frame path.
the context rate, so joins should be exact at any rate. That is read from the code, not measured.
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 ofnpm test.Changelog text for the next release
No
changelog/file:docs.test.cjsties the newest entry to the package version, and 0.99.8 is released.🤖 Generated with Claude Code