Repository navigation
fix(mobile): the Android audio engine forgets a stop issued while paused - #22132
Conversation
A JS toggleRecording(false) arriving while the activity was paused hit the value == isRecording early return, never reached stopRecording(), and left isRecordingBeforePause armed, so resumeRecordingAndPlayer() reopened the microphone with no JS owner (54 minutes on a Galaxy S24, OTA 0.0.51). Every stop now clears the resume flag and only the pause itself keeps it, via stopRecording(clearPauseResume), mirroring iOS's stopRecordingAndPlayer(clearInterruptionResume:); resume consumes the flag before acting on it. requestAudioFocus() also overwrote audioFocusRequest without abandoning the previous one, so every resume left a stale listener on the focus stack and tearDown() could only abandon the newest. Both paths now go through one abandonAudioFocus() owner. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughAudioEngine now abandons existing audio focus before requesting focus again and uses one helper for focus cleanup during focus loss and teardown. Recording stop and toggle operations now control whether pause-resume state is cleared. Pause preserves that state, while resume consumes it before restarting recording. Toggle operations no longer skip processing when the requested state matches the current state. Priority: ⬇️ Low Merge Risk: 🟡 Moderate · up to If microphone restart fails during app resume, recording can remain off until JavaScript explicitly starts it again; this should be corrected before merging. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Abandon focus after a pre-Q permanent focus loss. · AudioEngine.kt:204-207
mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/AudioEngine.kt:204-207
🎯 Functional Correctness | 🟠 Major | ⚡ Quick winAbandon focus after a pre-Q permanent focus loss.
On Android API 21–28, this branch stops audio but retains the active focus request. If the other application later releases focus before this engine resumes or tears down, this inactive engine can retain audio focus and block other audio. Call
abandonAudioFocus()in this branch after stopping recording and playback.Proposed fix
} else { stopRecording() stopPlayback() + abandonAudioFocus() }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 353a667e-5270-4e63-9d17-71a832e898c2
📒 Files selected for processing (1)
mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/AudioEngine.kt
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
…(round 1) CodeRabbit on #22132: on API 21-28 the AUDIOFOCUS_LOSS branch stops recording and playback for good but kept the focus request, so an idle engine could hold focus after the other app released it. Q+ pauses and keeps focus to resume. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
|
CodeRabbit's pre-Q finding folded in a08d9d1: the permanent focus-loss branch on API 21–28 now abandons the focus request after stopping. Q+ keeps it to resume, unchanged. |
There was a problem hiding this comment.
ℹ️ No critical issues — one narrow behavior change inline.
Reviewed changes
- Pause/stop resume-flag contract —
stopRecording(clearPauseResume)now clearsisRecordingBeforePausebefore its!isRecordingearly return,toggleRecordingdrops its equality guard so afalsealways reaches the stop,pauseRecordingAndPlayer()is the only stop that keeps the flag, andresumeRecordingAndPlayer()consumes it before acting. - Audio-focus stack leak —
requestAudioFocus()abandons the heldAudioFocusRequestbefore re-requesting through a new sharedabandonAudioFocus()owner, whichtearDown()now uses too, so N resumes no longer leave N stale entries on the focus stack.
Both mechanisms check out: I verified the state-machine trace across every public entry point (toggleRecording, pause/resume, tearDown, the AUDIOFOCUS_LOSS path) and confirmed no sequence leaves the resume flag armed with a closed mic and no JS owner, reopens the mic unasked, or desyncs isRecording from the AudioRecord state. Against AOSP MediaFocusControl, abandoning a non-locked focus request and immediately re-requesting cannot turn a previously-granted request into DELAYED/FAILED, so the resume path does not regress.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Clear isRecordingBeforePause only after recording restart succeeds. · AudioEngine.kt:410
mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/AudioEngine.kt:410
🩺 Stability & Availability | 🟠 Major | ⚡ Quick winClear
isRecordingBeforePauseonly after recording restart succeeds.When
shouldResumeRecordingistrue,toggleRecording(true)can throw fromstartRecording()before Line 411 completes. Line 410 has already cleared the flag, so a laterresumeRecordingAndPlayer()seesfalse, callstoggleRecording(false), and does not retry the microphone. Move the clear after the successful toggle or restore it when the restart fails.Proposed fix
val shouldResumeRecording = isRecordingBeforePause -isRecordingBeforePause = false isRecording = toggleRecording(shouldResumeRecording) +isRecordingBeforePause = false
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: c53720b9-fac3-4d21-afd7-6a08eec4169d
📒 Files selected for processing (1)
mobile/packages/expo-two-way-audio/android/src/main/java/expo/modules/twowayaudio/AudioEngine.kt
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.
There was a problem hiding this comment.
ℹ️ No new issues in the round-1 commit. The earlier resume-flag observation is the only open item.
Reviewed changes (since the prior pullfrog review)
- Pre-Q permanent focus loss now abandons focus — the
AUDIOFOCUS_LOSShandler's API < Q branch, which stops recording and playback for good rather than pausing, now callsabandonAudioFocus()after those stops so the request is released instead of lingering untiltearDown(). The Q+ branch still pauses and keeps focus so a resume can continue, unchanged.
Correct and consistent with the Arm 2 owner: on API 26–28 it abandons audioFocusRequest, on 21–25 the deprecated listener, and it runs after the engine has already been stopped, so there is nothing left to resume. Not reachable on the API 36 device the fix was verified on.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
pullfrog on #22132: with the equality guard gone, resume's toggleRecording(false) on a cleared flag stopped a recording JS started while the activity was paused, which a start straddling the permission activity does. Resume now only reopens. Claude-Session: https://claude.ai/code/session_01JNnE9qzUZMMnqpZWCqM3nb
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (since the prior pullfrog review at a08d9d1)
- Resume no longer stops a recording it did not pause —
resumeRecordingAndPlayer()now only callstoggleRecording(true)whenshouldResumeRecordingwas set; a cleared flag means the pause already closed the mic, so no stop is owed. This closes the narrow behavior change flagged in the prior review (AudioEngine.kt:411-415), and the one open inline thread is resolved. - Main merge —
fb12f2amergesorigin/maininto the branch; the merge changed no file in this package (git diff ef6803984 fb12f2a -- mobile/packages/expo-two-way-audiois empty), so the reviewed engine behavior is unchanged by it.
The round-2 change is the fix I asked for and reads correctly: isRecording is only reassigned on the reopen path, and a live JS-started recording survives onResume. resumeRecordingAndPlayer() still plays the track and requests focus unconditionally, matching the pause contract.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

