Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/audio-frame-data-length.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-rtc": patch
---

Use only an `AudioFrame`'s own samples, not extra bytes past them in its buffer.
4 changes: 2 additions & 2 deletions livekit-rtc/livekit/rtc/apm.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def process_stream(self, data: AudioFrame) -> None:
req = proto_ffi.FfiRequest()
req.apm_process_stream.apm_handle = self._ffi_handle.handle
req.apm_process_stream.data_ptr = get_address(data._data)
req.apm_process_stream.size = len(data._data)
req.apm_process_stream.size = data.data.nbytes
req.apm_process_stream.sample_rate = data.sample_rate
req.apm_process_stream.num_channels = data.num_channels

Expand Down Expand Up @@ -84,7 +84,7 @@ def process_reverse_stream(self, data: AudioFrame) -> None:
req = proto_ffi.FfiRequest()
req.apm_process_reverse_stream.apm_handle = self._ffi_handle.handle
req.apm_process_reverse_stream.data_ptr = get_address(data._data)
req.apm_process_reverse_stream.size = len(data._data)
req.apm_process_reverse_stream.size = data.data.nbytes
req.apm_process_reverse_stream.sample_rate = data.sample_rate
req.apm_process_reverse_stream.num_channels = data.num_channels

Expand Down
15 changes: 7 additions & 8 deletions livekit-rtc/livekit/rtc/audio_frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ def __init__(

Args:
data (Union[bytes, bytearray, memoryview]): The raw audio data, which must be at least
`num_channels * samples_per_channel * sizeof(int16)` bytes long.
`num_channels * samples_per_channel * sizeof(int16)` bytes long. Bytes past that
size are not part of the frame.

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.

nit, optional: with this contract, __init__ still checks the parity of the whole buffer (data_len % sizeof(int16) != 0), so a single trailing byte past the frame is rejected even though it's not part of the frame:

rtc.AudioFrame(bytearray(321), 16000, 1, 160)  # needs 320 bytes, raises ValueError

Since min_size is always even, the parity check could be dropped, or the docstring could say the buffer length must still be a multiple of 2 bytes. Either is fine.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dropped the parity check in 4cf7dcd, since min_size already guarantees enough whole samples. test_a_trailing_odd_byte_is_not_part_of_the_frame builds a frame over a buffer with one extra byte; it raised ValueError before.

sample_rate (int): The sample rate of the audio in Hz.
num_channels (int): The number of audio channels (e.g., 1 for mono, 2 for stereo).
samples_per_channel (int): The number of samples per channel.
Expand All @@ -62,10 +63,6 @@ def __init__(
"data length must be >= num_channels * samples_per_channel * sizeof(int16)"
)

if data_len % ctypes.sizeof(ctypes.c_int16) != 0:
# can happen if data is bigger than needed
raise ValueError("data length must be a multiple of sizeof(int16)")

self._data = data

self._sample_rate = sample_rate
Expand Down Expand Up @@ -121,9 +118,11 @@ def data(self) -> memoryview:
Returns a memory view of the audio data as 16-bit signed integers.

Returns:
memoryview: A memory view of the audio data.
memoryview: A memory view of the frame's `num_channels * samples_per_channel`
samples. Bytes of the buffer past them are left out.
"""
return memoryview(self._data).cast("B").cast("h")
size = self.num_channels * self.samples_per_channel * ctypes.sizeof(ctypes.c_int16)
return memoryview(self._data).cast("B")[:size].cast("h")

@property
def sample_rate(self) -> int:
Expand Down Expand Up @@ -180,7 +179,7 @@ def to_wav_bytes(self) -> bytes:
wav.setnchannels(self.num_channels)
wav.setsampwidth(2)
wav.setframerate(self.sample_rate)
wav.writeframes(self._data)
wav.writeframes(self.data)

return wav_file.getvalue()

Expand Down
78 changes: 78 additions & 0 deletions tests/rtc/test_audio_frame.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,90 @@
from __future__ import annotations

import array
import ctypes
import io
import types
import wave

import pytest

from livekit import rtc


def _frame(samples: list[int], samples_per_channel: int, num_channels: int = 1) -> rtc.AudioFrame:
return rtc.AudioFrame(
array.array("h", samples).tobytes(), 16000, num_channels, samples_per_channel
)


def test_data_holds_only_the_frame_samples() -> None:
# the buffer may be larger than the frame; the samples past it are not part of the frame
frame = _frame([1, 2, 3, 4, 99, 99], samples_per_channel=2, num_channels=2)

assert list(frame.data) == [1, 2, 3, 4]


def test_a_trailing_odd_byte_is_not_part_of_the_frame() -> None:
frame = rtc.AudioFrame(bytes([1, 0, 2, 0, 99]), 16000, 1, 2)

assert list(frame.data) == [1, 2]


def test_combine_audio_frames_keeps_every_frame_sample() -> None:
combined = rtc.combine_audio_frames([_frame([1, 2, 99, 99], 2), _frame([3, 4], 2)])

assert combined.samples_per_channel == 4
assert list(combined.data) == [1, 2, 3, 4]


def test_to_wav_bytes_writes_only_the_frame_samples() -> None:
frame = _frame([1, 2, 99, 99], samples_per_channel=2)

with wave.open(io.BytesIO(frame.to_wav_bytes())) as wav:
assert wav.getnframes() == 2
assert array.array("h", wav.readframes(wav.getnframes())).tolist() == [1, 2]


def test_frame_over_a_larger_bytearray_shares_its_memory() -> None:
# AudioProcessingModule processes frames in place, so the frame must not copy the buffer
buffer = bytearray(array.array("h", [1, 2, 99, 99]).tobytes())
frame = rtc.AudioFrame(buffer, 16000, 1, 2)

frame.data[0] = 7
assert array.array("h", bytes(buffer[:2])).tolist() == [7]


@pytest.mark.parametrize("method", ["process_stream", "process_reverse_stream"])
def test_apm_sends_only_the_frame_bytes(monkeypatch: pytest.MonkeyPatch, method: str) -> None:
from livekit.rtc import apm as apm_module

requests = []

class _FakeClient:
def request(self, req): # type: ignore[no-untyped-def]
requests.append(req)
return apm_module.proto_ffi.FfiResponse()

monkeypatch.setattr(apm_module, "FfiClient", types.SimpleNamespace(instance=_FakeClient()))
module = object.__new__(apm_module.AudioProcessingModule)
module._ffi_handle = types.SimpleNamespace(handle=1) # type: ignore[assignment]

# a 10 ms mono frame at 16 kHz over a buffer with 40 extra samples
getattr(module, method)(rtc.AudioFrame(bytearray(400), 16000, 1, 160))

sent = getattr(requests[0], "apm_" + method)
assert sent.size == 320


def test_serialized_frame_holds_only_the_frame_samples() -> None:
pydantic = pytest.importorskip("pydantic")
adapter = pydantic.TypeAdapter(rtc.AudioFrame)

data = adapter.dump_python(_frame([1, 2, 99, 99], samples_per_channel=2))

assert list(adapter.validate_python(data).data) == [1, 2]


def test_frame_from_a_read_only_numpy_buffer_can_be_captured() -> None:
# np.frombuffer returns a read-only array, so its memoryview is read-only too.
np = pytest.importorskip("numpy")
Expand Down
Loading