Skip to content

feat: compute convolver tail in large blocks - #1469

Merged
mdydek merged 1 commit into
software-mansion:mainfrom
abboskhon-dev:feat/convolver-large-block-tail
Nov 18, 2026
Merged

mdydek merged 1 commit into
software-mansion:mainfrom
abboskhon-dev:feat/convolver-large-block-tail

Conversation

@abboskhon-dev

@abboskhon-dev abboskhon-dev commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1463

⚠️ Breaking changes ⚠️

  • None. No JS API change. The output equals main within float rounding.

Introduced changes

Convolver becomes a two-stage partitioned convolver. T = TAIL_BLOCK_FRAMES = 2048.

  • Head: impulse response frames [0, 2T) in 128-frame partitions on the audio thread, as before (32 partitions instead of 8).
  • Tail: frames [2T, L) in T-frame partitions with their own 2T-point FFT. An impulse response of 2T frames or fewer has no tail and never touches the pool.
  • On the quantum that completes T frames of input, process() runs the tail's forward FFT into a second delay line. ConvolverNode::scheduleTails then hands one computeTail(block) task to the pool: one task per convolver per tail block (about 23 a second at 48 kHz), not one per quantum (375 a second).
  • A worker multiplies the tail partitions, runs the inverse FFT and publishes T time-domain frames in a slot. The audio thread starts playing that block T frames after its input completed, so the worker has about 43 ms.
  • A block that is not published in time is computed inline on its first quantum, as today. OfflineAudioContext has no pool and always takes this path.

What changed against the design in #1463

  • The audio thread never writes a slot. It loads the state, and on an exact match it copies the frames. No CAS is needed there: the only block that can claim the same slot later is block + 3, and its input is not complete until after this block has been played.
  • computeTail(block) returns early for a block whose input is not complete and for a block the audio thread already rendered.
  • nextTailBlock() is replaced by takeCompletedTailBlock(), which hands each block out once.
  • 3 result slots (two blocks are live at a time, the third covers a worker that is one block late). Each slot owns its accumulator, its time buffer and its own dsp::FFT, because an FFT object keeps scratch memory.

Open questions from the issue

  • Block size: 2048. Numbers below.
  • The tail's forward FFT stays on the audio thread, so the audio thread remains the only writer of input spectra. With 4 convolvers that quantum costs 27 µs against 11.5 µs for a plain quantum, about 1% of the 2.67 ms budget (host numbers, see below).
  • The constant sits in Convolver.h where HEAD_SEGMENTS was. HEAD_FRAMES = 2 × TAIL_BLOCK_FRAMES is derived from it.

Why the output is the same

Split the impulse response as h = head + tail, where the tail starts at frame 2T. Then y = head * x + (g * x) delayed by 2T, with g[m] = h[2T + m]. Block j of g * x depends only on input frames before (j + 1)T, and it is played over frames [(j + 2)T, (j + 3)T). So every tail block is computable one tail block before it is needed, and the head covers everything that depends on newer input.

Every test compares against a direct time-domain convolution, including impulse response lengths of 2T, 2T + 1, 3T, 3T + 1 and lengths that are not a multiple of T, on both the published and the inline path.

Max error against a double-precision direct convolution (uniform noise in, uniform noise impulse response, 128-frame blocks):

IR frames output peak main this PR
6,145 99 2.7e-5 2.3e-5
10,257 153 3.9e-5 3.2e-5
24,000 169 8.2e-5 4.2e-5

Host benchmark

Apple Silicon, Release build, 4 convolvers (a 4-channel impulse response), 104,859-frame impulse response (2.2 s at 48 kHz), 20 s of audio, pool of 4 workers, callbacks paced in real time. "Total CPU" is all threads of the process, as a share of one core. T = 1024 is the same code with the constant changed.

quanta per callback total CPU: main / 1024 / 2048 audio thread mean per quantum, µs: main / 1024 / 2048 tail misses: main / 1024 / 2048
1 59.0% / 9.0% / 6.4% 50 / 49 / 69 0 / 0 / 0
4 46.5% / 8.5% / 5.8% 29 / 44 / 65 0 / 0 / 0
8 57.6% / 8.2% / 5.4% 36 / 46 / 66 0 / 0 / 0
16 54.8% / 7.3% / 5.2% 392 / 43 / 59 5,371 / 0 / 0
32 45.1% / 5.7% / 4.3% 535 / 53 / 51 7,179 / 747 / 0
offline (no pool) 5.7% / 0.8% / 0.6% 151 / 22 / 17 every block, by design
  • Total CPU at one quantum per callback for the other lengths: 55,199 frames 25.5% / 5.1% / 5.0%, 181,251 frames 81.5% / 12.5% / 8.6%.
  • The audio thread pays for the longer head: about 20 to 35 µs more per quantum than main for 4 convolvers while main has no misses.
  • main computes every tail inline once a callback is longer than its 8-quantum deadline. With 2048-frame blocks that starts above 32 quanta per callback.
  • An inline tail block for 4 convolvers costs 134 / 236 / 391 µs for the 1.15 / 2.2 / 3.8 s impulse responses (median, offline).

