Skip to content

Refatora processamento de preview em tempo real para AudioWorklet#83

Merged
ovelhaaa merged 2 commits into
mainfrom
codex/refactor-demo.js-to-use-audioworklet
May 28, 2026
Merged

Refatora processamento de preview em tempo real para AudioWorklet#83
ovelhaaa merged 2 commits into
mainfrom
codex/refactor-demo.js-to-use-audioworklet

Conversation

@ovelhaaa

@ovelhaaa ovelhaaa commented May 28, 2026

Copy link
Copy Markdown
Owner

Motivation

  • Resolver estalos e underruns causados pelo uso de ScriptProcessorNode na thread principal movendo o processamento realtime para um AudioWorkletNode dedicado.
  • Evitar alocação e processamento de buffers pesados na UI thread enquanto mantém o caminho de processamento offline síncrono intacto.

Description

  • Substitui a criação do ScriptProcessorNode em ensurePreviewGraph() por await audioCtx.audioWorklet.addModule('./worklet-processor.js') e new AudioWorkletNode(audioCtx, 'orbit-delay-processor'), conectando drySource -> orbitNode -> wetGain -> audioCtx.destination e salvando a referência em previewGraph.orbitNode.
  • Remove a lógica de buffers realtime na thread principal (ensureRealtimeBuffers e ponteiros relacionados), preservando apenas realtimeState.isOfflineProcessing como sinalizador para o modo offline.
  • Atualiza setParam(key) para, quando o orbitNode estiver presente e não estivermos em processamento offline, aplicar valores realtime via previewGraph.orbitNode.parameters.get(paramName).setValueAtTime(value, audioCtx.currentTime); mantém chamadas diretas à API WASM no caminho offline (botão de processamento).
  • Adiciona tratamento básico de mensagens do Worklet (orbitNode.port.onmessage) para encaminhar diagnósticos orbit_diag ao UI se necessário, e mantém a rotina offline síncrona com _malloc/api.process sem alterações.

Testing

  • Executado node --check targets/wasm/js/demo.js para verificação sintática do script e o comando terminou sem erros (sucesso).

Codex Task

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Enhanced real-time audio preview processing for improved performance and reliability.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@ovelhaaa, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 44 minutes and 45 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fc0f5bdc-d5af-42dc-b91a-2106127d86cc

📥 Commits

Reviewing files that changed from the base of the PR and between 38c1c44 and 73b6f63.

📒 Files selected for processing (2)
  • targets/wasm/js/demo.js
  • targets/wasm/js/worklet-processor.js
📝 Walkthrough

Walkthrough

Replaced realtime audio processing from deprecated ScriptProcessorNode to modern AudioWorkletNode. The change simplifies state tracking, refactors the preview audio graph to load and integrate the worklet processor, and routes parameter updates directly to worklet parameters when realtime preview is active.

Changes

AudioWorkletNode Migration

Layer / File(s) Summary
State simplification for AudioWorkletNode
targets/wasm/js/demo.js
realtimeState now tracks only offline-processing mode, removing buffer pointer and block-size fields used by the deprecated ScriptProcessor path.
AudioWorkletNode initialization and audio routing
targets/wasm/js/demo.js
ensurePreviewGraph() loads the worklet module, creates an orbit-delay-processor AudioWorkletNode, attaches a port message handler for diagnostic logging, and rewires the audio graph so the wet signal flows through the worklet before reaching the destination.
Parameter routing to worklet
targets/wasm/js/demo.js
setParam() now sets worklet parameters directly via orbitNode.parameters when realtime preview is active and offline processing is inactive, otherwise falls back to WASM api setters.

Sequence Diagram

sequenceDiagram
  participant User
  participant setParam as setParam()
  participant orbitNode as orbit-delay-processor
  participant wasmAPI as WASM api
  
  User->>setParam: adjust parameter
  alt Realtime preview active
    setParam->>orbitNode: setValueAtTime(key, value)
    orbitNode->>orbitNode: update parameter
  else Offline or no preview
    setParam->>wasmAPI: call api setter
    wasmAPI->>wasmAPI: update state
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • ovelhaaa/orbit-echo#27: Both PRs modify targets/wasm/js/demo.js's realtime parameter update path—this PR routes updates to AudioWorkletNode parameters, while the related PR optimizes UI binding by coalescing setParam() calls via requestAnimationFrame.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: refactoring realtime preview processing to use AudioWorklet instead of ScriptProcessorNode, which aligns with the primary objective and the substantial code modifications in the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/refactor-demo.js-to-use-audioworklet

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the realtime audio processing in the WASM demo to use an AudioWorkletNode (orbit-delay-processor) instead of the deprecated ScriptProcessorNode. This involves removing the ensureRealtimeBuffers function and updating setParam to dynamically set parameters on the worklet node. The reviewer identified a critical issue where certain parameters (like shimmerMode, feedbackTapMixerEnabled, and feedbackTapMixerAmount) are not declared in the worklet's descriptors, causing them to be silently ignored during realtime playback. A code suggestion was provided to add warning logs for missing parameters.

