-
Notifications
You must be signed in to change notification settings - Fork 3.1k
feat(audio): add stream audio encoder for turn detection #5494
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
chenghao-mou
wants to merge
5
commits into
main
Choose a base branch
from
chenghao/feat/streaming-encoder
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
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
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,170 @@ | ||
| # 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. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import io | ||
| from dataclasses import dataclass | ||
| from typing import Literal | ||
|
|
||
| import av | ||
| import av.audio | ||
| import av.container | ||
|
|
||
| from livekit import rtc | ||
|
|
||
|
|
||
| @dataclass | ||
| class EncodedAudioData: | ||
| """Data returned by the encoder.""" | ||
|
|
||
| data: bytes | ||
| """The encoded audio data.""" | ||
| num_samples: int | ||
| """The number of samples in the encoded audio data, | ||
| useful if the receiver needs to buffer audio data based on duration without decoding.""" | ||
|
|
||
|
|
||
| _CODEC_TABLE: dict[str, tuple[str, str]] = { | ||
| "opus": ("libopus", "ogg"), | ||
| "mp3": ("libmp3lame", "mp3"), | ||
| "pcm": ("pcm_s16le", "wav"), | ||
| } | ||
|
|
||
| _SUPPORTED_CODECS = Literal["opus", "mp3", "pcm"] | ||
|
|
||
|
|
||
| def _resolve_codec(codec: str) -> tuple[str, str]: | ||
| """Return (av_encoder_name, container_format) for a public codec name.""" | ||
| if codec not in _CODEC_TABLE: | ||
| raise ValueError(f"unsupported codec for streaming encode: {codec!r}") | ||
| return _CODEC_TABLE[codec] | ||
|
|
||
|
|
||
| class _CompactableBuffer(io.RawIOBase): | ||
| _COMPACT_THRESHOLD = 1 * 1024 * 1024 # reclaim consumed prefix once it exceeds 1MB | ||
|
|
||
| def __init__(self) -> None: | ||
| super().__init__() | ||
| self._buf = bytearray() | ||
| self._read_pos = 0 | ||
|
|
||
| def writable(self) -> bool: | ||
| return True | ||
|
|
||
| def readable(self) -> bool: | ||
| return False | ||
|
|
||
| def seekable(self) -> bool: | ||
| """disable back-patching container headers""" | ||
| return False | ||
|
|
||
| def write(self, b) -> int: # type: ignore[no-untyped-def] | ||
| self._buf.extend(b) | ||
| return len(b) | ||
|
|
||
| def drain(self) -> bytes: | ||
| if self._read_pos >= len(self._buf): | ||
| return b"" | ||
| data = bytes(self._buf[self._read_pos :]) | ||
| self._read_pos = len(self._buf) | ||
| if self._read_pos >= self._COMPACT_THRESHOLD: | ||
| self._buf.clear() | ||
| self._read_pos = 0 | ||
| return data | ||
|
|
||
|
|
||
| class AudioStreamEncoder: | ||
| """Encode PCM AudioFrames into a compressed audio byte stream.""" | ||
|
devin-ai-integration[bot] marked this conversation as resolved.
|
||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| codec: _SUPPORTED_CODECS = "opus", | ||
| sample_rate: int = 48000, | ||
| num_channels: int = 1, | ||
| bit_rate: int = 24000, | ||
| codec_options: dict[str, str] | None = None, | ||
| ) -> None: | ||
| """Create an encoder. | ||
|
|
||
| ``codec_options`` is an optional mapping of libav private codec AVOptions | ||
| (e.g. ``{"application": "lowdelay", "frame_duration": "60", | ||
| "compression_level": "0", "vbr": "on"}`` for a low-latency libopus profile). | ||
| Values must be strings. | ||
| """ | ||
| self._sample_rate = sample_rate | ||
| self._num_channels = num_channels | ||
| self._layout = "mono" if num_channels == 1 else "stereo" | ||
|
|
||
| av_codec, container_format = _resolve_codec(codec) | ||
|
|
||
| self._output_buf = _CompactableBuffer() | ||
| self._container: av.container.OutputContainer = av.open( | ||
| self._output_buf, | ||
| mode="w", | ||
| format=container_format, | ||
| ) | ||
| self._stream: av.audio.AudioStream = self._container.add_stream( # type: ignore[assignment] | ||
| av_codec, | ||
| rate=sample_rate, | ||
| layout=self._layout, | ||
| options=codec_options, | ||
| ) | ||
| self._stream.bit_rate = bit_rate | ||
|
|
||
| self._closed = False | ||
|
|
||
| def push(self, frame: rtc.AudioFrame) -> EncodedAudioData: | ||
| """Encode a PCM audio frame. | ||
|
|
||
| Returns any new encoded bytes produced by the muxer (may be empty when | ||
| the container hasn't flushed a full page yet). The very first call | ||
| includes container headers (e.g. OGG OpusHead / OpusTags) if not empty. | ||
| """ | ||
| if self._closed: | ||
| raise RuntimeError("encoder is closed") | ||
|
|
||
| av_frame = av.AudioFrame( | ||
| format="s16", | ||
| layout=self._layout, | ||
| samples=frame.samples_per_channel, | ||
| ) | ||
| av_frame.rate = self._sample_rate | ||
| av_frame.planes[0].update(bytes(frame.data)) | ||
|
|
||
| num_samples = 0 | ||
| for packet in self._stream.encode(av_frame): | ||
| if packet.duration is not None: | ||
| num_samples += packet.duration | ||
| self._container.mux(packet) | ||
|
|
||
| return EncodedAudioData(data=self._output_buf.drain(), num_samples=num_samples) | ||
|
|
||
| def close(self) -> EncodedAudioData: | ||
| """Finalize the container and return any remaining bytes (e.g. OGG EOS). | ||
|
|
||
| The encoder must not be used after calling this method. | ||
| """ | ||
| if self._closed: | ||
| return EncodedAudioData(data=b"", num_samples=0) | ||
|
|
||
| self._closed = True | ||
| num_samples = 0 | ||
| for packet in self._stream.encode(None): | ||
| if packet.duration is not None: | ||
| num_samples += packet.duration | ||
| self._container.mux(packet) | ||
| self._container.close() | ||
| return EncodedAudioData(data=self._output_buf.drain(), num_samples=num_samples) | ||
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.
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.
We should encode in another thread, like we do for our AudioDecoder
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.
I thought about this before, but I can see some difference here:
Decoder: we need a thread so that the blocking read() wait doesn't stall the event loop
Encoder: caller pushes data (calling encode() when we have a frame) → no blocking wait, no thread needed
I can create a threaded version and show some benchmarks.
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.
Here are the results:
Threaded version has a 6ms delay for the first page, but all of them are pretty much invisible in real-time load (60ms input frame size, opus needs about 16 frames for a page)
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.
BTW, I updated the eot PR to use the threaded version: https://github.com/livekit/agents/pull/4722/changes#diff-07d680088a7c2a58bad7bec653cc4d5197cc212269eb0d76d35eab64a1195b07
Uh oh!
There was an error while loading. Please reload this page.
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.
So the Opus encode is almost instantaneous? Tho what if you push more than 60ms? like if you push 500ms?
isn't it going to block? I understand we will push tiny frames for the barge-in model, but since this is a public utility, we still need to get the interface right
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.
The sync version is still blocking 4ms sometimes, for the asyncio it's still not ideal (it accumulates with the user code and a lot of stuff inside our framework).
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.
Oh, reading this comment #5494 (comment)
Seems like we should close this PR then?