Skip to content

fix(audio-context): iOS render timeline, mixer fan-in and AudioNode.connect(AudioParam) - #283

Merged
triniwiz merged 8 commits into
masterfrom
feat/ios-audio-routing
Nov 24, 2026
Merged

triniwiz merged 8 commits into
masterfrom
feat/ios-audio-routing

Conversation

@triniwiz

Copy link
Copy Markdown
Member

Fixes four iOS problems in @nativescript/audio-context: how render timestamps map to currentTime, fan-in to mixer-backed nodes, node.connect(param), and the missing realtime gain automation spec.

Render timeline (start/stop and automation across sample rates)

In a realtime AVAudioEngine, render timestamps start at the device sample the engine started on and then count context frames. currentTime counts device samples. When the context runs at 44.1 kHz and the device at 48 kHz (the simulator does this), the two drift apart by about 8% of the time since the engine started.

  • The source nodes compared device-sample start/stop positions against these timestamps.
  • The gain and delay units scaled every timestamp by the device rate, so realtime automation lagged. A 0.6 s gain ramp was still sounding 150 ms after it should have ended.

The context now attaches a silent source to the main mixer. It records where the timestamps start and publishes the offset that turns a timestamp into a context frame: start · (1 − contextRate / deviceRate). NSCConstantSourceNode, NSCAudioBufferSourceNode and NSCAudioOscillatorNode now schedule start/stop at when · sampleRate and compare against timestamp − offset. The oscillator's frequency and the buffer's playbackRate automation use the same frame. The gain/delay units use the same offset. Offline, the offset is 0.

Fan-in to a mixer-backed node

connectTo:output: passed input 0, so a.connect(node, 0) followed by b.connect(node, 0) replaced a. A single-input node backed by a mixer (the destination, analyser, worklet inputs, gain/delay inputs) now gives each source the next free bus, and a repeated connect reuses its existing bus. Only ChannelMergerNode maps the input index to a bus.

node.connect(param)

Works for GainNode.gain and DelayNode.delayTime. The node's output, downmixed to mono, adds to the param's value on every frame. Connected audio sums in a mixer that feeds a sink unit. The sink outputs silence into the node's own input mixer, so it renders first in each cycle and leaves its downmix for the effect unit.

I tried a second input bus on the effect unit first, but it doesn't work. Connected while the engine is running, it pulls kAudioUnitErr_Uninitialized. Wired up at creation, it silences the unit. Other params ignore audio connected to them (noted in the README). Android doesn't support connect(param), so those specs are skipped there.

Specs

  • audio.scheduling:
    • buffer source start(when) lines up with gain automation: a ramp buffer started at when against a gain ramp from when. A start k frames off leaves 0.01·k. This read 566 frames with the device-rate scaling.
    • gain follows setValueAtTime and linearRampToValueAtTime: realtime step and ramp, with ≥150 ms margins. Failed on the old scaling.
    • a source connected to gain.gain while running opens it.
  • audio.offline.render:
    • sums sources connected with an output and input index
    • a node connected to a gain or delayTime param adds to it per frame: exact to the frame, gain and delayTime.

iOS simulator, --suite=audio: 39/39 pass, 0 skipped (it was 34/34). Three runs in a row all passed.

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.
…onnect(AudioParam)

Render timeline: in a realtime AVAudioEngine the render timestamps start at
the device sample the engine started on and then count context frames, while
currentTime counts device samples. With the context at 44.1 kHz and the device
at 48 kHz (the simulator) the two drift apart by about 8% of the time since the
engine started. The context now attaches a silent source to the main mixer that
records where the timestamps start, and publishes the offset that turns a
timestamp into a context frame (start * (1 - contextRate / deviceRate)). The
constant source, buffer source and oscillator schedule start/stop in context
frames (when * sampleRate) and compare them against that; the gain and delay
units use the same offset instead of scaling timestamps by the device rate,
which made realtime automation lag (a 0.6 s ramp was still not done 150 ms
after it ended). Offline the offset is 0.

Fan-in: connectTo:output: passed input 0, so a second source connected to a
mixer-backed node with connect(node, 0) replaced the first. A single-input
mixer-backed node now gives each source the next free bus (a repeated connect
reuses its bus); only a ChannelMergerNode maps the input index to a bus.

connect(param): GainNode.gain and DelayNode.delayTime take audio inputs. The
connected audio sums in a mixer feeding a sink unit, which outputs silence into
the node's own input mixer; it therefore renders first in each cycle and leaves
its mono downmix for the effect unit, which adds it to the param's per-frame
values. A second input bus on the effect unit was tried first: connected while
running it reports kAudioUnitErr_Uninitialized, and wired up front it silences
the unit. Other params ignore audio connected to them (README).
# Conflicts:
#	packages/audio-context/README.md
#	packages/audio-context/platforms/ios/src/NSCParamEffectNode.h
#	packages/audio-context/platforms/ios/src/NSCParamEffectNode.m
#	tools/demo/canvas/spec/audio-offline-render.ts
@coderabbitai

coderabbitai Bot commented Nov 24, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ecba88d2-e9b7-482b-bb96-51fb00a2ab60

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@triniwiz
triniwiz merged commit f874995 into master Nov 24, 2026
31 checks passed
@triniwiz
triniwiz deleted the feat/ios-audio-routing branch November 24, 2026 21:59
@github-actions

Copy link
Copy Markdown

ℹ️ Note: npm publishing is disabled for pull requests.
Publishing is performed only from tag pushes via the npm Release workflow.
If you need a test publish, merge to master — pushes publish pr-tagged prereleases.

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