Comment thread targets/wasm/js/demo.js
Comment on lines +858 to +864
if (previewGraph.orbitNode && previewGraph.audioCtx && !realtimeState.isOfflineProcessing) {
const param = previewGraph.orbitNode.parameters.get(key);
if (param) {
param.setValueAtTime(value, previewGraph.audioCtx.currentTime);
}
return;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Há uma incompatibilidade entre os parâmetros suportados pelo OrbitDelayProcessor (definidos em worklet-processor.js) e os parâmetros enviados por setParam.

Os parâmetros shimmerMode, feedbackTapMixerEnabled e feedbackTapMixerAmount estão presentes em PARAM_KEYS e são atualizados via UI, mas não estão declarados em parameterDescriptors nem são tratados em applyParams dentro do worklet-processor.js.

Como a função setParam retorna imediatamente quando previewGraph.orbitNode está ativo (mesmo se o parâmetro for undefined), essas configurações serão silenciosamente ignoradas e nunca serão aplicadas ao áudio em tempo real.

Para corrigir isso, você precisa:

  1. Adicionar esses parâmetros ao parameterDescriptors e ao método applyParams no arquivo targets/wasm/js/worklet-processor.js.
  2. Adicionar um aviso no console caso um parâmetro não seja encontrado no nó do Worklet para facilitar a depuração.
Suggested change
if (previewGraph.orbitNode && previewGraph.audioCtx && !realtimeState.isOfflineProcessing) {
const param = previewGraph.orbitNode.parameters.get(key);
if (param) {
param.setValueAtTime(value, previewGraph.audioCtx.currentTime);
}
return;
}
if (previewGraph.orbitNode && previewGraph.audioCtx && !realtimeState.isOfflineProcessing) {
const param = previewGraph.orbitNode.parameters.get(key);
if (param) {
param.setValueAtTime(value, previewGraph.audioCtx.currentTime);
} else {
console.warn(`Parâmetro "${key}" não encontrado no AudioWorkletNode.`);
}
return;
}

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@targets/wasm/js/demo.js`:
- Around line 243-249: Add error handling and lifecycle feedback around worklet
initialization: await audioCtx.audioWorklet.addModule('./worklet-processor.js')
should be wrapped to catch and log/display errors; creation of the
AudioWorkletNode (orbitNode = new AudioWorkletNode(...)) should also be guarded
to handle exceptions. Extend orbitNode.port.onmessage to handle event.data.type
=== 'ready' (signal successful WASM init) and event.data.type === 'error' (show
error details to UI/console) in addition to the existing 'orbit_diag' handling,
and surface errors to the user (e.g., processLogger/console and a UI
notification) so WASM init failures and node creation failures aren’t silent.
- Around line 251-263: applyParams() is being called before
previewGraph.orbitNode is assigned, causing setParam() to fall back to the WASM
path and not send initial values to the worklet; move the applyParams() call so
it runs after previewGraph.orbitNode (and
previewGraph.dryGain/wetGain/orbitNode) are assigned and previewGraph.audioCtx
is set, or alternatively call applyParams() again after those assignments,
ensuring applyParams(), setParam(), previewGraph.orbitNode and api see the
correct initialized graph so the worklet receives the UI/preset values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a5a47c74-9767-45c9-9ffd-c715ff06fda9

📥 Commits

Reviewing files that changed from the base of the PR and between 1c045b4 and 38c1c44.

📒 Files selected for processing (1)
  • targets/wasm/js/demo.js

Comment thread targets/wasm/js/demo.js Outdated
Comment thread targets/wasm/js/demo.js Outdated
@ovelhaaa
ovelhaaa merged commit a9422f2 into main May 28, 2026
4 checks passed
@ovelhaaa
ovelhaaa deleted the codex/refactor-demo.js-to-use-audioworklet branch May 28, 2026 05:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant