Repository navigation
fix: stop the microphone when a local audio track is stopped before joining a room #1216
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
d3c7225
672ed42
519973f
9819c3c
3db75c4
1e22979
ce71520
d7cbe62
fb4a730
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| patch type="fixed" "Stop the microphone when a local audio track is stopped or disposed before joining a room" |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -97,29 +97,65 @@ class LocalAudioTrack extends LocalTrack with AudioTrack, LocalAudioManagementMi | |
|
|
||
| AudioSenderStats? prevStats; | ||
|
|
||
| bool _nativeRecordingHeld = false; | ||
|
|
||
| /// Process-wide because [Native.startLocalRecording] starts one audio device | ||
| /// module, shared by every local audio track (pre-join mic, room mic, | ||
| /// pre-connect buffer). | ||
| static final NativeRecordingHolders _nativeRecordingHolders = NativeRecordingHolders(); | ||
| @override | ||
| Future<void> startCapture() async { | ||
| await super.startCapture(); | ||
| if (lkPlatformSupportsExplicitAudioRecordingStart()) { | ||
| // Recording can start before any policy push (pre-connect audio, | ||
| // pre-join mic). Hand native the resolved Dart policy first — cache-only | ||
| // while the engine is idle — so the session is not left to the native | ||
| // built-in preset. | ||
| await AudioManager.instance.ensureAppleAudioSessionPolicy(); | ||
| try { | ||
| // Match Swift: start the ADM before publishing so capture-time audio | ||
| // processing options are applied before WebRTC opens the microphone. | ||
| await Native.startLocalRecording(resolveCaptureProcessingOptions(currentOptions).toMap()); | ||
| } on PlatformException catch (error) { | ||
| // Missing microphone permission or an audio session that does not | ||
| // permit recording are not audio processing failures, so they surface | ||
| // as their own exception types. | ||
| throw audioEngineExceptionFrom(error) ?? | ||
| track_options.AudioProcessingException( | ||
| _audioProcessingFailureReason(error.code), | ||
| error.message ?? '', | ||
| ); | ||
| } | ||
| if (_nativeRecordingHeld || !lkPlatformSupportsExplicitAudioRecordingStart()) { | ||
| return; | ||
| } | ||
|
|
||
| // Recording can start before any policy push (pre-connect audio, | ||
| // pre-join mic). Hand native the resolved Dart policy first — cache-only | ||
| // while the engine is idle — so the session is not left to the native | ||
| // built-in preset. | ||
| await AudioManager.instance.ensureAppleAudioSessionPolicy(); | ||
| try { | ||
| // Match Swift: start the ADM before publishing so capture-time audio | ||
| // processing options are applied before WebRTC opens the microphone. | ||
| await Native.startLocalRecording( | ||
| resolveCaptureProcessingOptions(currentOptions).toMap(), | ||
| ); | ||
| } on PlatformException catch (error) { | ||
| // Missing microphone permission or an audio session that does not | ||
| // permit recording are not audio processing failures, so they surface | ||
| // as their own exception types. | ||
| throw audioEngineExceptionFrom(error) ?? | ||
| track_options.AudioProcessingException( | ||
| _audioProcessingFailureReason(error.code), | ||
| error.message ?? '', | ||
| ); | ||
| } | ||
|
|
||
| _nativeRecordingHeld = true; | ||
| _nativeRecordingHolders.add(this); | ||
|
Comment on lines
+135
to
+136
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Silent microphone after concurrent track handoff During overlapping Apple track handoffs, Learn moreThe holder set excludes starts that are still awaiting the platform channel. Apple's recording handlers run native start and stop on background queues and return results separately. While a new start is pending, _releaseNativeRecording can remove the previous last holder and issue a native stop. If that stop executes after the native start, Track.start still marks the new track active when its start future completes. No subsequent call restarts recording. Example: Track A is the only holder. Track B starts native recording, but its platform response has not reached Dart. A stops and issues a native stop because B is not yet registered. B registers and reports success, but A's native stop leaves the microphone off. Recommended fix: Serialize native acquisition and release through a process-wide coordinator, including their asynchronous native operations. Account for pending acquisitions and roll them back on failure. Add a lifecycle test with controllable native futures that interleaves B's start with A's last-holder release. Was this helpful? React with 👍 or 👎 to provide feedback. |
||
| } | ||
|
|
||
| @override | ||
| Future<void> stopCapture() async { | ||
| try { | ||
| await super.stopCapture(); | ||
| } finally { | ||
| // startCapture() opens the audio device module directly. Stopping the | ||
| // MediaStreamTrack does not close it, so a pre-join microphone (no peer | ||
| // connection to tear the module down on disconnect) keeps recording | ||
| // until the last holder releases it. | ||
| await _releaseNativeRecording(); | ||
| } | ||
| } | ||
|
|
||
| Future<void> _releaseNativeRecording() async { | ||
| if (!_nativeRecordingHeld) { | ||
| return; | ||
| } | ||
| _nativeRecordingHeld = false; | ||
| if (_nativeRecordingHolders.remove(this)) { | ||
| await Native.stopLocalRecording(); | ||
| } | ||
| } | ||
|
|
||
|
|
@@ -228,6 +264,31 @@ class LocalAudioTrack extends LocalTrack with AudioTrack, LocalAudioManagementMi | |
| } | ||
| } | ||
|
|
||
| /// Tracks which objects currently hold the process-wide native recording | ||
| /// session. Recording stops only when the last holder releases it. | ||
| @internal | ||
| @visibleForTesting | ||
| final class NativeRecordingHolders { | ||
| final Set<Object> _holders = <Object>{}; | ||
|
|
||
| int get length => _holders.length; | ||
|
|
||
| void add(Object holder) { | ||
| _holders.add(holder); | ||
| } | ||
|
|
||
| /// Removes [holder]. | ||
| /// | ||
| /// Returns true when [holder] was the last one and native recording should | ||
| /// stop. | ||
| bool remove(Object holder) { | ||
| if (!_holders.remove(holder)) { | ||
| return false; | ||
| } | ||
| return _holders.isEmpty; | ||
| } | ||
| } | ||
|
|
||
| void _throwIfAudioProcessingFailed(Map<String, dynamic> response) { | ||
| final code = response['code'] as String?; | ||
| final message = (response['message'] as String?) ?? ''; | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| // Copyright 2026 LiveKit, Inc. | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| import 'package:flutter_test/flutter_test.dart'; | ||
|
|
||
| import 'package:livekit_client/src/track/local/audio.dart'; | ||
|
|
||
| void main() { | ||
| test('stops native recording only after the last holder releases it', () { | ||
| final holders = NativeRecordingHolders(); | ||
| const preJoinMic = 'pre-join'; | ||
| const roomMic = 'room'; | ||
|
|
||
| holders.add(preJoinMic); | ||
| holders.add(roomMic); | ||
|
|
||
| expect(holders.remove(preJoinMic), isFalse); | ||
| expect(holders.length, 1); | ||
|
|
||
| expect(holders.remove(roomMic), isTrue); | ||
| expect(holders.length, 0); | ||
| }); | ||
|
|
||
| test('a second release of the same holder does not stop recording again', () { | ||
| final holders = NativeRecordingHolders(); | ||
| const mic = 'mic'; | ||
|
|
||
| holders.add(mic); | ||
|
|
||
| expect(holders.remove(mic), isTrue); | ||
| expect(holders.remove(mic), isFalse); | ||
| }); | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🔴 Failed pre-connect leaves permanent holder
When pre-connect fails after capture starts,
_nativeRecordingHoldersretains the abandoned track.resetdrops it without callingstop(), so later microphones never stop native recording.Learn more
A successfully started pre-connect track adds itself to the process-wide holder set. If the operation wrapped by
withPreConnectAudiothen throws,stopRecordingstops the native recorder directly but never stops the track.resetthen clears_localTrack, while the static set keeps the object reachable forever. Every later track can add and remove itself, but the abandoned entry prevents the set from becoming empty.Example: A pre-connect track starts, then
Room.connectfails. A later pre-join microphone starts and stops normally, but removing it leaves the abandoned pre-connect holder, soNative.stopLocalRecording()is never called.Recommended fix: Route pre-connect failure cleanup through the owned
LocalAudioTrack.stop()before clearing_localTrack. Remove the direct native stop from that path so holder removal and native shutdown remain one atomic lifecycle.Was this helpful? React with 👍 or 👎 to provide feedback.