Limits of these numbers:

  • Host only. I will post Galaxy S21 numbers for main and this branch (apps/fabric-example, ConvolverIR example) tomorrow morning.
  • The pacing thread is not a real-time thread, and every variant showed multi-millisecond outliers in the per-quantum maximum, so I do not quote maxima.
  • The deadline is audio time. A worker only gets wall time when a callback boundary falls between the quantum that completes a block and the quantum that first plays it. I have not checked which callback sizes the players use on each platform.
  • The benchmark is a standalone program and is not part of this PR. I can add it if you want it in the repo.

Notes

  • feat: variable render quantum size #1364 rewrites the same files, and fix: sum true-stereo convolver results at unity gain #1455 touches ConvolverNode.cpp. I will rebase this on whichever lands first. T is an absolute frame count and every other size derives from the block size, so it should carry over to a variable render quantum.
  • .claude/skills/thread-safety-itc/SKILL.md described the 8-segment prefetch; its convolver section is rewritten for this design.
  • directConvolution in ConvolverTest.cpp now sums in double. With impulse responses of 10,000 frames the float sum was less exact than the convolver, and the comparison failed on the reference's rounding. The tolerance is unchanged.

Checklist

  • Linked relevant issue
  • Targets the right branch (release/X.Y only for fixes to the released version)
  • Updated relevant documentation (n/a: no API or user-facing behaviour change)
  • Added/Conducted relevant tests
  • Performed self-review of the code
  • Updated Web Audio API coverage (n/a: coverage unchanged)
  • Added support for web (n/a: web uses the browser's ConvolverNode)
  • Updated old arch android spec file (n/a: no spec change)

Tests

Run:

  • ConvolverTest (12 cases: the 5 from main rewritten for impulse responses long enough to have a tail, and 7 new) and ConvolverThreadPoolTest: plain, --tsan and --ubasan.
  • Full C++ smoke suite: 616 tests pass.
  • WPT, --filter convolver: 182 of 255 pass on main and on this branch, and the two reports are identical test by test.
  • clang-format and cpplint on the changed files.

Not run:

  • Not built or run on a device yet (numbers follow, see above).
  • JS lint, typecheck and Jest: the change touches no TypeScript.

Summary by CodeRabbit

  • Improvements
    • Long impulse responses are processed in separate sections, helping keep audio processing responsive while preserving convolution output.
    • Tail processing can proceed inline when background results are unavailable or delayed, reducing the impact of missed processing deadlines.
    • Convolution behavior is now covered across varied impulse-response lengths, timing conditions, and delay-line wraparound.

@coderabbitai

coderabbitai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The convolver now processes long impulse responses with a 4096-frame head and 2048-frame tail blocks when the input block size permits. It hands completed tail blocks to the thread pool and renders inline when a result is unavailable. Tests cover output accuracy, block timing, and worker scheduling.

Changes: Two-stage convolver tail processing

Layer / File(s) Summary
Head and tail setup
packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.h, packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.cpp
Convolver defines fixed head and tail sizes and maintains separate state for each stage. Eligible impulse responses are split, with separate spectra and buffers prepared for the tail.
Tail rendering and worker handoff
packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.cpp, packages/react-native-audio-api/common/cpp/audioapi/core/effects/ConvolverNode.cpp, .claude/skills/thread-safety-itc/SKILL.md
The audio thread renders tail output from a ready worker result or computes it inline. ConvolverNode schedules only completed tail blocks. The documentation describes block deadlines, slot ownership, and result matching.
Convolution and handoff tests
packages/react-native-audio-api/common/cpp/test/src/dsp/ConvolverTest.cpp
Tests compare output with direct convolution and cover tail lengths, delay-line wraparound, completed-block handoff, late or stray requests, and thread-pool execution.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant ConvolverNode
  participant Convolver
  participant ThreadPool
  Convolver->>ConvolverNode: Provide completed tail block index
  ConvolverNode->>ThreadPool: Schedule tail computation
  ThreadPool->>Convolver: Compute tail block
  Convolver->>Convolver: Render ready result or compute inline
Loading

Suggested labels: refactor

Suggested reviewers: mdydek, maciejmakowski2003

Merge Risk: Minimal · up to 1c4f1

This change makes long impulse-response convolution cheaper by processing the tail in larger blocks, and output is reported to match the previous behavior. The one concurrency concern raised is an already-documented race with a wider safety margin than before. No merge-blocking risk remains.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "feat: compute convolver tail in large blocks" matches the main change: the convolver tail is now computed in 2048-frame blocks instead of per quantum. The title is short, specific, and foll…
Description check Passed The description follows the repository template. It links issue #1463 with 'Closes #1463', includes the Breaking changes section (stating none, with no JS API change), gives a detailed Introduced chan…
Linked Issues check Passed Directly linked issue [#1463] has these coding requirements. (1) Split the impulse response at 2T, with 128-frame head partitions and T-frame tail partitions using a 2T-point FFT. The PR does this wit…
Out of Scope Changes check Passed All changed areas connect to [#1463]. Convolver.h and Convolver.cpp implement the two-stage design, the tail state, and the slot scheme. The new public constants TAIL_BLOCK_FRAMES and HEAD_FRAMES repl…
Full details: Title check

Explanation

The title "feat: compute convolver tail in large blocks" matches the main change: the convolver tail is now computed in 2048-frame blocks instead of per quantum. The title is short, specific, and follows conventional commit style. It omits the two-stage head/tail design and the three-slot result scheme, which is acceptable because the title need not cover every detail.

Full details: Description check

Explanation

The description follows the repository template. It links issue #1463 with 'Closes #1463', includes the Breaking changes section (stating none, with no JS API change), gives a detailed Introduced changes section, and provides a checklist with several items marked. It also adds Tests and Notes sections, which go beyond the template but add useful context. Two checklist items are unchecked with 'n/a' reasons, and the documentation item is marked n/a even though the raw summary shows an agent skill documentation file was rewritten. The description is thorough and mostly complete.

Full details: Linked Issues check

Explanation

Directly linked issue [#1463] has these coding requirements. (1) Split the impulse response at 2T, with 128-frame head partitions and T-frame tail partitions using a 2T-point FFT. The PR does this with T = TAIL_BLOCK_FRAMES = 2048 and HEAD_FRAMES = 2T, per the Convolver.h and Convolver.cpp summaries. (2) Schedule one pool task per tail block, not per quantum. ConvolverNode::scheduleTails now schedules only when takeCompletedTailBlock() yields an index. (3) Keep the audio thread as the only writer of input spectra, using a second delay line. The PR does this. (4) Publish T time-domain frames per computeTail, with a slot scheme and an inline fallback when a block is late. The PR does this, with three slots. (5) Keep the head on the audio thread and never wait on the audio thread. The PR does this. (6) Add tests for split lengths (2T, 2T+1, non-multiple of T) and multi-block handoff on the ready and late paths, compared against direct convolution. ConvolverTest.cpp covers these per the PR description and the test-file summary. Deviation: the issue proposed an audio-thread CAS claim. The PR removes audio-thread slot writes and CAS, and it gives a reason (the block that can reuse a slot is not complete until after playback). This is a design change that keeps the required behavior. Non-coding items (device numbers, benchmarks, JS lint) do not apply. Limits: the test cases were confirmed from the PR description and the file summary, not from a read of the test hunks.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to [#1463]. Convolver.h and Convolver.cpp implement the two-stage design, the tail state, and the slot scheme. The new public constants TAIL_BLOCK_FRAMES and HEAD_FRAMES replace HEAD_SEGMENTS as the issue requested. The public method change (nextTailBlock() replaced by takeCompletedTailBlock()) is internal to the convolver API and is part of the design. ConvolverNode.cpp changes scheduleTails to the new tail-block handoff. ConvolverTest.cpp adds split-length and handoff tests, and it moves directConvolution to double precision so the reference is accurate at longer lengths. That supports the tests. The .claude/skills/thread-safety-itc/SKILL.md edit updates documentation that describes the convolver design this PR changes. The zero block-size rejection in Convolver.cpp is a small guard in the code this PR rewrites. No unrelated feature, refactor, or JS API change was found in the summaries. The benchmark program is explicitly excluded from the PR.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a6c3efab-d9c1-4817-bc5c-3d89b96565c8
Commits

Reviewing files that changed from the base of the PR and between fed8ffa and 1c4f1e4.

Files selected for processing: 5

  • .claude/skills/thread-safety-itc/SKILL.md
  • packages/react-native-audio-api/common/cpp/audioapi/core/effects/ConvolverNode.cpp
  • packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.cpp
  • packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.h
  • packages/react-native-audio-api/common/cpp/test/src/dsp/ConvolverTest.cpp

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

@mdydek mdydek added the feature New user-facing features or major capabilities label Nov 17, 2026
@mdydek

mdydek commented Nov 17, 2026

Copy link
Copy Markdown
Member

"Host only. I will post Galaxy S21 numbers for main and this branch (apps/fabric-example, ConvolverIR example) tomorrow morning."

will wait till tomorrow then and I will review it

@github-actions

Copy link
Copy Markdown
Contributor

C++ coverage

Smoke suites, Clang source-based coverage.

Covered Total %
Lines 7633 10504 72.67%
Functions 1064 1332 79.88%
Regions 3943 5401 73%

Lines changed in this pull request

  • Total: 121 lines

  • Missing: 3 lines

  • Coverage: 97%

  • packages/react-native-audio-api/common/cpp/audioapi/core/effects/ConvolverNode.cpp (0.0%): Missing lines 185-186,192

  • packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.cpp (100%)

  • packages/react-native-audio-api/common/cpp/audioapi/dsp/Convolver.h (100%)

Uncovered changed lines

packages/react-native-audio-api/common/cpp/audioapi/core/effects/ConvolverNode.cpp

Lines 181-190

  181   if (threadPool_ == nullptr) {
  182     return;
  183   }
  184   for (const auto &convolver : convolvers_) {
! 185     const std::optional<size_t> completedBlock = convolver->takeCompletedTailBlock();
! 186     if (!completedBlock.has_value()) {
  187       continue;
  188     }
  189     // A full queue means the workers are starved; the tail is then simply never published
  190     // and process() computes it inline when that block comes up.

Lines 188-196

  188     }
  189     // A full queue means the workers are starved; the tail is then simply never published
  190     // and process() computes it inline when that block comes up.
  191     (void)threadPool_->trySchedule(
! 192         [convolver, block = *completedBlock] { convolver->computeTail(block); });
  193   }
  194 }
  195 } // namespace audioapi

Workflow run · this comment is updated on every push.

@github-actions

Copy link
Copy Markdown
Contributor

WPT non-regression comparison

PASS — no regressions · 1 improved section(s) · overall 3431 → 3434 (+3)

Spec section Base pass Head pass Delta
ConvolverNode 179 182 +3
Unchanged sections (27)
Spec section Base pass Head pass Delta
Processing model 1 1 0
Other 56 56 0
AnalyserNode 138 138 0
AudioBuffer 142 142 0
AudioBufferSourceNode 221 221 0
AudioContext 58 58 0
AudioNode 261 261 0
AudioParam 680 680 0
BiquadFilterNode 275 275 0
ChannelMergerNode 30 30 0
ChannelSplitterNode 7 7 0
ConstantSourceNode 64 64 0
DelayNode 127 127 0
DestinationNode 0 0 0
DynamicsCompressorNode 4 4 0
GainNode 15 15 0
IIRFilterNode 87 87 0
MediaElementAudioSourceNode 0 0 0
MediaStreamAudioDestinationNode 1 1 0
MediaStreamAudioSourceNode 0 0 0
OfflineAudioContext 35 35 0
OscillatorNode 104 104 0
PannerNode 727 727 0
PeriodicWave 33 33 0
ScriptProcessorNode 0 0 0
StereoPannerNode 104 104 0
WaveShaperNode 82 82 0

Baseline: fed8ffa9f3514b05e6eb1c478a10bc31acff6d5e · Candidate: 1c4f1e48ee1605a2ee997d6861e93dc0b7e76442

Workflow run · this comment is updated on every push.

@abboskhon-dev

Copy link
Copy Markdown
Contributor Author

Galaxy S21 numbers, as promised.

Setup: Galaxy S21 (Exynos 2100, Android 15), apps/fabric-example release build (arm64), ConvolverIR example (2-channel, 2.17 s impulse response), 48 kHz stream with 96-frame bursts. Measured with simpleperf stat --per-thread, 3 × 10 s per build, mean. main is the merge-base 7da2c383. All rates are per second of wall time.

Convolver playing:

  • Pool threads: main 852 M cycles, 492 M instructions. This branch 48 M cycles, 27 M instructions.
  • Audio thread: main 144 M cycles, 41.3 M instructions. This branch 127 M cycles, 48.7 M instructions.
  • Whole process: main 1,043 M cycles. This branch 212 M cycles.

Dry playback (no convolver), both builds: audio thread 30.1 M instructions.

So the convolver costs about 9× fewer cycles (about 922 M → 105 M). The audio thread runs about 18% more instructions, because the head is now 32 partitions instead of 8.

I compare cycles and instructions, not CPU %. The governor changed the clock frequency between sessions, and the same dry playback read 3% of a core in one session and 12% in another.

Not checked: the xrun count. Both builds sound the same by ear on the device. One session per build, one device, one impulse response.

@mdydek

mdydek commented Nov 18, 2026

Copy link
Copy Markdown
Member

looks veeery solid, making benchmarks on some lower end devices right now, but I'm impressed

@mdydek
mdydek merged commit 5494366 into software-mansion:main Nov 18, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New user-facing features or major capabilities

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ConvolverNode: compute the impulse response tail in large blocks

2 participants