The Android audio engine kept a recording alive across an activity pause even when JS had ended
it, and left a stale entry on the audio focus stack on every resume. On a Galaxy S24 (Orca OTA
0.0.51) the microphone stayed open for 54 minutes after the composer went idle.
Arm 1 — a stop issued while paused was forgotten
pauseRecordingAndPlayer()storedisRecordingBeforePause = isRecordingand stopped. A JStoggleRecording(false)arriving while paused hitif (value == isRecording) returnand neverreached
stopRecording(), so the resume flag survived andresumeRecordingAndPlayer()reopenedthe microphone with no JS owner.
The engine now holds the contract iOS already has: every stop clears the resume flag, and the one
stop that keeps it is the pause itself.
stopRecording(clearPauseResume: Boolean = true)clearsisRecordingBeforePausebefore the!isRecordingearly return;toggleRecording(false, …)alwaysreaches it;
pauseRecordingAndPlayer()passesclearPauseResume = false; andresumeRecordingAndPlayer()consumes the flag before acting on it. This mirrorsAudioEngine.swift'sstopRecordingAndPlayer(clearInterruptionResume:)/wasRecordingBeforeInterruptionpair.tearDown()and the pre-Q audio-focus-loss path both callstopRecording()with the default, sothey clear the flag too.
pause → stop → resume
isRecording/ flag / micisRecording/ flag / mictrue/false/ opentrue/false/ openpauseRecordingAndPlayer()false/true/ closedfalse/true/ closedtoggleRecording(false)false/true/ closed (early return, flag untouched)false/false/ closedresumeRecordingAndPlayer()true/true/ open, no JS ownerfalse/false/ closedpause → resume → stop
isRecording/ flag / micisRecording/ flag / mictrue/false/ opentrue/false/ openpauseRecordingAndPlayer()false/true/ closedfalse/true/ closedresumeRecordingAndPlayer()true/true/ opentrue/false/ opentoggleRecording(false)false/true/ closed (flag still armed)false/false/ closedRow 3 is the behaviour the fix preserves: a recording JS did not end still resumes. Row 4 shows the
latent half of the defect before the fix — the flag stayed armed, so a later bare resume (JS
restart()) reopened the microphone.resume twice, with a JS stop in between
Starting from a pause taken while recording (
isRecording = false, flagtrue).isRecording/ flag / mic / live focus requestsresumeRecordingAndPlayer()#1true/true/ open / 2true/false/ open / 1toggleRecording(false)false/true/ closed / 2false/false/ closed / 1resumeRecordingAndPlayer()#2true/true/ reopened / 3false/false/ closed / 1Arm 2 — every resume leaked an audio focus request
requestAudioFocus()built a new listener and a newAudioFocusRequeston each call andoverwrote
audioFocusRequestwithout abandoning the previous one, so after N resumes N staleentries sat on the focus stack and
tearDown()could only abandon the newest. Logcat showed twoAudioEngine$$ExternalSyntheticLambda2clients with the older one takingonAudioFocusChange(-2).requestAudioFocus()now abandons what it holds before requesting again, through a singleabandonAudioFocus()owner that picksabandonAudioFocusRequeston O+ andabandonAudioFocus(listener)below, and clears both fields.tearDown()calls the same ownerinstead of repeating the branch; its pre-O arm previously passed a possibly-null listener.
tearDown()iOS
Left alone.
AudioEngine.swiftalready clearswasRecordingBeforeInterruptiononstopRecordingAndPlayer()and on both.endedbranches, andtearDown()goes through that stop.One gap is not the identical bug and is reported separately: a JS
toggleRecording(false)arrivingbetween
.beganand.endeddoes not clear the flag, and it cannot be fixed by clearing insidetoggleRecordingbecause the interruption-begin path itself callstoggleRecording(false)viastopRecordingAndPlayer(clearInterruptionResume: false).Verification
No Kotlin test harness exists in this package and the module cannot be compiled standalone: its
android/build.gradleappliescom.android.libraryand depends onproject(":expo-modules-core"),both of which resolve only inside a generated app project, and there is no gradle wrapper in the
tree. A gradle run against the module directory fails at configuration with
Plugin with id 'com.android.library' not found. The device APK has to be built from this commit.Verified on the phone
Galaxy S24, Orca OTA 0.0.51 rebuilt from this commit (the dex carries
abandonAudioFocus/clearPauseResume), native dictation path, same session and steps as the run that found the leak. Reads arecmd appops get … RECORD_AUDIO,dumpsys powerwake locks,dumpsys audioper uid, and the focus stack.RECORD_AUDIO (running),AudioInwake lock, live record thread, composer idleAudioInlock, no live record thread, composer idle; resume log shows abandon then request and no recording startRound 1 (CodeRabbit)
a08d9d187e: on API 21–28 the permanent focus-loss branch stops recording and playback for good but kept the focus request; it now abandons it. Q+ pauses and keeps focus so a resume can continue, unchanged. Not reachable on the S24 (API 36) the fix was verified on, so the device verification above stands.Round 2 (pullfrog)
ef68039838: with the equality guard gone, a resume whose flag was cleared rantoggleRecording(false)and would have stopped a recording JS started while the activity was paused, which a start straddling the permission activity does. Resume now only ever reopens; a cleared flag means the pause closed the mic and no stop is owed.Not addressed here
askForPermissionsWithPermissionsManagerruns it regardless), which pauses and resumes the activity for ~100 ms; the start that straddles it sometimes ends before recording begins, with nothing shown. Pre-existing, separate follow-up: check the grant before asking, and find the JS arm that bails.AudioRecordunreleased, and a delayed focus grant throws inside resume.