Closed AudioContext / OfflineAudioContext is never released: stateChange listener is never unregistered

未关闭
#1,497 1 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@choi138 已经在做这个了。

开始于 2026年11月25日。

  • #1498 来自 @choi138 —— 未关闭

评估

难度
4/5
预计耗时
1-2 天
新手友好度
35/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
android, cpp, ios, react-native, typescript

调研方向

Start in src/core/BaseAudioContext.ts around the constructor, where the stateChange listener is added and stored in stateChangeSubscription, then check close() in src/core/AudioContext.ts and startRendering() in src/core/OfflineAudioContext.ts. Read common/cpp/audioapi/events/AudioEventHandlerRegistry.cpp to see how handlers are kept until unregisterHandler. Done means the subscription is released after the closed state change is delivered, with a test showing listeners are removed and the closed event still fires.

由索引模型根据 Issue 内容生成。

描述

bug
Description

Every AudioContext / OfflineAudioContext registers a stateChange listener in the global native AudioEventHandlerRegistry and never removes it, so a closed context (the JS object and the whole native context behind it) is retained for the lifetime of the JS runtime.

Chain (react-native-audio-api 1.0.1, still present on main):

  1. src/core/BaseAudioContext.ts:43-47 - the constructor calls this.audioEventEmitter.addAudioEventListener('stateChange', () => this.onstatechange?.()) and stores it in this.stateChangeSubscription. Nothing ever calls this.stateChangeSubscription.remove().
  2. src/core/AudioContext.ts:47-57 - close() only removes this.errorSubscription. src/core/OfflineAudioContext.ts (startRendering()) removes nothing.
  3. common/cpp/audioapi/events/AudioEventHandlerRegistry.cpp - registerHandler stores the callback as std::shared_ptr<jsi::Function> in eventHandlers_ until unregisterHandler is called.
  4. The callback closes over this, which holds this.context (the BaseAudioContextHostObject), which holds the native BaseAudioContext (graph, event/GC scheduler queues, disposer thread, ...).

So every created context stays reachable from the registry forever. Apps that create a context per screen/session (in our case one per game round) grow native memory and thread count steadily until the OS kills them.

What we observed on an iPhone X (Release build): after 3 rounds, each creating and closing one AudioContext, the process thread count went from 23 to 37. 11 of the 14 new threads belong to the library: 3x audioapi DisposerImpl, 3x audioapi TaskOffloader, 5x audioapi ThreadPool. Memory went from 182 MB to 284 MB over the same rounds.

Ordering note: removing the subscription right after await this.context.close() would drop the closed statechange. ContextPromiseResolver::settle (common/cpp/audioapi/jsi/ContextPromiseResolver.hpp) resolves the JS promise first and only then calls dispatchStateChange, which goes through the registry's worker thread and a later invokeAsync. So the closed event lands in a later JS task than the promise resolution.

Proposed fix

Release the subscription once the terminal closed state change has been delivered. This covers both AudioContext.close() and OfflineAudioContext.startRendering() and keeps the closed event:

// BaseAudioContext.ts
this.stateChangeSubscription = this.audioEventEmitter.addAudioEventListener(
  'stateChange',
  (event: { state?: string }) => {
    this.onstatechange?.();
    if (event?.state === 'closed') {
      this.disposeStateChangeSubscription();
    }
  }
);

protected disposeStateChangeSubscription(): void {
  const subscription = this.stateChangeSubscription;
  if (subscription == null) {
    return;
  }
  this.stateChangeSubscription = null;
  this.context.onstatechange = '0'; // same as ~BaseAudioContextHostObject
  subscription.remove();
}

dispatchStateChange dedupes on lastDispatchedState_, so closed is delivered exactly once. Typing the stateChange payload as { state: ContextState } in events/types.ts would remove the inline type. We apply this as a local patch and can open a PR with a test if you agree with the approach.

Steps to reproduce
  1. Run const ctx = new AudioContext(); await ctx.close(); N times (e.g. in a loop, or once per screen mount/unmount).
  2. Count addAudioEventListener('stateChange') vs removeAudioEventListener('stateChange') calls, or inspect the registry: N listeners remain.
  3. On iOS, compare the thread list before and after (Xcode debugger / Instruments): one audioapi DisposerImpl and one audioapi TaskOffloader thread remain per closed context, and native memory does not go back down after GC.
Snack or a link to a repository

No public repro repo; the leak is visible from the code path above and reproduces with the 2-line snippet in step 1.

React Native Audio API version

1.0.1 (also present on main as of 2026-11-25)

React Native version

0.86.3

Platforms

iOS, Android

JavaScript runtime

Hermes

Architecture

Fabric (New Architecture)

Build type

Release and Debug

Device

Real device (iPhone X)

主要语言
C++
星标
864
派生
103
平均合并
1 天 16 小时
30 天内合并 PR
77

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

software-mansion/react-native-audio-api 的其他 Issue

查看 software-mansion/react-native-audio-api 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。