Repository navigation
fix(rtc): keep an AudioMixer input alive after a read timeout #862
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
Changes from 4 commits
17f66bb
8642fa8
2fe5a4e
09b6002
e57d4fd
5074667
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 |
|---|---|---|
|
|
@@ -52,6 +52,9 @@ def __init__( | |
| """ | ||
| self._streams: set[_Stream] = set() | ||
| self._buffers: dict[_Stream, np.ndarray] = {} | ||
| # A read that timed out is kept for the next round: cancelling it would close an | ||
| # async generator stream for good. | ||
| self._pending_reads: dict[_Stream, asyncio.Future[AudioFrame]] = {} | ||
| self._sample_rate: int = sample_rate | ||
| self._num_channels: int = num_channels | ||
| self._chunk_size: int = blocksize if blocksize > 0 else int(sample_rate // 10) | ||
|
|
@@ -90,6 +93,9 @@ def remove_stream(self, stream: AsyncIterator[AudioFrame]) -> None: | |
| """ | ||
| self._streams.discard(stream) | ||
| self._buffers.pop(stream, None) | ||
| pending = self._pending_reads.pop(stream, None) | ||
| if pending is not None: | ||
| _discard_read(pending) | ||
|
|
||
| def __aiter__(self) -> "AudioMixer": | ||
| return self | ||
|
|
@@ -110,6 +116,12 @@ async def aclose(self) -> None: | |
| self._mixer_task.cancel() | ||
| with contextlib.suppress(asyncio.CancelledError): | ||
| await self._mixer_task | ||
| pending = list(self._pending_reads.values()) | ||
| self._pending_reads.clear() | ||
| for read in pending: | ||
| _discard_read(read) | ||
| # let the streams finish their cleanup before the mixer counts as closed | ||
| await asyncio.gather(*pending, return_exceptions=True) | ||
|
Contributor
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. 🔴 Mixer shutdown hangs on uncancellable input When a pending stream read ignores cancellation, Learn moreA timed-out input read remains in Example: A stream repeatedly catches Recommended fix: Bound the wait for cancelled reads in Was this helpful? React with 👍 or 👎 to provide feedback.
Contributor
Author
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. This one is the same as on
Contributor
Author
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. Documented the contract in e57d4fd instead: |
||
|
|
||
| def end_input(self) -> None: | ||
| """ | ||
|
|
@@ -173,17 +185,29 @@ async def _get_contribution( | |
| ) -> _Contribution: | ||
| had_data = buf.shape[0] > 0 | ||
| exhausted = False | ||
| while buf.shape[0] < self._chunk_size and not exhausted: | ||
| try: | ||
| frame = await asyncio.wait_for( | ||
| stream.__anext__(), timeout=self._stream_timeout_ms / 1000 | ||
| ) | ||
| except asyncio.TimeoutError: | ||
| # a round scheduled before remove_stream() must not start a new read on that stream | ||
| while buf.shape[0] < self._chunk_size and not exhausted and stream in self._streams: | ||
| # The read stays in _pending_reads until it completes, so remove_stream() | ||
| # and aclose() can always cancel it. | ||
|
Contributor
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. how about end_input(): ? when end_input() is called, _ending is set to true, but it doesn't cancel anything, termination of that drain depends entirely on the _mixer loop's exit condition, and in that case, end_input() no longer terminates on a permanently stalled generator ? I wonder if we should consider bounding how long a stream may stall before it's dropped for real ?
Contributor
Author
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. Good catch, thanks. That's a regression from this PR: on 5074667 bounds it: after Happy to make the bound a constructor argument instead, or apply it outside |
||
| read = self._pending_reads.get(stream) | ||
| if read is None: | ||
| read = asyncio.ensure_future(stream.__anext__()) | ||
| self._pending_reads[stream] = read | ||
| done, _ = await asyncio.wait({read}, timeout=self._stream_timeout_ms / 1000) | ||
| if not done: | ||
| logger.warning(f"AudioMixer: stream {stream} timeout, ignoring") | ||
| break | ||
| if self._pending_reads.get(stream) is read: | ||
| del self._pending_reads[stream] | ||
| try: | ||
| frame = read.result() | ||
| except StopAsyncIteration: | ||
| exhausted = True | ||
| break | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
Resolved
|
||
| except asyncio.TimeoutError: | ||
| # raised by the stream itself: handled like the mixer's own timeout, as before | ||
| logger.warning(f"AudioMixer: stream {stream} timeout, ignoring") | ||
| break | ||
| new_data = np.frombuffer(frame.data.tobytes(), dtype=np.int16).reshape( | ||
| -1, self._num_channels | ||
| ) | ||
|
|
@@ -198,3 +222,14 @@ async def _get_contribution( | |
| np.empty((0, self._num_channels), dtype=np.int16), | ||
| ) | ||
| return _Contribution(stream, contrib, buf, had_data, exhausted) | ||
|
|
||
|
|
||
| def _discard_read(read: "asyncio.Future[AudioFrame]") -> None: | ||
| """Cancel a read that is no longer wanted and consume its outcome whenever it ends.""" | ||
| read.cancel() | ||
| read.add_done_callback(_consume_outcome) | ||
|
|
||
|
|
||
| def _consume_outcome(read: "asyncio.Future[AudioFrame]") -> None: | ||
| if not read.cancelled(): | ||
| read.exception() # mark a failed read as handled | ||
Uh oh!
There was an error while loading. Please reload this page.