Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: OfflineAudioContext

Karl Seguinf6f54adbda48
diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zig
index 8a7a855fb..da946210d 100644
--- a/src/browser/js/bridge.zig
+++ b/src/browser/js/bridge.zig
@@ -1310,6 +1310,20 @@ pub const PageJsApis = flattenTypes(&.{
@import("../webapi/webcodecs/AudioEncoder.zig"),
@import("../webapi/webcodecs/VideoDecoder.zig"),
@import("../webapi/webcodecs/VideoEncoder.zig"),
+ @import("../webapi/webaudio/AudioBuffer.zig"),
+ @import("../webapi/webaudio/AudioParam.zig"),
+ @import("../webapi/webaudio/PeriodicWave.zig"),
+ @import("../webapi/webaudio/BaseAudioContext.zig"),
+ @import("../webapi/webaudio/OfflineAudioContext.zig"),
+ @import("../webapi/webaudio/OfflineAudioCompletionEvent.zig"),
+ @import("../webapi/webaudio/AudioNode.zig"),
+ @import("../webapi/webaudio/AudioDestinationNode.zig"),
+ @import("../webapi/webaudio/AudioScheduledSourceNode.zig"),
+ @import("../webapi/webaudio/AudioBufferSourceNode.zig"),
+ @import("../webapi/webaudio/ConstantSourceNode.zig"),
+ @import("../webapi/webaudio/OscillatorNode.zig"),
+ @import("../webapi/webaudio/GainNode.zig"),
+ @import("../webapi/webaudio/DynamicsCompressorNode.zig"),
});
const webcodecs_apis = [_]type{
diff --git a/src/browser/tests/webaudio/audio_buffer.html b/src/browser/tests/webaudio/audio_buffer.html
new file mode 100644
index 000000000..5d2dba89e
--- /dev/null
+++ b/src/browser/tests/webaudio/audio_buffer.html
@@ -0,0 +1,90 @@
+<!DOCTYPE html>
+<script src="../testing.js"></script>
+
+<script id=buffer>
+{
+ const buffer = new AudioBuffer({length: 4, numberOfChannels: 2, sampleRate: 8000});
+ testing.expectEqual(4, buffer.length);
+ testing.expectEqual(2, buffer.numberOfChannels);
+ testing.expectEqual(8000, buffer.sampleRate);
+ testing.expectEqual(0.0005, buffer.duration);
+
+ const data = buffer.getChannelData(1);
+ testing.expectEqual(true, data instanceof Float32Array);
+ testing.expectEqual(data, buffer.getChannelData(1));
+ testing.expectEqual([0, 0, 0, 0], Array.from(data));
+ testing.expectError('IndexSizeError', () => buffer.getChannelData(2));
+
+ buffer.copyToChannel(new Float32Array([1, 2, 3]), 1, 1);
+ testing.expectEqual([0, 1, 2, 3], Array.from(data));
+ const into = new Float32Array(3);
+ buffer.copyFromChannel(into, 1, 2);
+ testing.expectEqual([2, 3, 0], Array.from(into));
+ testing.expectError('TypeError', () => buffer.copyFromChannel([], 0));
+ testing.expectError('IndexSizeError', () => buffer.copyToChannel(into, 2));
+
+ testing.expectError('NotSupportedError', () => new AudioBuffer({length: 0, sampleRate: 8000}));
+ testing.expectError('NotSupportedError', () => new AudioBuffer({length: 1, numberOfChannels: 33, sampleRate: 8000}));
+ testing.expectError('NotSupportedError', () => new AudioBuffer({length: 1, sampleRate: 100}));
+ testing.expectError('TypeError', () => new AudioBuffer({sampleRate: 8000}));
+
+ const ctx = new OfflineAudioContext(1, 128, 8000);
+ const created = ctx.createBuffer(3, 10, 22050);
+ testing.expectEqual(3, created.numberOfChannels);
+ testing.expectEqual(22050, created.sampleRate);
+ testing.expectError('NotSupportedError', () => ctx.createBuffer(1, 0, 8000));
+}
+</script>
+
+<script id=buffer_source type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(2, 256, 8000);
+ const buffer = ctx.createBuffer(2, 100, 8000);
+ const left = buffer.getChannelData(0);
+ const right = buffer.getChannelData(1);
+ for (let i = 0; i < 100; i++) {
+ left[i] = i;
+ right[i] = -i;
+ }
+
+ const src = ctx.createBufferSource();
+ testing.expectEqual(null, src.buffer);
+ src.buffer = buffer;
+ testing.expectEqual(buffer, src.buffer);
+ testing.expectError('InvalidStateError', () => src.buffer = buffer);
+ src.connect(ctx.destination);
+ src.start(10 / 8000, 50 / 8000);
+
+ const ended = new Promise(resolve => src.onended = resolve);
+ const out = await ctx.startRendering();
+ await ended;
+
+ state.resolve();
+ await state.done(() => {
+ const l = out.getChannelData(0);
+ const r = out.getChannelData(1);
+ testing.expectEqual(0, l[9]);
+ testing.expectEqual(50, l[10]);
+ testing.expectEqual(-99, r[59]);
+ testing.expectEqual(0, l[60]);
+ });
+</script>
+
+<script id=buffer_source_loop type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(1, 32, 8000);
+ const buffer = ctx.createBuffer(1, 8, 8000);
+ buffer.copyToChannel(new Float32Array([0, 1, 2, 3, 4, 5, 6, 7]), 0);
+ const src = new AudioBufferSourceNode(ctx, {buffer, loop: true, loopStart: 2 / 8000, loopEnd: 6 / 8000, playbackRate: 2});
+ src.connect(ctx.destination);
+ src.start(0, 0, 10 / 8000);
+ const data = Array.from((await ctx.startRendering()).getChannelData(0).slice(0, 8));
+
+ state.resolve();
+ await state.done(() => {
+ // every other frame, wrapping within [2, 6), for 10 frames of buffer time
+ testing.expectEqual([0, 2, 4, 2, 4, 0, 0, 0], data);
+ });
+</script>
diff --git a/src/browser/tests/webaudio/audio_graph.html b/src/browser/tests/webaudio/audio_graph.html
new file mode 100644
index 000000000..78e4d4bb2
--- /dev/null
+++ b/src/browser/tests/webaudio/audio_graph.html
@@ -0,0 +1,259 @@
+<!DOCTYPE html>
+<script src="../testing.js"></script>
+
+<script id=connect>
+{
+ const ctx = new OfflineAudioContext(1, 128, 8000);
+ const other = new OfflineAudioContext(1, 128, 8000);
+ const osc = ctx.createOscillator();
+ const gain = ctx.createGain();
+
+ testing.expectEqual(gain, osc.connect(gain));
+ testing.expectEqual(gain, osc.connect(gain));
+ testing.expectEqual(undefined, osc.connect(gain.gain));
+ testing.expectError('IndexSizeError', () => osc.connect(gain, 1));
+ testing.expectError('IndexSizeError', () => gain.connect(osc));
+ testing.expectError('InvalidAccessError', () => osc.connect(other.destination));
+ testing.expectError('InvalidAccessError', () => osc.connect(other.createGain().gain));
+ testing.expectError('TypeError', () => osc.connect({}));
+
+ osc.disconnect(gain);
+ testing.expectError('InvalidAccessError', () => osc.disconnect(gain));
+ osc.disconnect(gain.gain);
+ testing.expectError('InvalidAccessError', () => osc.disconnect(gain.gain));
+ testing.expectError('IndexSizeError', () => osc.disconnect(1));
+ osc.connect(gain);
+ osc.disconnect();
+ testing.expectError('InvalidAccessError', () => osc.disconnect(gain));
+}
+</script>
+
+<script id=scheduling>
+{
+ const ctx = new OfflineAudioContext(1, 128, 8000);
+ const osc = ctx.createOscillator();
+ testing.expectError('InvalidStateError', () => osc.stop());
+ testing.expectError('RangeError', () => osc.start(-1));
+ osc.start();
+ testing.expectError('InvalidStateError', () => osc.start());
+ testing.expectError('RangeError', () => osc.stop(-1));
+ osc.stop(1);
+
+ const src = ctx.createBufferSource();
+ testing.expectError('RangeError', () => src.start(0, -1));
+ testing.expectError('RangeError', () => src.start(0, 0, -1));
+}
+</script>
+
+<script id=param_automation type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(1, 1024, 1024 * 8);
+ const source = ctx.createConstantSource();
+ const gain = ctx.createGain();
+ source.connect(gain).connect(ctx.destination);
+ const param = gain.gain;
+
+ testing.expectEqual(param, param.setValueAtTime(0, 0));
+ param.linearRampToValueAtTime(1, 256 / ctx.sampleRate);
+ param.setValueAtTime(2, 512 / ctx.sampleRate);
+ param.exponentialRampToValueAtTime(8, 768 / ctx.sampleRate);
+ param.setValueCurveAtTime([8, 0], 768 / ctx.sampleRate, 128 / ctx.sampleRate);
+ // automation doesn't show in value until rendering
+ testing.expectEqual(1, param.value);
+
+ testing.expectError('RangeError', () => param.exponentialRampToValueAtTime(0, 1));
+ testing.expectError('RangeError', () => param.setValueAtTime(1, -1));
+ testing.expectError('TypeError', () => param.setValueAtTime(NaN, 1));
+ testing.expectError('RangeError', () => param.setTargetAtTime(1, 0, -1));
+ testing.expectError('InvalidStateError', () => param.setValueCurveAtTime([1], 0, 1));
+ testing.expectError('RangeError', () => param.setValueCurveAtTime([1, 2], 0, 0));
+ testing.expectError('NotSupportedError', () => param.setValueAtTime(1, 800 / ctx.sampleRate));
+ testing.expectError('NotSupportedError', () => param.setValueCurveAtTime([1, 2], 700 / ctx.sampleRate, 200 / ctx.sampleRate));
+
+ source.start();
+ const data = (await ctx.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(0, data[0]);
+ testing.expectEqual(0.5, data[128]);
+ testing.expectEqual(1, data[300]);
+ testing.expectEqual(2, data[512]);
+ testing.expectEqual(true, Math.abs(data[640] - 4) < 1e-5);
+ testing.expectEqual(8, data[768]);
+ testing.expectEqual(4, data[832]);
+ testing.expectEqual(0, data[1000]);
+ testing.expectEqual(0, param.value);
+ });
+</script>
+
+<script id=curve_then_ramp type=module>
+ const state = await testing.async();
+
+ const sr = 8192;
+ const ctx = new OfflineAudioContext(1, 1024, sr);
+ const source = ctx.createConstantSource();
+ const gain = ctx.createGain();
+ source.connect(gain).connect(ctx.destination);
+ gain.gain.setValueCurveAtTime([0, 4, 4], 128 / sr, 256 / sr);
+ gain.gain.linearRampToValueAtTime(8, 640 / sr);
+ source.start();
+ const data = (await ctx.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ // the curve plays out, then the ramp starts from its end
+ testing.expectEqual(0, data[128]);
+ testing.expectEqual(2, data[192]);
+ testing.expectEqual(4, data[256]);
+ testing.expectEqual(4, data[320]);
+ testing.expectEqual(4, data[384]);
+ testing.expectEqual(6, data[512]);
+ testing.expectEqual(8, data[700]);
+ });
+</script>
+
+<script id=set_target_and_cancel type=module>
+ const state = await testing.async();
+
+ const sr = 8192;
+ const ctx = new OfflineAudioContext(1, 1024, sr);
+ const source = ctx.createConstantSource();
+ const gain = ctx.createGain();
+ source.connect(gain).connect(ctx.destination);
+ gain.gain.setValueAtTime(0, 0);
+ gain.gain.setTargetAtTime(1, 0, 256 / sr);
+ gain.gain.cancelAndHoldAtTime(512 / sr);
+ gain.gain.setValueAtTime(5, 768 / sr);
+ gain.gain.cancelScheduledValues(768 / sr);
+ source.start();
+ const data = (await ctx.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ const near = (expected, actual) => Math.abs(expected - actual) < 1e-6;
+ testing.expectEqual(0, data[0]);
+ testing.expectEqual(true, near(1 - Math.exp(-1), data[256]));
+ testing.expectEqual(true, near(1 - Math.exp(-2), data[512]));
+ // held from the cancel on; the later setValueAtTime was cancelled
+ testing.expectEqual(true, near(1 - Math.exp(-2), data[1000]));
+ });
+</script>
+
+<script id=param_input type=module>
+ const state = await testing.async();
+
+ // A node connected to a param adds to its value.
+ const ctx = new OfflineAudioContext(1, 128, 8000);
+ const source = new ConstantSourceNode(ctx, {offset: 2});
+ const modulator = new ConstantSourceNode(ctx, {offset: 0.5});
+ const gain = new GainNode(ctx, {gain: 1});
+ source.connect(gain).connect(ctx.destination);
+ modulator.connect(gain.gain);
+ source.start();
+ modulator.start();
+ const data = (await ctx.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(3, data[0]);
+ testing.expectEqual(3, data[127]);
+ });
+</script>
+
+<script id=ended type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(1, 1024, 8000);
+ const osc = ctx.createOscillator();
+ osc.connect(ctx.destination);
+ const events = [];
+ osc.onended = (e) => events.push([e.type, e.target === osc, ctx.state]);
+ ctx.oncomplete = () => events.push('complete');
+ osc.start(0);
+ osc.stop(100 / 8000);
+ const data = (await ctx.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual([['ended', true, 'running'], 'complete'], events);
+ testing.expectEqual(true, data[99] != 0);
+ testing.expectEqual(0, data[100]);
+ });
+</script>
+
+<script id=periodic_wave type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(1, 128, 44100);
+ testing.expectError('IndexSizeError', () => ctx.createPeriodicWave([0, 1], [0]));
+ testing.expectError('IndexSizeError', () => ctx.createPeriodicWave([0], [0]));
+
+ const osc = ctx.createOscillator();
+ testing.expectError('InvalidStateError', () => osc.type = 'custom');
+ osc.type = 'bogus';
+ testing.expectEqual('sine', osc.type);
+
+ // the default wave is a sine, as is imag = [0, 1]
+ osc.setPeriodicWave(new PeriodicWave(ctx));
+ testing.expectEqual('custom', osc.type);
+ osc.frequency.value = 1000;
+ osc.connect(ctx.destination);
+ osc.start();
+ const custom = (await ctx.startRendering()).getChannelData(0);
+
+ const unnormalized = new OfflineAudioContext(1, 128, 44100);
+ const half = unnormalized.createOscillator();
+ half.setPeriodicWave(unnormalized.createPeriodicWave([0, 0], [0, 0.5], {disableNormalization: true}));
+ half.frequency.value = 1000;
+ half.connect(unnormalized.destination);
+ half.start();
+ const scaled = (await unnormalized.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, Math.abs(custom[1] - 0.14199429750442505) < 1e-6);
+ testing.expectEqual(true, Math.abs(scaled[11] - 0.5) < 1e-4);
+ });
+</script>
+
+<script id=robustness type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(2, 2048, 44100);
+
+ // a feedback cycle with no delay renders, as silence on the back edge
+ const source = new ConstantSourceNode(ctx, {offset: 0.5});
+ const merge = new GainNode(ctx, {channelCount: 2, channelCountMode: 'explicit'});
+ source.connect(merge);
+ merge.connect(merge.gain);
+ merge.connect(ctx.destination);
+ source.start();
+
+ // a negative frequency with a start between frames
+ const osc = new OscillatorNode(ctx, {frequency: -440});
+ osc.connect(ctx.destination);
+ osc.start(0.00001);
+
+ // many automation events, and a long chain
+ for (let i = 0; i < 2000; i++) {
+ source.offset.setTargetAtTime(0.5, i / 44100, 0.001);
+ source.offset.value = 0.5;
+ }
+ let node = source;
+ for (let i = 0; i < 2000; i++) {
+ const gain = ctx.createGain();
+ node.connect(gain);
+ node = gain;
+ }
+ node.connect(ctx.destination);
+
+ const data = (await ctx.startRendering()).getChannelData(1);
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(2048, data.length);
+ testing.expectEqual(false, data.some(isNaN));
+ });
+</script>
diff --git a/src/browser/tests/webaudio/offline_audio_context.html b/src/browser/tests/webaudio/offline_audio_context.html
new file mode 100644
index 000000000..ecff3b9be
--- /dev/null
+++ b/src/browser/tests/webaudio/offline_audio_context.html
@@ -0,0 +1,229 @@
+<!DOCTYPE html>
+<script src="../testing.js"></script>
+
+<script id=interfaces>
+{
+ const ctx = new OfflineAudioContext(1, 5000, 44100);
+ testing.expectEqual(BaseAudioContext.prototype, Object.getPrototypeOf(OfflineAudioContext.prototype));
+ testing.expectEqual(EventTarget.prototype, Object.getPrototypeOf(BaseAudioContext.prototype));
+ testing.expectEqual(AudioScheduledSourceNode.prototype, Object.getPrototypeOf(OscillatorNode.prototype));
+ testing.expectEqual(AudioNode.prototype, Object.getPrototypeOf(AudioScheduledSourceNode.prototype));
+ testing.expectEqual(AudioNode.prototype, Object.getPrototypeOf(DynamicsCompressorNode.prototype));
+ testing.expectError('TypeError', () => new BaseAudioContext());
+ testing.expectError('TypeError', () => new AudioNode());
+
+ testing.expectEqual(5000, ctx.length);
+ testing.expectEqual(44100, ctx.sampleRate);
+ testing.expectEqual(0, ctx.currentTime);
+ testing.expectEqual('suspended', ctx.state);
+ testing.expectEqual(true, ctx.destination instanceof AudioDestinationNode);
+ testing.expectEqual(ctx.destination, ctx.destination);
+ testing.expectEqual(ctx, ctx.destination.context);
+
+ const fromOptions = new OfflineAudioContext({length: 128, sampleRate: 8000});
+ testing.expectEqual(1, fromOptions.destination.channelCount);
+ testing.expectEqual(8000, fromOptions.sampleRate);
+
+ testing.expectError('NotSupportedError', () => new OfflineAudioContext(0, 5000, 44100));
+ testing.expectError('NotSupportedError', () => new OfflineAudioContext(33, 5000, 44100));
+ testing.expectError('NotSupportedError', () => new OfflineAudioContext(1, 0, 44100));
+ testing.expectError('NotSupportedError', () => new OfflineAudioContext(1, 5000, 1000));
+ testing.expectError('TypeError', () => new OfflineAudioContext({sampleRate: 44100}));
+}
+</script>
+
+<script id=defaults>
+{
+ const ctx = new OfflineAudioContext(2, 5000, 44100);
+ const destination = ctx.destination;
+ testing.expectEqual(2, destination.maxChannelCount);
+ testing.expectEqual(2, destination.channelCount);
+ testing.expectEqual('explicit', destination.channelCountMode);
+ testing.expectEqual('speakers', destination.channelInterpretation);
+ testing.expectEqual(1, destination.numberOfInputs);
+ destination.channelCount = 3;
+ testing.expectEqual(3, destination.channelCount);
+
+ const osc = ctx.createOscillator();
+ testing.expectEqual('sine', osc.type);
+ testing.expectEqual(440, osc.frequency.value);
+ testing.expectEqual(-22050, osc.frequency.minValue);
+ testing.expectEqual(22050, osc.frequency.maxValue);
+ testing.expectEqual(0, osc.detune.value);
+ testing.expectEqual(osc.frequency, osc.frequency);
+ testing.expectEqual(0, osc.numberOfInputs);
+ testing.expectEqual(1, osc.numberOfOutputs);
+ testing.expectEqual(2, osc.channelCount);
+ testing.expectEqual('max', osc.channelCountMode);
+
+ const comp = ctx.createDynamicsCompressor();
+ testing.expectEqual(-24, comp.threshold.value);
+ testing.expectEqual(30, comp.knee.value);
+ testing.expectEqual(12, comp.ratio.value);
+ testing.expectEqual(Math.fround(0.003), comp.attack.value);
+ testing.expectEqual(0.25, comp.release.value);
+ testing.expectEqual(0, comp.reduction);
+ testing.expectEqual('k-rate', comp.threshold.automationRate);
+ testing.expectEqual('clamped-max', comp.channelCountMode);
+ testing.expectError('NotSupportedError', () => comp.channelCount = 3);
+ testing.expectError('NotSupportedError', () => comp.channelCountMode = 'max');
+ testing.expectError('InvalidStateError', () => comp.threshold.automationRate = 'a-rate');
+
+ const gain = ctx.createGain();
+ testing.expectEqual(1, gain.gain.value);
+ testing.expectEqual('a-rate', gain.gain.automationRate);
+ gain.channelCountMode = 'bogus';
+ testing.expectEqual('max', gain.channelCountMode);
+
+ testing.expectEqual('max', ctx.createBufferSource().channelCountMode);
+ testing.expectEqual(1, ctx.createConstantSource().offset.value);
+
+ const fromCtor = new OscillatorNode(ctx, {type: 'square', frequency: 1000});
+ testing.expectEqual('square', fromCtor.type);
+ testing.expectEqual(1000, fromCtor.frequency.value);
+ testing.expectEqual(ctx, fromCtor.context);
+ testing.expectError('InvalidStateError', () => new OscillatorNode(ctx, {type: 'custom'}));
+ testing.expectError('TypeError', () => new OscillatorNode(ctx, {type: 'bogus'}));
+ testing.expectEqual(-50, new DynamicsCompressorNode(ctx, {threshold: -50}).threshold.value);
+}
+</script>
+
+<script id=fingerprint type=module>
+ const state = await testing.async();
+
+ // The graph audio fingerprinting scripts render.
+ async function render(type, frequency, release) {
+ const ctx = new OfflineAudioContext(1, 5000, 44100);
+ const osc = ctx.createOscillator();
+ osc.type = type;
+ osc.frequency.value = frequency;
+ const comp = ctx.createDynamicsCompressor();
+ comp.threshold.value = -50;
+ comp.knee.value = 40;
+ comp.ratio.value = 12;
+ comp.attack.value = 0;
+ comp.release.value = release;
+ osc.connect(comp);
+ comp.connect(ctx.destination);
+ osc.start(0);
+ const buffer = await ctx.startRendering();
+ const data = buffer.getChannelData(0);
+ let sum = 0;
+ for (let i = 0; i < data.length; i++) sum += Math.abs(data[i]);
+ return {sum, reduction: comp.reduction, length: data.length, zero: data[263], first: data[265]};
+ }
+ const sine = await render('sine', 1000, 0.2);
+ const triangle = await render('triangle', 10000, 0.25);
+
+ state.resolve();
+ await state.done(() => {
+ // Chrome 151 x86-64: 1168.9068228197468 and 1085.371121346027; the
+ // wavetables differ in the last bit only.
+ testing.expectEqual(true, Math.abs(sine.sum - 1168.90682) < 1e-4);
+ testing.expectEqual(true, Math.abs(triangle.sum - 1085.37112) < 1e-4);
+ testing.expectEqual(Math.fround(-21.242456436157227), sine.reduction);
+ testing.expectEqual(Math.fround(-20.538288116455078), triangle.reduction);
+ testing.expectEqual(5000, sine.length);
+ // the compressor's 6ms look-ahead
+ testing.expectEqual(0, sine.zero);
+ testing.expectEqual(true, Math.abs(sine.first - 0.0511644) < 1e-5);
+ });
+</script>
+
+<script id=raw_oscillator type=module>
+ const state = await testing.async();
+
+ const results = {};
+ for (const type of ['sine', 'square', 'sawtooth', 'triangle']) {
+ const ctx = new OfflineAudioContext(1, 256, 44100);
+ const osc = new OscillatorNode(ctx, {type, frequency: 1000});
+ osc.connect(ctx.destination);
+ osc.start();
+ results[type] = Array.from((await ctx.startRendering()).getChannelData(0).slice(0, 4));
+ }
+
+ state.resolve();
+ await state.done(() => {
+ const expected = {
+ sine: [0, 0.14199429750442505, 0.2811110317707062, 0.41453102231025696],
+ square: [0, 0.952648937702179, 0.8448548316955566, 0.817898154258728],
+ sawtooth: [0, 0.030252715572714806, 0.08926413208246231, 0.10508260130882263],
+ triangle: [0, 0.08988944441080093, 0.18264608085155487, 0.2712443470954895],
+ };
+ for (const type in expected) {
+ for (let i = 0; i < 4; i++) {
+ testing.expectEqual(true, Math.abs(results[type][i] - expected[type][i]) < 1e-6);
+ }
+ }
+ });
+</script>
+
+<script id=lifecycle type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(2, 300, 8000);
+ const events = [];
+ ctx.onstatechange = () => events.push('statechange:' + ctx.state);
+ ctx.oncomplete = (e) => events.push(['complete', e instanceof OfflineAudioCompletionEvent, e.renderedBuffer.length, ctx.state]);
+
+ const source = ctx.createConstantSource();
+ source.connect(ctx.destination);
+ source.start();
+
+ const rendering = ctx.startRendering();
+ events.push('started:' + ctx.state);
+ let again = null;
+ try { await ctx.startRendering(); } catch (e) { again = e.name; }
+
+ const buffer = await rendering;
+ events.push('resolved');
+ await new Promise(resolve => setTimeout(resolve, 10));
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual('InvalidStateError', again);
+ testing.expectEqual(['started:running', 'statechange:running', ['complete', true, 300, 'closed'], 'resolved', 'statechange:closed'], events);
+ testing.expectEqual(2, buffer.numberOfChannels);
+ testing.expectEqual(8000, buffer.sampleRate);
+ // a mono source up-mixes to both channels
+ testing.expectEqual(1, buffer.getChannelData(0)[299]);
+ testing.expectEqual(1, buffer.getChannelData(1)[0]);
+ testing.expectEqual('closed', ctx.state);
+ });
+</script>
+
+<script id=suspend_resume type=module>
+ const state = await testing.async();
+
+ const ctx = new OfflineAudioContext(1, 1024, 8000);
+ const source = ctx.createConstantSource();
+ source.connect(ctx.destination);
+ source.start();
+
+ let times = [];
+ ctx.suspend(200 / 8000).then(() => {
+ times.push([ctx.currentTime * 8000, ctx.state]);
+ source.offset.value = 0.5;
+ ctx.resume();
+ });
+ let errors = [];
+ for (const when of [-1, 2000 / 8000]) {
+ try { await ctx.suspend(when); } catch (e) { errors.push(e.name); }
+ }
+ try { await ctx.suspend(256 / 8000); } catch (e) { errors.push(e.name); }
+
+ let resumeError = null;
+ try { await new OfflineAudioContext(1, 128, 8000).resume(); } catch (e) { resumeError = e.name; }
+
+ const data = (await ctx.startRendering()).getChannelData(0);
+
+ state.resolve();
+ await state.done(() => {
+ // rounded up to a render quantum boundary
+ testing.expectEqual([[256, 'suspended']], times);
+ testing.expectEqual(['InvalidStateError', 'InvalidStateError', 'InvalidStateError'], errors);
+ testing.expectEqual('InvalidStateError', resumeError);
+ testing.expectEqual(1, data[255]);
+ testing.expectEqual(0.5, data[256]);
+ });
+</script>
diff --git a/src/browser/webapi/Event.zig b/src/browser/webapi/Event.zig
index 2997f3205..a58107787 100644
--- a/src/browser/webapi/Event.zig
+++ b/src/browser/webapi/Event.zig
@@ -105,6 +105,7 @@ pub const Type = union(enum) {
idb_version_change_event: *@import("storage/idb/IDBVersionChangeEvent.zig"),
toggle_event: *@import("event/ToggleEvent.zig"),
task_priority_change_event: *@import("event/TaskPriorityChangeEvent.zig"),
+ offline_audio_completion_event: *@import("webaudio/OfflineAudioCompletionEvent.zig"),
};
pub const Options = struct {
@@ -234,6 +235,7 @@ pub fn is(self: *Event, comptime T: type) ?*T {
.idb_version_change_event => |e| return if (T == @import("storage/idb/IDBVersionChangeEvent.zig")) e else null,
.toggle_event => |e| return if (T == @import("event/ToggleEvent.zig")) e else null,
.task_priority_change_event => |e| return if (T == @import("event/TaskPriorityChangeEvent.zig")) e else null,
+ .offline_audio_completion_event => |e| return if (T == @import("webaudio/OfflineAudioCompletionEvent.zig")) e else null,
.ui_event => |e| {
if (T == @import("event/UIEvent.zig")) {
return e;
diff --git a/src/browser/webapi/EventTarget.zig b/src/browser/webapi/EventTarget.zig
index 54ba65f31..bb9f0ee76 100644
--- a/src/browser/webapi/EventTarget.zig
+++ b/src/browser/webapi/EventTarget.zig
@@ -59,6 +59,9 @@ const TextTrackList = @import("media/TextTrackList.zig");
const Animation = @import("animation/Animation.zig");
+const AudioNode = @import("webaudio/AudioNode.zig");
+const BaseAudioContext = @import("webaudio/BaseAudioContext.zig");
+
const AudioDecoder = @import("webcodecs/AudioDecoder.zig");
const AudioEncoder = @import("webcodecs/AudioEncoder.zig");
const VideoDecoder = @import("webcodecs/VideoDecoder.zig");
@@ -81,6 +84,8 @@ pub const Type = enum(u8) {
animation,
audio_decoder,
audio_encoder,
+ audio_node,
+ base_audio_context,
broadcast_channel,
cookie_store,
event_source,
@@ -124,6 +129,8 @@ pub fn Subtype(comptime tag: Type) type {
.animation => Animation,
.audio_decoder => AudioDecoder,
.audio_encoder => AudioEncoder,
+ .audio_node => AudioNode,
+ .base_audio_context => BaseAudioContext,
.broadcast_channel => BroadcastChannel,
.cookie_store => CookieStore,
.event_source => EventSource,
@@ -387,6 +394,8 @@ pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {
.animation => writer.writeAll("<Animation>"),
.audio_decoder => writer.writeAll("<AudioDecoder>"),
.audio_encoder => writer.writeAll("<AudioEncoder>"),
+ .audio_node => self.subtype(AudioNode).format(writer),
+ .base_audio_context => writer.writeAll("<BaseAudioContext>"),
.video_decoder => writer.writeAll("<VideoDecoder>"),
.video_encoder => writer.writeAll("<VideoEncoder>"),
.media_query_list => writer.writeAll("<MediaQueryList>"),
@@ -418,6 +427,8 @@ pub fn toString(self: *EventTarget) []const u8 {
.animation => return "[object Animation]",
.audio_decoder => return "[object AudioDecoder]",
.audio_encoder => return "[object AudioEncoder]",
+ .audio_node => return self.subtype(AudioNode).toString(),
+ .base_audio_context => return "[object BaseAudioContext]",
.broadcast_channel => return "[object BroadcastChannel]",
.cookie_store => return "[object CookieStore]",
.event_source => return "[object EventSource]",
diff --git a/src/browser/webapi/webaudio/AudioBuffer.zig b/src/browser/webapi/webaudio/AudioBuffer.zig
new file mode 100644
index 000000000..bc0d964eb
--- /dev/null
+++ b/src/browser/webapi/webaudio/AudioBuffer.zig
@@ -0,0 +1,189 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#AudioBuffer
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+const Frame = @import("../../Frame.zig");
+
+const AudioBuffer = @This();
+
+pub const max_channels = 32;
+pub const min_sample_rate = 3000;
+pub const max_sample_rate = 768000;
+
+// Creating a typed array past the isolate's ArrayBuffer budget aborts the
+// process, so the buffer's total size is capped well below it.
+const max_bytes = 512 * 1024 * 1024;
+
+_rc: lp.RC = .{},
+_arena: *lp.Arena,
+_sample_rate: f32,
+_length: u32,
+// One Float32Array per channel: getChannelData() hands these out, and
+// rendering reads and writes them in place.
+_channels: []js.ArrayBufferRef(.float32).Global,
+
+const Options = struct {
+ length: u32,
+ numberOfChannels: u32 = 1,
+ sampleRate: f32,
+};
+
+fn constructor(options: Options, frame: *Frame) !*AudioBuffer {
+ return create(options.numberOfChannels, options.length, options.sampleRate, frame.js.local.?, frame.page);
+}
+
+pub fn create(number_of_channels: u32, length: u32, sample_rate: f32, local: *const js.Local, page: *Page) !*AudioBuffer {
+ try validate(number_of_channels, length, sample_rate);
+
+ const arena = try page.getArena(.tiny, "AudioBuffer");
+ errdefer arena.release();
+
+ const channels = try arena.allocator().alloc(js.ArrayBufferRef(.float32).Global, number_of_channels);
+ var created: usize = 0;
+ errdefer for (channels[0..created]) |c| c.release();
+ for (channels) |*c| {
+ c.* = try local.createTypedArray(.float32, length).persist();
+ created += 1;
+ }
+
+ const self = try arena.allocator().create(AudioBuffer);
+ self.* = .{
+ ._arena = arena,
+ ._sample_rate = sample_rate,
+ ._length = length,
+ ._channels = channels,
+ };
+ return self;
+}
+
+pub fn validate(number_of_channels: u32, length: u32, sample_rate: f32) !void {
+ if (number_of_channels == 0 or number_of_channels > max_channels) {
+ return error.NotSupported;
+ }
+ if (length == 0) {
+ return error.NotSupported;
+ }
+ if (std.math.isNan(sample_rate) or sample_rate < min_sample_rate or sample_rate > max_sample_rate) {
+ return error.NotSupported;
+ }
+ if (@as(u64, length) * number_of_channels * @sizeOf(f32) > max_bytes) {
+ return error.NotSupported;
+ }
+}
+
+pub fn deinit(self: *AudioBuffer, _: *Page) void {
+ for (self._channels) |c| c.release();
+ self._arena.release();
+}
+
+pub fn acquireRef(self: *AudioBuffer) void {
+ self._rc.acquire();
+}
+
+pub fn releaseRef(self: *AudioBuffer, page: *Page) void {
+ self._rc.release(self, page);
+}
+
+pub fn numberOfChannels(self: *const AudioBuffer) u32 {
+ return @intCast(self._channels.len);
+}
+
+pub fn sampleRate(self: *const AudioBuffer) f32 {
+ return self._sample_rate;
+}
+
+pub fn frameCount(self: *const AudioBuffer) u32 {
+ return self._length;
+}
+
+// A channel's samples. Empty once script detached the array (e.g. by
+// transferring its buffer).
+pub fn channelData(self: *const AudioBuffer, channel: usize, local: *const js.Local) []f32 {
+ return self._channels[channel].local(local).slice();
+}
+
+fn getDuration(self: *const AudioBuffer) f64 {
+ return @as(f64, @floatFromInt(self._length)) / self._sample_rate;
+}
+
+fn getChannelData(self: *const AudioBuffer, channel: u32) !js.ArrayBufferRef(.float32).Global {
+ if (channel >= self._channels.len) {
+ return error.IndexSizeError;
+ }
+ return self._channels[channel];
+}
+
+fn copyFromChannel(self: *const AudioBuffer, destination: js.Value, channel: u32, buffer_offset_: ?u32, frame: *Frame) !void {
+ const local = frame.js.local.?;
+ if (destination.isFloat32Array() == false) {
+ return error.TypeError;
+ }
+ if (channel >= self._channels.len) {
+ return error.IndexSizeError;
+ }
+ const into = try destination.toZig([]f32);
+ const from = self.channelData(channel, local);
+ const offset = buffer_offset_ orelse 0;
+ if (offset >= from.len) {
+ return;
+ }
+ const n = @min(into.len, from.len - offset);
+ @memmove(into[0..n], from[offset..][0..n]);
+}
+
+fn copyToChannel(self: *const AudioBuffer, source: js.Value, channel: u32, buffer_offset_: ?u32, frame: *Frame) !void {
+ const local = frame.js.local.?;
+ if (source.isFloat32Array() == false) {
+ return error.TypeError;
+ }
+ if (channel >= self._channels.len) {
+ return error.IndexSizeError;
+ }
+ const from = try source.toZig([]f32);
+ const into = self.channelData(channel, local);
+ const offset = buffer_offset_ orelse 0;
+ if (offset >= into.len) {
+ return;
+ }
+ const n = @min(from.len, into.len - offset);
+ @memmove(into[offset..][0..n], from[0..n]);
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(AudioBuffer);
+
+ pub const Meta = struct {
+ pub const name = "AudioBuffer";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(AudioBuffer.constructor, .{});
+ pub const sampleRate = bridge.accessor(AudioBuffer.sampleRate, null, .{});
+ pub const length = bridge.accessor(AudioBuffer.frameCount, null, .{});
+ pub const duration = bridge.accessor(AudioBuffer.getDuration, null, .{});
+ pub const numberOfChannels = bridge.accessor(AudioBuffer.numberOfChannels, null, .{});
+ pub const getChannelData = bridge.function(AudioBuffer.getChannelData, .{});
+ pub const copyFromChannel = bridge.function(AudioBuffer.copyFromChannel, .{});
+ pub const copyToChannel = bridge.function(AudioBuffer.copyToChannel, .{});
+};
diff --git a/src/browser/webapi/webaudio/AudioBufferSourceNode.zig b/src/browser/webapi/webaudio/AudioBufferSourceNode.zig
new file mode 100644
index 000000000..7fb83f5d5
--- /dev/null
+++ b/src/browser/webapi/webaudio/AudioBufferSourceNode.zig
@@ -0,0 +1,339 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#AudioBufferSourceNode
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const math = @import("dsp/math.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const AudioParam = @import("AudioParam.zig");
+const AudioBuffer = @import("AudioBuffer.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+const AudioScheduledSourceNode = @import("AudioScheduledSourceNode.zig");
+
+const AudioBufferSourceNode = @This();
+
+pub const Proto = AudioScheduledSourceNode;
+
+// Chrome's bound on the computed playback rate.
+const max_rate = 1024;
+
+_proto: *AudioScheduledSourceNode,
+_playback_rate: *AudioParam,
+_detune: *AudioParam,
+// holds a ref while set
+_buffer: ?*AudioBuffer = null,
+_buffer_set: bool = false,
+_loop: bool = false,
+_loop_start: f64 = 0,
+_loop_end: f64 = 0,
+// start()'s offset and duration, in seconds of buffer time
+_offset: f64 = 0,
+_duration: ?f64 = null,
+// playhead, in buffer frames
+_position: f64 = 0,
+// buffer frames played so far, for the grain duration
+_played: f64 = 0,
+_started_playing: bool = false,
+// started with no buffer: it ends right away, and a buffer set later is
+// never played (as in Chrome)
+_started_empty: bool = false,
+
+const Options = struct {
+ buffer: ?*AudioBuffer = null,
+ detune: f32 = 0,
+ loop: bool = false,
+ loopEnd: f64 = 0,
+ loopStart: f64 = 0,
+ playbackRate: f32 = 1,
+};
+
+fn constructor(context: *BaseAudioContext, options_: ?Options) !*AudioBufferSourceNode {
+ return create(context, options_ orelse .{});
+}
+
+pub fn create(context: *BaseAudioContext, options: Options) !*AudioBufferSourceNode {
+ if (std.math.isFinite(options.loopStart) == false or std.math.isFinite(options.loopEnd) == false) {
+ return error.TypeError;
+ }
+ const self = try Factory.chainedWithAllocator(context._arena.allocator(), .{
+ EventTarget{ ._type = .audio_node },
+ AudioNode.init(context, .{ .type = .scheduled_source, .inputs = 0, .outputs = 1 }),
+ AudioScheduledSourceNode.init(.buffer_source),
+ AudioBufferSourceNode{
+ ._proto = undefined,
+ ._playback_rate = try kRateParam(context, 1),
+ ._detune = try kRateParam(context, 0),
+ ._loop = options.loop,
+ ._loop_start = options.loopStart,
+ ._loop_end = options.loopEnd,
+ },
+ });
+ try self._playback_rate.setInitial(options.playbackRate);
+ try self._detune.setInitial(options.detune);
+ try self.asNode().setup(.{});
+ if (options.buffer) |buffer| {
+ try self.setBuffer(buffer);
+ }
+ return self;
+}
+
+fn kRateParam(context: *BaseAudioContext, default: f32) !*AudioParam {
+ return AudioParam.init(context, .{ .default = default, .rate = .@"k-rate", .fixed_rate = true });
+}
+
+fn asNode(self: *AudioBufferSourceNode) *AudioNode {
+ return self._proto._proto;
+}
+
+// The context releases what its nodes hold when it goes away.
+pub fn deinit(self: *AudioBufferSourceNode, page: *Page) void {
+ self.releaseBuffer(page);
+}
+
+fn releaseBuffer(self: *AudioBufferSourceNode, page: *Page) void {
+ if (self._buffer) |buffer| {
+ self._buffer = null;
+ buffer.releaseRef(page);
+ }
+}
+
+fn getBuffer(self: *const AudioBufferSourceNode) ?*AudioBuffer {
+ return self._buffer;
+}
+
+fn setBuffer(self: *AudioBufferSourceNode, buffer_: ?*AudioBuffer) !void {
+ const buffer = buffer_ orelse {
+ self.releaseBuffer(self.asNode()._context._page);
+ return;
+ };
+ if (self._buffer_set) {
+ return error.InvalidStateError;
+ }
+ self._buffer_set = true;
+ buffer.acquireRef();
+ self.releaseBuffer(self.asNode()._context._page);
+ self._buffer = buffer;
+}
+
+fn getPlaybackRate(self: *const AudioBufferSourceNode) *AudioParam {
+ return self._playback_rate;
+}
+
+fn getDetune(self: *const AudioBufferSourceNode) *AudioParam {
+ return self._detune;
+}
+
+fn getLoop(self: *const AudioBufferSourceNode) bool {
+ return self._loop;
+}
+
+fn setLoop(self: *AudioBufferSourceNode, loop: bool) void {
+ self._loop = loop;
+}
+
+fn getLoopStart(self: *const AudioBufferSourceNode) f64 {
+ return self._loop_start;
+}
+
+fn setLoopStart(self: *AudioBufferSourceNode, value: f64) !void {
+ if (std.math.isFinite(value) == false) return error.TypeError;
+ self._loop_start = value;
+}
+
+fn getLoopEnd(self: *const AudioBufferSourceNode) f64 {
+ return self._loop_end;
+}
+
+fn setLoopEnd(self: *AudioBufferSourceNode, value: f64) !void {
+ if (std.math.isFinite(value) == false) return error.TypeError;
+ self._loop_end = value;
+}
+
+fn start(self: *AudioBufferSourceNode, when: ?f64, offset_: ?f64, duration: ?f64) !void {
+ const offset = offset_ orelse 0;
+ if (std.math.isFinite(offset) == false) return error.TypeError;
+ if (offset < 0) return error.RangeError;
+ if (duration) |d| {
+ if (std.math.isFinite(d) == false) return error.TypeError;
+ if (d < 0) return error.RangeError;
+ }
+ try self._proto.start(when);
+ self._offset = offset;
+ self._duration = duration;
+ self._started_empty = self._buffer == null;
+}
+
+pub fn process(self: *AudioBufferSourceNode, r: *render.Quantum, output: *Bus) !void {
+ const base = self._proto;
+ // Started without a buffer, or had it cleared since: it ends right away.
+ if (base._state != .unscheduled and (self._started_empty or self._buffer == null)) {
+ try base.finish(r);
+ }
+ // A source that isn't playing a buffer outputs one silent channel.
+ const buffer = self._buffer orelse return silence(r, output);
+ if (base._state == .finished) {
+ return silence(r, output);
+ }
+
+ const channel_count = buffer.numberOfChannels();
+ try output.setChannels(r.allocator, channel_count);
+ const schedule = try base.schedule(r, output);
+ if (schedule.frames == 0) {
+ return;
+ }
+
+ var channels: [AudioBuffer.max_channels][]const f32 = undefined;
+ var length: usize = buffer.frameCount();
+ for (0..channel_count) |c| {
+ channels[c] = buffer.channelData(c, r.local);
+ // detached arrays read as silence
+ length = @min(length, channels[c].len);
+ }
+ const end = schedule.offset + schedule.frames;
+ if (length == 0) {
+ output.zeroFrames(schedule.offset, end);
+ return base.finish(r);
+ }
+
+ const buffer_rate: f64 = buffer.sampleRate();
+ const len_f: f64 = @floatFromInt(length);
+ const rate = try self.computeRate(r, buffer_rate);
+ if (self._started_playing == false) {
+ self._started_playing = true;
+ const offset = @min(self._offset * buffer_rate, len_f);
+ // at the native rate, start on a whole frame rather than interpolate
+ self._position = if (rate == 1) @round(offset) else offset;
+ }
+
+ const loop = self.loopFrames(buffer_rate, len_f);
+ if (loop) |l| {
+ if (@abs(rate) > l.end - l.start) {
+ output.zeroFrames(schedule.offset, end);
+ return;
+ }
+ if (rate >= 0 and self._position >= l.end) {
+ self._position = @min(l.start, len_f - 1);
+ } else if (rate < 0 and self._position < l.start) {
+ self._position = l.start;
+ }
+ }
+ const grain_frames: ?f64 = if (self._duration) |d| d * buffer_rate else null;
+
+ var frame = schedule.offset;
+ while (frame < end) : (frame += 1) {
+ if (grain_frames) |g| {
+ if (self._played >= g) break;
+ }
+ var position = self._position;
+ if (loop) |l| {
+ if (rate >= 0 and position >= l.end) {
+ position -= l.end - l.start;
+ } else if (rate < 0 and position < l.start) {
+ position += l.end - l.start;
+ }
+ } else if ((rate >= 0 and position >= len_f) or position < 0) {
+ break;
+ }
+
+ const index: usize = @intFromFloat(@floor(position));
+ const fraction: f32 = @floatCast(position - @floor(position));
+ const next = if (loop) |l| blk: {
+ const loop_end: usize = @intFromFloat(@ceil(l.end));
+ break :blk if (index + 1 < loop_end) index + 1 else @as(usize, @intFromFloat(l.start));
+ } else @min(index + 1, length - 1);
+ for (0..channel_count) |c| {
+ const data = channels[c];
+ if (index >= length) {
+ output.channel(c)[frame] = 0;
+ continue;
+ }
+ const s0 = data[index];
+ const s1 = data[@min(next, length - 1)];
+ output.channel(c)[frame] = s0 + (s1 - s0) * fraction;
+ }
+
+ self._position = position + rate;
+ self._played += @abs(rate);
+ }
+
+ if (frame < end) {
+ output.zeroFrames(frame, Bus.quantum);
+ try base.finish(r);
+ }
+}
+
+fn silence(r: *render.Quantum, output: *Bus) !void {
+ try output.setChannels(r.allocator, 1);
+ output.zero();
+}
+
+fn computeRate(self: *AudioBufferSourceNode, r: *render.Quantum, buffer_rate: f64) !f64 {
+ const playback_rate = try self._playback_rate.finalValue(r);
+ const detune = try self._detune.finalValue(r);
+ const sample_rate_factor = buffer_rate / r.sample_rate;
+ var rate = sample_rate_factor * playback_rate * math.exp2f(detune / 1200);
+ if (std.math.isFinite(rate) == false) {
+ rate = 0;
+ }
+ return std.math.clamp(rate, -max_rate, max_rate);
+}
+
+const Loop = struct { start: f64, end: f64 };
+
+// The loop region in buffer frames: loopStart and loopEnd clamped to the
+// buffer (a loopEnd of 0 meaning its end), or the whole buffer when that's
+// empty.
+fn loopFrames(self: *const AudioBufferSourceNode, buffer_rate: f64, length: f64) ?Loop {
+ if (self._loop == false) {
+ return null;
+ }
+ const loop_start = std.math.clamp(self._loop_start * buffer_rate, 0, length);
+ const loop_end = if (self._loop_end == 0) length else std.math.clamp(self._loop_end * buffer_rate, 0, length);
+ if (loop_start < loop_end) {
+ return .{ .start = loop_start, .end = loop_end };
+ }
+ return .{ .start = 0, .end = length };
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(AudioBufferSourceNode);
+
+ pub const Meta = struct {
+ pub const name = "AudioBufferSourceNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(AudioBufferSourceNode.constructor, .{});
+ pub const buffer = bridge.accessor(AudioBufferSourceNode.getBuffer, AudioBufferSourceNode.setBuffer, .{});
+ pub const playbackRate = bridge.accessor(AudioBufferSourceNode.getPlaybackRate, null, .{});
+ pub const detune = bridge.accessor(AudioBufferSourceNode.getDetune, null, .{});
+ pub const loop = bridge.accessor(AudioBufferSourceNode.getLoop, AudioBufferSourceNode.setLoop, .{});
+ pub const loopStart = bridge.accessor(AudioBufferSourceNode.getLoopStart, AudioBufferSourceNode.setLoopStart, .{});
+ pub const loopEnd = bridge.accessor(AudioBufferSourceNode.getLoopEnd, AudioBufferSourceNode.setLoopEnd, .{});
+ pub const start = bridge.function(AudioBufferSourceNode.start, .{});
+};
diff --git a/src/browser/webapi/webaudio/AudioDestinationNode.zig b/src/browser/webapi/webaudio/AudioDestinationNode.zig
new file mode 100644
index 000000000..e32e6480b
--- /dev/null
+++ b/src/browser/webapi/webaudio/AudioDestinationNode.zig
@@ -0,0 +1,72 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#AudioDestinationNode
+
+const js = @import("../../js/js.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const AudioNode = @import("AudioNode.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+
+const AudioDestinationNode = @This();
+
+pub const Proto = AudioNode;
+
+_proto: *AudioNode,
+_max_channel_count: u32,
+
+// An OfflineAudioContext's destination. As in Chrome, script can change its
+// channel count and mode: only the channels both the input and the rendered
+// buffer have are written.
+pub fn createOffline(context: *BaseAudioContext, channels: u32) !*AudioDestinationNode {
+ const self = try Factory.chainedWithAllocator(context._arena.allocator(), .{
+ EventTarget{ ._type = .audio_node },
+ AudioNode.init(context, .{
+ .type = .destination,
+ .inputs = 1,
+ .outputs = 1,
+ .channel_count = channels,
+ .channel_count_mode = .explicit,
+ }),
+ AudioDestinationNode{ ._proto = undefined, ._max_channel_count = channels },
+ });
+ try self._proto.setup(.{});
+ return self;
+}
+
+pub fn asNode(self: *AudioDestinationNode) *AudioNode {
+ return self._proto;
+}
+
+fn getMaxChannelCount(self: *const AudioDestinationNode) u32 {
+ return self._max_channel_count;
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(AudioDestinationNode);
+
+ pub const Meta = struct {
+ pub const name = "AudioDestinationNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const maxChannelCount = bridge.accessor(AudioDestinationNode.getMaxChannelCount, null, .{});
+};
diff --git a/src/browser/webapi/webaudio/AudioNode.zig b/src/browser/webapi/webaudio/AudioNode.zig
new file mode 100644
index 000000000..2ed770284
--- /dev/null
+++ b/src/browser/webapi/webaudio/AudioNode.zig
@@ -0,0 +1,419 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#AudioNode
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const render = @import("render.zig");
+const AudioParam = @import("AudioParam.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+const GainNode = @import("GainNode.zig");
+const AudioDestinationNode = @import("AudioDestinationNode.zig");
+const DynamicsCompressorNode = @import("DynamicsCompressorNode.zig");
+const AudioScheduledSourceNode = @import("AudioScheduledSourceNode.zig");
+
+const AudioNode = @This();
+
+pub const Proto = EventTarget;
+
+_proto: *EventTarget,
+_type: Type,
+// Every node lives in its context's arena; a node's wrapper keeps the
+// context alive.
+_context: *BaseAudioContext,
+_inputs: u8,
+_outputs: u8,
+_channel_count: u32,
+_channel_count_mode: ChannelCountMode,
+_channel_interpretation: Bus.Interpretation,
+_rules: ChannelRules = .{},
+// output 0's connections
+_targets: std.ArrayList(Target) = .empty,
+// input 0's connections
+_sources: std.ArrayList(*AudioNode) = .empty,
+
+_input: Bus = .{},
+_output: Bus = .{},
+_rendered: u64 = 0,
+_pulling: bool = false,
+
+pub const Type = enum(u8) {
+ destination,
+ dynamics_compressor,
+ gain,
+ scheduled_source,
+};
+
+pub fn Subtype(comptime tag: Type) type {
+ return switch (tag) {
+ .destination => AudioDestinationNode,
+ .dynamics_compressor => DynamicsCompressorNode,
+ .gain => GainNode,
+ .scheduled_source => AudioScheduledSourceNode,
+ };
+}
+
+pub fn subtype(self: *const AudioNode, comptime T: type) *T {
+ const offset = comptime Factory.chainOffsetOf(T, T) - Factory.chainOffsetOf(T, AudioNode);
+ const sub: *T = @ptrFromInt(@intFromPtr(self) + offset);
+ if (comptime lp.IS_DEBUG) {
+ std.debug.assert(Factory.protoOf(sub) == self);
+ }
+ return sub;
+}
+
+pub const ChannelCountMode = enum {
+ max,
+ @"clamped-max",
+ explicit,
+
+ pub const js_enum_from_string = true;
+};
+
+pub const ChannelInterpretation = enum {
+ speakers,
+ discrete,
+
+ pub const js_enum_from_string = true;
+};
+
+// What a node lets script change, beyond the general 1..32 channel count.
+pub const ChannelRules = struct {
+ max_channel_count: u32 = Bus.max_channels,
+ // channelCountMode "max" is rejected (NotSupportedError)
+ no_max_mode: bool = false,
+};
+
+pub const Target = union(enum) {
+ node: *AudioNode,
+ param: *AudioParam,
+};
+
+// The AudioNodeOptions every node constructor takes.
+pub const Options = struct {
+ channelCount: ?u32 = null,
+ channelCountMode: ?ChannelCountMode = null,
+ channelInterpretation: ?ChannelInterpretation = null,
+};
+
+pub const Init = struct {
+ type: Type,
+ inputs: u8,
+ outputs: u8,
+ channel_count: u32 = 2,
+ channel_count_mode: ChannelCountMode = .max,
+ channel_interpretation: Bus.Interpretation = .speakers,
+ rules: ChannelRules = .{},
+};
+
+pub fn init(context: *BaseAudioContext, opts: Init) AudioNode {
+ return .{
+ ._proto = undefined,
+ ._type = opts.type,
+ ._context = context,
+ ._inputs = opts.inputs,
+ ._outputs = opts.outputs,
+ ._channel_count = opts.channel_count,
+ ._channel_count_mode = opts.channel_count_mode,
+ ._channel_interpretation = opts.channel_interpretation,
+ ._rules = opts.rules,
+ };
+}
+
+// Applies a constructor's AudioNodeOptions, then registers the node with its
+// context.
+pub fn setup(self: *AudioNode, options: Options) !void {
+ if (options.channelCount) |count| {
+ try self.setChannelCount(count);
+ }
+ if (options.channelCountMode) |mode| {
+ try self.applyChannelCountMode(mode);
+ }
+ if (options.channelInterpretation) |interpretation| {
+ self._channel_interpretation = switch (interpretation) {
+ .speakers => .speakers,
+ .discrete => .discrete,
+ };
+ }
+ try self._context.registerNode(self);
+}
+
+pub fn asEventTarget(self: *AudioNode) *EventTarget {
+ return self._proto;
+}
+
+pub fn format(self: *const AudioNode, writer: *std.Io.Writer) !void {
+ return writer.writeAll(self.describe("<{s}>"));
+}
+
+pub fn toString(self: *const AudioNode) []const u8 {
+ return self.describe("[object {s}]");
+}
+
+// `fmt` applied to the concrete node's interface name.
+fn describe(self: *const AudioNode, comptime fmt: []const u8) []const u8 {
+ return switch (self._type) {
+ .scheduled_source => switch (self.subtype(AudioScheduledSourceNode)._type) {
+ inline else => |tag| std.fmt.comptimePrint(fmt, .{AudioScheduledSourceNode.Subtype(tag).JsApi.Meta.name}),
+ },
+ inline else => |tag| std.fmt.comptimePrint(fmt, .{Subtype(tag).JsApi.Meta.name}),
+ };
+}
+
+pub fn acquireRef(self: *AudioNode) void {
+ self._context.acquireRef();
+}
+
+pub fn releaseRef(self: *AudioNode, page: *Page) void {
+ self._context.releaseRef(page);
+}
+
+fn getContext(self: *const AudioNode) *BaseAudioContext {
+ return self._context;
+}
+
+fn getNumberOfInputs(self: *const AudioNode) u32 {
+ return self._inputs;
+}
+
+fn getNumberOfOutputs(self: *const AudioNode) u32 {
+ return self._outputs;
+}
+
+fn getChannelCount(self: *const AudioNode) u32 {
+ return self._channel_count;
+}
+
+fn setChannelCount(self: *AudioNode, count: u32) !void {
+ if (count == 0 or count > self._rules.max_channel_count) {
+ return error.NotSupported;
+ }
+ self._channel_count = count;
+}
+
+fn getChannelCountMode(self: *const AudioNode) []const u8 {
+ return @tagName(self._channel_count_mode);
+}
+
+// An unknown enum value is ignored, as for any IDL enum attribute.
+fn setChannelCountMode(self: *AudioNode, value: []const u8) !void {
+ const mode = std.meta.stringToEnum(ChannelCountMode, value) orelse return;
+ return self.applyChannelCountMode(mode);
+}
+
+fn applyChannelCountMode(self: *AudioNode, mode: ChannelCountMode) !void {
+ if (self._rules.no_max_mode and mode == .max) {
+ return error.NotSupported;
+ }
+ self._channel_count_mode = mode;
+}
+
+fn getChannelInterpretation(self: *const AudioNode) []const u8 {
+ return @tagName(self._channel_interpretation);
+}
+
+fn setChannelInterpretation(self: *AudioNode, value: []const u8) void {
+ self._channel_interpretation = std.meta.stringToEnum(Bus.Interpretation, value) orelse return;
+}
+
+const ConnectTarget = union(enum) {
+ node: *AudioNode,
+ param: *AudioParam,
+};
+
+const Connected = union(enum) {
+ node: *AudioNode,
+ param: js.Undefined,
+};
+
+fn connect(self: *AudioNode, destination: ConnectTarget, output_: ?u32, input_: ?u32) !Connected {
+ const output = output_ orelse 0;
+ if (output >= self._outputs) {
+ return error.IndexSizeError;
+ }
+ const allocator = self._context._arena.allocator();
+ switch (destination) {
+ .node => |node| {
+ if (node._context != self._context) {
+ return error.InvalidAccessError;
+ }
+ const input = input_ orelse 0;
+ if (input >= node._inputs) {
+ return error.IndexSizeError;
+ }
+ if (self.findTarget(.{ .node = node }) == null) {
+ try self._targets.ensureUnusedCapacity(allocator, 1);
+ try node._sources.append(allocator, self);
+ self._targets.appendAssumeCapacity(.{ .node = node });
+ }
+ return .{ .node = node };
+ },
+ .param => |param| {
+ if (param._context != self._context) {
+ return error.InvalidAccessError;
+ }
+ if (self.findTarget(.{ .param = param }) == null) {
+ try self._targets.ensureUnusedCapacity(allocator, 1);
+ try param.connect(self);
+ self._targets.appendAssumeCapacity(.{ .param = param });
+ }
+ return .{ .param = .{} };
+ },
+ }
+}
+
+const DisconnectFrom = union(enum) {
+ output: u32,
+ node: *AudioNode,
+ param: *AudioParam,
+};
+
+fn disconnect(self: *AudioNode, from_: ?DisconnectFrom, output_: ?u32, input_: ?u32) !void {
+ const from = from_ orelse {
+ self.disconnectAll();
+ return;
+ };
+ switch (from) {
+ .output => |output| {
+ if (output >= self._outputs) {
+ return error.IndexSizeError;
+ }
+ self.disconnectAll();
+ },
+ inline .node, .param => |target, tag| {
+ if (output_) |output| {
+ if (output >= self._outputs) return error.IndexSizeError;
+ }
+ if (tag == .node) {
+ if (input_) |input| {
+ if (input >= target._inputs) return error.IndexSizeError;
+ }
+ }
+ const index = self.findTarget(@unionInit(Target, @tagName(tag), target)) orelse {
+ return error.InvalidAccessError;
+ };
+ self.removeTarget(index);
+ },
+ }
+}
+
+fn disconnectAll(self: *AudioNode) void {
+ while (self._targets.items.len > 0) {
+ self.removeTarget(self._targets.items.len - 1);
+ }
+}
+
+fn findTarget(self: *const AudioNode, target: Target) ?usize {
+ for (self._targets.items, 0..) |t, i| {
+ if (std.meta.eql(t, target)) return i;
+ }
+ return null;
+}
+
+fn removeTarget(self: *AudioNode, index: usize) void {
+ switch (self._targets.orderedRemove(index)) {
+ .node => |node| {
+ for (node._sources.items, 0..) |s, i| {
+ if (s == self) {
+ _ = node._sources.orderedRemove(i);
+ break;
+ }
+ }
+ },
+ .param => |param| _ = param.disconnect(self),
+ }
+}
+
+// This quantum's output, rendering it first if needed. A node reached again
+// while rendering is part of a cycle, which renders silence. So does a node
+// more than `render.max_depth` connections from the destination, where Chrome
+// would render the whole chain.
+pub fn pull(self: *AudioNode, r: *render.Quantum) anyerror!*const Bus {
+ if (self._rendered == r.index) {
+ return &self._output;
+ }
+ if (self._pulling or r.depth >= render.max_depth) {
+ return r.silence;
+ }
+ self._pulling = true;
+ r.depth += 1;
+ defer {
+ self._pulling = false;
+ r.depth -= 1;
+ }
+
+ const input = if (self._inputs > 0) try self.pullInput(r) else null;
+ switch (self._type) {
+ .destination => {},
+ .gain => try self.subtype(GainNode).process(r, input.?, &self._output),
+ .dynamics_compressor => try self.subtype(DynamicsCompressorNode).process(r, input.?, &self._output),
+ .scheduled_source => try self.subtype(AudioScheduledSourceNode).process(r, &self._output),
+ }
+ self._rendered = r.index;
+ return &self._output;
+}
+
+// The input bus: every connection mixed to the computed channel count.
+fn pullInput(self: *AudioNode, r: *render.Quantum) !*const Bus {
+ var max: u32 = 0;
+ for (self._sources.items) |source| {
+ const bus = try source.pull(r);
+ max = @max(max, bus.channels);
+ }
+ max = @max(max, 1);
+ const channels = switch (self._channel_count_mode) {
+ .max => max,
+ .@"clamped-max" => @min(max, self._channel_count),
+ .explicit => self._channel_count,
+ };
+
+ const input = &self._input;
+ try input.setChannels(r.allocator, channels);
+ input.zero();
+ for (self._sources.items) |source| {
+ input.sumFrom(try source.pull(r), self._channel_interpretation);
+ }
+ return input;
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(AudioNode);
+
+ pub const Meta = struct {
+ pub const name = "AudioNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const context = bridge.accessor(AudioNode.getContext, null, .{});
+ pub const numberOfInputs = bridge.accessor(AudioNode.getNumberOfInputs, null, .{});
+ pub const numberOfOutputs = bridge.accessor(AudioNode.getNumberOfOutputs, null, .{});
+ pub const channelCount = bridge.accessor(AudioNode.getChannelCount, AudioNode.setChannelCount, .{});
+ pub const channelCountMode = bridge.accessor(AudioNode.getChannelCountMode, AudioNode.setChannelCountMode, .{});
+ pub const channelInterpretation = bridge.accessor(AudioNode.getChannelInterpretation, AudioNode.setChannelInterpretation, .{});
+ pub const connect = bridge.function(AudioNode.connect, .{});
+ pub const disconnect = bridge.function(AudioNode.disconnect, .{});
+};
diff --git a/src/browser/webapi/webaudio/AudioParam.zig b/src/browser/webapi/webaudio/AudioParam.zig
new file mode 100644
index 000000000..ad566440c
--- /dev/null
+++ b/src/browser/webapi/webaudio/AudioParam.zig
@@ -0,0 +1,330 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#AudioParam
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const Timeline = @import("dsp/Timeline.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+
+const AudioParam = @This();
+
+// Lives in its context's arena; a wrapper keeps the whole context alive.
+_context: *BaseAudioContext,
+_default: f32,
+_min: f32,
+_max: f32,
+_rate: Rate,
+_fixed_rate: bool,
+// [[current value]]: what `value` reads. Rendering updates it.
+_intrinsic: f32,
+_timeline: Timeline = .{},
+// nodes connected to this param
+_sources: std.ArrayList(*AudioNode) = .empty,
+_sum: Bus = .{},
+
+pub const Rate = enum { @"a-rate", @"k-rate" };
+
+pub const Descriptor = struct {
+ default: f32,
+ min: f32 = -std.math.floatMax(f32),
+ max: f32 = std.math.floatMax(f32),
+ rate: Rate = .@"a-rate",
+ // a rate the spec doesn't let script change
+ fixed_rate: bool = false,
+};
+
+pub fn init(context: *BaseAudioContext, descriptor: Descriptor) !*AudioParam {
+ const param = try context._arena.allocator().create(AudioParam);
+ param.* = .{
+ ._context = context,
+ ._default = descriptor.default,
+ ._min = descriptor.min,
+ ._max = descriptor.max,
+ ._rate = descriptor.rate,
+ ._fixed_rate = descriptor.fixed_rate,
+ ._intrinsic = descriptor.default,
+ };
+ return param;
+}
+
+pub fn acquireRef(self: *AudioParam) void {
+ self._context.acquireRef();
+}
+
+pub fn releaseRef(self: *AudioParam, page: *Page) void {
+ self._context.releaseRef(page);
+}
+
+// For a node's options dictionary: the initial value, as if set before any
+// automation (no event is scheduled).
+pub fn setInitial(self: *AudioParam, value: f32) !void {
+ try finite(value);
+ self._intrinsic = std.math.clamp(value, self._min, self._max);
+}
+
+fn getValue(self: *const AudioParam) f32 {
+ return self._intrinsic;
+}
+
+fn setValue(self: *AudioParam, value: f32) !void {
+ try finite(value);
+ self._intrinsic = std.math.clamp(value, self._min, self._max);
+ _ = try self.setValueAtTime(self._intrinsic, self._context.currentTime());
+}
+
+fn getAutomationRate(self: *const AudioParam) []const u8 {
+ return @tagName(self._rate);
+}
+
+// An unknown enum value is ignored, as for any IDL enum attribute.
+fn setAutomationRate(self: *AudioParam, value: []const u8) !void {
+ const rate = std.meta.stringToEnum(Rate, value) orelse return;
+ if (self._fixed_rate and rate != self._rate) {
+ return error.InvalidStateError;
+ }
+ self._rate = rate;
+}
+
+fn getDefaultValue(self: *const AudioParam) f32 {
+ return self._default;
+}
+
+fn getMinValue(self: *const AudioParam) f32 {
+ return self._min;
+}
+
+fn getMaxValue(self: *const AudioParam) f32 {
+ return self._max;
+}
+
+fn setValueAtTime(self: *AudioParam, value: f32, start_time: f64) !*AudioParam {
+ try finite(value);
+ const time = try self.eventTime(start_time);
+ try self.insert(.{ .kind = .set_value, .time = time, .value = value });
+ return self;
+}
+
+fn linearRampToValueAtTime(self: *AudioParam, value: f32, end_time: f64) !*AudioParam {
+ try finite(value);
+ const time = try self.eventTime(end_time);
+ try self.insert(self.ramp(.linear_ramp, value, time));
+ return self;
+}
+
+fn exponentialRampToValueAtTime(self: *AudioParam, value: f32, end_time: f64) !*AudioParam {
+ try finite(value);
+ if (value == 0) {
+ return error.RangeError;
+ }
+ const time = try self.eventTime(end_time);
+ try self.insert(self.ramp(.exponential_ramp, value, time));
+ return self;
+}
+
+fn setTargetAtTime(self: *AudioParam, target: f32, start_time: f64, time_constant: f32) !*AudioParam {
+ try finite(target);
+ try finite(time_constant);
+ if (time_constant < 0) {
+ return error.RangeError;
+ }
+ const time = try self.eventTime(start_time);
+ try self.insert(.{ .kind = .set_target, .time = time, .value = target, .time_constant = time_constant });
+ return self;
+}
+
+fn setValueCurveAtTime(self: *AudioParam, values: []const f32, start_time: f64, duration: f64) !*AudioParam {
+ for (values) |v| try finite(v);
+ if (values.len < 2) {
+ return error.InvalidStateError;
+ }
+ if (std.math.isFinite(duration) == false) {
+ return error.TypeError;
+ }
+ if (duration <= 0) {
+ return error.RangeError;
+ }
+ const time = try self.eventTime(start_time);
+ const curve = try self._context._arena.allocator().dupe(f32, values);
+ try self.insert(.{ .kind = .set_value_curve, .time = time, .duration = duration, .end_time = time + duration, .curve = curve });
+ return self;
+}
+
+fn cancelScheduledValues(self: *AudioParam, cancel_time: f64) !*AudioParam {
+ const time = try self.eventTime(cancel_time);
+ self._timeline.cancelScheduledValues(time);
+ return self;
+}
+
+fn cancelAndHoldAtTime(self: *AudioParam, cancel_time: f64) !*AudioParam {
+ const time = try self.eventTime(cancel_time);
+ try self._timeline.cancelAndHoldAtTime(self._context._arena.allocator(), time);
+ return self;
+}
+
+// Times must be finite and non-negative; past times mean "now".
+fn eventTime(self: *const AudioParam, time: f64) !f64 {
+ if (std.math.isFinite(time) == false) {
+ return error.TypeError;
+ }
+ if (time < 0) {
+ return error.RangeError;
+ }
+ return @max(time, self._context.currentTime());
+}
+
+fn ramp(self: *const AudioParam, kind: Timeline.Kind, value: f32, time: f64) Timeline.Event {
+ return .{
+ .kind = kind,
+ .time = time,
+ .value = value,
+ .start_time = self._context.currentTime(),
+ .start_value = self._intrinsic,
+ };
+}
+
+fn insert(self: *AudioParam, event: Timeline.Event) !void {
+ return self._timeline.insert(self._context._arena.allocator(), event, self._intrinsic);
+}
+
+fn finite(value: f32) !void {
+ if (std.math.isFinite(value) == false) {
+ return error.TypeError;
+ }
+}
+
+pub fn connect(self: *AudioParam, source: *AudioNode) !void {
+ for (self._sources.items) |s| {
+ if (s == source) return;
+ }
+ try self._sources.append(self._context._arena.allocator(), source);
+}
+
+pub fn disconnect(self: *AudioParam, source: *AudioNode) bool {
+ for (self._sources.items, 0..) |s, i| {
+ if (s == source) {
+ _ = self._sources.orderedRemove(i);
+ return true;
+ }
+ }
+ return false;
+}
+
+// Whether this quantum needs per-frame values. Nodes with a cheaper path for
+// a constant value (the oscillator) check this first.
+pub fn hasSampleAccurateValues(self: *AudioParam, r: *const render.Quantum) bool {
+ if (self._sources.items.len > 0) {
+ return true;
+ }
+ const sample_rate: f64 = r.sample_rate;
+ const start: f64 = @floatFromInt(r.frame);
+ self._timeline.prune(start / sample_rate);
+ return self._timeline.hasSampleAccurateValues(start / sample_rate, (start + Bus.quantum) / sample_rate);
+}
+
+pub fn isAudioRate(self: *const AudioParam) bool {
+ return self._rate == .@"a-rate";
+}
+
+// The k-rate value: the timeline at the quantum's start, plus the inputs'
+// first frame.
+pub fn finalValue(self: *AudioParam, r: *render.Quantum) !f32 {
+ var values: [1]f32 = undefined;
+ try self.computeValues(r, &values, false);
+ return values[0];
+}
+
+// The computedValue for each frame of the quantum (`values.len` frames), or
+// one value repeated when not sample accurate.
+pub fn sampleAccurateValues(self: *AudioParam, r: *render.Quantum, values: *[Bus.quantum]f32) !void {
+ try self.computeValues(r, values, self.isAudioRate() and self.hasSampleAccurateValues(r));
+}
+
+fn computeValues(self: *AudioParam, r: *render.Quantum, values: []f32, sample_accurate: bool) !void {
+ const sample_rate: f64 = r.sample_rate;
+ const now = @as(f64, @floatFromInt(r.frame)) / sample_rate;
+ const timeline = &self._timeline;
+ timeline.prune(now);
+
+ if (sample_accurate) {
+ for (values, 0..) |*v, i| {
+ const t = @as(f64, @floatFromInt(r.frame + i)) / sample_rate;
+ v.* = std.math.clamp(timeline.valueAt(t, self._intrinsic), self._min, self._max);
+ }
+ self._intrinsic = values[values.len - 1];
+ } else {
+ var value = self._intrinsic;
+ if (timeline.isEmpty() == false) {
+ value = std.math.clamp(timeline.valueAt(now, value), self._min, self._max);
+ }
+ @memset(values, value);
+ self._intrinsic = value;
+ }
+
+ if (self._sources.items.len == 0) {
+ return;
+ }
+
+ // Connected outputs are summed in, down-mixed to mono.
+ try self._sum.setChannels(r.allocator, 1);
+ self._sum.zero();
+ for (self._sources.items) |source| {
+ self._sum.sumFrom(try source.pull(r), .speakers);
+ }
+ const sum = self._sum.channel(0);
+ if (sample_accurate) {
+ for (values, sum[0..values.len]) |*v, s| v.* += s;
+ } else {
+ const first = values[0] + sum[0];
+ @memset(values, first);
+ }
+ for (values) |*v| {
+ if (std.math.isNan(v.*)) v.* = self._default;
+ v.* = std.math.clamp(v.*, self._min, self._max);
+ }
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(AudioParam);
+
+ pub const Meta = struct {
+ pub const name = "AudioParam";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const value = bridge.accessor(AudioParam.getValue, AudioParam.setValue, .{});
+ pub const automationRate = bridge.accessor(AudioParam.getAutomationRate, AudioParam.setAutomationRate, .{});
+ pub const defaultValue = bridge.accessor(AudioParam.getDefaultValue, null, .{});
+ pub const minValue = bridge.accessor(AudioParam.getMinValue, null, .{});
+ pub const maxValue = bridge.accessor(AudioParam.getMaxValue, null, .{});
+ pub const setValueAtTime = bridge.function(AudioParam.setValueAtTime, .{});
+ pub const linearRampToValueAtTime = bridge.function(AudioParam.linearRampToValueAtTime, .{});
+ pub const exponentialRampToValueAtTime = bridge.function(AudioParam.exponentialRampToValueAtTime, .{});
+ pub const setTargetAtTime = bridge.function(AudioParam.setTargetAtTime, .{});
+ pub const setValueCurveAtTime = bridge.function(AudioParam.setValueCurveAtTime, .{});
+ pub const cancelScheduledValues = bridge.function(AudioParam.cancelScheduledValues, .{});
+ pub const cancelAndHoldAtTime = bridge.function(AudioParam.cancelAndHoldAtTime, .{});
+};
diff --git a/src/browser/webapi/webaudio/AudioScheduledSourceNode.zig b/src/browser/webapi/webaudio/AudioScheduledSourceNode.zig
new file mode 100644
index 000000000..366d019ec
--- /dev/null
+++ b/src/browser/webapi/webaudio/AudioScheduledSourceNode.zig
@@ -0,0 +1,198 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#AudioScheduledSourceNode
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const math = @import("dsp/math.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const OscillatorNode = @import("OscillatorNode.zig");
+const ConstantSourceNode = @import("ConstantSourceNode.zig");
+const AudioBufferSourceNode = @import("AudioBufferSourceNode.zig");
+
+const AudioScheduledSourceNode = @This();
+
+pub const Proto = AudioNode;
+
+_proto: *AudioNode,
+_type: Type,
+_state: State = .unscheduled,
+_start_time: f64 = 0,
+_end_time: ?f64 = null,
+
+pub const Type = enum(u8) {
+ buffer_source,
+ constant_source,
+ oscillator,
+};
+
+pub fn Subtype(comptime tag: Type) type {
+ return switch (tag) {
+ .buffer_source => AudioBufferSourceNode,
+ .constant_source => ConstantSourceNode,
+ .oscillator => OscillatorNode,
+ };
+}
+
+pub fn subtype(self: *const AudioScheduledSourceNode, comptime T: type) *T {
+ const offset = comptime Factory.chainOffsetOf(T, T) - Factory.chainOffsetOf(T, AudioScheduledSourceNode);
+ const sub: *T = @ptrFromInt(@intFromPtr(self) + offset);
+ if (comptime lp.IS_DEBUG) {
+ std.debug.assert(Factory.protoOf(sub) == self);
+ }
+ return sub;
+}
+
+pub const State = enum { unscheduled, scheduled, playing, finished };
+
+pub fn init(typ: Type) AudioScheduledSourceNode {
+ return .{ ._proto = undefined, ._type = typ };
+}
+
+pub fn asNode(self: *AudioScheduledSourceNode) *AudioNode {
+ return self._proto;
+}
+
+pub fn asEventTarget(self: *AudioScheduledSourceNode) *EventTarget {
+ return self._proto._proto;
+}
+
+pub fn start(self: *AudioScheduledSourceNode, when_: ?f64) !void {
+ const when = when_ orelse 0;
+ if (self._state != .unscheduled) {
+ return error.InvalidStateError;
+ }
+ if (std.math.isFinite(when) == false) {
+ return error.TypeError;
+ }
+ if (when < 0) {
+ return error.RangeError;
+ }
+ self._start_time = when;
+ self._state = .scheduled;
+}
+
+fn stop(self: *AudioScheduledSourceNode, when_: ?f64) !void {
+ const when = when_ orelse 0;
+ if (self._state == .unscheduled) {
+ return error.InvalidStateError;
+ }
+ if (std.math.isFinite(when) == false) {
+ return error.TypeError;
+ }
+ if (when < 0) {
+ return error.RangeError;
+ }
+ self._end_time = when;
+}
+
+// Ends playback; the context fires `ended` once the quantum is done.
+pub fn finish(self: *AudioScheduledSourceNode, r: *render.Quantum) !void {
+ if (self._state == .finished) {
+ return;
+ }
+ self._state = .finished;
+ try r.finished.append(r.allocator, self);
+}
+
+// Which frames of this quantum play. Frames outside [offset, offset + frames)
+// are already zeroed in `output`, which the source sized first.
+pub const Schedule = struct {
+ offset: usize,
+ frames: usize,
+ // How far before the first frame the exact start time is (<= 0), on the
+ // quantum the source starts.
+ start_frame_offset: f64,
+};
+
+// Port of Chrome's AudioScheduledSourceHandler::UpdateSchedulingInfo.
+pub fn schedule(self: *AudioScheduledSourceNode, r: *render.Quantum, output: *Bus) !Schedule {
+ const sample_rate: f64 = r.sample_rate;
+ const quantum_start = r.frame;
+ const quantum_end = quantum_start + Bus.quantum;
+ const start_frame = math.timeToSampleFrame(self._start_time, sample_rate, .up);
+ const end_frame: ?u64 = if (self._end_time) |end| math.timeToSampleFrame(end, sample_rate, .up) else null;
+
+ if (end_frame) |end| {
+ if (end <= quantum_start) {
+ try self.finish(r);
+ }
+ }
+
+ if (self._state == .unscheduled or self._state == .finished or start_frame >= quantum_end) {
+ output.zero();
+ return .{ .offset = 0, .frames = 0, .start_frame_offset = 0 };
+ }
+
+ var start_frame_offset: f64 = 0;
+ if (self._state == .scheduled) {
+ self._state = .playing;
+ start_frame_offset = self._start_time * sample_rate - @as(f64, @floatFromInt(start_frame));
+ }
+
+ const offset: usize = @intCast(@min(if (start_frame > quantum_start) start_frame - quantum_start else 0, Bus.quantum));
+ var frames = Bus.quantum - offset;
+ if (frames == 0) {
+ output.zero();
+ return .{ .offset = offset, .frames = 0, .start_frame_offset = start_frame_offset };
+ }
+ if (offset > 0) {
+ output.zeroFrames(0, offset);
+ }
+
+ if (end_frame) |end| {
+ if (end >= quantum_start and end <= quantum_end) {
+ if (end < quantum_end) {
+ const zero_start: usize = @intCast(end - quantum_start);
+ const zero_frames = Bus.quantum - zero_start;
+ frames = if (zero_frames > frames) 0 else frames - zero_frames;
+ output.zeroFrames(zero_start, Bus.quantum);
+ }
+ try self.finish(r);
+ }
+ }
+ return .{ .offset = offset, .frames = frames, .start_frame_offset = start_frame_offset };
+}
+
+pub fn process(self: *AudioScheduledSourceNode, r: *render.Quantum, output: *Bus) !void {
+ switch (self._type) {
+ inline else => |tag| try self.subtype(Subtype(tag)).process(r, output),
+ }
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(AudioScheduledSourceNode);
+
+ pub const Meta = struct {
+ pub const name = "AudioScheduledSourceNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const start = bridge.function(AudioScheduledSourceNode.start, .{});
+ pub const stop = bridge.function(AudioScheduledSourceNode.stop, .{});
+ pub const onended = EventTarget.handlerAccessor(AudioScheduledSourceNode, "ended");
+};
diff --git a/src/browser/webapi/webaudio/BaseAudioContext.zig b/src/browser/webapi/webaudio/BaseAudioContext.zig
new file mode 100644
index 000000000..875ad5d45
--- /dev/null
+++ b/src/browser/webapi/webaudio/BaseAudioContext.zig
@@ -0,0 +1,334 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#BaseAudioContext
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+const Frame = @import("../../Frame.zig");
+const Factory = @import("../../Factory.zig");
+
+const Event = @import("../Event.zig");
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const Wavetable = @import("dsp/PeriodicWave.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const GainNode = @import("GainNode.zig");
+const AudioBuffer = @import("AudioBuffer.zig");
+const PeriodicWave = @import("PeriodicWave.zig");
+const OscillatorNode = @import("OscillatorNode.zig");
+const ConstantSourceNode = @import("ConstantSourceNode.zig");
+const OfflineAudioContext = @import("OfflineAudioContext.zig");
+const AudioBufferSourceNode = @import("AudioBufferSourceNode.zig");
+const AudioDestinationNode = @import("AudioDestinationNode.zig");
+const DynamicsCompressorNode = @import("DynamicsCompressorNode.zig");
+const AudioScheduledSourceNode = @import("AudioScheduledSourceNode.zig");
+
+const log = lp.log;
+
+const BaseAudioContext = @This();
+
+pub const Proto = EventTarget;
+
+_proto: *EventTarget,
+_type: Type,
+// Held by the context's wrapper, every node and param wrapper, and pending
+// tasks. The whole graph lives in _arena.
+_rc: lp.RC = .{},
+_arena: *lp.Arena,
+// where tasks run and events dispatch
+_frame: *Frame,
+// for releasing refs: teardown can outlive the frame
+_page: *Page,
+_sample_rate: f32,
+// the first frame of the next quantum to render
+_current_frame: u64 = 0,
+_render_count: u64 = 0,
+_state: State = .suspended,
+_destination: *AudioDestinationNode = undefined,
+_nodes: std.ArrayList(*AudioNode) = .empty,
+_waves: [@typeInfo(Wavetable.Shape).@"enum".field_names.len]?*Wavetable = @splat(null),
+// sources that finished in the quanta rendered since the last `ended` events
+_finished: std.ArrayList(*AudioScheduledSourceNode) = .empty,
+_silence: Bus = .{},
+
+pub const Type = enum(u8) {
+ offline,
+};
+
+pub fn Subtype(comptime tag: Type) type {
+ return switch (tag) {
+ .offline => OfflineAudioContext,
+ };
+}
+
+pub fn subtype(self: *const BaseAudioContext, comptime T: type) *T {
+ const offset = comptime Factory.chainOffsetOf(T, T) - Factory.chainOffsetOf(T, BaseAudioContext);
+ const sub: *T = @ptrFromInt(@intFromPtr(self) + offset);
+ if (comptime lp.IS_DEBUG) {
+ std.debug.assert(Factory.protoOf(sub) == self);
+ }
+ return sub;
+}
+
+pub const State = enum { suspended, running, closed };
+
+pub fn init(typ: Type, arena: *lp.Arena, sample_rate: f32, frame: *Frame) BaseAudioContext {
+ return .{
+ ._proto = undefined,
+ ._type = typ,
+ ._arena = arena,
+ ._frame = frame,
+ ._page = frame.page,
+ ._sample_rate = sample_rate,
+ };
+}
+
+pub fn deinit(self: *BaseAudioContext, page: *Page) void {
+ for (self._nodes.items) |node| {
+ if (node._type == .scheduled_source) {
+ const source = node.subtype(AudioScheduledSourceNode);
+ switch (source._type) {
+ .oscillator => source.subtype(OscillatorNode).deinit(page),
+ .buffer_source => source.subtype(AudioBufferSourceNode).deinit(page),
+ .constant_source => {},
+ }
+ }
+ page.removeTarget(node.asEventTarget());
+ }
+ switch (self._type) {
+ .offline => self.subtype(OfflineAudioContext).deinit(page),
+ }
+ page.removeTarget(self.asEventTarget());
+ self._arena.release();
+}
+
+pub fn acquireRef(self: *BaseAudioContext) void {
+ self._rc.acquire();
+}
+
+pub fn releaseRef(self: *BaseAudioContext, page: *Page) void {
+ self._rc.release(self, page);
+}
+
+pub fn asEventTarget(self: *BaseAudioContext) *EventTarget {
+ return self._proto;
+}
+
+pub fn currentTime(self: *const BaseAudioContext) f64 {
+ return @as(f64, @floatFromInt(self._current_frame)) / self._sample_rate;
+}
+
+pub fn registerNode(self: *BaseAudioContext, node: *AudioNode) !void {
+ try self._nodes.append(self._arena.allocator(), node);
+}
+
+// The built-in waveforms' tables, built on first use.
+pub fn basicWave(self: *BaseAudioContext, shape: Wavetable.Shape) !*const Wavetable {
+ const slot = &self._waves[@backingInt(shape)];
+ if (slot.*) |wave| {
+ return wave;
+ }
+ const allocator = self._arena.allocator();
+ const wave = try allocator.create(Wavetable);
+ wave.* = try .initBasic(allocator, self._sample_rate, shape);
+ slot.* = wave;
+ return wave;
+}
+
+// Renders the next quantum; the destination's input is the result.
+pub fn renderQuantum(self: *BaseAudioContext, local: *const js.Local) !*const Bus {
+ self._render_count += 1;
+ if (self._silence.channels == 0) {
+ try self._silence.setChannels(self._arena.allocator(), 1);
+ self._silence.zero();
+ }
+ var quantum: render.Quantum = .{
+ .index = self._render_count,
+ .frame = self._current_frame,
+ .sample_rate = self._sample_rate,
+ .allocator = self._arena.allocator(),
+ .local = local,
+ .finished = &self._finished,
+ .silence = &self._silence,
+ };
+ const destination = self._destination.asNode();
+ _ = try destination.pull(&quantum);
+
+ // Sources play (and end) whether or not they reach the destination.
+ for (self._nodes.items) |node| {
+ if (node._type != .scheduled_source or node._rendered == quantum.index) {
+ continue;
+ }
+ const state = node.subtype(AudioScheduledSourceNode)._state;
+ if (state == .scheduled or state == .playing) {
+ _ = try node.pull(&quantum);
+ }
+ }
+ self._current_frame += Bus.quantum;
+ return &destination._input;
+}
+
+// Listeners run script, so the list is re-read after each one.
+pub fn dispatchEnded(self: *BaseAudioContext) void {
+ const frame = self._frame;
+ while (self._finished.items.len > 0) {
+ const source = self._finished.orderedRemove(0);
+ const target = source.asEventTarget();
+ if (frame._event_manager.hasDirectListeners(target, "ended") == false) {
+ continue;
+ }
+ const event = Event.initTrusted(comptime .wrap("ended"), .{}, frame.page) catch |err| {
+ log.warn(.js, "AudioScheduledSourceNode ended", .{ .err = err });
+ continue;
+ };
+ frame._event_manager.dispatchDirect(target, event, .{ .context = "AudioScheduledSourceNode ended" }) catch |err| {
+ log.debug(.js, "AudioScheduledSourceNode ended", .{ .err = err });
+ };
+ }
+}
+
+// The state changes now; the `statechange` event fires a task later.
+pub fn setState(self: *BaseAudioContext, state: State) void {
+ if (self._state == state) {
+ return;
+ }
+ self._state = state;
+ StateChangeTask.queue(self) catch |err| {
+ log.warn(.js, "AudioContext statechange", .{ .err = err });
+ };
+}
+
+const StateChangeTask = struct {
+ context: *BaseAudioContext,
+
+ fn queue(context: *BaseAudioContext) !void {
+ const frame = context._frame;
+ const task = try frame._factory.create(StateChangeTask{ .context = context });
+ errdefer frame._factory.destroy(task);
+ context.acquireRef();
+ errdefer context.releaseRef(frame.page);
+ try frame.js.scheduler.add(task, run, 0, .{
+ .name = "AudioContext.statechange",
+ .finalizer = cancelled,
+ });
+ }
+
+ fn run(ctx: *anyopaque) !?u32 {
+ const task: *StateChangeTask = @ptrCast(@alignCast(ctx));
+ const context = task.context;
+ const frame = context._frame;
+ frame._factory.destroy(task);
+ defer context.releaseRef(frame.page);
+
+ const target = context.asEventTarget();
+ if (frame._event_manager.hasDirectListeners(target, "statechange")) {
+ const event = try Event.initTrusted(comptime .wrap("statechange"), .{}, frame.page);
+ try frame._event_manager.dispatchDirect(target, event, .{ .context = "AudioContext statechange" });
+ }
+ return null;
+ }
+
+ fn cancelled(ctx: *anyopaque) void {
+ const task: *StateChangeTask = @ptrCast(@alignCast(ctx));
+ const context = task.context;
+ const frame = context._frame;
+ frame._factory.destroy(task);
+ context.releaseRef(frame.page);
+ }
+};
+
+fn getDestination(self: *const BaseAudioContext) *AudioDestinationNode {
+ return self._destination;
+}
+
+fn getSampleRate(self: *const BaseAudioContext) f32 {
+ return self._sample_rate;
+}
+
+fn getCurrentTime(self: *const BaseAudioContext) f64 {
+ return self.currentTime();
+}
+
+fn getState(self: *const BaseAudioContext) []const u8 {
+ return @tagName(self._state);
+}
+
+fn createBuffer(_: *BaseAudioContext, number_of_channels: u32, length: u32, sample_rate: f32, frame: *Frame) !*AudioBuffer {
+ return AudioBuffer.create(number_of_channels, length, sample_rate, frame.js.local.?, frame.page);
+}
+
+fn createBufferSource(self: *BaseAudioContext) !*AudioBufferSourceNode {
+ return AudioBufferSourceNode.create(self, .{});
+}
+
+fn createConstantSource(self: *BaseAudioContext) !*ConstantSourceNode {
+ return ConstantSourceNode.create(self, .{});
+}
+
+fn createDynamicsCompressor(self: *BaseAudioContext) !*DynamicsCompressorNode {
+ return DynamicsCompressorNode.create(self, .{});
+}
+
+fn createGain(self: *BaseAudioContext) !*GainNode {
+ return GainNode.create(self, .{});
+}
+
+fn createOscillator(self: *BaseAudioContext) !*OscillatorNode {
+ return OscillatorNode.create(self, .{});
+}
+
+const PeriodicWaveConstraints = struct {
+ disableNormalization: bool = false,
+};
+
+fn createPeriodicWave(self: *BaseAudioContext, real: []const f32, imag: []const f32, constraints_: ?PeriodicWaveConstraints) !*PeriodicWave {
+ const constraints = constraints_ orelse PeriodicWaveConstraints{};
+ return PeriodicWave.create(self, .{
+ .real = real,
+ .imag = imag,
+ .disableNormalization = constraints.disableNormalization,
+ });
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(BaseAudioContext);
+
+ pub const Meta = struct {
+ pub const name = "BaseAudioContext";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const destination = bridge.accessor(BaseAudioContext.getDestination, null, .{});
+ pub const sampleRate = bridge.accessor(BaseAudioContext.getSampleRate, null, .{});
+ pub const currentTime = bridge.accessor(BaseAudioContext.getCurrentTime, null, .{});
+ pub const state = bridge.accessor(BaseAudioContext.getState, null, .{});
+ pub const onstatechange = EventTarget.handlerAccessor(BaseAudioContext, "statechange");
+ pub const createBuffer = bridge.function(BaseAudioContext.createBuffer, .{});
+ pub const createBufferSource = bridge.function(BaseAudioContext.createBufferSource, .{});
+ pub const createConstantSource = bridge.function(BaseAudioContext.createConstantSource, .{});
+ pub const createDynamicsCompressor = bridge.function(BaseAudioContext.createDynamicsCompressor, .{});
+ pub const createGain = bridge.function(BaseAudioContext.createGain, .{});
+ pub const createOscillator = bridge.function(BaseAudioContext.createOscillator, .{});
+ pub const createPeriodicWave = bridge.function(BaseAudioContext.createPeriodicWave, .{});
+};
diff --git a/src/browser/webapi/webaudio/ConstantSourceNode.zig b/src/browser/webapi/webaudio/ConstantSourceNode.zig
new file mode 100644
index 000000000..d6561601b
--- /dev/null
+++ b/src/browser/webapi/webaudio/ConstantSourceNode.zig
@@ -0,0 +1,86 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#ConstantSourceNode
+
+const js = @import("../../js/js.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const AudioParam = @import("AudioParam.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+const AudioScheduledSourceNode = @import("AudioScheduledSourceNode.zig");
+
+const ConstantSourceNode = @This();
+
+pub const Proto = AudioScheduledSourceNode;
+
+_proto: *AudioScheduledSourceNode,
+_offset: *AudioParam,
+
+const Options = struct {
+ offset: f32 = 1,
+};
+
+fn constructor(context: *BaseAudioContext, options_: ?Options) !*ConstantSourceNode {
+ return create(context, options_ orelse .{});
+}
+
+pub fn create(context: *BaseAudioContext, options: Options) !*ConstantSourceNode {
+ const self = try Factory.chainedWithAllocator(context._arena.allocator(), .{
+ EventTarget{ ._type = .audio_node },
+ AudioNode.init(context, .{ .type = .scheduled_source, .inputs = 0, .outputs = 1 }),
+ AudioScheduledSourceNode.init(.constant_source),
+ ConstantSourceNode{ ._proto = undefined, ._offset = try AudioParam.init(context, .{ .default = 1 }) },
+ });
+ try self._offset.setInitial(options.offset);
+ try self._proto._proto.setup(.{});
+ return self;
+}
+
+fn getOffset(self: *const ConstantSourceNode) *AudioParam {
+ return self._offset;
+}
+
+pub fn process(self: *ConstantSourceNode, r: *render.Quantum, output: *Bus) !void {
+ try output.setChannels(r.allocator, 1);
+ const schedule = try self._proto.schedule(r, output);
+ if (schedule.frames == 0) {
+ return;
+ }
+ var values: [Bus.quantum]f32 = undefined;
+ try self._offset.sampleAccurateValues(r, &values);
+ const start = schedule.offset;
+ @memcpy(output.channel(0)[start..][0..schedule.frames], values[start..][0..schedule.frames]);
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(ConstantSourceNode);
+
+ pub const Meta = struct {
+ pub const name = "ConstantSourceNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(ConstantSourceNode.constructor, .{});
+ pub const offset = bridge.accessor(ConstantSourceNode.getOffset, null, .{});
+};
diff --git a/src/browser/webapi/webaudio/DynamicsCompressorNode.zig b/src/browser/webapi/webaudio/DynamicsCompressorNode.zig
new file mode 100644
index 000000000..fe83b393c
--- /dev/null
+++ b/src/browser/webapi/webaudio/DynamicsCompressorNode.zig
@@ -0,0 +1,159 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#DynamicsCompressorNode
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const Compressor = @import("dsp/Compressor.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const AudioParam = @import("AudioParam.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+
+const DynamicsCompressorNode = @This();
+
+pub const Proto = AudioNode;
+
+_proto: *AudioNode,
+_threshold: *AudioParam,
+_knee: *AudioParam,
+_ratio: *AudioParam,
+_attack: *AudioParam,
+_release: *AudioParam,
+_kernel: Compressor,
+_reduction: f32 = 0,
+
+const Options = struct {
+ attack: f32 = 0.003,
+ channelCount: ?u32 = null,
+ channelCountMode: ?AudioNode.ChannelCountMode = null,
+ channelInterpretation: ?AudioNode.ChannelInterpretation = null,
+ knee: f32 = 30,
+ ratio: f32 = 12,
+ release: f32 = 0.25,
+ threshold: f32 = -24,
+};
+
+fn constructor(context: *BaseAudioContext, options_: ?Options) !*DynamicsCompressorNode {
+ return create(context, options_ orelse .{});
+}
+
+pub fn create(context: *BaseAudioContext, options: Options) !*DynamicsCompressorNode {
+ const self = try Factory.chainedWithAllocator(context._arena.allocator(), .{
+ EventTarget{ ._type = .audio_node },
+ AudioNode.init(context, .{
+ .type = .dynamics_compressor,
+ .inputs = 1,
+ .outputs = 1,
+ .channel_count_mode = .@"clamped-max",
+ .rules = .{ .max_channel_count = 2, .no_max_mode = true },
+ }),
+ DynamicsCompressorNode{
+ ._proto = undefined,
+ ._threshold = try param(context, -24, -100, 0),
+ ._knee = try param(context, 30, 0, 40),
+ ._ratio = try param(context, 12, 1, 20),
+ ._attack = try param(context, 0.003, 0, 1),
+ ._release = try param(context, 0.25, 0, 1),
+ ._kernel = .init(context._sample_rate),
+ },
+ });
+ try self._threshold.setInitial(options.threshold);
+ try self._knee.setInitial(options.knee);
+ try self._ratio.setInitial(options.ratio);
+ try self._attack.setInitial(options.attack);
+ try self._release.setInitial(options.release);
+ try self._proto.setup(.{
+ .channelCount = options.channelCount,
+ .channelCountMode = options.channelCountMode,
+ .channelInterpretation = options.channelInterpretation,
+ });
+ return self;
+}
+
+fn param(context: *BaseAudioContext, default: f32, min: f32, max: f32) !*AudioParam {
+ return AudioParam.init(context, .{ .default = default, .min = min, .max = max, .rate = .@"k-rate", .fixed_rate = true });
+}
+
+fn getThreshold(self: *const DynamicsCompressorNode) *AudioParam {
+ return self._threshold;
+}
+
+fn getKnee(self: *const DynamicsCompressorNode) *AudioParam {
+ return self._knee;
+}
+
+fn getRatio(self: *const DynamicsCompressorNode) *AudioParam {
+ return self._ratio;
+}
+
+fn getAttack(self: *const DynamicsCompressorNode) *AudioParam {
+ return self._attack;
+}
+
+fn getRelease(self: *const DynamicsCompressorNode) *AudioParam {
+ return self._release;
+}
+
+fn getReduction(self: *const DynamicsCompressorNode) f32 {
+ return self._reduction;
+}
+
+// The kernel runs two channels whatever the input, as Chrome's does.
+pub fn process(self: *DynamicsCompressorNode, r: *render.Quantum, input: *const Bus, output: *Bus) !void {
+ const params: Compressor.Params = .{
+ .threshold = try self._threshold.finalValue(r),
+ .knee = try self._knee.finalValue(r),
+ .ratio = try self._ratio.finalValue(r),
+ .attack = try self._attack.finalValue(r),
+ .release = try self._release.finalValue(r),
+ };
+
+ try output.setChannels(r.allocator, Compressor.channels);
+ var source: [Compressor.channels][]const f32 = undefined;
+ for (0..@min(input.channels, Compressor.channels)) |c| {
+ source[c] = input.constChannel(c);
+ }
+ const destination: [Compressor.channels][]f32 = .{ output.channel(0), output.channel(1) };
+ self._kernel.process(source[0..@min(input.channels, Compressor.channels)], &destination, params);
+ self._reduction = self._kernel.reduction();
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(DynamicsCompressorNode);
+
+ pub const Meta = struct {
+ pub const name = "DynamicsCompressorNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(DynamicsCompressorNode.constructor, .{});
+ pub const threshold = bridge.accessor(DynamicsCompressorNode.getThreshold, null, .{});
+ pub const knee = bridge.accessor(DynamicsCompressorNode.getKnee, null, .{});
+ pub const ratio = bridge.accessor(DynamicsCompressorNode.getRatio, null, .{});
+ pub const attack = bridge.accessor(DynamicsCompressorNode.getAttack, null, .{});
+ pub const release = bridge.accessor(DynamicsCompressorNode.getRelease, null, .{});
+ pub const reduction = bridge.accessor(DynamicsCompressorNode.getReduction, null, .{});
+};
diff --git a/src/browser/webapi/webaudio/GainNode.zig b/src/browser/webapi/webaudio/GainNode.zig
new file mode 100644
index 000000000..8f0e25208
--- /dev/null
+++ b/src/browser/webapi/webaudio/GainNode.zig
@@ -0,0 +1,92 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#GainNode
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const AudioParam = @import("AudioParam.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+
+const GainNode = @This();
+
+pub const Proto = AudioNode;
+
+_proto: *AudioNode,
+_gain: *AudioParam,
+
+const Options = struct {
+ channelCount: ?u32 = null,
+ channelCountMode: ?AudioNode.ChannelCountMode = null,
+ channelInterpretation: ?AudioNode.ChannelInterpretation = null,
+ gain: f32 = 1,
+};
+
+fn constructor(context: *BaseAudioContext, options_: ?Options) !*GainNode {
+ return create(context, options_ orelse .{});
+}
+
+pub fn create(context: *BaseAudioContext, options: Options) !*GainNode {
+ const self = try Factory.chainedWithAllocator(context._arena.allocator(), .{
+ EventTarget{ ._type = .audio_node },
+ AudioNode.init(context, .{ .type = .gain, .inputs = 1, .outputs = 1 }),
+ GainNode{ ._proto = undefined, ._gain = try AudioParam.init(context, .{ .default = 1 }) },
+ });
+ try self._gain.setInitial(options.gain);
+ try self._proto.setup(.{
+ .channelCount = options.channelCount,
+ .channelCountMode = options.channelCountMode,
+ .channelInterpretation = options.channelInterpretation,
+ });
+ return self;
+}
+
+fn getGain(self: *const GainNode) *AudioParam {
+ return self._gain;
+}
+
+pub fn process(self: *GainNode, r: *render.Quantum, input: *const Bus, output: *Bus) !void {
+ try output.setChannels(r.allocator, input.channels);
+ var gains: [Bus.quantum]f32 = undefined;
+ try self._gain.sampleAccurateValues(r, &gains);
+ for (0..input.channels) |c| {
+ const in = input.constChannel(c);
+ const out = output.channel(c);
+ for (out, in, gains) |*o, i, g| o.* = i * g;
+ }
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(GainNode);
+
+ pub const Meta = struct {
+ pub const name = "GainNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(GainNode.constructor, .{});
+ pub const gain = bridge.accessor(GainNode.getGain, null, .{});
+};
diff --git a/src/browser/webapi/webaudio/OfflineAudioCompletionEvent.zig b/src/browser/webapi/webaudio/OfflineAudioCompletionEvent.zig
new file mode 100644
index 000000000..767613db0
--- /dev/null
+++ b/src/browser/webapi/webaudio/OfflineAudioCompletionEvent.zig
@@ -0,0 +1,97 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#OfflineAudioCompletionEvent
+
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+
+const Event = @import("../Event.zig");
+const AudioBuffer = @import("AudioBuffer.zig");
+
+const String = lp.String;
+
+const OfflineAudioCompletionEvent = @This();
+
+pub const Proto = Event;
+
+_proto: *Event,
+// holds a ref
+_rendered_buffer: *AudioBuffer,
+
+const Options = Event.inheritOptions(OfflineAudioCompletionEvent, struct {
+ renderedBuffer: *AudioBuffer,
+});
+
+fn constructor(typ: []const u8, options: Options, page: *Page) !*OfflineAudioCompletionEvent {
+ const arena = try page.getArena(.tiny, "OfflineAudioCompletionEvent");
+ errdefer arena.release();
+ const type_string = try String.init(arena.allocator(), typ, .{});
+ return initWithTrusted(arena, type_string, options, false, page);
+}
+
+pub fn initTrusted(rendered_buffer: *AudioBuffer, page: *Page) !*OfflineAudioCompletionEvent {
+ const arena = try page.getArena(.tiny, "OfflineAudioCompletionEvent.trusted");
+ errdefer arena.release();
+ return initWithTrusted(arena, comptime .wrap("complete"), .{ .renderedBuffer = rendered_buffer }, true, page);
+}
+
+fn initWithTrusted(arena: *lp.Arena, typ: String, options: Options, trusted: bool, page: *Page) !*OfflineAudioCompletionEvent {
+ const event = try page.factory.event(arena, typ, OfflineAudioCompletionEvent{
+ ._proto = undefined,
+ ._rendered_buffer = options.renderedBuffer,
+ });
+ options.renderedBuffer.acquireRef();
+ Event.populatePrototypes(event, options, trusted);
+ return event;
+}
+
+pub fn deinit(self: *OfflineAudioCompletionEvent, page: *Page) void {
+ self._rendered_buffer.releaseRef(page);
+ self._proto.deinit(page);
+}
+
+pub fn acquireRef(self: *OfflineAudioCompletionEvent) void {
+ self._proto.acquireRef();
+}
+
+pub fn releaseRef(self: *OfflineAudioCompletionEvent, page: *Page) void {
+ self._proto._rc.release(self, page);
+}
+
+pub fn asEvent(self: *OfflineAudioCompletionEvent) *Event {
+ return self._proto;
+}
+
+fn getRenderedBuffer(self: *const OfflineAudioCompletionEvent) *AudioBuffer {
+ return self._rendered_buffer;
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(OfflineAudioCompletionEvent);
+
+ pub const Meta = struct {
+ pub const name = "OfflineAudioCompletionEvent";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(OfflineAudioCompletionEvent.constructor, .{});
+ pub const renderedBuffer = bridge.accessor(OfflineAudioCompletionEvent.getRenderedBuffer, null, .{});
+};
diff --git a/src/browser/webapi/webaudio/OfflineAudioContext.zig b/src/browser/webapi/webaudio/OfflineAudioContext.zig
new file mode 100644
index 000000000..fb65c0bd3
--- /dev/null
+++ b/src/browser/webapi/webaudio/OfflineAudioContext.zig
@@ -0,0 +1,363 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#OfflineAudioContext
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+const Frame = @import("../../Frame.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const AudioBuffer = @import("AudioBuffer.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+const AudioDestinationNode = @import("AudioDestinationNode.zig");
+const OfflineAudioCompletionEvent = @import("OfflineAudioCompletionEvent.zig");
+
+const log = lp.log;
+
+const OfflineAudioContext = @This();
+
+pub const Proto = BaseAudioContext;
+
+// Quanta rendered per task, so a long render doesn't hog the event loop.
+const quanta_per_task = 1024;
+
+_proto: *BaseAudioContext,
+_length: u32,
+_channels: u32,
+_started: bool = false,
+_render_scheduled: bool = false,
+_complete: ?js.PromiseResolver.Global = null,
+_rendered: ?*AudioBuffer = null,
+// suspend() promises, by frame (a multiple of the quantum size)
+_suspends: std.ArrayList(Suspend) = .empty,
+
+const Suspend = struct {
+ frame: u64,
+ resolver: js.PromiseResolver.Global,
+};
+
+const Options = struct {
+ length: u32,
+ numberOfChannels: u32 = 1,
+ sampleRate: f32,
+};
+
+const OptionsOrChannels = union(enum) {
+ options: Options,
+ channels: u32,
+};
+
+fn constructor(first: OptionsOrChannels, length_: ?u32, sample_rate_: ?f32, frame: *Frame) !*OfflineAudioContext {
+ const options: Options = switch (first) {
+ .options => |o| o,
+ .channels => |channels| .{
+ .numberOfChannels = channels,
+ .length = length_ orelse return error.TypeError,
+ .sampleRate = sample_rate_ orelse return error.TypeError,
+ },
+ };
+ try AudioBuffer.validate(options.numberOfChannels, options.length, options.sampleRate);
+
+ const arena = try frame.getArena(.medium, "OfflineAudioContext");
+ errdefer arena.release();
+
+ const self = try Factory.chainedWithAllocator(arena.allocator(), .{
+ EventTarget{ ._type = .base_audio_context },
+ BaseAudioContext.init(.offline, arena, options.sampleRate, frame),
+ OfflineAudioContext{
+ ._proto = undefined,
+ ._length = options.length,
+ ._channels = options.numberOfChannels,
+ },
+ });
+ const base = self._proto;
+ base._destination = try AudioDestinationNode.createOffline(base, options.numberOfChannels);
+ return self;
+}
+
+pub fn deinit(self: *OfflineAudioContext, page: *Page) void {
+ if (self._complete) |resolver| {
+ resolver.release();
+ }
+ for (self._suspends.items) |s| {
+ s.resolver.release();
+ }
+ if (self._rendered) |buffer| {
+ buffer.releaseRef(page);
+ }
+}
+
+pub fn asEventTarget(self: *OfflineAudioContext) *EventTarget {
+ return self._proto._proto;
+}
+
+fn getLength(self: *const OfflineAudioContext) u32 {
+ return self._length;
+}
+
+fn startRendering(self: *OfflineAudioContext, frame: *Frame) !js.Promise {
+ const base = self._proto;
+ if (base._state == .closed or self._started) {
+ return error.InvalidStateError;
+ }
+
+ const local = frame.js.local.?;
+ const buffer = try AudioBuffer.create(self._channels, self._length, base._sample_rate, local, frame.page);
+ buffer.acquireRef();
+ errdefer buffer.releaseRef(frame.page);
+
+ const resolver = local.createPromiseResolver();
+ const global = try resolver.persist();
+ errdefer global.release();
+
+ // statechange is queued ahead of the render
+ base.setState(.running);
+ errdefer base._state = .suspended;
+ try self.scheduleRender();
+ self._rendered = buffer;
+ self._complete = global;
+ self._started = true;
+ return resolver.promise();
+}
+
+fn suspendContext(self: *OfflineAudioContext, when: f64, frame: *Frame) !js.Promise {
+ const base = self._proto;
+ if (base._state == .closed) {
+ return error.InvalidStateError;
+ }
+ if (std.math.isFinite(when) == false) {
+ return error.TypeError;
+ }
+ // In f32, as Chrome: a suspend at exactly the duration can pass, and
+ // then never resolves.
+ const duration: f32 = @as(f32, @floatFromInt(self._length)) / base._sample_rate;
+ if (when < 0 or when >= duration) {
+ return error.InvalidStateError;
+ }
+
+ const exact: u64 = @intFromFloat(when * base._sample_rate);
+ const at = std.mem.alignForward(u64, exact, Bus.quantum);
+ if (at < base._current_frame) {
+ return error.InvalidStateError;
+ }
+
+ var index: usize = self._suspends.items.len;
+ for (self._suspends.items, 0..) |s, i| {
+ if (s.frame == at) return error.InvalidStateError;
+ if (s.frame > at) {
+ index = i;
+ break;
+ }
+ }
+
+ const resolver = frame.js.local.?.createPromiseResolver();
+ const global = try resolver.persist();
+ errdefer global.release();
+ try self._suspends.insert(base._arena.allocator(), index, .{ .frame = at, .resolver = global });
+ return resolver.promise();
+}
+
+fn resumeContext(self: *OfflineAudioContext, frame: *Frame) !js.Promise {
+ const base = self._proto;
+ if (self._started == false or base._state == .closed) {
+ return error.InvalidStateError;
+ }
+ if (base._state == .suspended) {
+ base.setState(.running);
+ try self.scheduleRender();
+ }
+ return frame.js.local.?.resolvePromise(js.Undefined{});
+}
+
+fn scheduleRender(self: *OfflineAudioContext) !void {
+ if (self._render_scheduled) {
+ return;
+ }
+ const base = self._proto;
+ const frame = base._frame;
+ const task = try frame._factory.create(RenderTask{ .context = self });
+ errdefer frame._factory.destroy(task);
+ base.acquireRef();
+ errdefer base.releaseRef(frame.page);
+ try frame.js.scheduler.add(task, RenderTask.run, 0, .{
+ .name = "OfflineAudioContext.render",
+ .finalizer = RenderTask.cancelled,
+ });
+ self._render_scheduled = true;
+}
+
+const RenderTask = struct {
+ context: *OfflineAudioContext,
+
+ fn run(ctx: *anyopaque) !?u32 {
+ const task: *RenderTask = @ptrCast(@alignCast(ctx));
+ const self = task.context;
+ const base = self._proto;
+ const frame = base._frame;
+ frame._factory.destroy(task);
+ defer base.releaseRef(frame.page);
+
+ self._render_scheduled = false;
+ if (base._state != .running) {
+ return null;
+ }
+
+ const outcome = self.renderSome() catch |err| {
+ log.warn(.js, "OfflineAudioContext render", .{ .err = err });
+ self.fail(err);
+ return null;
+ };
+ base.dispatchEnded();
+ switch (outcome) {
+ .more => self.scheduleRender() catch |err| self.fail(err),
+ .suspended => self.suspendNow(),
+ .done => self.complete(),
+ }
+ return null;
+ }
+
+ fn cancelled(ctx: *anyopaque) void {
+ const task: *RenderTask = @ptrCast(@alignCast(ctx));
+ const self = task.context;
+ const base = self._proto;
+ const frame = base._frame;
+ frame._factory.destroy(task);
+ self._render_scheduled = false;
+ base.releaseRef(frame.page);
+ }
+};
+
+const Outcome = enum { more, suspended, done };
+
+fn renderSome(self: *OfflineAudioContext) !Outcome {
+ const base = self._proto;
+ var ls: js.Local.Scope = undefined;
+ base._frame.js.localScope(&ls);
+ defer ls.deinit();
+ const local = &ls.local;
+
+ // No script runs until this slice is done (`ended` fires after it), so
+ // these views of the buffer's channel arrays stay valid throughout.
+ const buffer = self._rendered.?;
+ var outputs: [AudioBuffer.max_channels][]f32 = undefined;
+ for (0..self._channels) |c| {
+ outputs[c] = buffer.channelData(c, local);
+ }
+
+ for (0..quanta_per_task) |_| {
+ const start = base._current_frame;
+ if (start >= self._length) {
+ return .done;
+ }
+ if (self._suspends.items.len > 0 and self._suspends.items[0].frame == start) {
+ return .suspended;
+ }
+ const bus = try base.renderQuantum(local);
+ const n: usize = @intCast(@min(Bus.quantum, self._length - start));
+ for (0..@min(bus.channels, self._channels)) |c| {
+ const out = outputs[c];
+ // a detached channel array just isn't written
+ if (out.len < start + n) continue;
+ @memcpy(out[start..][0..n], bus.constChannel(c)[0..n]);
+ }
+ }
+ return if (base._current_frame >= self._length) .done else .more;
+}
+
+fn suspendNow(self: *OfflineAudioContext) void {
+ const base = self._proto;
+ base.setState(.suspended);
+ const s = self._suspends.orderedRemove(0);
+ defer s.resolver.release();
+
+ var ls: js.Local.Scope = undefined;
+ base._frame.js.localScope(&ls);
+ defer ls.deinit();
+ s.resolver.local(&ls.local).resolve("OfflineAudioContext.suspend", js.Undefined{});
+}
+
+// The context closes, `complete` fires, then the promise resolves.
+fn complete(self: *OfflineAudioContext) void {
+ const base = self._proto;
+ const frame = base._frame;
+ base.setState(.closed);
+
+ const buffer = self._rendered.?;
+ const target = base.asEventTarget();
+ if (frame._event_manager.hasDirectListeners(target, "complete")) blk: {
+ const event = OfflineAudioCompletionEvent.initTrusted(buffer, frame.page) catch |err| {
+ log.warn(.js, "OfflineAudioContext complete", .{ .err = err });
+ break :blk;
+ };
+ frame._event_manager.dispatchDirect(target, event.asEvent(), .{ .context = "OfflineAudioContext complete" }) catch |err| {
+ log.debug(.js, "OfflineAudioContext complete", .{ .err = err });
+ };
+ }
+
+ const resolver = self._complete orelse return;
+ self._complete = null;
+ defer resolver.release();
+
+ var ls: js.Local.Scope = undefined;
+ frame.js.localScope(&ls);
+ defer ls.deinit();
+ resolver.local(&ls.local).resolve("OfflineAudioContext.startRendering", buffer);
+}
+
+fn fail(self: *OfflineAudioContext, err: anyerror) void {
+ const base = self._proto;
+ base.setState(.closed);
+
+ const resolver = self._complete orelse return;
+ self._complete = null;
+ defer resolver.release();
+
+ var ls: js.Local.Scope = undefined;
+ base._frame.js.localScope(&ls);
+ defer ls.deinit();
+ const rejection: anyerror = if (err == error.OutOfMemory) error.NotSupported else error.InvalidStateError;
+ resolver.local(&ls.local).rejectError("OfflineAudioContext.startRendering", .{ .dom_exception = .{ .err = rejection } });
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(OfflineAudioContext);
+
+ pub const Meta = struct {
+ pub const name = "OfflineAudioContext";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(OfflineAudioContext.constructor, .{});
+ pub const length = bridge.accessor(OfflineAudioContext.getLength, null, .{});
+ pub const oncomplete = EventTarget.handlerAccessor(OfflineAudioContext, "complete");
+ pub const startRendering = bridge.function(OfflineAudioContext.startRendering, .{});
+ pub const @"suspend" = bridge.function(OfflineAudioContext.suspendContext, .{});
+ pub const @"resume" = bridge.function(OfflineAudioContext.resumeContext, .{});
+};
+
+const testing = @import("../../../testing.zig");
+test "WebApi: webaudio" {
+ try testing.htmlRunner("webaudio", .{});
+}
diff --git a/src/browser/webapi/webaudio/OscillatorNode.zig b/src/browser/webapi/webaudio/OscillatorNode.zig
new file mode 100644
index 000000000..edf1a7d49
--- /dev/null
+++ b/src/browser/webapi/webaudio/OscillatorNode.zig
@@ -0,0 +1,273 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#OscillatorNode
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+const Factory = @import("../../Factory.zig");
+
+const EventTarget = @import("../EventTarget.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const math = @import("dsp/math.zig");
+const oscillator = @import("dsp/oscillator.zig");
+const Wavetable = @import("dsp/PeriodicWave.zig");
+const render = @import("render.zig");
+const AudioNode = @import("AudioNode.zig");
+const AudioParam = @import("AudioParam.zig");
+const PeriodicWave = @import("PeriodicWave.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+const AudioScheduledSourceNode = @import("AudioScheduledSourceNode.zig");
+
+const OscillatorNode = @This();
+
+pub const Proto = AudioScheduledSourceNode;
+
+// 1200 * log2(FLT_MAX)
+const max_detune: f32 = 153600;
+
+_proto: *AudioScheduledSourceNode,
+_frequency: *AudioParam,
+_detune: *AudioParam,
+_type: OscillatorType = .sine,
+_table: *const Wavetable,
+// holds a ref while set
+_custom: ?*PeriodicWave = null,
+_virtual_read_index: f64 = 0,
+
+pub const OscillatorType = enum {
+ sine,
+ square,
+ sawtooth,
+ triangle,
+ custom,
+
+ pub const js_enum_from_string = true;
+};
+
+const Options = struct {
+ channelCount: ?u32 = null,
+ channelCountMode: ?AudioNode.ChannelCountMode = null,
+ channelInterpretation: ?AudioNode.ChannelInterpretation = null,
+ detune: f32 = 0,
+ frequency: f32 = 440,
+ periodicWave: ?*PeriodicWave = null,
+ type: OscillatorType = .sine,
+};
+
+fn constructor(context: *BaseAudioContext, options_: ?Options) !*OscillatorNode {
+ return create(context, options_ orelse .{});
+}
+
+pub fn create(context: *BaseAudioContext, options: Options) !*OscillatorNode {
+ if (options.type == .custom and options.periodicWave == null) {
+ return error.InvalidStateError;
+ }
+ const nyquist = context._sample_rate / 2;
+ const self = try Factory.chainedWithAllocator(context._arena.allocator(), .{
+ EventTarget{ ._type = .audio_node },
+ AudioNode.init(context, .{ .type = .scheduled_source, .inputs = 0, .outputs = 1 }),
+ AudioScheduledSourceNode.init(.oscillator),
+ OscillatorNode{
+ ._proto = undefined,
+ ._frequency = try AudioParam.init(context, .{ .default = 440, .min = -nyquist, .max = nyquist }),
+ ._detune = try AudioParam.init(context, .{ .default = 0, .min = -max_detune, .max = max_detune }),
+ ._table = undefined,
+ },
+ });
+ try self._frequency.setInitial(options.frequency);
+ try self._detune.setInitial(options.detune);
+ if (options.periodicWave) |wave| {
+ self.setPeriodicWave(wave);
+ } else {
+ try self.setBasicType(options.type);
+ }
+ try self.asNode().setup(.{
+ .channelCount = options.channelCount,
+ .channelCountMode = options.channelCountMode,
+ .channelInterpretation = options.channelInterpretation,
+ });
+ return self;
+}
+
+fn asNode(self: *OscillatorNode) *AudioNode {
+ return self._proto._proto;
+}
+
+fn audioContext(self: *OscillatorNode) *BaseAudioContext {
+ return self.asNode()._context;
+}
+
+fn getType(self: *const OscillatorNode) []const u8 {
+ return @tagName(self._type);
+}
+
+// An unknown enum value is ignored, as for any IDL enum attribute.
+fn setType(self: *OscillatorNode, value: []const u8) !void {
+ const typ = std.meta.stringToEnum(OscillatorType, value) orelse return;
+ if (typ == .custom) {
+ return error.InvalidStateError;
+ }
+ try self.setBasicType(typ);
+}
+
+fn setBasicType(self: *OscillatorNode, typ: OscillatorType) !void {
+ const shape: Wavetable.Shape = switch (typ) {
+ .sine => .sine,
+ .square => .square,
+ .sawtooth => .sawtooth,
+ .triangle => .triangle,
+ .custom => unreachable,
+ };
+ self._table = try self.audioContext().basicWave(shape);
+ self.releaseCustom(self.audioContext()._page);
+ self._type = typ;
+}
+
+fn setPeriodicWave(self: *OscillatorNode, wave: *PeriodicWave) void {
+ wave.acquireRef();
+ self.releaseCustom(self.audioContext()._page);
+ self._custom = wave;
+ self._table = &wave._table;
+ self._type = .custom;
+}
+
+fn releaseCustom(self: *OscillatorNode, page: *Page) void {
+ if (self._custom) |wave| {
+ self._custom = null;
+ wave.releaseRef(page);
+ }
+}
+
+// The context releases what its nodes hold when it goes away.
+pub fn deinit(self: *OscillatorNode, page: *Page) void {
+ self.releaseCustom(page);
+}
+
+fn getFrequency(self: *const OscillatorNode) *AudioParam {
+ return self._frequency;
+}
+
+fn getDetune(self: *const OscillatorNode) *AudioParam {
+ return self._detune;
+}
+
+pub fn process(self: *OscillatorNode, r: *render.Quantum, output: *Bus) !void {
+ try output.setChannels(r.allocator, 1);
+ const schedule = try self._proto.schedule(r, output);
+ if (schedule.frames == 0) {
+ return;
+ }
+
+ const table = self._table;
+ const nyquist = r.sample_rate / 2;
+
+ var increments: [Bus.quantum]f32 = undefined;
+ var frequency: f32 = 0;
+ const sample_accurate = try self.phaseIncrements(r, &increments, &frequency);
+ frequency = if (sample_accurate) 0 else clampFrequency(frequency, nyquist);
+
+ var index = self._virtual_read_index;
+ var destination_index = schedule.offset;
+ var n = schedule.frames;
+ if (schedule.start_frame_offset > 0) {
+ destination_index += 1;
+ n -= 1;
+ index += (1 - schedule.start_frame_offset) * frequency * table.rate_scale;
+ } else if (schedule.start_frame_offset < 0) {
+ index = -schedule.start_frame_offset * frequency * table.rate_scale;
+ }
+ // a negative frequency moves the start index below 0
+ const size: f64 = @floatFromInt(table.size);
+ index -= @floor(index / size) * size;
+
+ const destination = output.channel(0)[destination_index..][0..n];
+ if (sample_accurate) {
+ // Chrome reads the increments from the quantum's first frame even
+ // when the source starts part way in.
+ index = oscillator.processARate(table, destination, index, increments[0..n]);
+ } else {
+ index = oscillator.processKRate(table, destination, index, frequency);
+ }
+ self._virtual_read_index = index;
+}
+
+// Port of Chrome's OscillatorHandler::CalculateSampleAccuratePhaseIncrements.
+// When neither param needs per-frame values, `frequency` gets the k-rate
+// (detuned) frequency instead.
+fn phaseIncrements(self: *OscillatorNode, r: *render.Quantum, increments: *[Bus.quantum]f32, frequency: *f32) !bool {
+ var sample_accurate = false;
+ var frequency_changes = false;
+ var final_scale = self._table.rate_scale;
+
+ if (self._frequency.isAudioRate() and self._frequency.hasSampleAccurateValues(r)) {
+ sample_accurate = true;
+ frequency_changes = true;
+ try self._frequency.sampleAccurateValues(r, increments);
+ } else {
+ frequency.* = try self._frequency.finalValue(r);
+ final_scale *= frequency.*;
+ }
+
+ if (self._detune.isAudioRate() and self._detune.hasSampleAccurateValues(r)) {
+ sample_accurate = true;
+ var detunes: [Bus.quantum]f32 = undefined;
+ const values = if (frequency_changes) &detunes else increments;
+ try self._detune.sampleAccurateValues(r, values);
+ const k: f32 = 1.0 / 1200.0;
+ for (values) |*v| v.* = math.exp2f(v.* * k);
+ if (frequency_changes) {
+ for (increments, detunes) |*inc, d| inc.* = d * inc.*;
+ }
+ } else {
+ const multiplier = math.exp2f(try self._detune.finalValue(r) / 1200);
+ final_scale *= multiplier;
+ frequency.* *= multiplier;
+ }
+
+ if (sample_accurate) {
+ const nyquist = r.sample_rate / 2;
+ for (increments) |*inc| inc.* = clampFrequency(inc.*, nyquist) * final_scale;
+ }
+ return sample_accurate;
+}
+
+fn clampFrequency(frequency: f32, nyquist: f32) f32 {
+ if (std.math.isNan(frequency)) {
+ return nyquist;
+ }
+ return std.math.clamp(frequency, -nyquist, nyquist);
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(OscillatorNode);
+
+ pub const Meta = struct {
+ pub const name = "OscillatorNode";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(OscillatorNode.constructor, .{});
+ pub const @"type" = bridge.accessor(OscillatorNode.getType, OscillatorNode.setType, .{});
+ pub const frequency = bridge.accessor(OscillatorNode.getFrequency, null, .{});
+ pub const detune = bridge.accessor(OscillatorNode.getDetune, null, .{});
+ pub const setPeriodicWave = bridge.function(OscillatorNode.setPeriodicWave, .{});
+};
diff --git a/src/browser/webapi/webaudio/PeriodicWave.zig b/src/browser/webapi/webaudio/PeriodicWave.zig
new file mode 100644
index 000000000..4bb5fb327
--- /dev/null
+++ b/src/browser/webapi/webaudio/PeriodicWave.zig
@@ -0,0 +1,105 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// https://webaudio.github.io/web-audio-api/#PeriodicWave
+
+const std = @import("std");
+const lp = @import("lightpanda");
+
+const js = @import("../../js/js.zig");
+const Page = @import("../../Page.zig");
+
+const Wavetable = @import("dsp/PeriodicWave.zig");
+const BaseAudioContext = @import("BaseAudioContext.zig");
+
+const PeriodicWave = @This();
+
+_rc: lp.RC = .{},
+_arena: *lp.Arena,
+_table: Wavetable,
+
+pub const Options = struct {
+ disableNormalization: bool = false,
+ imag: ?[]const f32 = null,
+ real: ?[]const f32 = null,
+};
+
+fn constructor(context: *BaseAudioContext, options_: ?Options) !*PeriodicWave {
+ return create(context, options_ orelse .{});
+}
+
+pub fn create(context: *BaseAudioContext, options: Options) !*PeriodicWave {
+ const page = context._page;
+ const arena = try page.getArena(.medium, "PeriodicWave");
+ errdefer arena.release();
+ const allocator = arena.allocator();
+
+ var real: []const f32 = undefined;
+ var imag: []const f32 = undefined;
+ if (options.real) |r| {
+ real = r;
+ imag = options.imag orelse try zeros(allocator, r.len);
+ } else if (options.imag) |i| {
+ real = try zeros(allocator, i.len);
+ imag = i;
+ } else {
+ real = &.{ 0, 0 };
+ imag = &.{ 0, 1 };
+ }
+ for (real) |v| if (std.math.isFinite(v) == false) return error.TypeError;
+ for (imag) |v| if (std.math.isFinite(v) == false) return error.TypeError;
+ if (real.len != imag.len or real.len < 2) {
+ return error.IndexSizeError;
+ }
+
+ const self = try allocator.create(PeriodicWave);
+ self.* = .{
+ ._arena = arena,
+ ._table = try .initCoefficients(allocator, context._sample_rate, real, imag, options.disableNormalization),
+ };
+ return self;
+}
+
+fn zeros(allocator: std.mem.Allocator, len: usize) ![]const f32 {
+ const values = try allocator.alloc(f32, len);
+ @memset(values, 0);
+ return values;
+}
+
+pub fn deinit(self: *PeriodicWave, _: *Page) void {
+ self._arena.release();
+}
+
+pub fn acquireRef(self: *PeriodicWave) void {
+ self._rc.acquire();
+}
+
+pub fn releaseRef(self: *PeriodicWave, page: *Page) void {
+ self._rc.release(self, page);
+}
+
+pub const JsApi = struct {
+ pub const bridge = js.Bridge(PeriodicWave);
+
+ pub const Meta = struct {
+ pub const name = "PeriodicWave";
+ pub var class_id: bridge.ClassId = undefined;
+ };
+
+ pub const constructor = bridge.constructor(PeriodicWave.constructor, .{});
+};
diff --git a/src/browser/webapi/webaudio/dsp/Bus.zig b/src/browser/webapi/webaudio/dsp/Bus.zig
new file mode 100644
index 000000000..cb486a9ea
--- /dev/null
+++ b/src/browser/webapi/webaudio/dsp/Bus.zig
@@ -0,0 +1,184 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// One render quantum of multi-channel audio.
+// https://webaudio.github.io/web-audio-api/#channel-up-mixing-and-down-mixing
+
+const std = @import("std");
+
+const Allocator = std.mem.Allocator;
+
+const Bus = @This();
+
+pub const quantum = 128;
+pub const max_channels = 32;
+
+pub const Channel = [quantum]f32;
+
+pub const Interpretation = enum { speakers, discrete };
+
+// capacity is data.len
+data: []Channel = &.{},
+channels: u32 = 0,
+
+// Grows the storage as needed; contents are unspecified afterwards.
+pub fn setChannels(self: *Bus, allocator: Allocator, channels: u32) !void {
+ std.debug.assert(channels <= max_channels);
+ if (channels > self.data.len) {
+ allocator.free(self.data);
+ self.data = &.{};
+ self.channels = 0;
+ self.data = try allocator.alloc(Channel, channels);
+ }
+ self.channels = channels;
+}
+
+pub fn deinit(self: *Bus, allocator: Allocator) void {
+ allocator.free(self.data);
+}
+
+pub fn channel(self: *Bus, index: usize) *Channel {
+ return &self.data[index];
+}
+
+pub fn constChannel(self: *const Bus, index: usize) *const Channel {
+ return &self.data[index];
+}
+
+pub fn zero(self: *Bus) void {
+ for (self.data[0..self.channels]) |*c| @memset(c, 0);
+}
+
+pub fn zeroFrames(self: *Bus, start: usize, end: usize) void {
+ for (self.data[0..self.channels]) |*c| @memset(c[start..end], 0);
+}
+
+// Mixes source into self, up- or down-mixing between the channel counts.
+pub fn sumFrom(self: *Bus, source: *const Bus, interpretation: Interpretation) void {
+ const from = source.channels;
+ const to = self.channels;
+ if (from == to or interpretation == .discrete) {
+ return self.discreteSumFrom(source);
+ }
+ if (from < to) {
+ return self.upMix(source);
+ }
+ return self.downMix(source);
+}
+
+fn discreteSumFrom(self: *Bus, source: *const Bus) void {
+ const n = @min(self.channels, source.channels);
+ for (0..n) |i| add(self.channel(i), source.constChannel(i));
+}
+
+fn upMix(self: *Bus, source: *const Bus) void {
+ const from = source.channels;
+ const to = self.channels;
+ if (from == 1 and (to == 2 or to == 4)) {
+ add(self.channel(0), source.constChannel(0));
+ add(self.channel(1), source.constChannel(0));
+ } else if (from == 1 and to == 6) {
+ add(self.channel(2), source.constChannel(0));
+ } else if (from == 2 and (to == 4 or to == 6)) {
+ add(self.channel(0), source.constChannel(0));
+ add(self.channel(1), source.constChannel(1));
+ } else if (from == 4 and to == 6) {
+ add(self.channel(0), source.constChannel(0));
+ add(self.channel(1), source.constChannel(1));
+ add(self.channel(4), source.constChannel(2));
+ add(self.channel(5), source.constChannel(3));
+ } else {
+ self.discreteSumFrom(source);
+ }
+}
+
+fn downMix(self: *Bus, source: *const Bus) void {
+ const from = source.channels;
+ const to = self.channels;
+ const sqrt_half: f32 = @sqrt(@as(f32, 0.5));
+ const s = source;
+ if (from == 2 and to == 1) {
+ const d = self.channel(0);
+ scaledAdd(d, s.constChannel(0), 0.5);
+ scaledAdd(d, s.constChannel(1), 0.5);
+ } else if (from == 4 and to == 1) {
+ const d = self.channel(0);
+ for (0..4) |i| scaledAdd(d, s.constChannel(i), 0.25);
+ } else if (from == 6 and to == 1) {
+ const d = self.channel(0);
+ scaledAdd(d, s.constChannel(0), sqrt_half);
+ scaledAdd(d, s.constChannel(1), sqrt_half);
+ add(d, s.constChannel(2));
+ scaledAdd(d, s.constChannel(4), 0.5);
+ scaledAdd(d, s.constChannel(5), 0.5);
+ } else if (from == 4 and to == 2) {
+ scaledAdd(self.channel(0), s.constChannel(0), 0.5);
+ scaledAdd(self.channel(0), s.constChannel(2), 0.5);
+ scaledAdd(self.channel(1), s.constChannel(1), 0.5);
+ scaledAdd(self.channel(1), s.constChannel(3), 0.5);
+ } else if (from == 6 and (to == 2 or to == 4)) {
+ add(self.channel(0), s.constChannel(0));
+ scaledAdd(self.channel(0), s.constChannel(2), sqrt_half);
+ if (to == 2) scaledAdd(self.channel(0), s.constChannel(4), sqrt_half);
+ add(self.channel(1), s.constChannel(1));
+ scaledAdd(self.channel(1), s.constChannel(2), sqrt_half);
+ if (to == 2) {
+ scaledAdd(self.channel(1), s.constChannel(5), sqrt_half);
+ } else {
+ add(self.channel(2), s.constChannel(4));
+ add(self.channel(3), s.constChannel(5));
+ }
+ } else {
+ self.discreteSumFrom(source);
+ }
+}
+
+fn add(destination: *Channel, source: *const Channel) void {
+ for (destination, source) |*d, s| d.* += s;
+}
+
+fn scaledAdd(destination: *Channel, source: *const Channel, scale: f32) void {
+ for (destination, source) |*d, s| d.* += s * scale;
+}
+
+const testing = std.testing;
+test "Bus: speaker mixing" {
+ const allocator = testing.allocator;
+ var mono: Bus = .{};
+ defer mono.deinit(allocator);
+ var stereo: Bus = .{};
+ defer stereo.deinit(allocator);
+
+ try mono.setChannels(allocator, 1);
+ try stereo.setChannels(allocator, 2);
+ @memset(mono.channel(0), 0.5);
+
+ stereo.zero();
+ stereo.sumFrom(&mono, .speakers);
+ try testing.expectEqual(0.5, stereo.channel(0)[0]);
+ try testing.expectEqual(0.5, stereo.channel(1)[127]);
+
+ @memset(stereo.channel(1), 1.5);
+ mono.zero();
+ mono.sumFrom(&stereo, .speakers);
+ try testing.expectEqual(1, mono.channel(0)[3]);
+
+ mono.zero();
+ mono.sumFrom(&stereo, .discrete);
+ try testing.expectEqual(0.5, mono.channel(0)[3]);
+}
diff --git a/src/browser/webapi/webaudio/dsp/Compressor.zig b/src/browser/webapi/webaudio/dsp/Compressor.zig
new file mode 100644
index 000000000..b392ada43
--- /dev/null
+++ b/src/browser/webapi/webaudio/dsp/Compressor.zig
@@ -0,0 +1,290 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// The DynamicsCompressorNode kernel, ported from Chromium's
+// platform/audio/dynamics_compressor.cc (Copyright (C) 2011 Google Inc., BSD
+// license). The float/double mix of every expression follows the original.
+
+const std = @import("std");
+const math = @import("math.zig");
+
+const Compressor = @This();
+
+pub const channels = 2;
+
+const max_pre_delay_frames = 1024;
+const max_pre_delay_mask = max_pre_delay_frames - 1;
+const default_pre_delay_frames = 256;
+const pre_delay: f32 = 0.006; // seconds
+const metering_release_time_constant: f32 = 0.325;
+const sat_release_time: f32 = 0.0025;
+const division_frames = 32;
+const uninitialized: f32 = -1;
+
+// Release curve: a polynomial fit through these four zones (seconds).
+const release_zone1: f32 = 0.09;
+const release_zone2: f32 = 0.16;
+const release_zone3: f32 = 0.42;
+const release_zone4: f32 = 0.98;
+const a_base: f32 = 0.9999999999999998 * release_zone1 + 1.8432219684323923e-16 * release_zone2 - 1.9373394351676423e-16 * release_zone3 + 8.824516011816245e-18 * release_zone4;
+const b_base: f32 = -1.5788320352845888 * release_zone1 + 2.3305837032074286 * release_zone2 - 0.9141194204840429 * release_zone3 + 0.1623677525612032 * release_zone4;
+const c_base: f32 = 0.5334142869106424 * release_zone1 - 1.272736789213631 * release_zone2 + 0.9258856042207512 * release_zone3 - 0.18656310191776226 * release_zone4;
+const d_base: f32 = 0.08783463138207234 * release_zone1 - 0.1694162967925622 * release_zone2 + 0.08588057951595272 * release_zone3 - 0.00429891410546283 * release_zone4;
+const e_base: f32 = -0.042416883008123074 * release_zone1 + 0.1115693827987602 * release_zone2 - 0.09764676325265872 * release_zone3 + 0.028494263462021576 * release_zone4;
+
+pub const Params = struct {
+ threshold: f32,
+ knee: f32,
+ ratio: f32,
+ attack: f32,
+ release: f32,
+};
+
+sample_rate: f32,
+pre_delay_buffers: [channels][max_pre_delay_frames]f32 = @splat(@splat(0)),
+pre_delay_read: u32 = 0,
+pre_delay_write: u32 = default_pre_delay_frames,
+last_pre_delay_frames: u32 = default_pre_delay_frames,
+
+detector_average: f32 = 0,
+compressor_gain: f32 = 1,
+metering_gain: f32 = 1,
+metering_release_k: f32,
+max_attack_compression_diff_db: f32 = -1,
+
+// static curve, recomputed when threshold, knee or ratio change
+ratio: f32 = uninitialized,
+slope: f32 = uninitialized,
+linear_threshold: f32 = uninitialized,
+threshold_db: f32 = uninitialized,
+knee_db: f32 = uninitialized,
+knee_threshold: f32 = uninitialized,
+knee_threshold_db: f32 = uninitialized,
+yknee_threshold_db: f32 = uninitialized,
+knee_k: f32 = uninitialized,
+
+pub fn init(sample_rate: f32) Compressor {
+ return .{
+ .sample_rate = sample_rate,
+ .metering_release_k = @floatCast(math.discreteTimeConstant(metering_release_time_constant, sample_rate)),
+ };
+}
+
+// The gain reduction in dB, for DynamicsCompressorNode.reduction.
+pub fn reduction(self: *const Compressor) f32 {
+ return self.metering_gain;
+}
+
+// The kernel always runs two channels; a mono source feeds both.
+pub fn process(self: *Compressor, source: []const []const f32, destination: *const [channels][]f32, params: Params) void {
+ const frames = destination[0].len;
+ std.debug.assert(source.len > 0);
+
+ const k = self.updateStaticCurve(params.threshold, params.knee, params.ratio);
+ const linear_post_gain: f32 = @floatCast(math.powd(1 / self.saturate(1, k), @as(f32, 0.6)));
+ const attack_frames = @max(@as(f32, 0.001), params.attack) * self.sample_rate;
+ const release_frames = self.sample_rate * params.release;
+ const sat_release_frames = sat_release_time * self.sample_rate;
+ const a = release_frames * a_base;
+ const b = release_frames * b_base;
+ const c = release_frames * c_base;
+ const d = release_frames * d_base;
+ const e = release_frames * e_base;
+
+ self.setPreDelayFrames(@intFromFloat(pre_delay * self.sample_rate));
+
+ var frame_index: usize = 0;
+ while (frame_index < frames) {
+ self.detector_average = ensureFinite(self.detector_average, 1);
+ const desired_gain = self.detector_average;
+ const scaled_desired_gain = @as(f32, @floatCast(math.asind(desired_gain))) / math.pi_over_two_f32;
+
+ const is_releasing = scaled_desired_gain > self.compressor_gain;
+ var compression_diff_db: f32 = undefined;
+ if (scaled_desired_gain == 0) {
+ compression_diff_db = if (is_releasing) -1 else 1;
+ } else {
+ compression_diff_db = math.linearToDecibels(self.compressor_gain / scaled_desired_gain);
+ }
+
+ var envelope_rate: f32 = undefined;
+ if (is_releasing) {
+ self.max_attack_compression_diff_db = -1;
+ var x = ensureFinite(compression_diff_db, -1);
+ x = std.math.clamp(x, -12, 0);
+ x = 0.25 * (x + 12);
+ const x2 = x * x;
+ const x3 = x2 * x;
+ const x4 = x2 * x2;
+ const calc_release_frames = a + b * x + c * x2 + d * x3 + e * x4;
+ const db_spacing: f32 = 5;
+ envelope_rate = math.decibelsToLinear(db_spacing / calc_release_frames);
+ } else {
+ compression_diff_db = ensureFinite(compression_diff_db, 1);
+ if (self.max_attack_compression_diff_db == -1 or self.max_attack_compression_diff_db < compression_diff_db) {
+ self.max_attack_compression_diff_db = compression_diff_db;
+ }
+ const eff_atten_diff_db = @max(@as(f32, 0.5), self.max_attack_compression_diff_db);
+ const x: f32 = 0.25 / eff_atten_diff_db;
+ envelope_rate = 1 - @as(f32, @floatCast(math.powd(x, 1 / attack_frames)));
+ }
+
+ var read = self.pre_delay_read;
+ var write = self.pre_delay_write;
+ var detector_average = self.detector_average;
+ var compressor_gain = self.compressor_gain;
+
+ const loop_frames = @min(division_frames, frames - frame_index);
+ for (0..loop_frames) |_| {
+ var compressor_input: f32 = 0;
+ for (0..channels) |j| {
+ const undelayed = (if (source.len > j) source[j] else source[0])[frame_index];
+ self.pre_delay_buffers[j][write] = undelayed;
+ const abs_undelayed = if (undelayed > 0) undelayed else -undelayed;
+ if (compressor_input < abs_undelayed) {
+ compressor_input = abs_undelayed;
+ }
+ }
+
+ const abs_input = if (compressor_input > 0) compressor_input else -compressor_input;
+ const shaped_input = self.saturate(abs_input, k);
+ const attenuation: f32 = if (abs_input <= 0.0001) 1 else shaped_input / abs_input;
+ const attenuation_db = @max(@as(f32, 2), -math.linearToDecibels(attenuation));
+ const db_per_frame = attenuation_db / sat_release_frames;
+ const sat_release_rate = math.decibelsToLinear(db_per_frame) - 1;
+ const rate: f32 = if (attenuation > detector_average) sat_release_rate else 1;
+ detector_average += (attenuation - detector_average) * rate;
+ detector_average = @min(@as(f32, 1), detector_average);
+ detector_average = ensureFinite(detector_average, 1);
+
+ if (envelope_rate < 1) {
+ compressor_gain += (scaled_desired_gain - compressor_gain) * envelope_rate;
+ } else {
+ compressor_gain *= envelope_rate;
+ compressor_gain = @min(@as(f32, 1), compressor_gain);
+ }
+
+ const post_warp_gain: f32 = @floatCast(math.sind(math.pi_over_two_f32 * compressor_gain));
+ const total_gain = linear_post_gain * post_warp_gain;
+
+ const real_gain_db = math.linearToDecibels(post_warp_gain);
+ if (real_gain_db < self.metering_gain) {
+ self.metering_gain = real_gain_db;
+ } else {
+ self.metering_gain += (real_gain_db - self.metering_gain) * self.metering_release_k;
+ }
+
+ for (0..channels) |j| {
+ destination[j][frame_index] = self.pre_delay_buffers[j][read] * total_gain;
+ }
+
+ frame_index += 1;
+ read = (read + 1) & max_pre_delay_mask;
+ write = (write + 1) & max_pre_delay_mask;
+ }
+
+ self.pre_delay_read = read;
+ self.pre_delay_write = write;
+ self.detector_average = flushDenormal(detector_average);
+ self.compressor_gain = flushDenormal(compressor_gain);
+ }
+}
+
+fn setPreDelayFrames(self: *Compressor, requested: u32) void {
+ const frames = @min(requested, max_pre_delay_frames - 1);
+ if (self.last_pre_delay_frames == frames) {
+ return;
+ }
+ self.last_pre_delay_frames = frames;
+ self.pre_delay_buffers = @splat(@splat(0));
+ self.pre_delay_read = 0;
+ self.pre_delay_write = frames;
+}
+
+fn kneeCurve(self: *const Compressor, x: f32, k: f32) f32 {
+ if (x < self.linear_threshold) {
+ return x;
+ }
+ return self.linear_threshold + (1 - @as(f32, @floatCast(math.expd(-k * (x - self.linear_threshold))))) / k;
+}
+
+fn saturate(self: *const Compressor, x: f32, k: f32) f32 {
+ if (x < self.knee_threshold) {
+ return self.kneeCurve(x, k);
+ }
+ const x_db = math.linearToDecibels(x);
+ const y_db = self.yknee_threshold_db + self.slope * (x_db - self.knee_threshold_db);
+ return math.decibelsToLinear(y_db);
+}
+
+// Binary search for the knee curve's k whose slope at the knee's end is
+// `desired_slope`.
+fn kAtSlope(self: *const Compressor, desired_slope: f32) f32 {
+ const x_db = self.threshold_db + self.knee_db;
+ const x = math.decibelsToLinear(x_db);
+
+ var x2: f32 = 1;
+ var x2_db: f32 = 0;
+ if ((x < self.linear_threshold) == false) {
+ x2 = @floatCast(@as(f64, x) * 1.001);
+ x2_db = math.linearToDecibels(x2);
+ }
+
+ var min_k: f32 = 0.1;
+ var max_k: f32 = 10000;
+ var k: f32 = 5;
+ var slope: f32 = 1;
+ for (0..15) |_| {
+ if ((x < self.linear_threshold) == false) {
+ const y_db = math.linearToDecibels(self.kneeCurve(x, k));
+ const y2_db = math.linearToDecibels(self.kneeCurve(x2, k));
+ slope = (y2_db - y_db) / (x2_db - x_db);
+ }
+ if (slope < desired_slope) {
+ max_k = k;
+ } else {
+ min_k = k;
+ }
+ k = @sqrt(min_k * max_k);
+ }
+ return k;
+}
+
+fn updateStaticCurve(self: *Compressor, threshold_db: f32, knee_db: f32, ratio: f32) f32 {
+ if (threshold_db != self.threshold_db or knee_db != self.knee_db or ratio != self.ratio) {
+ self.threshold_db = threshold_db;
+ self.linear_threshold = math.decibelsToLinear(threshold_db);
+ self.knee_db = knee_db;
+ self.ratio = ratio;
+ self.slope = 1 / ratio;
+ const k = self.kAtSlope(1 / ratio);
+ self.knee_threshold_db = threshold_db + knee_db;
+ self.knee_threshold = math.decibelsToLinear(self.knee_threshold_db);
+ self.yknee_threshold_db = math.linearToDecibels(self.kneeCurve(self.knee_threshold, k));
+ self.knee_k = k;
+ }
+ return self.knee_k;
+}
+
+fn ensureFinite(x: f32, default: f32) f32 {
+ return if (std.math.isFinite(x)) x else default;
+}
+
+fn flushDenormal(x: f32) f32 {
+ return if (@abs(x) < std.math.floatMin(f32)) 0 else x;
+}
diff --git a/src/browser/webapi/webaudio/dsp/PeriodicWave.zig b/src/browser/webapi/webaudio/dsp/PeriodicWave.zig
new file mode 100644
index 000000000..8935941fd
--- /dev/null
+++ b/src/browser/webapi/webaudio/dsp/PeriodicWave.zig
@@ -0,0 +1,211 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// Band-limited wavetables for OscillatorNode, ported from Chromium's
+// modules/webaudio/periodic_wave.cc (Copyright (C) 2012 Google Inc., BSD
+// license). Each table holds one period; table `r` drops the partials that
+// would alias for fundamentals in pitch range `r` (three ranges per octave).
+
+const std = @import("std");
+const math = @import("math.zig");
+
+const Allocator = std.mem.Allocator;
+
+const PeriodicWave = @This();
+
+const octave_bands = 3;
+const cents_per_range: f32 = 1200 / octave_bands;
+
+size: u32,
+number_of_ranges: u32,
+lowest_fundamental: f32,
+// table index per sample of frequency: size / sample_rate
+rate_scale: f32,
+tables: []const []const f32,
+
+pub const Shape = enum { sine, square, sawtooth, triangle };
+
+pub fn initBasic(allocator: Allocator, sample_rate: f32, shape: Shape) !PeriodicWave {
+ const size = waveSize(sample_rate);
+ const half = size / 2;
+ const imag = try allocator.alloc(f32, half);
+ defer allocator.free(imag);
+
+ imag[0] = 0;
+ for (1..half) |n| {
+ const pi_factor: f32 = 2 / (@as(f32, @floatFromInt(n)) * math.pi_f32);
+ const odd = n & 1 == 1;
+ // Fourier sine coefficients; all four shapes are odd functions.
+ imag[n] = switch (shape) {
+ .sine => if (n == 1) 1 else 0,
+ .square => if (odd) 2 * pi_factor else 0,
+ .sawtooth => pi_factor * @as(f32, if (odd) 1 else -1),
+ .triangle => if (odd) 2 * (pi_factor * pi_factor) * @as(f32, if (((n - 1) >> 1) & 1 == 1) -1 else 1) else 0,
+ };
+ }
+ return initCoefficients(allocator, sample_rate, null, imag, false);
+}
+
+// `real` null means all-zero cosine terms.
+pub fn initCoefficients(allocator: Allocator, sample_rate: f32, real: ?[]const f32, imag: []const f32, disable_normalization: bool) !PeriodicWave {
+ const size = waveSize(sample_rate);
+ const half = size / 2;
+ const nyquist: f32 = 0.5 * sample_rate;
+ const number_of_ranges: u32 = @intFromFloat(0.5 + octave_bands * math.log2f(@floatFromInt(size)));
+ const components: u32 = @intCast(@min(imag.len, half));
+
+ const tables = try allocator.alloc([]const f32, number_of_ranges);
+ const work = try allocator.alloc(Complex, size);
+ defer allocator.free(work);
+
+ var normalization: f32 = 0.5;
+ var previous_cutoff: ?u32 = null;
+ for (0..number_of_ranges) |range| {
+ // Bins [1, cutoff) survive; DC and Nyquist never do.
+ const cutoff = @min(components, partialsForRange(half, @intCast(range)) + 1);
+ if (previous_cutoff == cutoff) {
+ tables[range] = tables[range - 1];
+ continue;
+ }
+ previous_cutoff = cutoff;
+
+ @memset(work, .{ .re = 0, .im = 0 });
+ for (1..cutoff) |k| {
+ const a: f64 = if (real) |r| r[k] else 0;
+ const b: f64 = imag[k];
+ work[k] = .{ .re = a, .im = -b };
+ work[size - k] = .{ .re = a, .im = b };
+ }
+ inverseFft(work);
+
+ const table = try allocator.alloc(f32, size);
+ for (table, work) |*t, w| {
+ // x[n] = 2 * sum(a cos + b sin); the default (unnormalized)
+ // scale of 0.5 leaves the sum the spec defines.
+ t.* = @floatCast(w.re);
+ }
+ if (range == 0 and disable_normalization == false) {
+ var max: f32 = 0;
+ for (table) |t| max = @max(max, @abs(t));
+ if (max != 0) normalization = 1.0 / max;
+ }
+ for (table) |*t| t.* *= normalization;
+ tables[range] = table;
+ }
+
+ return .{
+ .size = size,
+ .number_of_ranges = number_of_ranges,
+ .lowest_fundamental = nyquist / @as(f32, @floatFromInt(half)),
+ .rate_scale = @as(f32, @floatFromInt(size)) / sample_rate,
+ .tables = tables,
+ };
+}
+
+// Shorter tables at low rates keep the FFTs small; 4096 around 44.1kHz.
+fn waveSize(sample_rate: f32) u32 {
+ if (sample_rate <= 24000) return 2048;
+ if (sample_rate <= 88200) return 4096;
+ return 16384;
+}
+
+fn partialsForRange(max_partials: u32, range: u32) u32 {
+ const cents_to_cull = @as(f32, @floatFromInt(range)) * cents_per_range;
+ const culling_scale: f32 = @floatCast(math.powd(2, -cents_to_cull / 1200));
+ return @intFromFloat(culling_scale * @as(f32, @floatFromInt(max_partials)));
+}
+
+pub const WaveData = struct {
+ // fewer partials
+ lower: []const f32,
+ higher: []const f32,
+ // 0 => higher, 1 => lower
+ factor: f32,
+};
+
+pub fn waveData(self: *const PeriodicWave, fundamental: f32) WaveData {
+ // negative frequencies alias to the positive one
+ const frequency = @abs(fundamental);
+ const ratio: f32 = if (frequency > 0) frequency / self.lowest_fundamental else 0.5;
+ const cents_above_lowest = math.log2f(ratio) * 1200;
+ // Plus one rounds up to the next range just before partials would alias.
+ var pitch_range: f32 = 1 + cents_above_lowest / cents_per_range;
+ pitch_range = @max(pitch_range, 0);
+ pitch_range = @min(pitch_range, @as(f32, @floatFromInt(self.number_of_ranges - 1)));
+
+ const index1: u32 = @intFromFloat(pitch_range);
+ const index2 = if (index1 < self.number_of_ranges - 1) index1 + 1 else index1;
+ return .{
+ .lower = self.tables[index2],
+ .higher = self.tables[index1],
+ .factor = pitch_range - @as(f32, @floatFromInt(index1)),
+ };
+}
+
+const Complex = struct { re: f64, im: f64 };
+
+// In-place radix-2 inverse DFT, unscaled: x[n] = sum X[k] e^(2 pi i k n / N).
+fn inverseFft(data: []Complex) void {
+ const n = data.len;
+ std.debug.assert(std.math.isPowerOfTwo(n));
+
+ var j: usize = 0;
+ for (1..n) |i| {
+ var bit = n >> 1;
+ while (j & bit != 0) : (bit >>= 1) {
+ j ^= bit;
+ }
+ j |= bit;
+ if (i < j) {
+ std.mem.swap(Complex, &data[i], &data[j]);
+ }
+ }
+
+ var len: usize = 2;
+ while (len <= n) : (len <<= 1) {
+ const angle = 2 * std.math.pi / @as(f64, @floatFromInt(len));
+ const half = len / 2;
+ var start: usize = 0;
+ while (start < n) : (start += len) {
+ for (0..half) |k| {
+ const theta = angle * @as(f64, @floatFromInt(k));
+ const w: Complex = .{ .re = @cos(theta), .im = @sin(theta) };
+ const a = data[start + k];
+ const b = data[start + k + half];
+ const t: Complex = .{ .re = b.re * w.re - b.im * w.im, .im = b.re * w.im + b.im * w.re };
+ data[start + k] = .{ .re = a.re + t.re, .im = a.im + t.im };
+ data[start + k + half] = .{ .re = a.re - t.re, .im = a.im - t.im };
+ }
+ }
+ }
+}
+
+const testing = std.testing;
+test "PeriodicWave: sine table is a normalized sine" {
+ const allocator = testing.allocator;
+ var arena: std.heap.ArenaAllocator = .init(allocator);
+ defer arena.deinit();
+
+ const wave = try initBasic(arena.allocator(), 44100, .sine);
+ try testing.expectEqual(4096, wave.size);
+ try testing.expectEqual(36, wave.number_of_ranges);
+ const table = wave.tables[0];
+ try testing.expectApproxEqAbs(@as(f32, 0), table[0], 1e-6);
+ try testing.expectApproxEqAbs(@as(f32, 1), table[1024], 1e-6);
+ try testing.expectApproxEqAbs(@as(f32, -1), table[3072], 1e-6);
+}
diff --git a/src/browser/webapi/webaudio/dsp/Timeline.zig b/src/browser/webapi/webaudio/dsp/Timeline.zig
new file mode 100644
index 000000000..fb124b295
--- /dev/null
+++ b/src/browser/webapi/webaudio/dsp/Timeline.zig
@@ -0,0 +1,388 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// An AudioParam's automation events.
+// https://webaudio.github.io/web-audio-api/#computation-of-value
+
+const std = @import("std");
+
+const Allocator = std.mem.Allocator;
+
+const Timeline = @This();
+
+events: std.ArrayList(Event) = .empty,
+// The param's value when the first event was scheduled: what it holds until
+// that event, and where a set_target with nothing before it decays from.
+base: f32 = 0,
+
+pub const Kind = enum {
+ set_value,
+ linear_ramp,
+ exponential_ramp,
+ set_target,
+ set_value_curve,
+};
+
+pub const Event = struct {
+ kind: Kind,
+ // A ramp's end time; every other kind's start time.
+ time: f64,
+ value: f32 = 0,
+ time_constant: f64 = 0,
+ // set_value_curve: the duration the curve's values are spread over, and
+ // when the event stops holding the timeline (earlier after a
+ // cancelAndHoldAtTime).
+ duration: f64 = 0,
+ end_time: f64 = 0,
+ curve: []const f32 = &.{},
+ // A ramp with no event before it starts from where the param was when the
+ // ramp was scheduled.
+ start_time: f64 = 0,
+ start_value: f32 = 0,
+
+ fn isRamp(self: *const Event) bool {
+ return self.kind == .linear_ramp or self.kind == .exponential_ramp;
+ }
+
+ // When the next event takes over. Curves hold their last value from
+ // end_time on, like the implicit setValueAtTime the spec inserts there.
+ fn endTime(self: *const Event) f64 {
+ return if (self.kind == .set_value_curve) self.end_time else self.time;
+ }
+};
+
+pub const InsertError = error{NotSupported} || Allocator.Error;
+
+pub fn isEmpty(self: *const Timeline) bool {
+ return self.events.items.len == 0;
+}
+
+// `current` is the param's value now.
+pub fn insert(self: *Timeline, allocator: Allocator, event: Event, current: f32) InsertError!void {
+ const events = self.events.items;
+ for (events) |*e| {
+ // nothing goes in a curve's [start, end), and a curve can't span an
+ // event (one at its start time is fine)
+ if (e.kind == .set_value_curve and event.time >= e.time and event.time < e.end_time) {
+ return error.NotSupported;
+ }
+ if (event.kind == .set_value_curve and e.time > event.time and e.time < event.end_time) {
+ return error.NotSupported;
+ }
+ }
+
+ if (events.len == 0) {
+ self.base = current;
+ }
+ // after every event at the same time
+ var index: usize = events.len;
+ for (events, 0..) |*e, i| {
+ if (e.time > event.time) {
+ index = i;
+ break;
+ }
+ }
+ // A set_value right after another at the same time overrides it, so
+ // repeatedly assigning `value` doesn't grow the list.
+ if (event.kind == .set_value and index > 0) {
+ const previous = &events[index - 1];
+ if (previous.kind == .set_value and previous.time == event.time) {
+ previous.* = event;
+ return;
+ }
+ }
+ try self.events.insert(allocator, index, event);
+}
+
+// Drops the events that only matter before `now`, so a long render doesn't
+// walk its whole history for every frame. What they left behind becomes
+// `base`: where the first remaining event starts from.
+pub fn prune(self: *Timeline, now: f64) void {
+ const events = self.events.items;
+ var first: usize = 0;
+ for (events, 0..) |*e, i| {
+ if (e.time <= now) first = i;
+ }
+ if (first == 0) {
+ return;
+ }
+ self.base = valueIn(events[0..first], events[first].time, self.base);
+ self.events.replaceRangeAssumeCapacity(0, first, &.{});
+}
+
+pub fn cancelScheduledValues(self: *Timeline, cancel_time: f64) void {
+ var keep: usize = 0;
+ for (self.events.items) |e| {
+ const active_curve = e.kind == .set_value_curve and e.time < cancel_time and cancel_time < e.end_time;
+ if (e.time >= cancel_time or active_curve) {
+ continue;
+ }
+ self.events.items[keep] = e;
+ keep += 1;
+ }
+ self.events.shrinkRetainingCapacity(keep);
+}
+
+pub fn cancelAndHoldAtTime(self: *Timeline, allocator: Allocator, cancel_time: f64) Allocator.Error!void {
+ const events = self.events.items;
+
+ // The first event to cancel: anything starting at or after the cancel
+ // time, or a ramp still running then.
+ var first: usize = events.len;
+ for (events, 0..) |*e, i| {
+ const started = if (e.isRamp()) e.time <= cancel_time else e.time < cancel_time;
+ if (started == false) {
+ first = i;
+ break;
+ }
+ }
+
+ if (first < events.len and events[first].isRamp()) {
+ // the running ramp now ends at the cancel time, where it was
+ const hold = self.valueAt(cancel_time, self.base);
+ events[first].time = cancel_time;
+ events[first].value = hold;
+ self.events.shrinkRetainingCapacity(first + 1);
+ return;
+ }
+
+ self.events.shrinkRetainingCapacity(first);
+ const last = if (first > 0) &self.events.items[first - 1] else return;
+ const hold = self.valueAt(cancel_time, self.base);
+ switch (last.kind) {
+ .set_target => {},
+ .set_value_curve => {
+ if (cancel_time >= last.end_time) return;
+ last.end_time = cancel_time;
+ },
+ else => return,
+ }
+ try self.events.append(allocator, .{ .kind = .set_value, .time = cancel_time, .value = hold });
+}
+
+// The automation value at time t; `current` (the param's value) when nothing
+// is scheduled.
+pub fn valueAt(self: *const Timeline, t: f64, current: f32) f32 {
+ if (self.events.items.len == 0) {
+ return current;
+ }
+ return valueIn(self.events.items, t, self.base);
+}
+
+// One pass over the events, tracking the automation in effect.
+fn valueIn(events: []const Event, t: f64, base: f32) f32 {
+ var active: Active = .{ .constant = base };
+ var previous_end: ?f64 = null;
+ for (events) |*e| {
+ if (e.isRamp()) {
+ // from the previous event's end (or where the param was when
+ // the ramp was scheduled) to this event's time
+ const t0, const v0 = if (previous_end) |end| .{ end, active.at(end) } else .{ e.start_time, e.start_value };
+ if (t < t0) {
+ // still in the previous event (a curve), or before the first
+ return if (previous_end == null) base else active.at(t);
+ }
+ if (t < e.time) {
+ return rampValue(e, t0, v0, t);
+ }
+ active = .{ .constant = e.value };
+ } else {
+ if (e.time > t) break;
+ const start = active.at(e.time);
+ active = switch (e.kind) {
+ .set_value => .{ .constant = e.value },
+ .set_target => .{ .target = .{ .event = e, .start = start } },
+ .set_value_curve => .{ .curve = e },
+ .linear_ramp, .exponential_ramp => unreachable,
+ };
+ }
+ previous_end = e.endTime();
+ }
+ return active.at(t);
+}
+
+const Active = union(enum) {
+ constant: f32,
+ target: struct { event: *const Event, start: f32 },
+ curve: *const Event,
+
+ fn at(self: Active, t: f64) f32 {
+ return switch (self) {
+ .constant => |v| v,
+ .target => |target| blk: {
+ const e = target.event;
+ if (e.time_constant == 0) break :blk e.value;
+ const decay = std.math.exp(-(t - e.time) / e.time_constant);
+ break :blk @floatCast(e.value + (target.start - e.value) * decay);
+ },
+ .curve => |e| curveValue(e, t),
+ };
+ }
+};
+
+fn rampValue(ramp: *const Event, t0: f64, v0: f32, t: f64) f32 {
+ const t1 = ramp.time;
+ const v1 = ramp.value;
+ if (t1 <= t0) return v1;
+ const fraction = (t - t0) / (t1 - t0);
+ if (ramp.kind == .linear_ramp) {
+ return @floatCast(v0 + (v1 - v0) * fraction);
+ }
+ // An exponential ramp from 0, or across 0, holds its start value.
+ if (v0 == 0 or (v0 < 0) != (v1 < 0)) {
+ return v0;
+ }
+ const ratio: f64 = v1 / v0;
+ return @floatCast(v0 * std.math.pow(f64, ratio, fraction));
+}
+
+fn curveValue(e: *const Event, t: f64) f32 {
+ const curve = e.curve;
+ const n = curve.len;
+ if (t >= e.time + e.duration) {
+ return curve[n - 1];
+ }
+ const position = @as(f64, @floatFromInt(n - 1)) / e.duration * (t - e.time);
+ const k: usize = @intFromFloat(@floor(position));
+ if (k + 1 >= n) {
+ return curve[n - 1];
+ }
+ const fraction: f32 = @floatCast(position - @as(f64, @floatFromInt(k)));
+ return curve[k] + (curve[k + 1] - curve[k]) * fraction;
+}
+
+// Whether the value can change at or after `t`, i.e. a per-frame computation
+// is needed. Mirrors Chrome's AudioParamHandler::HasSampleAccurateValues,
+// which the oscillator's bit-exact output depends on.
+pub fn hasSampleAccurateValues(self: *const Timeline, quantum_start: f64, quantum_end: f64) bool {
+ const events = self.events.items;
+ if (events.len == 0) return false;
+
+ const first = &events[0];
+ if (first.time > quantum_end) {
+ switch (first.kind) {
+ .set_target, .set_value, .set_value_curve => return false,
+ else => {},
+ }
+ }
+ if (events.len >= 2) return true;
+
+ return switch (first.kind) {
+ .set_target => first.time <= quantum_end,
+ .set_value, .linear_ramp, .exponential_ramp => (first.time < quantum_start) == false,
+ .set_value_curve => first.time <= quantum_start and quantum_start < first.time + first.duration,
+ };
+}
+
+const testing = std.testing;
+fn testInsert(tl: *Timeline, event: Event) !void {
+ return tl.insert(testing.allocator, event, 1);
+}
+
+fn expectValue(timeline: *const Timeline, t: f64, expected: f32) !void {
+ try testing.expectApproxEqAbs(expected, timeline.valueAt(t, 1), 1e-6);
+}
+
+test "Timeline: set value and ramps" {
+ var tl: Timeline = .{};
+ defer tl.events.deinit(testing.allocator);
+ try testInsert(&tl, .{ .kind = .set_value, .time = 1, .value = 0 });
+ try testInsert(&tl, .{ .kind = .linear_ramp, .time = 2, .value = 10 });
+ try testInsert(&tl, .{ .kind = .exponential_ramp, .time = 3, .value = 1000 });
+
+ try expectValue(&tl, 0.5, 1);
+ try expectValue(&tl, 1, 0);
+ try expectValue(&tl, 1.5, 5);
+ try expectValue(&tl, 2, 10);
+ try expectValue(&tl, 2.5, 100);
+ try expectValue(&tl, 4, 1000);
+}
+
+test "Timeline: ramp with nothing before it" {
+ var tl: Timeline = .{};
+ defer tl.events.deinit(testing.allocator);
+ try testInsert(&tl, .{ .kind = .linear_ramp, .time = 2, .value = 3, .start_time = 1, .start_value = 1 });
+ try expectValue(&tl, 0.5, 1);
+ try expectValue(&tl, 1.5, 2);
+ try expectValue(&tl, 3, 3);
+}
+
+test "Timeline: set target and curve" {
+ var tl: Timeline = .{};
+ defer tl.events.deinit(testing.allocator);
+ try testInsert(&tl, .{ .kind = .set_value, .time = 0, .value = 1 });
+ try testInsert(&tl, .{ .kind = .set_target, .time = 1, .value = 0, .time_constant = 1 });
+ try expectValue(&tl, 2, @floatCast(std.math.exp(-1.0)));
+
+ const curve = [_]f32{ 0, 2, 4 };
+ try testInsert(&tl, .{ .kind = .set_value_curve, .time = 3, .duration = 2, .end_time = 5, .curve = &curve });
+ try expectValue(&tl, 3.5, 1);
+ try expectValue(&tl, 4.5, 3);
+ try expectValue(&tl, 6, 4);
+
+ try testing.expectError(error.NotSupported, testInsert(&tl, .{ .kind = .set_value, .time = 4, .value = 1 }));
+}
+
+test "Timeline: ramp after a curve" {
+ var tl: Timeline = .{};
+ defer tl.events.deinit(testing.allocator);
+ const curve = [_]f32{ 0, 2, 4 };
+ try testInsert(&tl, .{ .kind = .set_value_curve, .time = 1, .duration = 1, .end_time = 2, .curve = &curve });
+ try testInsert(&tl, .{ .kind = .linear_ramp, .time = 3, .value = 10 });
+ try expectValue(&tl, 1.5, 2);
+ try expectValue(&tl, 2.5, 7);
+
+ // a ramp at the curve's end
+ try testInsert(&tl, .{ .kind = .linear_ramp, .time = 2, .value = 10 });
+ try expectValue(&tl, 1.5, 2);
+ try expectValue(&tl, 2, 10);
+}
+
+test "Timeline: prune" {
+ var tl: Timeline = .{};
+ defer tl.events.deinit(testing.allocator);
+ try testInsert(&tl, .{ .kind = .set_value, .time = 0, .value = 0 });
+ try testInsert(&tl, .{ .kind = .linear_ramp, .time = 2, .value = 2 });
+ try testInsert(&tl, .{ .kind = .set_target, .time = 3, .value = 0, .time_constant = 1 });
+ const decayed: f32 = @floatCast(2 * std.math.exp(-1.0));
+
+ tl.prune(1);
+ try testing.expectEqual(3, tl.events.items.len);
+ tl.prune(2.5);
+ try testing.expectEqual(2, tl.events.items.len);
+ try expectValue(&tl, 2.5, 2);
+ try expectValue(&tl, 4, decayed);
+ // the set_target keeps decaying from where the ramp left the param
+ tl.prune(3.5);
+ try testing.expectEqual(1, tl.events.items.len);
+ try expectValue(&tl, 4, decayed);
+}
+
+test "Timeline: cancel and hold" {
+ var tl: Timeline = .{};
+ defer tl.events.deinit(testing.allocator);
+ try testInsert(&tl, .{ .kind = .set_value, .time = 0, .value = 0 });
+ try testInsert(&tl, .{ .kind = .linear_ramp, .time = 2, .value = 2 });
+ try tl.cancelAndHoldAtTime(testing.allocator, 1);
+ try expectValue(&tl, 0.5, 0.5);
+ try expectValue(&tl, 1, 1);
+ try expectValue(&tl, 3, 1);
+
+ tl.cancelScheduledValues(0.5);
+ try expectValue(&tl, 3, 0);
+}
diff --git a/src/browser/webapi/webaudio/dsp/math.zig b/src/browser/webapi/webaudio/dsp/math.zig
new file mode 100644
index 000000000..c2a1aa911
--- /dev/null
+++ b/src/browser/webapi/webaudio/dsp/math.zig
@@ -0,0 +1,101 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// Audio fingerprinting hashes the rendered samples, and the compressor's
+// binary search flips on a single ulp. Chrome's float functions behave as the
+// correctly rounded double result, so the f32 ones here round libm's double.
+
+const std = @import("std");
+
+extern "c" fn pow(x: f64, y: f64) f64;
+extern "c" fn exp(x: f64) f64;
+extern "c" fn sin(x: f64) f64;
+extern "c" fn asin(x: f64) f64;
+extern "c" fn log10(x: f64) f64;
+extern "c" fn log2(x: f64) f64;
+extern "c" fn exp2(x: f64) f64;
+
+pub const pi_f32: f32 = @floatCast(std.math.pi);
+pub const pi_over_two_f32: f32 = @floatCast(std.math.pi / 2.0);
+
+fn powf(x: f32, y: f32) f32 {
+ return @floatCast(pow(x, y));
+}
+
+pub fn log10f(x: f32) f32 {
+ return @floatCast(log10(x));
+}
+
+pub fn log2f(x: f32) f32 {
+ return @floatCast(log2(x));
+}
+
+pub fn exp2f(x: f32) f32 {
+ return @floatCast(exp2(x));
+}
+
+pub fn powd(x: f64, y: f64) f64 {
+ return pow(x, y);
+}
+
+pub fn expd(x: f64) f64 {
+ return exp(x);
+}
+
+pub fn sind(x: f64) f64 {
+ return sin(x);
+}
+
+pub fn asind(x: f64) f64 {
+ return asin(x);
+}
+
+pub fn decibelsToLinear(decibels: f32) f32 {
+ return powf(10, 0.05 * decibels);
+}
+
+pub fn linearToDecibels(linear: f32) f32 {
+ return 20 * log10f(linear);
+}
+
+// The per-frame factor k that makes x += (target - x) * k approach target
+// with the given time constant.
+pub fn discreteTimeConstant(time_constant: f64, sample_rate: f64) f64 {
+ return 1 - exp(-1 / (sample_rate * time_constant));
+}
+
+pub const Rounding = enum { nearest, down, up };
+
+// Oversampling by a power of two first makes k / sample_rate map back to k for
+// most integer k, despite the round-off in the division.
+pub fn timeToSampleFrame(time: f64, sample_rate: f64, comptime rounding: Rounding) u64 {
+ const oversample: f64 = 1024;
+ var frame = @round(time * sample_rate * oversample) / oversample;
+ frame = switch (rounding) {
+ .nearest => @round(frame),
+ .down => @floor(frame),
+ .up => @ceil(frame),
+ };
+ if (frame <= 0) {
+ return 0;
+ }
+ if (frame >= @as(f64, @floatFromInt(std.math.maxInt(u64)))) {
+ return std.math.maxInt(u64);
+ }
+ return @intFromFloat(frame);
+}
diff --git a/src/browser/webapi/webaudio/dsp/oscillator.zig b/src/browser/webapi/webaudio/dsp/oscillator.zig
new file mode 100644
index 000000000..758344ebf
--- /dev/null
+++ b/src/browser/webapi/webaudio/dsp/oscillator.zig
@@ -0,0 +1,268 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// Wavetable oscillator, ported from Chromium's oscillator_handler.cc and
+// cpu/x86/oscillator_kernel_sse2.cc (Copyright The Chromium Authors, BSD
+// license). The four-wide paths reproduce the SSE2 kernels' f32/f64 mix, so
+// the samples match Chrome on x86-64 bit for bit, given the same tables.
+
+const std = @import("std");
+const PeriodicWave = @import("PeriodicWave.zig");
+
+// Below these phase increments, 2-point interpolation is too coarse.
+const interpolate_2_point: f32 = 0.3;
+const interpolate_3_point: f32 = 0.16;
+
+const V4 = @Vector(4, f32);
+const I4 = @Vector(4, i32);
+
+// Frequency (already detuned and clamped) constant over the quantum.
+pub fn processKRate(wave: *const PeriodicWave, destination: []f32, virtual_read_index: f64, frequency: f32) f64 {
+ const size = wave.size;
+ const size_f: f64 = @floatFromInt(size);
+ const inv_size: f64 = 1.0 / size_f;
+ const mask = size - 1;
+ const n = destination.len;
+
+ const data = wave.waveData(frequency);
+ const incr = frequency * wave.rate_scale;
+
+ var index = virtual_read_index;
+ if (incr >= interpolate_2_point) {
+ const k = kRateVector(wave, destination, index, incr, data);
+ index += @as(f32, @floatFromInt(k)) * incr;
+ index -= @floor(index * inv_size) * size_f;
+ if (k < n) {
+ _ = kRateScalar(destination[k..], index, incr, mask, inv_size, size_f, data);
+ }
+ var result = virtual_read_index + @as(f32, @floatFromInt(n)) * incr;
+ result -= @floor(result * inv_size) * size_f;
+ return result;
+ }
+
+ for (destination) |*d| {
+ d.* = interpolate(index, @abs(incr), mask, data);
+ index += incr;
+ index -= @floor(index * inv_size) * size_f;
+ }
+ return index;
+}
+
+fn kRateVector(wave: *const PeriodicWave, destination: []f32, virtual_read_index: f64, incr: f32, data: PeriodicWave.WaveData) usize {
+ const size_v: V4 = @splat(@floatFromInt(wave.size));
+ const inv_size_v: V4 = @splat(1.0 / @as(f32, @floatFromInt(wave.size)));
+ const mask_v: I4 = @splat(@intCast(wave.size - 1));
+ const factor_v: V4 = @splat(data.factor);
+ const incr_v: V4 = @splat(4 * incr);
+
+ var virt: V4 = .{
+ @floatCast(virtual_read_index),
+ @floatCast(virtual_read_index + incr),
+ @floatCast(virtual_read_index + 2 * incr),
+ @floatCast(virtual_read_index + 3 * incr),
+ };
+ virt = wrapVector(virt, size_v, inv_size_v);
+
+ var k: usize = 0;
+ const loops = destination.len / 4;
+ for (0..loops) |_| {
+ const read0 = truncate(virt) & mask_v;
+ const read1 = (read0 + @as(I4, @splat(1))) & mask_v;
+ var s1_lower: V4 = undefined;
+ var s2_lower: V4 = undefined;
+ var s1_higher: V4 = undefined;
+ var s2_higher: V4 = undefined;
+ inline for (0..4) |m| {
+ const r0: usize = @intCast(read0[m]);
+ const r1: usize = @intCast(read1[m]);
+ s1_lower[m] = data.lower[r0];
+ s2_lower[m] = data.lower[r1];
+ s1_higher[m] = data.higher[r0];
+ s2_higher[m] = data.higher[r1];
+ }
+ const interpolation = virt - @as(V4, @floatFromInt(read0));
+ const higher = s1_higher + interpolation * (s2_higher - s1_higher);
+ const lower = s1_lower + interpolation * (s2_lower - s1_lower);
+ const sample = higher + factor_v * (lower - higher);
+ destination[k..][0..4].* = sample;
+
+ virt += incr_v;
+ virt = wrapVector(virt, size_v, inv_size_v);
+ k += 4;
+ }
+ return k;
+}
+
+fn kRateScalar(destination: []f32, virtual_read_index: f64, incr: f32, mask: u32, inv_size: f64, size_f: f64, data: PeriodicWave.WaveData) f64 {
+ var index = virtual_read_index;
+ for (destination) |*d| {
+ const read0 = @as(u32, @intFromFloat(index)) & mask;
+ const read1 = (read0 + 1) & mask;
+ const interpolation = @as(f32, @floatCast(index)) - @as(f32, @floatFromInt(read0));
+ const higher = data.higher[read0] + interpolation * (data.higher[read1] - data.higher[read0]);
+ const lower = data.lower[read0] + interpolation * (data.lower[read1] - data.lower[read0]);
+ d.* = higher + data.factor * (lower - higher);
+ index += incr;
+ index -= @floor(index * inv_size) * size_f;
+ }
+ return index;
+}
+
+// Per-frame phase increments (frequency * rate_scale), from an a-rate
+// frequency or detune.
+pub fn processARate(wave: *const PeriodicWave, destination: []f32, virtual_read_index: f64, increments: []const f32) f64 {
+ const size = wave.size;
+ const size_f: f64 = @floatFromInt(size);
+ const inv_size: f64 = 1.0 / size_f;
+ const mask = size - 1;
+ const inv_rate_scale: f32 = 1 / wave.rate_scale;
+
+ var index = virtual_read_index;
+ var k: usize = 0;
+ const loops = destination.len / 4;
+ for (0..loops) |_| {
+ var big = true;
+ var data: [4]PeriodicWave.WaveData = undefined;
+ for (0..4) |m| {
+ const incr = increments[k + m];
+ big = big and @abs(incr) >= interpolate_2_point;
+ data[m] = wave.waveData(inv_rate_scale * incr);
+ }
+ if (big) {
+ index = aRateVectorKernel(destination[k..][0..4], index, increments[k..][0..4], size, &data);
+ } else {
+ for (0..4) |m| {
+ destination[k + m] = interpolate(index, @abs(increments[k + m]), mask, data[m]);
+ index += increments[k + m];
+ index -= @floor(index * inv_size) * size_f;
+ }
+ }
+ k += 4;
+ }
+
+ while (k < destination.len) : (k += 1) {
+ const incr = increments[k];
+ const data = wave.waveData(inv_rate_scale * incr);
+ destination[k] = interpolate(index, @abs(incr), mask, data);
+ index += incr;
+ index -= @floor(index * inv_size) * size_f;
+ }
+ return index;
+}
+
+fn aRateVectorKernel(destination: *[4]f32, virtual_read_index: f64, increments: *const [4]f32, size: u32, data: *const [4]PeriodicWave.WaveData) f64 {
+ const size_f: f64 = @floatFromInt(size);
+ const inv_size: f64 = 1.0 / size_f;
+ const mask: i32 = @intCast(size - 1);
+
+ var sum: [4]f64 = undefined;
+ sum[0] = increments[0];
+ for (1..4) |m| sum[m] = sum[m - 1] + increments[m];
+
+ var read_index: [4]f64 = .{
+ virtual_read_index,
+ virtual_read_index + sum[0],
+ virtual_read_index + sum[1],
+ virtual_read_index + sum[2],
+ };
+ var read0: [4]i32 = undefined;
+ var factor: V4 = undefined;
+ var s1_lower: V4 = undefined;
+ var s2_lower: V4 = undefined;
+ var s1_higher: V4 = undefined;
+ var s2_higher: V4 = undefined;
+ var table_factor: V4 = undefined;
+ inline for (0..4) |m| {
+ // floor via truncate-and-adjust, as WrapVirtualIndexVectorPd
+ const r = read_index[m] * inv_size;
+ var f: i32 = @intFromFloat(r);
+ if (r < @as(f64, @floatFromInt(f))) f -= 1;
+ read_index[m] -= @as(f64, @floatFromInt(f)) * size_f;
+
+ const r0: i32 = @intFromFloat(read_index[m]);
+ read0[m] = r0 & mask;
+ const r1: usize = @intCast((r0 + 1) & mask);
+ const r0_index: usize = @intCast(read0[m]);
+ s1_lower[m] = data[m].lower[r0_index];
+ s2_lower[m] = data[m].lower[r1];
+ s1_higher[m] = data[m].higher[r0_index];
+ s2_higher[m] = data[m].higher[r1];
+ table_factor[m] = data[m].factor;
+ factor[m] = @as(f32, @floatCast(read_index[m])) - @as(f32, @floatFromInt(read0[m]));
+ }
+ const higher = s1_higher + factor * (s2_higher - s1_higher);
+ const lower = s1_lower + factor * (s2_lower - s1_lower);
+ destination.* = higher + table_factor * (lower - higher);
+
+ var index = virtual_read_index + sum[3];
+ index -= @floor(index * inv_size) * size_f;
+ return index;
+}
+
+// Small increments (low frequencies) get 3- or 5-point Lagrange
+// interpolation.
+fn interpolate(virtual_read_index: f64, incr: f32, mask: u32, data: PeriodicWave.WaveData) f32 {
+ var lower: f64 = 0;
+ var higher: f64 = 0;
+ const read0: u32 = @intFromFloat(virtual_read_index);
+
+ if (incr >= interpolate_2_point) {
+ const r0 = read0 & mask;
+ const r1 = (read0 + 1) & mask;
+ const t: f64 = @as(f32, @floatCast(virtual_read_index)) - @as(f32, @floatFromInt(r0));
+ higher = (1 - t) * data.higher[r0] + t * data.higher[r1];
+ lower = (1 - t) * data.lower[r0] + t * data.lower[r1];
+ } else if (incr >= interpolate_3_point) {
+ const t = virtual_read_index - @as(f64, @floatFromInt(read0));
+ const a = [3]f64{ 0.5 * t * (t - 1), 1 - t * t, 0.5 * t * (t + 1) };
+ inline for (0..3) |i| {
+ const r = (read0 +% @as(u32, @bitCast(@as(i32, i) - 1))) & mask;
+ lower += a[i] * data.lower[r];
+ higher += a[i] * data.higher[r];
+ }
+ } else {
+ const t = virtual_read_index - @as(f64, @floatFromInt(read0));
+ const t2 = t * t;
+ const a = [5]f64{
+ t * (t2 - 1) * (t - 2) / 24,
+ -t * (t - 1) * (t2 - 4) / 6,
+ (t2 - 1) * (t2 - 4) / 4,
+ -t * (t + 1) * (t2 - 4) / 6,
+ t * (t2 - 1) * (t + 2) / 24,
+ };
+ inline for (0..5) |i| {
+ const r = (read0 +% @as(u32, @bitCast(@as(i32, i) - 2))) & mask;
+ lower += a[i] * data.lower[r];
+ higher += a[i] * data.higher[r];
+ }
+ }
+ const factor = data.factor;
+ return @floatCast((1 - factor) * higher + factor * lower);
+}
+
+fn truncate(v: V4) I4 {
+ return @intFromFloat(v);
+}
+
+// x - floor(x / size) * size, in f32 as the SSE kernel computes it.
+fn wrapVector(x: V4, size: V4, inv_size: V4) V4 {
+ const r = x * inv_size;
+ var f = truncate(r);
+ f -= @select(i32, r < @as(V4, @floatFromInt(f)), @as(I4, @splat(1)), @as(I4, @splat(0)));
+ return x - @as(V4, @floatFromInt(f)) * size;
+}
diff --git a/src/browser/webapi/webaudio/render.zig b/src/browser/webapi/webaudio/render.zig
new file mode 100644
index 000000000..85a7651c7
--- /dev/null
+++ b/src/browser/webapi/webaudio/render.zig
@@ -0,0 +1,51 @@
+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)
+//
+// Francis Bouvier <[email protected]>
+// Pierre Tachoire <[email protected]>
+//
+// This program is free software: you can redistribute it and/or modify
+// it under the terms of the GNU Affero General Public License as
+// published by the Free Software Foundation, either version 3 of the
+// License, or (at your option) any later version.
+//
+// This program is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU Affero General Public License for more details.
+//
+// You should have received a copy of the GNU Affero General Public License
+// along with this program. If not, see <https://www.gnu.org/licenses/>.
+
+// The graph renders one quantum at a time, pulled from the destination: a
+// node pulls its inputs, then processes. Each node renders at most once per
+// quantum (`AudioNode._rendered`).
+
+const std = @import("std");
+
+const js = @import("../../js/js.zig");
+
+const Bus = @import("dsp/Bus.zig");
+const AudioScheduledSourceNode = @import("AudioScheduledSourceNode.zig");
+
+const Allocator = std.mem.Allocator;
+
+pub const Quantum = struct {
+ // render count, starting at 1
+ index: u64,
+ // first sample frame
+ frame: u64,
+ sample_rate: f32,
+ // the context's arena, for buses that grow
+ allocator: Allocator,
+ // for reading AudioBuffers' channel arrays
+ local: *const js.Local,
+ // sources that finished during this quantum, to get an `ended` event
+ finished: *std.ArrayList(*AudioScheduledSourceNode),
+ // one silent channel, for a node reached through a cycle or too deep
+ silence: *const Bus,
+ // nodes currently being pulled
+ depth: u32 = 0,
+};
+
+// Deeper graphs render the excess as silence rather than overflow the stack.
+pub const max_depth = 256;