Skip to content

Commit 698e8f0

Browse files
authored
feat(audio-context): OfflineAudioContext suspend(when) and resume() (#278)
* feat(audio-context): OfflineAudioContext suspend(when) and resume() 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. * fix(audio-context): iOS offline worklets render with no suspend scheduled 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. * chore(demo): iOS runtime 9.1.0 for AudioWorklet specs 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.
1 parent 7621b16 commit 698e8f0

20 files changed

Lines changed: 758 additions & 22 deletions

File tree

‎apps/demo/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
"devDependencies": {
3737
"@nativescript/android": "9.1.1",
3838
"@nativescript/devtools": "~0.0.1",
39-
"@nativescript/ios": "9.0.4-next.2026-08-13-31742124335",
39+
"@nativescript/ios": "9.1.0",
4040
"@nativescript/linux": "0.1.0-alpha.3",
4141
"@nativescript/visionos": "~9.0.1",
4242
"@nativescript/webpack": "https://pkg.pr.new/@nativescript/webpack@11620",

‎crates/audio-context-napi/Cargo.toml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ napi7 = ["napi/napi7"]
1717
[dependencies]
1818
napi = { version = "3.13.0", default-features = false, features = ["dyn-symbols"] }
1919
napi-derive = "3.6.9"
20-
web-audio-api = "1.8.0"
20+
# Unconnected AudioWorklet inputs are empty, as in browsers.
21+
web-audio-api = { version = "1.8.0", features = ["spec-compliant-worklet-inputs"] }
2122
base64 = "0.22.1"
2223

2324
[build-dependencies]
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// OfflineAudioContext suspend(when)/resume(): the render thread holds at a quantum.
2+
import assert from 'node:assert/strict';
3+
import fs from 'node:fs';
4+
import path from 'node:path';
5+
import test from 'node:test';
6+
import url from 'node:url';
7+
8+
const here = path.dirname(url.fileURLToPath(import.meta.url));
9+
const root = path.resolve(here, '../../..');
10+
const file = { win32: 'audio_context_napi.dll', darwin: 'libaudio_context_napi.dylib', linux: 'libaudio_context_napi.so' }[process.platform];
11+
const addon = [process.env.AUDIO_CONTEXT_NAPI_ADDON, path.join(root, 'target', 'debug', file), path.join(root, 'target', 'release-napi', file)].filter(Boolean).find((f) => fs.existsSync(f));
12+
const module = { exports: {} };
13+
process.dlopen(module, addon);
14+
const Audio = module.exports;
15+
16+
test('changes made while suspended apply from the suspend frame', async () => {
17+
const context = Audio.AudioContext.offline(1, 128 * 32, 48000);
18+
const seen = [];
19+
let source;
20+
context.setOnsuspend((frame) => {
21+
seen.push([frame, context.currentTime]);
22+
if (frame === 128 * 8) {
23+
source = context.createConstantSource();
24+
source.connect(context.destination());
25+
source.start(context.currentTime);
26+
// Scheduled while held, after rendering started.
27+
assert.equal(context.suspendAt((128 * 20) / 48000), 128 * 20);
28+
} else {
29+
source.stop(context.currentTime);
30+
}
31+
context.resumeRendering();
32+
});
33+
assert.equal(context.suspendAt((128 * 8) / 48000), 128 * 8);
34+
const samples = (await context.startRendering()).channelData(0);
35+
assert.deepEqual(seen, [
36+
[128 * 8, (128 * 8) / 48000],
37+
[128 * 20, (128 * 20) / 48000],
38+
]);
39+
assert.equal(samples[128 * 8 - 1], 0);
40+
assert.equal(samples[128 * 8], 1);
41+
assert.equal(samples[128 * 20 - 1], 1);
42+
assert.equal(samples[128 * 20], 0);
43+
});
44+
45+
test('rounds up to a quantum and suspends at 0', async () => {
46+
const context = Audio.AudioContext.offline(1, 128 * 4, 44100);
47+
assert.equal(context.suspendAt(1 / 44100), 128);
48+
assert.equal(context.suspendAt(0), 0);
49+
const frames = [];
50+
context.setOnsuspend((frame) => {
51+
frames.push(frame);
52+
setTimeout(() => context.resumeRendering(), 5);
53+
});
54+
await context.startRendering();
55+
assert.deepEqual(frames, [0, 128]);
56+
});
57+
58+
test('rejects invalid suspends and an early resume', () => {
59+
const context = Audio.AudioContext.offline(1, 128 * 4, 48000);
60+
assert.throws(() => context.resumeRendering(), /InvalidStateError: rendering has not started/);
61+
assert.throws(() => context.suspendAt(-1), /InvalidStateError/);
62+
assert.throws(() => context.suspendAt((128 * 4) / 48000), /InvalidStateError: suspendTime is at or past the end/);
63+
context.suspendAt(128 / 48000);
64+
assert.throws(() => context.suspendAt(100 / 48000), /InvalidStateError: a suspend is already scheduled/);
65+
});
66+
67+
test('a suspend at or before the held frame is rejected', async () => {
68+
const context = Audio.AudioContext.offline(1, 128 * 8, 48000);
69+
let error;
70+
context.setOnsuspend(() => {
71+
try {
72+
context.suspendAt((128 * 2) / 48000);
73+
} catch (e) {
74+
error = e;
75+
}
76+
context.resumeRendering();
77+
});
78+
context.suspendAt((128 * 2) / 48000);
79+
await context.startRendering();
80+
assert.match(String(error), /InvalidStateError: suspendTime is not after the current time/);
81+
assert.throws(() => context.suspendAt(0), /closed/);
82+
});

‎crates/audio-context-napi/__test__/worklet.test.mjs‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,14 @@ class Once extends AudioWorkletProcessor {
123123
}
124124
}
125125
registerProcessor('once', Once);
126+
127+
class Counter extends AudioWorkletProcessor {
128+
process(inputs, outputs) {
129+
outputs[0][0].fill(inputs[0].length);
130+
return true;
131+
}
132+
}
133+
registerProcessor('counter', Counter);
126134
`;
127135

128136
test('runs a processor with params, options and a port, sample-exact offline', async () => {
@@ -188,6 +196,29 @@ test('processes inputs', async () => {
188196
}
189197
});
190198

199+
test('an input with nothing playing into it is empty', async () => {
200+
const context = Audio.AudioContext.offline(2, 128 * 3, 48000);
201+
const scope = new Scope(context);
202+
try {
203+
await scope.addModule(processors);
204+
const merger = context.createChannelMerger(2);
205+
merger.connect(context.destination());
206+
const fed = scope.node('counter', { outputChannelCount: [1] });
207+
fed.connect(merger, 0, 0);
208+
const unconnected = scope.node('counter', { outputChannelCount: [1] });
209+
unconnected.connect(merger, 0, 1);
210+
const source = context.createConstantSource();
211+
source.connect(fed);
212+
source.start(128 / 48000);
213+
const rendered = await context.startRendering();
214+
const [left, right] = [rendered.channelData(0), rendered.channelData(1)];
215+
assert.deepEqual([0, 1, 2].map((q) => left[q * 128]), [0, 1, 1], 'empty until the source starts');
216+
assert.ok(right.every((v) => v === 0), 'empty with nothing connected');
217+
} finally {
218+
await scope.close();
219+
}
220+
});
221+
191222
test('a throwing processor reports processorerror and goes silent; false ends it', async () => {
192223
const context = Audio.AudioContext.offline(1, 128 * 4, 48000);
193224
const scope = new Scope(context);

‎crates/audio-context-napi/src/context.rs‎

Lines changed: 90 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ use crate::buffer::{AudioBuffer, PeriodicWave};
2020
use crate::node::{AudioNode, Kind, WorkletNode};
2121
use crate::worklet::{self, AudioWorkletScope, JsProcessor, Layout, ProcessorOptions, Ring, Scope};
2222
use crate::param::AudioParam;
23+
use crate::suspend::{SuspendProcessor, Suspends};
2324
use crate::{error, guard};
2425

2526
#[napi(object)]
@@ -57,11 +58,20 @@ pub struct WorkletNodeOptions {
5758

5859
enum Backing {
5960
Online(Arc<web_audio_api::context::AudioContext>),
61+
Offline(Box<Offline>),
62+
}
63+
64+
struct Offline {
6065
/// Taken by `startRendering`.
61-
Offline(Mutex<Option<OfflineAudioContext>>, usize),
66+
context: Mutex<Option<OfflineAudioContext>>,
67+
length: usize,
68+
suspends: Arc<Suspends>,
69+
/// Holds the render thread at suspends.
70+
_holder: AudioWorkletNode,
6271
}
6372

6473
type StateChangeCallback<'a> = Function<'a, (), UnknownReturnValue>;
74+
type SuspendCallback<'a> = Function<'a, f64, UnknownReturnValue>;
6575

6676
/// An `AudioContext` or an `OfflineAudioContext`. Nodes are made on the shared base, so both
6777
/// kinds build graphs the same way.
@@ -79,6 +89,13 @@ impl AudioContext {
7989
}
8090
}
8191

92+
fn suspends(&self) -> Result<&Arc<Suspends>> {
93+
match &self.backing {
94+
Backing::Offline(offline) => Ok(&offline.suspends),
95+
Backing::Online(_) => Err(error("InvalidStateError: only an OfflineAudioContext suspends at a time")),
96+
}
97+
}
98+
8299
fn node(&self, make: impl FnOnce(&ConcreteBaseAudioContext) -> Kind) -> Result<AudioNode> {
83100
guard(|| AudioNode::new(make(&self.base)))
84101
}
@@ -116,9 +133,28 @@ impl AudioContext {
116133
#[napi(factory)]
117134
pub fn offline(number_of_channels: u32, length: u32, sample_rate: f64) -> Result<Self> {
118135
let context = guard(|| OfflineAudioContext::new(number_of_channels as usize, length as usize, sample_rate as f32))?;
136+
let suspends = Suspends::new(length as u64, context.sample_rate() as f64);
137+
let holder = guard(|| {
138+
AudioWorkletNode::new::<SuspendProcessor>(
139+
&context,
140+
AudioWorkletNodeOptions {
141+
number_of_inputs: 0,
142+
number_of_outputs: 1,
143+
output_channel_count: vec![1],
144+
parameter_data: HashMap::new(),
145+
processor_options: suspends.clone(),
146+
audio_node_options: AudioNodeOptions::default(),
147+
},
148+
)
149+
})?;
119150
Ok(Self {
120151
base: context.base().clone(),
121-
backing: Backing::Offline(Mutex::new(Some(context)), length as usize),
152+
backing: Backing::Offline(Box::new(Offline {
153+
context: Mutex::new(Some(context)),
154+
length: length as usize,
155+
suspends,
156+
_holder: holder,
157+
})),
122158
})
123159
}
124160

@@ -160,7 +196,7 @@ impl AudioContext {
160196
#[napi(getter)]
161197
pub fn length(&self) -> u32 {
162198
match &self.backing {
163-
Backing::Offline(_, length) => *length as u32,
199+
Backing::Offline(offline) => offline.length as u32,
164200
Backing::Online(_) => 0,
165201
}
166202
}
@@ -207,16 +243,50 @@ impl AudioContext {
207243
/// Renders the graph once, off the JS thread.
208244
#[napi(ts_return_type = "Promise<AudioBuffer>")]
209245
pub fn start_rendering(&self) -> Result<AsyncTask<RenderTask>> {
210-
let Backing::Offline(context, _) = &self.backing else {
246+
let Backing::Offline(offline) = &self.backing else {
211247
return Err(error("InvalidStateError: only an OfflineAudioContext renders"));
212248
};
213-
let context = context.lock().ok().and_then(|mut context| context.take());
249+
let suspends = &offline.suspends;
250+
let context = offline.context.lock().ok().and_then(|mut context| context.take());
214251
match context {
215-
Some(context) => Ok(AsyncTask::new(RenderTask { context: Some(context) })),
252+
Some(context) => {
253+
suspends.start();
254+
Ok(AsyncTask::new(RenderTask { context: Some(context), suspends: suspends.clone() }))
255+
}
216256
None => Err(error("InvalidStateError: startRendering can only be called once")),
217257
}
218258
}
219259

260+
/// Offline: schedules a suspend at `time`, rounded up to a quantum; returns its frame.
261+
#[napi]
262+
pub fn suspend_at(&self, time: f64) -> Result<f64> {
263+
let suspends = self.suspends()?;
264+
let current = (self.base.current_time() * self.base.sample_rate() as f64).round() as u64;
265+
suspends.schedule(time, current).map(|frame| frame as f64).map_err(error)
266+
}
267+
268+
/// Offline: continues a render held at a suspend.
269+
#[napi]
270+
pub fn resume_rendering(&self) -> Result<()> {
271+
self.suspends()?.resume().map_err(error)
272+
}
273+
274+
/// Offline: `callback` runs on the JS thread with the frame each suspend holds at.
275+
#[napi(ts_args_type = "callback: ((frame: number) => void) | null")]
276+
pub fn set_onsuspend(&self, callback: Option<SuspendCallback>) -> Result<()> {
277+
let suspends = self.suspends()?;
278+
match callback {
279+
Some(callback) => {
280+
let tsfn = callback.build_threadsafe_function::<f64>().weak::<true>().build_callback(|ctx| Ok(ctx.value))?;
281+
suspends.set_notify(Some(Box::new(move |frame| {
282+
tsfn.call(frame as f64, ThreadsafeFunctionCallMode::NonBlocking);
283+
})));
284+
}
285+
None => suspends.set_notify(None),
286+
}
287+
Ok(())
288+
}
289+
220290
/// Decodes a complete encoded file (wav, mp3, ogg/vorbis, flac, aac, ...) to the context's
221291
/// sample rate, off the JS thread.
222292
#[napi(ts_return_type = "Promise<AudioBuffer>")]
@@ -467,6 +537,7 @@ impl Task for StateTask {
467537

468538
pub struct RenderTask {
469539
context: Option<OfflineAudioContext>,
540+
suspends: Arc<Suspends>,
470541
}
471542

472543
impl Task for RenderTask {
@@ -475,7 +546,10 @@ impl Task for RenderTask {
475546

476547
fn compute(&mut self) -> Result<Self::Output> {
477548
let mut context = self.context.take().ok_or_else(|| error("InvalidStateError: already rendered"))?;
478-
guard(|| context.start_rendering_sync())
549+
self.suspends.reach(0);
550+
let rendered = guard(|| context.start_rendering_sync());
551+
self.suspends.finish();
552+
rendered
479553
}
480554

481555
fn resolve(&mut self, _: Env, buffer: Self::Output) -> Result<AudioBuffer> {
@@ -521,3 +595,12 @@ impl Task for DecodeTask {
521595
Ok(AudioBuffer { inner: buffer })
522596
}
523597
}
598+
599+
impl Drop for AudioContext {
600+
/// A render held at a suspend would otherwise wait forever.
601+
fn drop(&mut self) {
602+
if let Backing::Offline(offline) = &self.backing {
603+
offline.suspends.finish();
604+
}
605+
}
606+
}

‎crates/audio-context-napi/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ mod buffer;
1010
mod context;
1111
mod node;
1212
mod param;
13+
mod suspend;
1314
mod tap;
1415
mod worklet;
1516

0 commit comments

Comments
 (0)