Skip to content
Merged
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
2 changes: 1 addition & 1 deletion tests/test_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ async def capture_sleep(delay: float) -> None:
await call.send_audio(audio)

assert len(sleep_calls) == 2
assert all(s == call.rpt_packet_duration.total_seconds() for s in sleep_calls)
assert all(s <= call.rpt_packet_duration.total_seconds() for s in sleep_calls)


def make_echo_call(**kwargs) -> EchoCall:
Expand Down
24 changes: 20 additions & 4 deletions voip/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import json
import logging
import secrets
import time
from typing import ClassVar

import numpy as np
Expand Down Expand Up @@ -73,6 +74,13 @@ class AudioCall(RTPCall):
rtp_ssrc: int = dataclasses.field(
init=False, repr=False, default_factory=generate_ssrc
)
last_packet_time: float = dataclasses.field(
init=False, repr=False, default_factory=time.perf_counter
)
send_audio_lock: asyncio.Lock = dataclasses.field(
default_factory=asyncio.Lock,
init=False,
)

def __post_init__(self) -> None:
fmt = self.media.fmt[0]
Expand Down Expand Up @@ -207,9 +215,17 @@ async def send_audio(self, audio: np.ndarray) -> None:
if remote_addr is None:
logger.warning("No remote RTP address for this call; dropping audio")
return
for payload in self.codec.packetize(audio):
self.send_packet(self.next_rtp_packet(payload), remote_addr)
await asyncio.sleep(self.rpt_packet_duration.total_seconds())
async with self.send_audio_lock:
for payload in self.codec.packetize(audio):
await asyncio.sleep(
max(
0.0,
self.rpt_packet_duration.total_seconds()
- (time.perf_counter() - self.last_packet_time),
)
)
self.send_packet(self.next_rtp_packet(payload), remote_addr)
self.last_packet_time = time.perf_counter()

def audio_received(self, *, audio: np.ndarray, rms: float) -> None:
"""
Expand Down Expand Up @@ -310,7 +326,7 @@ def flush_voice_buffer(self) -> None:
< self.sampling_rate_hz * self.silence_gap.total_seconds()
or self.rms(self._speech_buffer) < self.utterances_rms_threshold
):
asyncio.create_task(self.voice_received(self._speech_buffer[:]))
asyncio.create_task(self.voice_received(self._speech_buffer.copy()))
self._speech_buffer = np.empty((0,), dtype=np.float32)

async def voice_received(self, audio: np.ndarray) -> None:
Expand Down
Loading