Skip to content

fix(mobile): the Android audio engine forgets a stop issued while paused - #22132

Merged
Jinwoo-H merged 4 commits into
mainfrom
ota-audio-engine-pause-resume
Sep 22, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
ota-audio-engine-pause-resume

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 0 0 0 0
Prod 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​36 $\color{#cf222e}{\Huge{\mathbf{−}}}$​16 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​20

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() stored isRecordingBeforePause = isRecording and stopped. A JS
toggleRecording(false) arriving while paused hit if (value == isRecording) return and never
reached stopRecording(), so the resume flag survived and resumeRecordingAndPlayer() reopened
the 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) clears
isRecordingBeforePause before the !isRecording early return; toggleRecording(false, …) always
reaches it; pauseRecordingAndPlayer() passes clearPauseResume = false; and
resumeRecordingAndPlayer() consumes the flag before acting on it. This mirrors
AudioEngine.swift's stopRecordingAndPlayer(clearInterruptionResume:) /
wasRecordingBeforeInterruption pair.

tearDown() and the pre-Q audio-focus-loss path both call stopRecording() with the default, so
they clear the flag too.

pause → stop → resume

step before: isRecording / flag / mic after: isRecording / flag / mic
recording, foreground true / false / open true / false / open
pauseRecordingAndPlayer() false / true / closed false / true / closed
JS toggleRecording(false) false / true / closed (early return, flag untouched) false / false / closed
resumeRecordingAndPlayer() true / true / open, no JS owner false / false / closed

pause → resume → stop

step before: isRecording / flag / mic after: isRecording / flag / mic
recording, foreground true / false / open true / false / open
pauseRecordingAndPlayer() false / true / closed false / true / closed
resumeRecordingAndPlayer() true / true / open true / false / open
JS toggleRecording(false) false / true / closed (flag still armed) false / false / closed

Row 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, flag true).

step before: isRecording / flag / mic / live focus requests after
resumeRecordingAndPlayer() #1 true / true / open / 2 true / false / open / 1
JS toggleRecording(false) false / true / closed / 2 false / false / closed / 1
resumeRecordingAndPlayer() #2 true / true / reopened / 3 false / false / closed / 1

Arm 2 — every resume leaked an audio focus request

requestAudioFocus() built a new listener and a new AudioFocusRequest on each call and
overwrote audioFocusRequest without abandoning the previous one, so after N resumes N stale
entries sat on the focus stack and tearDown() could only abandon the newest. Logcat showed two
AudioEngine$$ExternalSyntheticLambda2 clients with the older one taking
onAudioFocusChange(-2).

requestAudioFocus() now abandons what it holds before requesting again, through a single
abandonAudioFocus() owner that picks abandonAudioFocusRequest on O+ and
abandonAudioFocus(listener) below, and clears both fields. tearDown() calls the same owner
instead of repeating the branch; its pre-O arm previously passed a possibly-null listener.

before after
live focus requests after N resumes N + 1 1
after tearDown() N (only the newest abandoned) 0

iOS

Left alone. AudioEngine.swift already clears wasRecordingBeforeInterruption on
stopRecordingAndPlayer() and on both .ended branches, and tearDown() goes through that stop.
One gap is not the identical bug and is reported separately: a JS toggleRecording(false) arriving
between .began and .ended does not clear the flag, and it cannot be fixed by clearing inside
toggleRecording because the interruption-begin path itself calls toggleRecording(false) via
stopRecordingAndPlayer(clearInterruptionResume: false).

Verification

No Kotlin test harness exists in this package and the module cannot be compiled standalone: its
android/build.gradle applies com.android.library and depends on project(":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 are cmd appops get … RECORD_AUDIO, dumpsys power wake locks, dumpsys audio per uid, and the focus stack.

step before this fix with this fix
locked mid-dictation, read after 43 s tap stopped, resume flag armed recording ended at 17 s, not running
after unlock RECORD_AUDIO (running), AudioIn wake lock, live record thread, composer idle not running, no AudioIn lock, no live record thread, composer idle; resume log shows abandon then request and no recording start
fresh start afterwards, then stop start died after 234 ms recorded 18 s, transcript "Testing one two three four five" inserted, stop released everything
focus stack after the run stale entries, one per resume 5 requests, 5 abandons, nothing from the app's uid

Round 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 ran toggleRecording(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

  • A dictation start still aborts silently about half the time on this phone. Every start launches the OS permission activity even though the permission is granted (askForPermissionsWithPermissionsManager runs 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.
  • The iOS gap named above, and two older engine holes: a mic-read error leaves the AudioRecord unreleased, and a delayed focus grant throws inside resume.

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
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 85ba0f69-ab42-44c9-872b-26c7b88dd81d

📥 Commits

Reviewing files that changed from the base of the PR and between a08d9d1 and fb12f2a.

📒 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.


📝 Walkthrough

Walkthrough

AudioEngine 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 fb12f

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 1 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely identifies the primary Android audio-engine fix: handling a stop issued while paused.
Description check ✅ Passed The description is detailed, relevant, and covers the problem, behavior changes, rationale, testing limits, device verification, and scope. It does not follow all template headings and does not includ…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 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 win

Abandon 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

📥 Commits

Reviewing files that changed from the base of the PR and between 841d06a and cd13169.

📒 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
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

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.

@pullfrog pullfrog 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.

ℹ️ No critical issues — one narrow behavior change inline.

Reviewed changes

  • Pause/stop resume-flag contract — stopRecording(clearPauseResume) now clears isRecordingBeforePause before its !isRecording early return, toggleRecording drops its equality guard so a false always reaches the stop, pauseRecordingAndPlayer() is the only stop that keeps the flag, and resumeRecordingAndPlayer() consumes it before acting.
  • Audio-focus stack leak — requestAudioFocus() abandons the held AudioFocusRequest before re-requesting through a new shared abandonAudioFocus() owner, which tearDown() 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟠 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 win

Clear isRecordingBeforePause only after recording restart succeeds.

When shouldResumeRecording is true, toggleRecording(true) can throw from startRecording() before Line 411 completes. Line 410 has already cleared the flag, so a later resumeRecordingAndPlayer() sees false, calls toggleRecording(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

📥 Commits

Reviewing files that changed from the base of the PR and between cd13169 and a08d9d1.

📒 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.

@pullfrog pullfrog 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.

ℹ️ 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_LOSS handler's API < Q branch, which stops recording and playback for good rather than pausing, now calls abandonAudioFocus() after those stops so the request is released instead of lingering until tearDown(). 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.

Pullfrog  | Fix it ➔ | View workflow run | Using 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
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

pullfrog's resume finding folded in ef68039: resume only reopens when the pause closed the mic, so a recording JS started while paused stays live. The 'mobile web app bundle' failure is main's closure pin (4,359 vs 4,360 after #21705), repinned in a separate PR.

@pullfrog pullfrog 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.

✅ 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 calls toggleRecording(true) when shouldResumeRecording was 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 — fb12f2a merges origin/main into the branch; the merge changed no file in this package (git diff ef6803984 fb12f2a -- mobile/packages/expo-two-way-audio is 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.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit b964336 into main Sep 22, 2026
24 checks passed
@Jinwoo-H
Jinwoo-H deleted the ota-audio-engine-pause-resume branch September 22, 2026 03:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant