Closed AudioContext / OfflineAudioContext is never released: stateChange listener is never unregistered
Los mantenedores suelen responder en 1 día
Evaluación
- Dificultad
- 4/5
- Tiempo estimado
- 1-2 días
- Aptitud para principiantes
- 35/100
- Tipo de issue
- Error
- Claridad
- Bien especificado
- Estado de actividad
- Activo
- Stack tecnológico
- android, cpp, ios, react-native, typescript
- Área
- audio-video-rtc, mobile-dev
Línea de trabajo
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.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
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):
src/core/BaseAudioContext.ts:43-47- the constructor callsthis.audioEventEmitter.addAudioEventListener('stateChange', () => this.onstatechange?.())and stores it inthis.stateChangeSubscription. Nothing ever callsthis.stateChangeSubscription.remove().src/core/AudioContext.ts:47-57-close()only removesthis.errorSubscription.src/core/OfflineAudioContext.ts(startRendering()) removes nothing.common/cpp/audioapi/events/AudioEventHandlerRegistry.cpp-registerHandlerstores the callback asstd::shared_ptr<jsi::Function>ineventHandlers_untilunregisterHandleris called.- The callback closes over
this, which holdsthis.context(theBaseAudioContextHostObject), which holds the nativeBaseAudioContext(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
- Run
const ctx = new AudioContext(); await ctx.close();N times (e.g. in a loop, or once per screen mount/unmount). - Count
addAudioEventListener('stateChange')vsremoveAudioEventListener('stateChange')calls, or inspect the registry: N listeners remain. - On iOS, compare the thread list before and after (Xcode debugger / Instruments): one
audioapi DisposerImpland oneaudioapi TaskOffloaderthread 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)
- Lenguaje dominante
- C++
- Estrellas
- 864
- Forks
- 103
- Merge medio
- 1 d 16 h
- PR fusionados (30 d)
- 77
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de software-mansion/react-native-audio-api
-
AudioContext destructor dereferences a null audioPlayer_ when construction fails before initialize()Posiblemente ocupada @maciejmakowski2003 la tomó hoy. Abiertobug
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
software-mansion/react-native-audio-api#1504 · 1 asignado ·
Los mantenedores suelen responder en 1 día
-
bug ios
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
software-mansion/react-native-audio-api#1238 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
android bug
Dificultad 4/5 3-5 días Aptitud para principiantes 20/100
software-mansion/react-native-audio-api#1494 · 3 comentarios ·
Los mantenedores suelen responder en 1 día
-
DelayNode: signals connected to delayTime are ignored, and delayTime = 0 delays by maxDelayTimePosiblemente ocupada @mdydek la tomó hace 6 días. Abiertobug
Dificultad 4/5 3-5 días Aptitud para principiantes 30/100
software-mansion/react-native-audio-api#1491 ·
Los mantenedores suelen responder en 1 día
-
[Android] AudioRecorder reopens a disconnected input stream with no limit: a re-route on every open (Samsung, concurrent capture) loops hundreds of times a minute and records nothingPosiblemente ocupada @maciejmakowski2003 la tomó hace 18 días. Abiertoandroid bug
Dificultad 4/5 3-5 días Aptitud para principiantes 48/100
software-mansion/react-native-audio-api#1416 · 1 asignado ·
Los mantenedores suelen responder en 1 día
Todos los issues de software-mansion/react-native-audio-api
Issues similares
-
bug
Dificultad 2/5 1-3 horas Aptitud para principiantes 78/100
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 85/100
Los mantenedores suelen responder en 1 día
-
component: tabs platform: macOS
Dificultad 2/5 1-3 horas Aptitud para principiantes 72/100
zen-browser/desktop#16860 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 88/100
metasequoiaime/msime#12003 ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
windirstat/windirstat#776 ·
Los mantenedores suelen responder en 2 días