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
48 changes: 48 additions & 0 deletions tests/calls/test_audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,54 @@ async def test_26_ready_rtc_frames_do_not_overflow_with_a_fast_sender(self):
async def test_100_ready_rtc_frames_are_sent_in_order(self):
await self._assert_rtc_frames_sent(100)

async def _send_frames_at(self, frame_positions, options=None):
class ReadyTrack:
def __init__(self, frames):
self.frames = deque(frames)

async def recv(self):
if not self.frames:
raise MediaStreamError
return self.frames.popleft()

class FastSink:
def __init__(self):
self.sent = []

async def write_audio(self, data):
self.sent.append(data)

frames = []
for position in frame_positions:
frame = av.AudioFrame(format="s16", layout="mono", samples=PCM.samples_per_frame)
frame.planes[0].update(FRAME)
frame.sample_rate = PCM.rate
frame.pts = position * PCM.samples_per_frame
frame.time_base = Fraction(1, PCM.rate)
frames.append(frame)

sink = FastSink()
caller = CallerSink(sink, RecordingTap(Capture()), lambda event: None, options)
try:
await asyncio.wait_for(caller._consume(ReadyTrack(frames)), timeout=1)
finally:
await caller.close()
return b"".join(sink.sent)

async def test_caller_timestamp_gap_is_sent_as_silence(self):
sent = await self._send_frames_at([0, 1, 11])
self.assertEqual(sent, FRAME * 2 + bytes(9 * PCM.bytes_per_frame) + FRAME)

async def test_caller_gap_fill_is_limited(self):
sent = await self._send_frames_at(
[0, 500], InputAudioOptions(max_gap_fill_seconds=PCM.frame_seconds * 3),
)
self.assertEqual(sent, FRAME + bytes(3 * PCM.bytes_per_frame) + FRAME)

async def test_caller_gap_fill_can_be_turned_off(self):
sent = await self._send_frames_at([0, 11], InputAudioOptions(max_gap_fill_seconds=0))
self.assertEqual(sent, FRAME * 2)

async def test_sender_failure_is_reported_without_another_rtc_frame(self):
class OneFrameTrack:
def __init__(self):
Expand Down
34 changes: 28 additions & 6 deletions whatsapp_chatbot_python/calls/audio.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ async def _consume(self, track: MediaStreamTrack) -> None:
stream_ended = False
reported_dropped_samples = 0
next_loss_report_at = 0.0
next_media_time = None

try:
while True:
Expand All @@ -363,7 +364,15 @@ async def _consume(self, track: MediaStreamTrack) -> None:
if sender.done():
return

await self._queue_frame(frame, buffer, frame_start_at)
media_time = self._media_time(frame)

if media_time is not None:
if next_media_time is not None:
await self._fill_gap(media_time - next_media_time, buffer)

next_media_time = media_time + frame.samples / PCM.rate

await self._queue_frame(frame, buffer, frame_start_at, media_time)

frame_start_at += frame.samples / PCM.rate

Expand Down Expand Up @@ -410,17 +419,30 @@ async def _read_resampled_frames(

return frames, received_at - duration

@staticmethod
def _media_time(frame: AudioFrame) -> float | None:
if frame.pts is None or frame.time_base is None:
return None

return float(frame.pts * frame.time_base)

async def _fill_gap(self, gap_seconds: float, buffer: _InputAudioBuffer) -> None:
"""Send silence for caller audio the network did not deliver, such as WhatsApp's silence suppression."""
if gap_seconds <= PCM.frame_seconds / 2:
return

samples = round(min(gap_seconds, self._options.max_gap_fill_seconds) * PCM.rate)

if samples > 0:
await buffer.put(bytes(samples * PCM16_SAMPLE_BYTES))

async def _queue_frame(
self, frame: AudioFrame, buffer: _InputAudioBuffer, frame_start_at: float,
media_time: float | None,
) -> None:
frame_bytes = frame.samples * PCM16_SAMPLE_BYTES
data = bytes(frame.planes[0])[:frame_bytes]

media_time = (
float(frame.pts * frame.time_base)
if frame.pts is not None and frame.time_base is not None else None
)

self._tap.write(Track.CALLER, data, media_time, frame_start_at=frame_start_at)
await buffer.put(data)

Expand Down
4 changes: 4 additions & 0 deletions whatsapp_chatbot_python/calls/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,10 +353,14 @@ class InputAudioOptions:
send_seconds: float = 2
enqueue_seconds: float = 0.25
overflow_policy: InputOverflowPolicy | str = InputOverflowPolicy.DROP_OLDEST
max_gap_fill_seconds: float = 2

def __post_init__(self) -> None:
positive_values(self.buffer_seconds, self.send_seconds, self.enqueue_seconds)

if not isfinite(self.max_gap_fill_seconds) or self.max_gap_fill_seconds < 0:
raise ValueError("Gap fill limit must be zero or positive seconds")

try:
policy = InputOverflowPolicy(self.overflow_policy)
except ValueError as error:
Expand Down
Loading