-
Notifications
You must be signed in to change notification settings - Fork 208
Fix buffered AudioSource.capture_frame hanging when the source drain stalls #1289
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
Open
sam-hark
wants to merge
5
commits into
livekit:main
Choose a base branch
from
sam-hark:fix/audiosource-capture-frame-drain-stall
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9bc008d
fix(audio): bound buffered AudioSource.capture_frame so a stalled dra…
sam-hark 096a065
audio(webrtc-sys): address review nits on the drain-stall fix
sam-hark 83e5c3f
Update libwebrtc/src/native/audio_source.rs
sam-hark a5c788c
Update libwebrtc/src/native/drain_stall_tests.rs
sam-hark fdd552e
audio(libwebrtc): route capture_frame timeout through livekit_runtime
sam-hark File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| --- | ||
| libwebrtc: patch | ||
| livekit: patch | ||
| livekit-ffi: patch | ||
| webrtc-sys: patch | ||
| --- | ||
|
|
||
| Bound the buffered `AudioSource::capture_frame` completion wait and split the drain lock so a stalled or wedged source drain returns a recoverable error instead of hanging the producer (and the session) forever (#408, #420, #497) - #1289 (@sam-hark) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,169 @@ | ||
| // 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. | ||
|
|
||
| //! Regression tests for the buffered `NativeAudioSource::capture_frame` drain stall | ||
| //! (rust-sdks #408 / #420 / #497): the C++ `AudioTrackSource` drain fires the per-chunk completion | ||
| //! that `capture_frame` awaits. If the drain stops progressing — a sink blocked in `OnData`, or the | ||
| //! drain TaskQueue CPU-starved — an unbounded await would wedge the producer (and any session built | ||
| //! on it) forever. | ||
|
|
||
| use crate::audio_frame::AudioFrame; | ||
| use crate::audio_source::native::NativeAudioSource; | ||
| use crate::audio_source::AudioSourceOptions; | ||
|
|
||
| const SAMPLE_RATE: u32 = 48000; | ||
|
|
||
| fn silent_frame<'a>(samples: usize) -> AudioFrame<'a> { | ||
| AudioFrame { | ||
| data: vec![0i16; samples].into(), | ||
| sample_rate: SAMPLE_RATE, | ||
| num_channels: 1, | ||
| samples_per_channel: samples as u32, | ||
| } | ||
| } | ||
|
|
||
| #[tokio::test(flavor = "multi_thread", worker_threads = 2)] | ||
| async fn capture_frame_completes_under_normal_backpressure() { | ||
| // The fix must not regress the healthy path. A large queue keeps the derived timeout far above | ||
| // the ~one-queue-duration a healthy deferral needs, so this asserts "no false-trip on legitimate | ||
| // backpressure" without coupling to the production floor (which would make it flaky on a loaded | ||
| // CI runner). No sink/track is created, so this is safe on every platform. | ||
| const QUEUE_MS: u32 = 1000; | ||
| let q = (SAMPLE_RATE / 1000 * QUEUE_MS) as usize; | ||
| let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, QUEUE_MS); | ||
|
|
||
| for i in 0..3u32 { | ||
| // q + q/2 forces a deferral (completion routed through the drain) every call. | ||
| source | ||
| .capture_frame(&silent_frame(q + q / 2)) | ||
| .await | ||
| .unwrap_or_else(|e| panic!("healthy capture {i} failed: {e:?}")); | ||
| } | ||
| } | ||
|
|
||
| // The stall reproducer needs a real audio track, which requires a `PeerConnectionFactory`. On | ||
| // macOS/Windows that brings up the platform AudioDeviceModule, whose real-time audio thread aborts | ||
| // the process when the test's blocking sink stalls it. The Linux CI webrtc build has no such device | ||
| // backend, so the reproducer runs there and is deterministic. The fix itself is platform-independent | ||
| // and the healthy-path test above runs everywhere. This test also creates a factory, so — like the | ||
| // sibling factory tests — it relies on serial execution (CI runs `--test-threads=1`). | ||
| #[cfg(target_os = "linux")] | ||
| mod stall { | ||
| use std::sync::atomic::{AtomicBool, Ordering}; | ||
| use std::sync::Arc; | ||
| use std::time::Duration; | ||
|
|
||
| use tokio::sync::mpsc; | ||
| use webrtc_sys::audio_track as sys_at; | ||
|
|
||
| use super::{silent_frame, SAMPLE_RATE}; | ||
| use crate::audio_source::native::NativeAudioSource; | ||
| use crate::audio_source::AudioSourceOptions; | ||
| use crate::peer_connection_factory::native::PeerConnectionFactoryExt; | ||
| use crate::peer_connection_factory::PeerConnectionFactory; | ||
| use crate::RtcErrorType; | ||
|
|
||
| /// A sink whose `on_data` blocks the C++ 10ms drain task, modelling a wedged/starved consumer. | ||
| /// It signals `entered` on its first call (so the test awaits the stall instead of sleeping for | ||
| /// it) and unblocks when `released` is set. | ||
| struct BlockingSink { | ||
| entered: mpsc::UnboundedSender<()>, | ||
| released: Arc<AtomicBool>, | ||
| } | ||
|
|
||
| impl sys_at::AudioSink for BlockingSink { | ||
| fn on_data( | ||
| &self, | ||
| _data: &[i16], | ||
| _sample_rate: i32, | ||
| _num_channels: usize, | ||
| _num_frames: usize, | ||
| ) { | ||
| let _ = self.entered.send(()); | ||
| while !self.released.load(Ordering::Acquire) { | ||
| std::thread::sleep(Duration::from_millis(5)); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // worker_threads = 2: one for the (on a revert, possibly-wedged) capture task, one for the timeout. | ||
| #[tokio::test(flavor = "multi_thread", worker_threads = 2)] | ||
| async fn capture_frame_recovers_when_drain_stalls() { | ||
| const QUEUE_MS: u32 = 200; | ||
| let q = (SAMPLE_RATE / 1000 * QUEUE_MS) as usize; | ||
|
|
||
| let factory = PeerConnectionFactory::default(); | ||
| let source = | ||
| NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, QUEUE_MS); | ||
| let track = factory.create_audio_track("drain-stall", source.clone()); | ||
|
|
||
| let (entered_tx, mut entered_rx) = mpsc::unbounded_channel(); | ||
| let released = Arc::new(AtomicBool::new(false)); | ||
| let native_sink = sys_at::ffi::new_native_audio_sink( | ||
| Box::new(sys_at::AudioSinkWrapper::new(Arc::new(BlockingSink { | ||
| entered: entered_tx, | ||
| released: released.clone(), | ||
| }))), | ||
| SAMPLE_RATE as i32, | ||
| 1, | ||
| ); | ||
| // SAFETY: `track` is an audio track created by `create_audio_track`, so downcasting its | ||
| // media-stream-track handle back to an `AudioTrack` is valid. | ||
| let audio = unsafe { sys_at::ffi::media_to_audio(track.sys_handle()) }; | ||
| audio.add_sink(&native_sink); | ||
|
|
||
| // Wait until the drain is actually stalled inside the sink (bounded, so a wiring regression | ||
| // fails the test cleanly instead of hanging the CI job). | ||
| tokio::time::timeout(Duration::from_secs(5), entered_rx.recv()) | ||
| .await | ||
| .expect("drain never entered the sink within 5s") | ||
| .expect("sink signal channel closed"); | ||
|
|
||
| // Feed 2x the queue so the second chunk must wait on the (now stalled) drain. | ||
| let src = source.clone(); | ||
| let mut handle = tokio::spawn(async move { src.capture_frame(&silent_frame(q * 2)).await }); | ||
|
|
||
| // Outer bound distinguishes "returned" from "hung", well above the fix's own timeout. | ||
| let res = tokio::time::timeout(Duration::from_secs(8), &mut handle).await; | ||
|
|
||
| // Release the drain regardless, so teardown and the recovery check below can proceed. | ||
| released.store(true, Ordering::Release); | ||
| if res.is_err() { | ||
| let _ = handle.await; | ||
| } | ||
|
|
||
| match res { | ||
| Ok(Ok(Err(e))) => { | ||
| assert_eq!(e.error_type, RtcErrorType::InvalidState); | ||
| assert!( | ||
| e.message.contains("source drain stalled"), | ||
| "unexpected error: {}", | ||
| e.message | ||
| ); | ||
| } | ||
| other => { | ||
| panic!("capture_frame should return an error on a stalled drain, got: {other:?}") | ||
| } | ||
| } | ||
|
|
||
| // The stall must leave the source usable: the timeout path releases the pending completion | ||
| // rather than poisoning the slot, so a fresh capture succeeds once the drain is unstuck. | ||
| tokio::time::timeout(Duration::from_secs(5), source.capture_frame(&silent_frame(q))) | ||
| .await | ||
| .expect("recovery capture hung") | ||
| .expect("source did not recover after the stall cleared"); | ||
|
|
||
| audio.remove_sink(&native_sink); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.