Repository navigation
fix(audio-context): sample-exact GainNode and DelayNode on iOS - #281
Merged
Merged
Conversation
OfflineAudioContext.suspend(when) and resume() on iOS, Windows and Linux, as in browsers. A suspend holds rendering at `when` rounded up to a 128-frame quantum; changes made before resume() apply from that frame. Suspends can be scheduled before startRendering() or while held. Windows and Linux: - web-audio-api only takes suspends scheduled before rendering starts. A hidden worklet processor holds the render thread at each requested quantum until resume(), and posts an event so the offline loop applies the control messages queued meanwhile. - The offline context's state is kept in JS (startRendering, suspends, resume, completion) rather than taken from engine events. - Unconnected AudioWorklet inputs are empty, as in browsers (web-audio-api's spec-compliant-worklet-inputs). iOS: - The main-thread render loop stops at a suspend frame and pauses the engine until resume(). - Worklets don't queue requests past the next suspend, so changes made while held reach the Worker too. - A node connected after rendering started rendered 2 frames late and 3 dB loud: an initialized mixer keeps a new input bus at its 44.1 kHz stereo default. The engine now stops before such a connect and restarts for the next quantum. Stopping keeps the sample time but clears effect state; the README notes it. - Node start() no longer starts an offline engine; only rendering does.
…uled With no suspend scheduled the suspend set is nil, and messaging nil gave a look-ahead limit of 0, so a source worklet never queued a request and rendered silence after a 5 s stall. Adds a spec: a worklet source renders offline, and a param set while held applies from the suspend frame.
The worklet scope runs as a plain script in a Worker and polls its rings with setInterval. 9.0.4-next gives such Workers no timers, so addModule rejected; 9.1.0 has them. The README notes the requirement.
The iOS worklet node is now an effect unit when it has inputs. Each input sums its connections in its own mixer, and each output is its own bus. Offline, a node with inputs waits for the Worker each quantum, so it stays sample-exact. Ports of 1 or 2 channels use the context's channel count on the AVAudio side, and the node up/down-mixes with Web Audio's speaker rules. AVAudioMixerNode would otherwise pan equal-power (mono read 0.707x). A realtime worklet now starts the engine and marks the context active when it connects. With no start() of its own, a graph whose only source was a worklet never played.
…r, with suspend/resume and DelayNode Android's OfflineAudioContext resolved startRendering() with an empty buffer: the native renderer kept its result where the Java wrapper never looked. It was also a separate, simpler mixer (each param took only its first event; no delay, compressor or convolver), and an offline context's sources played through the device as well. Each OfflineAudioContext now gets its own NativeEngine: the realtime mixer with no stream, a virtual clock and the context's rate and channels. Its ids carry the engine's prefix, so every JNI call reaches the engine that owns the id; creation calls take the context id. Java drives the render in quanta on its own thread and holds at each suspend frame. The result is written straight into the AudioBuffer's native memory, and sources read their AudioBuffer in place, so no audio passes through the Java heap. OfflineAudioContext gains state, suspend(when), resume(), sampleRate, length, currentTime and listener, as on iOS, Windows and Linux. Offline output is no longer clipped to [-1, 1]. Times converted from seconds now land on their own frame. DelayNode delayed nothing on Android: it was a gain whose value was delayTime, starting at 1 s. Each DelayNode now has a native delay line (fractional, sized by maxDelayTime) that the voices routed through it feed, so its tail plays out after its sources stop; delayTime defaults to 0. On iOS, delayTime changes never reached the AVAudioUnitDelay and its 15 kHz low-pass smoothed the signal; both are fixed. AudioContext.renderOffline(trackIds, ...), an undocumented Android-only method that also returned empty buffers, is removed.
A GainNode was an AVAudioMixerNode whose outputVolume a timer (realtime) or the offline render loop (per 128-frame quantum) set from the gain param. The mixer de-zippers outputVolume changes: each one ramps linearly over about 25 ms (1200 frames at 48 kHz), so a setValueAtTime on frame 512 left frame 512 at the old value and reached the new one 1200 frames later. outputVolume is also limited to [0, 1], so gains above 1 or below 0 were clamped. The per-source mixer bookkeeping (voiceGainByOutput) was not involved: the automated mixer was in the signal path. A DelayNode wrapped AVAudioUnitDelay, which ramps its delayed signal in over a few frames, caps delayTime at 2 s, and applied delayTime only once per quantum offline. Both are now NSCParamEffectNode: the node's inputs sum in a mixer at unit volume feeding a custom AUAudioUnit effect (registered in-process, instantiated synchronously, ports at the context's channel count) that evaluates its NSCAudioParam for every frame of each render call: - gain multiplies each frame by its gain value, any sign or size; - delay keeps a delay line per channel sized from maxDelayTime (default 1 s, up to 180 s) and reads it at delayTime, interpolating linearly between frames; whole-frame delays are exact. The line outlives render resources, so the tail survives the engine stop an offline connect causes, and it keeps playing after its sources stop. Frame times come from the render timestamp. Offline that is the context's frame; realtime it counts output-device samples, which can run at another rate than the context (44.1 kHz context on a 48 kHz device in the simulator), so it is scaled by the output node's rate, refreshed on engine configuration changes. NSCAudioParam gains fillValuesFromFrame:, which times frame i at (start + i) / rate so an event on a frame lands exactly on it. NSCAudioParam now holds its context weakly: the audio units retain their param, and a strong param -> context reference would keep every context with a gain or delay alive through its engine. The three iOS skips in audio-offline-render are removed; all 34 iOS audio specs pass.
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
|
ℹ️ Note: npm publishing is disabled for pull requests. |
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.
What was wrong
GainNode automation missed its frame. An iOS
GainNodewas anAVAudioMixerNode; itsoutputVolumewas set from thegainparam by a 500 Hz timer (realtime) or before each 128-frame quantum (offline).AVAudioMixerNodede-zippersoutputVolume: every change ramps linearly over about 25 ms (1200 frames at 48 kHz). InOfflineAudioContext(1, 1024, 48000)withgain.setValueAtTime(0.5, 512/48000)on a 0.5 constant, frames 512.. read 0.5, 0.49958, 0.49917, ... instead of 0.25.outputVolumeis also limited to [0, 1], so a gain of 2 rendered as 1. The per-source mixer bookkeeping (voiceGainByOutput) was not the cause: it is only a map, and the automated mixer was in the signal path.DelayNode was not sample-exact. It wrapped
AVAudioUnitDelay, which ramps the delayed signal in over a few frames (0.478, 0.499, 0.5 for a 0.5 step), so a 10-frame delay had not arrived by frame 10. It capped the delay at 2 s and tookdelayTimeonce per quantum.What changed
GainNodeandDelayNodenow shareNSCParamEffectNode: inputs sum in a mixer at unit volume, which feeds a customAUAudioUniteffect (registered in-process and instantiated synchronously, like the worklet unit, with ports at the context's channel count). The unit reads itsNSCAudioParamfor every frame of each render call.maxDelayTime(default 1 s, up to 180 s), is read atdelayTimefor each frame. Fractional delays interpolate linearly between frames, and whole-frame delays are exact. The line outlives the unit's render resources, so it survives the engine stop that an offline connect causes, and the tail keeps playing after the sources stop.delayTimedefaults to 0.AVAudioEngineConfigurationChangeNotification.NSCAudioParamgainsfillValuesFromFrame:sampleRate:frameCount:into:, which times frame i at(start + i) / rate, so an event on a frame lands exactly on it.NSCAudioParamnow holds its context weakly. The units retain their param, and a strong param → context reference would keep every context that has a gain or delay alive through its engine.createGainNode,gainParam,gain,createDelayNodeMaxDelayTime(delay, max),delayTimeParam,maxDelayTime.DelayNode's line.Tests
Removed the three
if (isIOS) skip(...)gates intools/demo/canvas/spec/audio-offline-render.ts: 'applies setValueAtTime on its frame', 'delays by delayTime, tail included' and 'delays into a gain'.iOS simulator (iPhone 17 Pro),
--suite=audio: 34 passed, 0 failed, 0 skipped, on two consecutive runs. Before this PR: 31 passed, 3 skipped. The realtime 'a delay holds its input back by delayTime, tail included' still passes.I also checked these with temporary probes, which are not committed:
suspend()while a 256-frame delay holds a tail: the tail plays through intact.setValueAtTime(0, t0+0.3)→linearRamp(4, t0+0.9)on a 0.25 constant. The analyser reads 0.5 before the event, a partial ramp shortly after it, and 1.0 after it.